LLVM 17.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
977static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
978 Type *Ty2) {
979 std::string ErrString;
980 raw_string_ostream ErrOS(ErrString);
981 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
982 return ErrOS.str();
983}
984
985/// parseAliasOrIFunc:
986/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
987/// OptionalVisibility OptionalDLLStorageClass
988/// OptionalThreadLocal OptionalUnnamedAddr
989/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
990///
991/// AliaseeOrResolver
992/// ::= TypeAndValue
993///
994/// SymbolAttrs
995/// ::= ',' 'partition' StringConstant
996///
997/// Everything through OptionalUnnamedAddr has already been parsed.
998///
999bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc,
1000 unsigned L, unsigned Visibility,
1001 unsigned DLLStorageClass, bool DSOLocal,
1003 GlobalVariable::UnnamedAddr UnnamedAddr) {
1004 bool IsAlias;
1005 if (Lex.getKind() == lltok::kw_alias)
1006 IsAlias = true;
1007 else if (Lex.getKind() == lltok::kw_ifunc)
1008 IsAlias = false;
1009 else
1010 llvm_unreachable("Not an alias or ifunc!");
1011 Lex.Lex();
1012
1014
1015 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1016 return error(NameLoc, "invalid linkage type for alias");
1017
1018 if (!isValidVisibilityForLinkage(Visibility, L))
1019 return error(NameLoc,
1020 "symbol with local linkage must have default visibility");
1021
1022 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1023 return error(NameLoc,
1024 "symbol with local linkage cannot have a DLL storage class");
1025
1026 Type *Ty;
1027 LocTy ExplicitTypeLoc = Lex.getLoc();
1028 if (parseType(Ty) ||
1029 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1030 return true;
1031
1032 Constant *Aliasee;
1033 LocTy AliaseeLoc = Lex.getLoc();
1034 if (Lex.getKind() != lltok::kw_bitcast &&
1037 Lex.getKind() != lltok::kw_inttoptr) {
1038 if (parseGlobalTypeAndValue(Aliasee))
1039 return true;
1040 } else {
1041 // The bitcast dest type is not present, it is implied by the dest type.
1042 ValID ID;
1043 if (parseValID(ID, /*PFS=*/nullptr))
1044 return true;
1045 if (ID.Kind != ValID::t_Constant)
1046 return error(AliaseeLoc, "invalid aliasee");
1047 Aliasee = ID.ConstantVal;
1048 }
1049
1050 Type *AliaseeType = Aliasee->getType();
1051 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1052 if (!PTy)
1053 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1054 unsigned AddrSpace = PTy->getAddressSpace();
1055
1056 if (IsAlias) {
1057 if (!PTy->isOpaqueOrPointeeTypeMatches(Ty))
1058 return error(
1059 ExplicitTypeLoc,
1061 "explicit pointee type doesn't match operand's pointee type", Ty,
1062 PTy->getNonOpaquePointerElementType()));
1063 } else {
1064 if (!PTy->isOpaque() &&
1065 !PTy->getNonOpaquePointerElementType()->isFunctionTy())
1066 return error(ExplicitTypeLoc,
1067 "explicit pointee type should be a function type");
1068 }
1069
1070 GlobalValue *GVal = nullptr;
1071
1072 // See if the alias was forward referenced, if so, prepare to replace the
1073 // forward reference.
1074 if (!Name.empty()) {
1075 auto I = ForwardRefVals.find(Name);
1076 if (I != ForwardRefVals.end()) {
1077 GVal = I->second.first;
1078 ForwardRefVals.erase(Name);
1079 } else if (M->getNamedValue(Name)) {
1080 return error(NameLoc, "redefinition of global '@" + Name + "'");
1081 }
1082 } else {
1083 auto I = ForwardRefValIDs.find(NumberedVals.size());
1084 if (I != ForwardRefValIDs.end()) {
1085 GVal = I->second.first;
1086 ForwardRefValIDs.erase(I);
1087 }
1088 }
1089
1090 // Okay, create the alias/ifunc but do not insert it into the module yet.
1091 std::unique_ptr<GlobalAlias> GA;
1092 std::unique_ptr<GlobalIFunc> GI;
1093 GlobalValue *GV;
1094 if (IsAlias) {
1095 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1097 Aliasee, /*Parent*/ nullptr));
1098 GV = GA.get();
1099 } else {
1100 GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1102 Aliasee, /*Parent*/ nullptr));
1103 GV = GI.get();
1104 }
1105 GV->setThreadLocalMode(TLM);
1108 GV->setUnnamedAddr(UnnamedAddr);
1109 maybeSetDSOLocal(DSOLocal, *GV);
1110
1111 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1112 // Now parse them if there are any.
1113 while (Lex.getKind() == lltok::comma) {
1114 Lex.Lex();
1115
1116 if (Lex.getKind() == lltok::kw_partition) {
1117 Lex.Lex();
1118 GV->setPartition(Lex.getStrVal());
1119 if (parseToken(lltok::StringConstant, "expected partition string"))
1120 return true;
1121 } else {
1122 return tokError("unknown alias or ifunc property!");
1123 }
1124 }
1125
1126 if (Name.empty())
1127 NumberedVals.push_back(GV);
1128
1129 if (GVal) {
1130 // Verify that types agree.
1131 if (GVal->getType() != GV->getType())
1132 return error(
1133 ExplicitTypeLoc,
1134 "forward reference and definition of alias have different types");
1135
1136 // If they agree, just RAUW the old value with the alias and remove the
1137 // forward ref info.
1138 GVal->replaceAllUsesWith(GV);
1139 GVal->eraseFromParent();
1140 }
1141
1142 // Insert into the module, we know its name won't collide now.
1143 if (IsAlias)
1144 M->insertAlias(GA.release());
1145 else
1146 M->insertIFunc(GI.release());
1147 assert(GV->getName() == Name && "Should not be a name conflict!");
1148
1149 return false;
1150}
1151
1152static bool isSanitizer(lltok::Kind Kind) {
1153 switch (Kind) {
1156 case lltok::kw_sanitize_memtag:
1158 return true;
1159 default:
1160 return false;
1161 }
1162}
1163
1164bool LLParser::parseSanitizer(GlobalVariable *GV) {
1167 if (GV->hasSanitizerMetadata())
1168 Meta = GV->getSanitizerMetadata();
1169
1170 switch (Lex.getKind()) {
1172 Meta.NoAddress = true;
1173 break;
1175 Meta.NoHWAddress = true;
1176 break;
1177 case lltok::kw_sanitize_memtag:
1178 Meta.Memtag = true;
1179 break;
1181 Meta.IsDynInit = true;
1182 break;
1183 default:
1184 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1185 }
1186 GV->setSanitizerMetadata(Meta);
1187 Lex.Lex();
1188 return false;
1189}
1190
1191/// parseGlobal
1192/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1193/// OptionalVisibility OptionalDLLStorageClass
1194/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1195/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1196/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1197/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1198/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1199/// Const OptionalAttrs
1200///
1201/// Everything up to and including OptionalUnnamedAddr has been parsed
1202/// already.
1203///
1204bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1205 unsigned Linkage, bool HasLinkage,
1206 unsigned Visibility, unsigned DLLStorageClass,
1207 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1208 GlobalVariable::UnnamedAddr UnnamedAddr) {
1209 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1210 return error(NameLoc,
1211 "symbol with local linkage must have default visibility");
1212
1213 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1214 return error(NameLoc,
1215 "symbol with local linkage cannot have a DLL storage class");
1216
1217 unsigned AddrSpace;
1218 bool IsConstant, IsExternallyInitialized;
1219 LocTy IsExternallyInitializedLoc;
1220 LocTy TyLoc;
1221
1222 Type *Ty = nullptr;
1223 if (parseOptionalAddrSpace(AddrSpace) ||
1224 parseOptionalToken(lltok::kw_externally_initialized,
1225 IsExternallyInitialized,
1226 &IsExternallyInitializedLoc) ||
1227 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1228 return true;
1229
1230 // If the linkage is specified and is external, then no initializer is
1231 // present.
1232 Constant *Init = nullptr;
1233 if (!HasLinkage ||
1235 (GlobalValue::LinkageTypes)Linkage)) {
1236 if (parseGlobalValue(Ty, Init))
1237 return true;
1238 }
1239
1241 return error(TyLoc, "invalid type for global variable");
1242
1243 GlobalValue *GVal = nullptr;
1244
1245 // See if the global was forward referenced, if so, use the global.
1246 if (!Name.empty()) {
1247 auto I = ForwardRefVals.find(Name);
1248 if (I != ForwardRefVals.end()) {
1249 GVal = I->second.first;
1250 ForwardRefVals.erase(I);
1251 } else if (M->getNamedValue(Name)) {
1252 return error(NameLoc, "redefinition of global '@" + Name + "'");
1253 }
1254 } else {
1255 auto I = ForwardRefValIDs.find(NumberedVals.size());
1256 if (I != ForwardRefValIDs.end()) {
1257 GVal = I->second.first;
1258 ForwardRefValIDs.erase(I);
1259 }
1260 }
1261
1263 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1265
1266 if (Name.empty())
1267 NumberedVals.push_back(GV);
1268
1269 // Set the parsed properties on the global.
1270 if (Init)
1271 GV->setInitializer(Init);
1272 GV->setConstant(IsConstant);
1274 maybeSetDSOLocal(DSOLocal, *GV);
1277 GV->setExternallyInitialized(IsExternallyInitialized);
1278 GV->setThreadLocalMode(TLM);
1279 GV->setUnnamedAddr(UnnamedAddr);
1280
1281 if (GVal) {
1282 if (GVal->getType() != Ty->getPointerTo(AddrSpace))
1283 return error(
1284 TyLoc,
1285 "forward reference and definition of global have different types");
1286
1287 GVal->replaceAllUsesWith(GV);
1288 GVal->eraseFromParent();
1289 }
1290
1291 // parse attributes on the global.
1292 while (Lex.getKind() == lltok::comma) {
1293 Lex.Lex();
1294
1295 if (Lex.getKind() == lltok::kw_section) {
1296 Lex.Lex();
1297 GV->setSection(Lex.getStrVal());
1298 if (parseToken(lltok::StringConstant, "expected global section string"))
1299 return true;
1300 } else if (Lex.getKind() == lltok::kw_partition) {
1301 Lex.Lex();
1302 GV->setPartition(Lex.getStrVal());
1303 if (parseToken(lltok::StringConstant, "expected partition string"))
1304 return true;
1305 } else if (Lex.getKind() == lltok::kw_align) {
1306 MaybeAlign Alignment;
1307 if (parseOptionalAlignment(Alignment))
1308 return true;
1309 if (Alignment)
1310 GV->setAlignment(*Alignment);
1311 } else if (Lex.getKind() == lltok::MetadataVar) {
1312 if (parseGlobalObjectMetadataAttachment(*GV))
1313 return true;
1314 } else if (isSanitizer(Lex.getKind())) {
1315 if (parseSanitizer(GV))
1316 return true;
1317 } else {
1318 Comdat *C;
1319 if (parseOptionalComdat(Name, C))
1320 return true;
1321 if (C)
1322 GV->setComdat(C);
1323 else
1324 return tokError("unknown global variable property!");
1325 }
1326 }
1327
1329 LocTy BuiltinLoc;
1330 std::vector<unsigned> FwdRefAttrGrps;
1331 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1332 return true;
1333 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1334 GV->setAttributes(AttributeSet::get(Context, Attrs));
1335 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1336 }
1337
1338 return false;
1339}
1340
1341/// parseUnnamedAttrGrp
1342/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1343bool LLParser::parseUnnamedAttrGrp() {
1345 LocTy AttrGrpLoc = Lex.getLoc();
1346 Lex.Lex();
1347
1348 if (Lex.getKind() != lltok::AttrGrpID)
1349 return tokError("expected attribute group id");
1350
1351 unsigned VarID = Lex.getUIntVal();
1352 std::vector<unsigned> unused;
1353 LocTy BuiltinLoc;
1354 Lex.Lex();
1355
1356 if (parseToken(lltok::equal, "expected '=' here") ||
1357 parseToken(lltok::lbrace, "expected '{' here"))
1358 return true;
1359
1360 auto R = NumberedAttrBuilders.find(VarID);
1361 if (R == NumberedAttrBuilders.end())
1362 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1363
1364 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1365 parseToken(lltok::rbrace, "expected end of attribute group"))
1366 return true;
1367
1368 if (!R->second.hasAttributes())
1369 return error(AttrGrpLoc, "attribute group has no attributes");
1370
1371 return false;
1372}
1373
1375 switch (Kind) {
1376#define GET_ATTR_NAMES
1377#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1378 case lltok::kw_##DISPLAY_NAME: \
1379 return Attribute::ENUM_NAME;
1380#include "llvm/IR/Attributes.inc"
1381 default:
1382 return Attribute::None;
1383 }
1384}
1385
1386bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1387 bool InAttrGroup) {
1388 if (Attribute::isTypeAttrKind(Attr))
1389 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1390
1391 switch (Attr) {
1392 case Attribute::Alignment: {
1393 MaybeAlign Alignment;
1394 if (InAttrGroup) {
1395 uint32_t Value = 0;
1396 Lex.Lex();
1397 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1398 return true;
1399 Alignment = Align(Value);
1400 } else {
1401 if (parseOptionalAlignment(Alignment, true))
1402 return true;
1403 }
1404 B.addAlignmentAttr(Alignment);
1405 return false;
1406 }
1407 case Attribute::StackAlignment: {
1408 unsigned Alignment;
1409 if (InAttrGroup) {
1410 Lex.Lex();
1411 if (parseToken(lltok::equal, "expected '=' here") ||
1412 parseUInt32(Alignment))
1413 return true;
1414 } else {
1415 if (parseOptionalStackAlignment(Alignment))
1416 return true;
1417 }
1418 B.addStackAlignmentAttr(Alignment);
1419 return false;
1420 }
1421 case Attribute::AllocSize: {
1422 unsigned ElemSizeArg;
1423 std::optional<unsigned> NumElemsArg;
1424 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1425 return true;
1426 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1427 return false;
1428 }
1429 case Attribute::VScaleRange: {
1430 unsigned MinValue, MaxValue;
1431 if (parseVScaleRangeArguments(MinValue, MaxValue))
1432 return true;
1433 B.addVScaleRangeAttr(MinValue,
1434 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1435 return false;
1436 }
1437 case Attribute::Dereferenceable: {
1438 uint64_t Bytes;
1439 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1440 return true;
1441 B.addDereferenceableAttr(Bytes);
1442 return false;
1443 }
1444 case Attribute::DereferenceableOrNull: {
1445 uint64_t Bytes;
1446 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1447 return true;
1448 B.addDereferenceableOrNullAttr(Bytes);
1449 return false;
1450 }
1451 case Attribute::UWTable: {
1453 if (parseOptionalUWTableKind(Kind))
1454 return true;
1455 B.addUWTableAttr(Kind);
1456 return false;
1457 }
1458 case Attribute::AllocKind: {
1460 if (parseAllocKind(Kind))
1461 return true;
1462 B.addAllocKindAttr(Kind);
1463 return false;
1464 }
1465 case Attribute::Memory: {
1466 std::optional<MemoryEffects> ME = parseMemoryAttr();
1467 if (!ME)
1468 return true;
1469 B.addMemoryAttr(*ME);
1470 return false;
1471 }
1472 case Attribute::NoFPClass: {
1473 if (FPClassTest NoFPClass =
1474 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1475 B.addNoFPClassAttr(NoFPClass);
1476 return false;
1477 }
1478
1479 return true;
1480 }
1481 default:
1482 B.addAttribute(Attr);
1483 Lex.Lex();
1484 return false;
1485 }
1486}
1487
1489 switch (Kind) {
1490 case lltok::kw_readnone:
1491 ME &= MemoryEffects::none();
1492 return true;
1493 case lltok::kw_readonly:
1495 return true;
1496 case lltok::kw_writeonly:
1498 return true;
1501 return true;
1504 return true;
1507 return true;
1508 default:
1509 return false;
1510 }
1511}
1512
1513/// parseFnAttributeValuePairs
1514/// ::= <attr> | <attr> '=' <value>
1515bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1516 std::vector<unsigned> &FwdRefAttrGrps,
1517 bool InAttrGrp, LocTy &BuiltinLoc) {
1518 bool HaveError = false;
1519
1520 B.clear();
1521
1523 while (true) {
1524 lltok::Kind Token = Lex.getKind();
1525 if (Token == lltok::rbrace)
1526 break; // Finished.
1527
1528 if (Token == lltok::StringConstant) {
1529 if (parseStringAttribute(B))
1530 return true;
1531 continue;
1532 }
1533
1534 if (Token == lltok::AttrGrpID) {
1535 // Allow a function to reference an attribute group:
1536 //
1537 // define void @foo() #1 { ... }
1538 if (InAttrGrp) {
1539 HaveError |= error(
1540 Lex.getLoc(),
1541 "cannot have an attribute group reference in an attribute group");
1542 } else {
1543 // Save the reference to the attribute group. We'll fill it in later.
1544 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1545 }
1546 Lex.Lex();
1547 continue;
1548 }
1549
1550 SMLoc Loc = Lex.getLoc();
1551 if (Token == lltok::kw_builtin)
1552 BuiltinLoc = Loc;
1553
1554 if (upgradeMemoryAttr(ME, Token)) {
1555 Lex.Lex();
1556 continue;
1557 }
1558
1560 if (Attr == Attribute::None) {
1561 if (!InAttrGrp)
1562 break;
1563 return error(Lex.getLoc(), "unterminated attribute group");
1564 }
1565
1566 if (parseEnumAttribute(Attr, B, InAttrGrp))
1567 return true;
1568
1569 // As a hack, we allow function alignment to be initially parsed as an
1570 // attribute on a function declaration/definition or added to an attribute
1571 // group and later moved to the alignment field.
1572 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1573 HaveError |= error(Loc, "this attribute does not apply to functions");
1574 }
1575
1576 if (ME != MemoryEffects::unknown())
1577 B.addMemoryAttr(ME);
1578 return HaveError;
1579}
1580
1581//===----------------------------------------------------------------------===//
1582// GlobalValue Reference/Resolution Routines.
1583//===----------------------------------------------------------------------===//
1584
1586 // For opaque pointers, the used global type does not matter. We will later
1587 // RAUW it with a global/function of the correct type.
1588 if (PTy->isOpaque())
1589 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1592 PTy->getAddressSpace());
1593
1594 Type *ElemTy = PTy->getNonOpaquePointerElementType();
1595 if (auto *FT = dyn_cast<FunctionType>(ElemTy))
1597 PTy->getAddressSpace(), "", M);
1598 else
1599 return new GlobalVariable(
1600 *M, ElemTy, false, GlobalValue::ExternalWeakLinkage, nullptr, "",
1601 nullptr, GlobalVariable::NotThreadLocal, PTy->getAddressSpace());
1602}
1603
1604Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1605 Value *Val) {
1606 Type *ValTy = Val->getType();
1607 if (ValTy == Ty)
1608 return Val;
1609 if (Ty->isLabelTy())
1610 error(Loc, "'" + Name + "' is not a basic block");
1611 else
1612 error(Loc, "'" + Name + "' defined with type '" +
1613 getTypeString(Val->getType()) + "' but expected '" +
1614 getTypeString(Ty) + "'");
1615 return nullptr;
1616}
1617
1618/// getGlobalVal - Get a value with the specified name or ID, creating a
1619/// forward reference record if needed. This can return null if the value
1620/// exists but does not have the right type.
1621GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1622 LocTy Loc) {
1623 PointerType *PTy = dyn_cast<PointerType>(Ty);
1624 if (!PTy) {
1625 error(Loc, "global variable reference must have pointer type");
1626 return nullptr;
1627 }
1628
1629 // Look this name up in the normal function symbol table.
1630 GlobalValue *Val =
1631 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1632
1633 // If this is a forward reference for the value, see if we already created a
1634 // forward ref record.
1635 if (!Val) {
1636 auto I = ForwardRefVals.find(Name);
1637 if (I != ForwardRefVals.end())
1638 Val = I->second.first;
1639 }
1640
1641 // If we have the value in the symbol table or fwd-ref table, return it.
1642 if (Val)
1643 return cast_or_null<GlobalValue>(
1644 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1645
1646 // Otherwise, create a new forward reference for this value and remember it.
1647 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1648 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1649 return FwdVal;
1650}
1651
1652GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1653 PointerType *PTy = dyn_cast<PointerType>(Ty);
1654 if (!PTy) {
1655 error(Loc, "global variable reference must have pointer type");
1656 return nullptr;
1657 }
1658
1659 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1660
1661 // If this is a forward reference for the value, see if we already created a
1662 // forward ref record.
1663 if (!Val) {
1664 auto I = ForwardRefValIDs.find(ID);
1665 if (I != ForwardRefValIDs.end())
1666 Val = I->second.first;
1667 }
1668
1669 // If we have the value in the symbol table or fwd-ref table, return it.
1670 if (Val)
1671 return cast_or_null<GlobalValue>(
1672 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1673
1674 // Otherwise, create a new forward reference for this value and remember it.
1675 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1676 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1677 return FwdVal;
1678}
1679
1680//===----------------------------------------------------------------------===//
1681// Comdat Reference/Resolution Routines.
1682//===----------------------------------------------------------------------===//
1683
1684Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1685 // Look this name up in the comdat symbol table.
1688 if (I != ComdatSymTab.end())
1689 return &I->second;
1690
1691 // Otherwise, create a new forward reference for this value and remember it.
1693 ForwardRefComdats[Name] = Loc;
1694 return C;
1695}
1696
1697//===----------------------------------------------------------------------===//
1698// Helper Routines.
1699//===----------------------------------------------------------------------===//
1700
1701/// parseToken - If the current token has the specified kind, eat it and return
1702/// success. Otherwise, emit the specified error and return failure.
1703bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1704 if (Lex.getKind() != T)
1705 return tokError(ErrMsg);
1706 Lex.Lex();
1707 return false;
1708}
1709
1710/// parseStringConstant
1711/// ::= StringConstant
1712bool LLParser::parseStringConstant(std::string &Result) {
1713 if (Lex.getKind() != lltok::StringConstant)
1714 return tokError("expected string constant");
1715 Result = Lex.getStrVal();
1716 Lex.Lex();
1717 return false;
1718}
1719
1720/// parseUInt32
1721/// ::= uint32
1722bool LLParser::parseUInt32(uint32_t &Val) {
1723 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1724 return tokError("expected integer");
1725 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1726 if (Val64 != unsigned(Val64))
1727 return tokError("expected 32-bit integer (too large)");
1728 Val = Val64;
1729 Lex.Lex();
1730 return false;
1731}
1732
1733/// parseUInt64
1734/// ::= uint64
1735bool LLParser::parseUInt64(uint64_t &Val) {
1736 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1737 return tokError("expected integer");
1738 Val = Lex.getAPSIntVal().getLimitedValue();
1739 Lex.Lex();
1740 return false;
1741}
1742
1743/// parseTLSModel
1744/// := 'localdynamic'
1745/// := 'initialexec'
1746/// := 'localexec'
1747bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1748 switch (Lex.getKind()) {
1749 default:
1750 return tokError("expected localdynamic, initialexec or localexec");
1753 break;
1756 break;
1759 break;
1760 }
1761
1762 Lex.Lex();
1763 return false;
1764}
1765
1766/// parseOptionalThreadLocal
1767/// := /*empty*/
1768/// := 'thread_local'
1769/// := 'thread_local' '(' tlsmodel ')'
1770bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1772 if (!EatIfPresent(lltok::kw_thread_local))
1773 return false;
1774
1776 if (Lex.getKind() == lltok::lparen) {
1777 Lex.Lex();
1778 return parseTLSModel(TLM) ||
1779 parseToken(lltok::rparen, "expected ')' after thread local model");
1780 }
1781 return false;
1782}
1783
1784/// parseOptionalAddrSpace
1785/// := /*empty*/
1786/// := 'addrspace' '(' uint32 ')'
1787bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1788 AddrSpace = DefaultAS;
1789 if (!EatIfPresent(lltok::kw_addrspace))
1790 return false;
1791
1792 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1793 if (Lex.getKind() == lltok::StringConstant) {
1794 auto AddrSpaceStr = Lex.getStrVal();
1795 if (AddrSpaceStr == "A") {
1796 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1797 } else if (AddrSpaceStr == "G") {
1799 } else if (AddrSpaceStr == "P") {
1800 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1801 } else {
1802 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1803 }
1804 Lex.Lex();
1805 return false;
1806 }
1807 if (Lex.getKind() != lltok::APSInt)
1808 return tokError("expected integer or string constant");
1809 SMLoc Loc = Lex.getLoc();
1810 if (parseUInt32(AddrSpace))
1811 return true;
1812 if (!isUInt<24>(AddrSpace))
1813 return error(Loc, "invalid address space, must be a 24-bit integer");
1814 return false;
1815 };
1816
1817 return parseToken(lltok::lparen, "expected '(' in address space") ||
1818 ParseAddrspaceValue(AddrSpace) ||
1819 parseToken(lltok::rparen, "expected ')' in address space");
1820}
1821
1822/// parseStringAttribute
1823/// := StringConstant
1824/// := StringConstant '=' StringConstant
1825bool LLParser::parseStringAttribute(AttrBuilder &B) {
1826 std::string Attr = Lex.getStrVal();
1827 Lex.Lex();
1828 std::string Val;
1829 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1830 return true;
1831 B.addAttribute(Attr, Val);
1832 return false;
1833}
1834
1835/// Parse a potentially empty list of parameter or return attributes.
1836bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1837 bool HaveError = false;
1838
1839 B.clear();
1840
1841 while (true) {
1842 lltok::Kind Token = Lex.getKind();
1843 if (Token == lltok::StringConstant) {
1844 if (parseStringAttribute(B))
1845 return true;
1846 continue;
1847 }
1848
1849 SMLoc Loc = Lex.getLoc();
1851 if (Attr == Attribute::None)
1852 return HaveError;
1853
1854 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1855 return true;
1856
1857 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1858 HaveError |= error(Loc, "this attribute does not apply to parameters");
1859 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1860 HaveError |= error(Loc, "this attribute does not apply to return values");
1861 }
1862}
1863
1864static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1865 HasLinkage = true;
1866 switch (Kind) {
1867 default:
1868 HasLinkage = false;
1870 case lltok::kw_private:
1872 case lltok::kw_internal:
1874 case lltok::kw_weak:
1876 case lltok::kw_weak_odr:
1878 case lltok::kw_linkonce:
1886 case lltok::kw_common:
1890 case lltok::kw_external:
1892 }
1893}
1894
1895/// parseOptionalLinkage
1896/// ::= /*empty*/
1897/// ::= 'private'
1898/// ::= 'internal'
1899/// ::= 'weak'
1900/// ::= 'weak_odr'
1901/// ::= 'linkonce'
1902/// ::= 'linkonce_odr'
1903/// ::= 'available_externally'
1904/// ::= 'appending'
1905/// ::= 'common'
1906/// ::= 'extern_weak'
1907/// ::= 'external'
1908bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1909 unsigned &Visibility,
1910 unsigned &DLLStorageClass, bool &DSOLocal) {
1911 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1912 if (HasLinkage)
1913 Lex.Lex();
1914 parseOptionalDSOLocal(DSOLocal);
1915 parseOptionalVisibility(Visibility);
1916 parseOptionalDLLStorageClass(DLLStorageClass);
1917
1918 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1919 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1920 }
1921
1922 return false;
1923}
1924
1925void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1926 switch (Lex.getKind()) {
1927 default:
1928 DSOLocal = false;
1929 break;
1931 DSOLocal = true;
1932 Lex.Lex();
1933 break;
1935 DSOLocal = false;
1936 Lex.Lex();
1937 break;
1938 }
1939}
1940
1941/// parseOptionalVisibility
1942/// ::= /*empty*/
1943/// ::= 'default'
1944/// ::= 'hidden'
1945/// ::= 'protected'
1946///
1947void LLParser::parseOptionalVisibility(unsigned &Res) {
1948 switch (Lex.getKind()) {
1949 default:
1951 return;
1952 case lltok::kw_default:
1954 break;
1955 case lltok::kw_hidden:
1957 break;
1960 break;
1961 }
1962 Lex.Lex();
1963}
1964
1965/// parseOptionalDLLStorageClass
1966/// ::= /*empty*/
1967/// ::= 'dllimport'
1968/// ::= 'dllexport'
1969///
1970void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1971 switch (Lex.getKind()) {
1972 default:
1974 return;
1977 break;
1980 break;
1981 }
1982 Lex.Lex();
1983}
1984
1985/// parseOptionalCallingConv
1986/// ::= /*empty*/
1987/// ::= 'ccc'
1988/// ::= 'fastcc'
1989/// ::= 'intel_ocl_bicc'
1990/// ::= 'coldcc'
1991/// ::= 'cfguard_checkcc'
1992/// ::= 'x86_stdcallcc'
1993/// ::= 'x86_fastcallcc'
1994/// ::= 'x86_thiscallcc'
1995/// ::= 'x86_vectorcallcc'
1996/// ::= 'arm_apcscc'
1997/// ::= 'arm_aapcscc'
1998/// ::= 'arm_aapcs_vfpcc'
1999/// ::= 'aarch64_vector_pcs'
2000/// ::= 'aarch64_sve_vector_pcs'
2001/// ::= 'aarch64_sme_preservemost_from_x0'
2002/// ::= 'aarch64_sme_preservemost_from_x2'
2003/// ::= 'msp430_intrcc'
2004/// ::= 'avr_intrcc'
2005/// ::= 'avr_signalcc'
2006/// ::= 'ptx_kernel'
2007/// ::= 'ptx_device'
2008/// ::= 'spir_func'
2009/// ::= 'spir_kernel'
2010/// ::= 'x86_64_sysvcc'
2011/// ::= 'win64cc'
2012/// ::= 'webkit_jscc'
2013/// ::= 'anyregcc'
2014/// ::= 'preserve_mostcc'
2015/// ::= 'preserve_allcc'
2016/// ::= 'ghccc'
2017/// ::= 'swiftcc'
2018/// ::= 'swifttailcc'
2019/// ::= 'x86_intrcc'
2020/// ::= 'hhvmcc'
2021/// ::= 'hhvm_ccc'
2022/// ::= 'cxx_fast_tlscc'
2023/// ::= 'amdgpu_vs'
2024/// ::= 'amdgpu_ls'
2025/// ::= 'amdgpu_hs'
2026/// ::= 'amdgpu_es'
2027/// ::= 'amdgpu_gs'
2028/// ::= 'amdgpu_ps'
2029/// ::= 'amdgpu_cs'
2030/// ::= 'amdgpu_kernel'
2031/// ::= 'tailcc'
2032/// ::= 'cc' UINT
2033///
2034bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2035 switch (Lex.getKind()) {
2036 default: CC = CallingConv::C; return false;
2037 case lltok::kw_ccc: CC = CallingConv::C; break;
2038 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2039 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2052 break;
2055 break;
2058 break;
2073 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2077 case lltok::kw_hhvmcc:
2079 break;
2080 case lltok::kw_hhvm_ccc:
2082 break;
2093 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2094 case lltok::kw_cc: {
2095 Lex.Lex();
2096 return parseUInt32(CC);
2097 }
2098 }
2099
2100 Lex.Lex();
2101 return false;
2102}
2103
2104/// parseMetadataAttachment
2105/// ::= !dbg !42
2106bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2107 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2108
2109 std::string Name = Lex.getStrVal();
2110 Kind = M->getMDKindID(Name);
2111 Lex.Lex();
2112
2113 return parseMDNode(MD);
2114}
2115
2116/// parseInstructionMetadata
2117/// ::= !dbg !42 (',' !dbg !57)*
2118bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2119 do {
2120 if (Lex.getKind() != lltok::MetadataVar)
2121 return tokError("expected metadata after comma");
2122
2123 unsigned MDK;
2124 MDNode *N;
2125 if (parseMetadataAttachment(MDK, N))
2126 return true;
2127
2128 if (MDK == LLVMContext::MD_DIAssignID)
2129 TempDIAssignIDAttachments[N].push_back(&Inst);
2130 else
2131 Inst.setMetadata(MDK, N);
2132
2133 if (MDK == LLVMContext::MD_tbaa)
2134 InstsWithTBAATag.push_back(&Inst);
2135
2136 // If this is the end of the list, we're done.
2137 } while (EatIfPresent(lltok::comma));
2138 return false;
2139}
2140
2141/// parseGlobalObjectMetadataAttachment
2142/// ::= !dbg !57
2143bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2144 unsigned MDK;
2145 MDNode *N;
2146 if (parseMetadataAttachment(MDK, N))
2147 return true;
2148
2149 GO.addMetadata(MDK, *N);
2150 return false;
2151}
2152
2153/// parseOptionalFunctionMetadata
2154/// ::= (!dbg !57)*
2155bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2156 while (Lex.getKind() == lltok::MetadataVar)
2157 if (parseGlobalObjectMetadataAttachment(F))
2158 return true;
2159 return false;
2160}
2161
2162/// parseOptionalAlignment
2163/// ::= /* empty */
2164/// ::= 'align' 4
2165bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2166 Alignment = std::nullopt;
2167 if (!EatIfPresent(lltok::kw_align))
2168 return false;
2169 LocTy AlignLoc = Lex.getLoc();
2170 uint64_t Value = 0;
2171
2172 LocTy ParenLoc = Lex.getLoc();
2173 bool HaveParens = false;
2174 if (AllowParens) {
2175 if (EatIfPresent(lltok::lparen))
2176 HaveParens = true;
2177 }
2178
2179 if (parseUInt64(Value))
2180 return true;
2181
2182 if (HaveParens && !EatIfPresent(lltok::rparen))
2183 return error(ParenLoc, "expected ')'");
2184
2185 if (!isPowerOf2_64(Value))
2186 return error(AlignLoc, "alignment is not a power of two");
2188 return error(AlignLoc, "huge alignments are not supported yet");
2189 Alignment = Align(Value);
2190 return false;
2191}
2192
2193/// parseOptionalDerefAttrBytes
2194/// ::= /* empty */
2195/// ::= AttrKind '(' 4 ')'
2196///
2197/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2198bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2199 uint64_t &Bytes) {
2200 assert((AttrKind == lltok::kw_dereferenceable ||
2201 AttrKind == lltok::kw_dereferenceable_or_null) &&
2202 "contract!");
2203
2204 Bytes = 0;
2205 if (!EatIfPresent(AttrKind))
2206 return false;
2207 LocTy ParenLoc = Lex.getLoc();
2208 if (!EatIfPresent(lltok::lparen))
2209 return error(ParenLoc, "expected '('");
2210 LocTy DerefLoc = Lex.getLoc();
2211 if (parseUInt64(Bytes))
2212 return true;
2213 ParenLoc = Lex.getLoc();
2214 if (!EatIfPresent(lltok::rparen))
2215 return error(ParenLoc, "expected ')'");
2216 if (!Bytes)
2217 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2218 return false;
2219}
2220
2221bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2222 Lex.Lex();
2224 if (!EatIfPresent(lltok::lparen))
2225 return false;
2226 LocTy KindLoc = Lex.getLoc();
2227 if (Lex.getKind() == lltok::kw_sync)
2229 else if (Lex.getKind() == lltok::kw_async)
2231 else
2232 return error(KindLoc, "expected unwind table kind");
2233 Lex.Lex();
2234 return parseToken(lltok::rparen, "expected ')'");
2235}
2236
2237bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2238 Lex.Lex();
2239 LocTy ParenLoc = Lex.getLoc();
2240 if (!EatIfPresent(lltok::lparen))
2241 return error(ParenLoc, "expected '('");
2242 LocTy KindLoc = Lex.getLoc();
2243 std::string Arg;
2244 if (parseStringConstant(Arg))
2245 return error(KindLoc, "expected allockind value");
2246 for (StringRef A : llvm::split(Arg, ",")) {
2247 if (A == "alloc") {
2249 } else if (A == "realloc") {
2251 } else if (A == "free") {
2253 } else if (A == "uninitialized") {
2255 } else if (A == "zeroed") {
2257 } else if (A == "aligned") {
2259 } else {
2260 return error(KindLoc, Twine("unknown allockind ") + A);
2261 }
2262 }
2263 ParenLoc = Lex.getLoc();
2264 if (!EatIfPresent(lltok::rparen))
2265 return error(ParenLoc, "expected ')'");
2266 if (Kind == AllocFnKind::Unknown)
2267 return error(KindLoc, "expected allockind value");
2268 return false;
2269}
2270
2271static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2272 switch (Tok) {
2273 case lltok::kw_argmem:
2274 return MemoryEffects::ArgMem;
2277 default:
2278 return std::nullopt;
2279 }
2280}
2281
2282static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2283 switch (Tok) {
2284 case lltok::kw_none:
2285 return ModRefInfo::NoModRef;
2286 case lltok::kw_read:
2287 return ModRefInfo::Ref;
2288 case lltok::kw_write:
2289 return ModRefInfo::Mod;
2291 return ModRefInfo::ModRef;
2292 default:
2293 return std::nullopt;
2294 }
2295}
2296
2297std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2299
2300 // We use syntax like memory(argmem: read), so the colon should not be
2301 // interpreted as a label terminator.
2303 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2304
2305 Lex.Lex();
2306 if (!EatIfPresent(lltok::lparen)) {
2307 tokError("expected '('");
2308 return std::nullopt;
2309 }
2310
2311 bool SeenLoc = false;
2312 do {
2313 std::optional<MemoryEffects::Location> Loc = keywordToLoc(Lex.getKind());
2314 if (Loc) {
2315 Lex.Lex();
2316 if (!EatIfPresent(lltok::colon)) {
2317 tokError("expected ':' after location");
2318 return std::nullopt;
2319 }
2320 }
2321
2322 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2323 if (!MR) {
2324 if (!Loc)
2325 tokError("expected memory location (argmem, inaccessiblemem) "
2326 "or access kind (none, read, write, readwrite)");
2327 else
2328 tokError("expected access kind (none, read, write, readwrite)");
2329 return std::nullopt;
2330 }
2331
2332 Lex.Lex();
2333 if (Loc) {
2334 SeenLoc = true;
2335 ME = ME.getWithModRef(*Loc, *MR);
2336 } else {
2337 if (SeenLoc) {
2338 tokError("default access kind must be specified first");
2339 return std::nullopt;
2340 }
2341 ME = MemoryEffects(*MR);
2342 }
2343
2344 if (EatIfPresent(lltok::rparen))
2345 return ME;
2346 } while (EatIfPresent(lltok::comma));
2347
2348 tokError("unterminated memory attribute");
2349 return std::nullopt;
2350}
2351
2352static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2353 switch (Tok) {
2354 case lltok::kw_all:
2355 return fcAllFlags;
2356 case lltok::kw_nan:
2357 return fcNan;
2358 case lltok::kw_snan:
2359 return fcSNan;
2360 case lltok::kw_qnan:
2361 return fcQNan;
2362 case lltok::kw_inf:
2363 return fcInf;
2364 case lltok::kw_ninf:
2365 return fcNegInf;
2366 case lltok::kw_pinf:
2367 return fcPosInf;
2368 case lltok::kw_norm:
2369 return fcNormal;
2370 case lltok::kw_nnorm:
2371 return fcNegNormal;
2372 case lltok::kw_pnorm:
2373 return fcPosNormal;
2374 case lltok::kw_sub:
2375 return fcSubnormal;
2376 case lltok::kw_nsub:
2377 return fcNegSubnormal;
2378 case lltok::kw_psub:
2379 return fcPosSubnormal;
2380 case lltok::kw_zero:
2381 return fcZero;
2382 case lltok::kw_nzero:
2383 return fcNegZero;
2384 case lltok::kw_pzero:
2385 return fcPosZero;
2386 default:
2387 return 0;
2388 }
2389}
2390
2391unsigned LLParser::parseNoFPClassAttr() {
2392 unsigned Mask = fcNone;
2393
2394 Lex.Lex();
2395 if (!EatIfPresent(lltok::lparen)) {
2396 tokError("expected '('");
2397 return 0;
2398 }
2399
2400 do {
2401 uint64_t Value = 0;
2402 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2403 if (TestMask != 0) {
2404 Mask |= TestMask;
2405 // TODO: Disallow overlapping masks to avoid copy paste errors
2406 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2407 !parseUInt64(Value)) {
2408 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2409 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2410 return 0;
2411 }
2412
2413 if (!EatIfPresent(lltok::rparen)) {
2414 error(Lex.getLoc(), "expected ')'");
2415 return 0;
2416 }
2417
2418 return Value;
2419 } else {
2420 error(Lex.getLoc(), "expected nofpclass test mask");
2421 return 0;
2422 }
2423
2424 Lex.Lex();
2425 if (EatIfPresent(lltok::rparen))
2426 return Mask;
2427 } while (1);
2428
2429 llvm_unreachable("unterminated nofpclass attribute");
2430}
2431
2432/// parseOptionalCommaAlign
2433/// ::=
2434/// ::= ',' align 4
2435///
2436/// This returns with AteExtraComma set to true if it ate an excess comma at the
2437/// end.
2438bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2439 bool &AteExtraComma) {
2440 AteExtraComma = false;
2441 while (EatIfPresent(lltok::comma)) {
2442 // Metadata at the end is an early exit.
2443 if (Lex.getKind() == lltok::MetadataVar) {
2444 AteExtraComma = true;
2445 return false;
2446 }
2447
2448 if (Lex.getKind() != lltok::kw_align)
2449 return error(Lex.getLoc(), "expected metadata or 'align'");
2450
2451 if (parseOptionalAlignment(Alignment))
2452 return true;
2453 }
2454
2455 return false;
2456}
2457
2458/// parseOptionalCommaAddrSpace
2459/// ::=
2460/// ::= ',' addrspace(1)
2461///
2462/// This returns with AteExtraComma set to true if it ate an excess comma at the
2463/// end.
2464bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2465 bool &AteExtraComma) {
2466 AteExtraComma = false;
2467 while (EatIfPresent(lltok::comma)) {
2468 // Metadata at the end is an early exit.
2469 if (Lex.getKind() == lltok::MetadataVar) {
2470 AteExtraComma = true;
2471 return false;
2472 }
2473
2474 Loc = Lex.getLoc();
2475 if (Lex.getKind() != lltok::kw_addrspace)
2476 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2477
2478 if (parseOptionalAddrSpace(AddrSpace))
2479 return true;
2480 }
2481
2482 return false;
2483}
2484
2485bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2486 std::optional<unsigned> &HowManyArg) {
2487 Lex.Lex();
2488
2489 auto StartParen = Lex.getLoc();
2490 if (!EatIfPresent(lltok::lparen))
2491 return error(StartParen, "expected '('");
2492
2493 if (parseUInt32(BaseSizeArg))
2494 return true;
2495
2496 if (EatIfPresent(lltok::comma)) {
2497 auto HowManyAt = Lex.getLoc();
2498 unsigned HowMany;
2499 if (parseUInt32(HowMany))
2500 return true;
2501 if (HowMany == BaseSizeArg)
2502 return error(HowManyAt,
2503 "'allocsize' indices can't refer to the same parameter");
2504 HowManyArg = HowMany;
2505 } else
2506 HowManyArg = std::nullopt;
2507
2508 auto EndParen = Lex.getLoc();
2509 if (!EatIfPresent(lltok::rparen))
2510 return error(EndParen, "expected ')'");
2511 return false;
2512}
2513
2514bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2515 unsigned &MaxValue) {
2516 Lex.Lex();
2517
2518 auto StartParen = Lex.getLoc();
2519 if (!EatIfPresent(lltok::lparen))
2520 return error(StartParen, "expected '('");
2521
2522 if (parseUInt32(MinValue))
2523 return true;
2524
2525 if (EatIfPresent(lltok::comma)) {
2526 if (parseUInt32(MaxValue))
2527 return true;
2528 } else
2529 MaxValue = MinValue;
2530
2531 auto EndParen = Lex.getLoc();
2532 if (!EatIfPresent(lltok::rparen))
2533 return error(EndParen, "expected ')'");
2534 return false;
2535}
2536
2537/// parseScopeAndOrdering
2538/// if isAtomic: ::= SyncScope? AtomicOrdering
2539/// else: ::=
2540///
2541/// This sets Scope and Ordering to the parsed values.
2542bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2543 AtomicOrdering &Ordering) {
2544 if (!IsAtomic)
2545 return false;
2546
2547 return parseScope(SSID) || parseOrdering(Ordering);
2548}
2549
2550/// parseScope
2551/// ::= syncscope("singlethread" | "<target scope>")?
2552///
2553/// This sets synchronization scope ID to the ID of the parsed value.
2554bool LLParser::parseScope(SyncScope::ID &SSID) {
2555 SSID = SyncScope::System;
2556 if (EatIfPresent(lltok::kw_syncscope)) {
2557 auto StartParenAt = Lex.getLoc();
2558 if (!EatIfPresent(lltok::lparen))
2559 return error(StartParenAt, "Expected '(' in syncscope");
2560
2561 std::string SSN;
2562 auto SSNAt = Lex.getLoc();
2563 if (parseStringConstant(SSN))
2564 return error(SSNAt, "Expected synchronization scope name");
2565
2566 auto EndParenAt = Lex.getLoc();
2567 if (!EatIfPresent(lltok::rparen))
2568 return error(EndParenAt, "Expected ')' in syncscope");
2569
2570 SSID = Context.getOrInsertSyncScopeID(SSN);
2571 }
2572
2573 return false;
2574}
2575
2576/// parseOrdering
2577/// ::= AtomicOrdering
2578///
2579/// This sets Ordering to the parsed value.
2580bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2581 switch (Lex.getKind()) {
2582 default:
2583 return tokError("Expected ordering on atomic instruction");
2584 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2585 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2586 // Not specified yet:
2587 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2588 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2589 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2590 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2591 case lltok::kw_seq_cst:
2593 break;
2594 }
2595 Lex.Lex();
2596 return false;
2597}
2598
2599/// parseOptionalStackAlignment
2600/// ::= /* empty */
2601/// ::= 'alignstack' '(' 4 ')'
2602bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2603 Alignment = 0;
2604 if (!EatIfPresent(lltok::kw_alignstack))
2605 return false;
2606 LocTy ParenLoc = Lex.getLoc();
2607 if (!EatIfPresent(lltok::lparen))
2608 return error(ParenLoc, "expected '('");
2609 LocTy AlignLoc = Lex.getLoc();
2610 if (parseUInt32(Alignment))
2611 return true;
2612 ParenLoc = Lex.getLoc();
2613 if (!EatIfPresent(lltok::rparen))
2614 return error(ParenLoc, "expected ')'");
2615 if (!isPowerOf2_32(Alignment))
2616 return error(AlignLoc, "stack alignment is not a power of two");
2617 return false;
2618}
2619
2620/// parseIndexList - This parses the index list for an insert/extractvalue
2621/// instruction. This sets AteExtraComma in the case where we eat an extra
2622/// comma at the end of the line and find that it is followed by metadata.
2623/// Clients that don't allow metadata can call the version of this function that
2624/// only takes one argument.
2625///
2626/// parseIndexList
2627/// ::= (',' uint32)+
2628///
2629bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2630 bool &AteExtraComma) {
2631 AteExtraComma = false;
2632
2633 if (Lex.getKind() != lltok::comma)
2634 return tokError("expected ',' as start of index list");
2635
2636 while (EatIfPresent(lltok::comma)) {
2637 if (Lex.getKind() == lltok::MetadataVar) {
2638 if (Indices.empty())
2639 return tokError("expected index");
2640 AteExtraComma = true;
2641 return false;
2642 }
2643 unsigned Idx = 0;
2644 if (parseUInt32(Idx))
2645 return true;
2646 Indices.push_back(Idx);
2647 }
2648
2649 return false;
2650}
2651
2652//===----------------------------------------------------------------------===//
2653// Type Parsing.
2654//===----------------------------------------------------------------------===//
2655
2656/// parseType - parse a type.
2657bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2658 SMLoc TypeLoc = Lex.getLoc();
2659 switch (Lex.getKind()) {
2660 default:
2661 return tokError(Msg);
2662 case lltok::Type:
2663 // Type ::= 'float' | 'void' (etc)
2664 Result = Lex.getTyVal();
2665 Lex.Lex();
2666
2667 // Handle "ptr" opaque pointer type.
2668 //
2669 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2670 if (Result->isOpaquePointerTy()) {
2671 unsigned AddrSpace;
2672 if (parseOptionalAddrSpace(AddrSpace))
2673 return true;
2674 Result = PointerType::get(getContext(), AddrSpace);
2675
2676 // Give a nice error for 'ptr*'.
2677 if (Lex.getKind() == lltok::star)
2678 return tokError("ptr* is invalid - use ptr instead");
2679
2680 // Fall through to parsing the type suffixes only if this 'ptr' is a
2681 // function return. Otherwise, return success, implicitly rejecting other
2682 // suffixes.
2683 if (Lex.getKind() != lltok::lparen)
2684 return false;
2685 }
2686 break;
2687 case lltok::kw_target: {
2688 // Type ::= TargetExtType
2689 if (parseTargetExtType(Result))
2690 return true;
2691 break;
2692 }
2693 case lltok::lbrace:
2694 // Type ::= StructType
2695 if (parseAnonStructType(Result, false))
2696 return true;
2697 break;
2698 case lltok::lsquare:
2699 // Type ::= '[' ... ']'
2700 Lex.Lex(); // eat the lsquare.
2701 if (parseArrayVectorType(Result, false))
2702 return true;
2703 break;
2704 case lltok::less: // Either vector or packed struct.
2705 // Type ::= '<' ... '>'
2706 Lex.Lex();
2707 if (Lex.getKind() == lltok::lbrace) {
2708 if (parseAnonStructType(Result, true) ||
2709 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2710 return true;
2711 } else if (parseArrayVectorType(Result, true))
2712 return true;
2713 break;
2714 case lltok::LocalVar: {
2715 // Type ::= %foo
2716 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2717
2718 // If the type hasn't been defined yet, create a forward definition and
2719 // remember where that forward def'n was seen (in case it never is defined).
2720 if (!Entry.first) {
2721 Entry.first = StructType::create(Context, Lex.getStrVal());
2722 Entry.second = Lex.getLoc();
2723 }
2724 Result = Entry.first;
2725 Lex.Lex();
2726 break;
2727 }
2728
2729 case lltok::LocalVarID: {
2730 // Type ::= %4
2731 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2732
2733 // If the type hasn't been defined yet, create a forward definition and
2734 // remember where that forward def'n was seen (in case it never is defined).
2735 if (!Entry.first) {
2736 Entry.first = StructType::create(Context);
2737 Entry.second = Lex.getLoc();
2738 }
2739 Result = Entry.first;
2740 Lex.Lex();
2741 break;
2742 }
2743 }
2744
2745 // parse the type suffixes.
2746 while (true) {
2747 switch (Lex.getKind()) {
2748 // End of type.
2749 default:
2750 if (!AllowVoid && Result->isVoidTy())
2751 return error(TypeLoc, "void type only allowed for function results");
2752 return false;
2753
2754 // Type ::= Type '*'
2755 case lltok::star:
2756 if (Result->isLabelTy())
2757 return tokError("basic block pointers are invalid");
2758 if (Result->isVoidTy())
2759 return tokError("pointers to void are invalid - use i8* instead");
2761 return tokError("pointer to this type is invalid");
2763 Lex.Lex();
2764 break;
2765
2766 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2767 case lltok::kw_addrspace: {
2768 if (Result->isLabelTy())
2769 return tokError("basic block pointers are invalid");
2770 if (Result->isVoidTy())
2771 return tokError("pointers to void are invalid; use i8* instead");
2773 return tokError("pointer to this type is invalid");
2774 unsigned AddrSpace;
2775 if (parseOptionalAddrSpace(AddrSpace) ||
2776 parseToken(lltok::star, "expected '*' in address space"))
2777 return true;
2778
2779 Result = PointerType::get(Result, AddrSpace);
2780 break;
2781 }
2782
2783 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2784 case lltok::lparen:
2785 if (parseFunctionType(Result))
2786 return true;
2787 break;
2788 }
2789 }
2790}
2791
2792/// parseParameterList
2793/// ::= '(' ')'
2794/// ::= '(' Arg (',' Arg)* ')'
2795/// Arg
2796/// ::= Type OptionalAttributes Value OptionalAttributes
2797bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2798 PerFunctionState &PFS, bool IsMustTailCall,
2799 bool InVarArgsFunc) {
2800 if (parseToken(lltok::lparen, "expected '(' in call"))
2801 return true;
2802
2803 while (Lex.getKind() != lltok::rparen) {
2804 // If this isn't the first argument, we need a comma.
2805 if (!ArgList.empty() &&
2806 parseToken(lltok::comma, "expected ',' in argument list"))
2807 return true;
2808
2809 // parse an ellipsis if this is a musttail call in a variadic function.
2810 if (Lex.getKind() == lltok::dotdotdot) {
2811 const char *Msg = "unexpected ellipsis in argument list for ";
2812 if (!IsMustTailCall)
2813 return tokError(Twine(Msg) + "non-musttail call");
2814 if (!InVarArgsFunc)
2815 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2816 Lex.Lex(); // Lex the '...', it is purely for readability.
2817 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2818 }
2819
2820 // parse the argument.
2821 LocTy ArgLoc;
2822 Type *ArgTy = nullptr;
2823 Value *V;
2824 if (parseType(ArgTy, ArgLoc))
2825 return true;
2826
2827 AttrBuilder ArgAttrs(M->getContext());
2828
2829 if (ArgTy->isMetadataTy()) {
2830 if (parseMetadataAsValue(V, PFS))
2831 return true;
2832 } else {
2833 // Otherwise, handle normal operands.
2834 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2835 return true;
2836 }
2837 ArgList.push_back(ParamInfo(
2838 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2839 }
2840
2841 if (IsMustTailCall && InVarArgsFunc)
2842 return tokError("expected '...' at end of argument list for musttail call "
2843 "in varargs function");
2844
2845 Lex.Lex(); // Lex the ')'.
2846 return false;
2847}
2848
2849/// parseRequiredTypeAttr
2850/// ::= attrname(<ty>)
2851bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2852 Attribute::AttrKind AttrKind) {
2853 Type *Ty = nullptr;
2854 if (!EatIfPresent(AttrToken))
2855 return true;
2856 if (!EatIfPresent(lltok::lparen))
2857 return error(Lex.getLoc(), "expected '('");
2858 if (parseType(Ty))
2859 return true;
2860 if (!EatIfPresent(lltok::rparen))
2861 return error(Lex.getLoc(), "expected ')'");
2862
2863 B.addTypeAttr(AttrKind, Ty);
2864 return false;
2865}
2866
2867/// parseOptionalOperandBundles
2868/// ::= /*empty*/
2869/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2870///
2871/// OperandBundle
2872/// ::= bundle-tag '(' ')'
2873/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2874///
2875/// bundle-tag ::= String Constant
2876bool LLParser::parseOptionalOperandBundles(
2877 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2878 LocTy BeginLoc = Lex.getLoc();
2879 if (!EatIfPresent(lltok::lsquare))
2880 return false;
2881
2882 while (Lex.getKind() != lltok::rsquare) {
2883 // If this isn't the first operand bundle, we need a comma.
2884 if (!BundleList.empty() &&
2885 parseToken(lltok::comma, "expected ',' in input list"))
2886 return true;
2887
2888 std::string Tag;
2889 if (parseStringConstant(Tag))
2890 return true;
2891
2892 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2893 return true;
2894
2895 std::vector<Value *> Inputs;
2896 while (Lex.getKind() != lltok::rparen) {
2897 // If this isn't the first input, we need a comma.
2898 if (!Inputs.empty() &&
2899 parseToken(lltok::comma, "expected ',' in input list"))
2900 return true;
2901
2902 Type *Ty = nullptr;
2903 Value *Input = nullptr;
2904 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2905 return true;
2906 Inputs.push_back(Input);
2907 }
2908
2909 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2910
2911 Lex.Lex(); // Lex the ')'.
2912 }
2913
2914 if (BundleList.empty())
2915 return error(BeginLoc, "operand bundle set must not be empty");
2916
2917 Lex.Lex(); // Lex the ']'.
2918 return false;
2919}
2920
2921/// parseArgumentList - parse the argument list for a function type or function
2922/// prototype.
2923/// ::= '(' ArgTypeListI ')'
2924/// ArgTypeListI
2925/// ::= /*empty*/
2926/// ::= '...'
2927/// ::= ArgTypeList ',' '...'
2928/// ::= ArgType (',' ArgType)*
2929///
2930bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2931 bool &IsVarArg) {
2932 unsigned CurValID = 0;
2933 IsVarArg = false;
2934 assert(Lex.getKind() == lltok::lparen);
2935 Lex.Lex(); // eat the (.
2936
2937 if (Lex.getKind() == lltok::rparen) {
2938 // empty
2939 } else if (Lex.getKind() == lltok::dotdotdot) {
2940 IsVarArg = true;
2941 Lex.Lex();
2942 } else {
2943 LocTy TypeLoc = Lex.getLoc();
2944 Type *ArgTy = nullptr;
2946 std::string Name;
2947
2948 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2949 return true;
2950
2951 if (ArgTy->isVoidTy())
2952 return error(TypeLoc, "argument can not have void type");
2953
2954 if (Lex.getKind() == lltok::LocalVar) {
2955 Name = Lex.getStrVal();
2956 Lex.Lex();
2957 } else if (Lex.getKind() == lltok::LocalVarID) {
2958 if (Lex.getUIntVal() != CurValID)
2959 return error(TypeLoc, "argument expected to be numbered '%" +
2960 Twine(CurValID) + "'");
2961 ++CurValID;
2962 Lex.Lex();
2963 }
2964
2966 return error(TypeLoc, "invalid type for function argument");
2967
2968 ArgList.emplace_back(TypeLoc, ArgTy,
2969 AttributeSet::get(ArgTy->getContext(), Attrs),
2970 std::move(Name));
2971
2972 while (EatIfPresent(lltok::comma)) {
2973 // Handle ... at end of arg list.
2974 if (EatIfPresent(lltok::dotdotdot)) {
2975 IsVarArg = true;
2976 break;
2977 }
2978
2979 // Otherwise must be an argument type.
2980 TypeLoc = Lex.getLoc();
2981 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2982 return true;
2983
2984 if (ArgTy->isVoidTy())
2985 return error(TypeLoc, "argument can not have void type");
2986
2987 if (Lex.getKind() == lltok::LocalVar) {
2988 Name = Lex.getStrVal();
2989 Lex.Lex();
2990 } else {
2991 if (Lex.getKind() == lltok::LocalVarID) {
2992 if (Lex.getUIntVal() != CurValID)
2993 return error(TypeLoc, "argument expected to be numbered '%" +
2994 Twine(CurValID) + "'");
2995 Lex.Lex();
2996 }
2997 ++CurValID;
2998 Name = "";
2999 }
3000
3001 if (!ArgTy->isFirstClassType())
3002 return error(TypeLoc, "invalid type for function argument");
3003
3004 ArgList.emplace_back(TypeLoc, ArgTy,
3005 AttributeSet::get(ArgTy->getContext(), Attrs),
3006 std::move(Name));
3007 }
3008 }
3009
3010 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3011}
3012
3013/// parseFunctionType
3014/// ::= Type ArgumentList OptionalAttrs
3015bool LLParser::parseFunctionType(Type *&Result) {
3016 assert(Lex.getKind() == lltok::lparen);
3017
3019 return tokError("invalid function return type");
3020
3022 bool IsVarArg;
3023 if (parseArgumentList(ArgList, IsVarArg))
3024 return true;
3025
3026 // Reject names on the arguments lists.
3027 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3028 if (!ArgList[i].Name.empty())
3029 return error(ArgList[i].Loc, "argument name invalid in function type");
3030 if (ArgList[i].Attrs.hasAttributes())
3031 return error(ArgList[i].Loc,
3032 "argument attributes invalid in function type");
3033 }
3034
3035 SmallVector<Type*, 16> ArgListTy;
3036 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3037 ArgListTy.push_back(ArgList[i].Ty);
3038
3039 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3040 return false;
3041}
3042
3043/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3044/// other structs.
3045bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3047 if (parseStructBody(Elts))
3048 return true;
3049
3050 Result = StructType::get(Context, Elts, Packed);
3051 return false;
3052}
3053
3054/// parseStructDefinition - parse a struct in a 'type' definition.
3055bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3056 std::pair<Type *, LocTy> &Entry,
3057 Type *&ResultTy) {
3058 // If the type was already defined, diagnose the redefinition.
3059 if (Entry.first && !Entry.second.isValid())
3060 return error(TypeLoc, "redefinition of type");
3061
3062 // If we have opaque, just return without filling in the definition for the
3063 // struct. This counts as a definition as far as the .ll file goes.
3064 if (EatIfPresent(lltok::kw_opaque)) {
3065 // This type is being defined, so clear the location to indicate this.
3066 Entry.second = SMLoc();
3067
3068 // If this type number has never been uttered, create it.
3069 if (!Entry.first)
3070 Entry.first = StructType::create(Context, Name);
3071 ResultTy = Entry.first;
3072 return false;
3073 }
3074
3075 // If the type starts with '<', then it is either a packed struct or a vector.
3076 bool isPacked = EatIfPresent(lltok::less);
3077
3078 // If we don't have a struct, then we have a random type alias, which we
3079 // accept for compatibility with old files. These types are not allowed to be
3080 // forward referenced and not allowed to be recursive.
3081 if (Lex.getKind() != lltok::lbrace) {
3082 if (Entry.first)
3083 return error(TypeLoc, "forward references to non-struct type");
3084
3085 ResultTy = nullptr;
3086 if (isPacked)
3087 return parseArrayVectorType(ResultTy, true);
3088 return parseType(ResultTy);
3089 }
3090
3091 // This type is being defined, so clear the location to indicate this.
3092 Entry.second = SMLoc();
3093
3094 // If this type number has never been uttered, create it.
3095 if (!Entry.first)
3096 Entry.first = StructType::create(Context, Name);
3097
3098 StructType *STy = cast<StructType>(Entry.first);
3099
3101 if (parseStructBody(Body) ||
3102 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3103 return true;
3104
3105 STy->setBody(Body, isPacked);
3106 ResultTy = STy;
3107 return false;
3108}
3109
3110/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3111/// StructType
3112/// ::= '{' '}'
3113/// ::= '{' Type (',' Type)* '}'
3114/// ::= '<' '{' '}' '>'
3115/// ::= '<' '{' Type (',' Type)* '}' '>'
3116bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3117 assert(Lex.getKind() == lltok::lbrace);
3118 Lex.Lex(); // Consume the '{'
3119
3120 // Handle the empty struct.
3121 if (EatIfPresent(lltok::rbrace))
3122 return false;
3123
3124 LocTy EltTyLoc = Lex.getLoc();
3125 Type *Ty = nullptr;
3126 if (parseType(Ty))
3127 return true;
3128 Body.push_back(Ty);
3129
3131 return error(EltTyLoc, "invalid element type for struct");
3132
3133 while (EatIfPresent(lltok::comma)) {
3134 EltTyLoc = Lex.getLoc();
3135 if (parseType(Ty))
3136 return true;
3137
3139 return error(EltTyLoc, "invalid element type for struct");
3140
3141 Body.push_back(Ty);
3142 }
3143
3144 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3145}
3146
3147/// parseArrayVectorType - parse an array or vector type, assuming the first
3148/// token has already been consumed.
3149/// Type
3150/// ::= '[' APSINTVAL 'x' Types ']'
3151/// ::= '<' APSINTVAL 'x' Types '>'
3152/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3153bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3154 bool Scalable = false;
3155
3156 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3157 Lex.Lex(); // consume the 'vscale'
3158 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3159 return true;
3160
3161 Scalable = true;
3162 }
3163
3164 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3165 Lex.getAPSIntVal().getBitWidth() > 64)
3166 return tokError("expected number in address space");
3167
3168 LocTy SizeLoc = Lex.getLoc();
3170 Lex.Lex();
3171
3172 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3173 return true;
3174
3175 LocTy TypeLoc = Lex.getLoc();
3176 Type *EltTy = nullptr;
3177 if (parseType(EltTy))
3178 return true;
3179
3180 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3181 "expected end of sequential type"))
3182 return true;
3183
3184 if (IsVector) {
3185 if (Size == 0)
3186 return error(SizeLoc, "zero element vector is illegal");
3187 if ((unsigned)Size != Size)
3188 return error(SizeLoc, "size too large for vector");
3190 return error(TypeLoc, "invalid vector element type");
3191 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3192 } else {
3194 return error(TypeLoc, "invalid array element type");
3195 Result = ArrayType::get(EltTy, Size);
3196 }
3197 return false;
3198}
3199
3200/// parseTargetExtType - handle target extension type syntax
3201/// TargetExtType
3202/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3203///
3204/// TargetExtTypeParams
3205/// ::= /*empty*/
3206/// ::= ',' Type TargetExtTypeParams
3207///
3208/// TargetExtIntParams
3209/// ::= /*empty*/
3210/// ::= ',' uint32 TargetExtIntParams
3211bool LLParser::parseTargetExtType(Type *&Result) {
3212 Lex.Lex(); // Eat the 'target' keyword.
3213
3214 // Get the mandatory type name.
3215 std::string TypeName;
3216 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3217 parseStringConstant(TypeName))
3218 return true;
3219
3220 // Parse all of the integer and type parameters at the same time; the use of
3221 // SeenInt will allow us to catch cases where type parameters follow integer
3222 // parameters.
3223 SmallVector<Type *> TypeParams;
3224 SmallVector<unsigned> IntParams;
3225 bool SeenInt = false;
3226 while (Lex.getKind() == lltok::comma) {
3227 Lex.Lex(); // Eat the comma.
3228
3229 if (Lex.getKind() == lltok::APSInt) {
3230 SeenInt = true;
3231 unsigned IntVal;
3232 if (parseUInt32(IntVal))
3233 return true;
3234 IntParams.push_back(IntVal);
3235 } else if (SeenInt) {
3236 // The only other kind of parameter we support is type parameters, which
3237 // must precede the integer parameters. This is therefore an error.
3238 return tokError("expected uint32 param");
3239 } else {
3240 Type *TypeParam;
3241 if (parseType(TypeParam, /*AllowVoid=*/true))
3242 return true;
3243 TypeParams.push_back(TypeParam);
3244 }
3245 }
3246
3247 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3248 return true;
3249
3250 Result = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
3251 return false;
3252}
3253
3254//===----------------------------------------------------------------------===//
3255// Function Semantic Analysis.
3256//===----------------------------------------------------------------------===//
3257
3258LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3259 int functionNumber)
3260 : P(p), F(f), FunctionNumber(functionNumber) {
3261
3262 // Insert unnamed arguments into the NumberedVals list.
3263 for (Argument &A : F.args())
3264 if (!A.hasName())
3265 NumberedVals.push_back(&A);
3266}
3267
3268LLParser::PerFunctionState::~PerFunctionState() {
3269 // If there were any forward referenced non-basicblock values, delete them.
3270
3271 for (const auto &P : ForwardRefVals) {
3272 if (isa<BasicBlock>(P.second.first))
3273 continue;
3274 P.second.first->replaceAllUsesWith(
3275 UndefValue::get(P.second.first->getType()));
3276 P.second.first->deleteValue();
3277 }
3278
3279 for (const auto &P : ForwardRefValIDs) {
3280 if (isa<BasicBlock>(P.second.first))
3281 continue;
3282 P.second.first->replaceAllUsesWith(
3283 UndefValue::get(P.second.first->getType()));
3284 P.second.first->deleteValue();
3285 }
3286}
3287
3288bool LLParser::PerFunctionState::finishFunction() {
3289 if (!ForwardRefVals.empty())
3290 return P.error(ForwardRefVals.begin()->second.second,
3291 "use of undefined value '%" + ForwardRefVals.begin()->first +
3292 "'");
3293 if (!ForwardRefValIDs.empty())
3294 return P.error(ForwardRefValIDs.begin()->second.second,
3295 "use of undefined value '%" +
3296 Twine(ForwardRefValIDs.begin()->first) + "'");
3297 return false;
3298}
3299
3300/// getVal - Get a value with the specified name or ID, creating a
3301/// forward reference record if needed. This can return null if the value
3302/// exists but does not have the right type.
3303Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3304 LocTy Loc) {
3305 // Look this name up in the normal function symbol table.
3306 Value *Val = F.getValueSymbolTable()->lookup(Name);
3307
3308 // If this is a forward reference for the value, see if we already created a
3309 // forward ref record.
3310 if (!Val) {
3311 auto I = ForwardRefVals.find(Name);
3312 if (I != ForwardRefVals.end())
3313 Val = I->second.first;
3314 }
3315
3316 // If we have the value in the symbol table or fwd-ref table, return it.
3317 if (Val)
3318 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3319
3320 // Don't make placeholders with invalid type.
3321 if (!Ty->isFirstClassType()) {
3322 P.error(Loc, "invalid use of a non-first-class type");
3323 return nullptr;
3324 }
3325
3326 // Otherwise, create a new forward reference for this value and remember it.
3327 Value *FwdVal;
3328 if (Ty->isLabelTy()) {
3329 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3330 } else {
3331 FwdVal = new Argument(Ty, Name);
3332 }
3333 if (FwdVal->getName() != Name) {
3334 P.error(Loc, "name is too long which can result in name collisions, "
3335 "consider making the name shorter or "
3336 "increasing -non-global-value-max-name-size");
3337 return nullptr;
3338 }
3339
3340 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3341 return FwdVal;
3342}
3343
3344Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3345 // Look this name up in the normal function symbol table.
3346 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3347
3348 // If this is a forward reference for the value, see if we already created a
3349 // forward ref record.
3350 if (!Val) {
3351 auto I = ForwardRefValIDs.find(ID);
3352 if (I != ForwardRefValIDs.end())
3353 Val = I->second.first;
3354 }
3355
3356 // If we have the value in the symbol table or fwd-ref table, return it.
3357 if (Val)
3358 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3359
3360 if (!Ty->isFirstClassType()) {
3361 P.error(Loc, "invalid use of a non-first-class type");
3362 return nullptr;
3363 }
3364
3365 // Otherwise, create a new forward reference for this value and remember it.
3366 Value *FwdVal;
3367 if (Ty->isLabelTy()) {
3368 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3369 } else {
3370 FwdVal = new Argument(Ty);
3371 }
3372
3373 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3374 return FwdVal;
3375}
3376
3377/// setInstName - After an instruction is parsed and inserted into its
3378/// basic block, this installs its name.
3379bool LLParser::PerFunctionState::setInstName(int NameID,
3380 const std::string &NameStr,
3381 LocTy NameLoc, Instruction *Inst) {
3382 // If this instruction has void type, it cannot have a name or ID specified.
3383 if (Inst->getType()->isVoidTy()) {
3384 if (NameID != -1 || !NameStr.empty())
3385 return P.error(NameLoc, "instructions returning void cannot have a name");
3386 return false;
3387 }
3388
3389 // If this was a numbered instruction, verify that the instruction is the
3390 // expected value and resolve any forward references.
3391 if (NameStr.empty()) {
3392 // If neither a name nor an ID was specified, just use the next ID.
3393 if (NameID == -1)
3394 NameID = NumberedVals.size();
3395
3396 if (unsigned(NameID) != NumberedVals.size())
3397 return P.error(NameLoc, "instruction expected to be numbered '%" +
3398 Twine(NumberedVals.size()) + "'");
3399
3400 auto FI = ForwardRefValIDs.find(NameID);
3401 if (FI != ForwardRefValIDs.end()) {
3402 Value *Sentinel = FI->second.first;
3403 if (Sentinel->getType() != Inst->getType())
3404 return P.error(NameLoc, "instruction forward referenced with type '" +
3405 getTypeString(FI->second.first->getType()) +
3406 "'");
3407
3408 Sentinel->replaceAllUsesWith(Inst);
3409 Sentinel->deleteValue();
3410 ForwardRefValIDs.erase(FI);
3411 }
3412
3413 NumberedVals.push_back(Inst);
3414 return false;
3415 }
3416
3417 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3418 auto FI = ForwardRefVals.find(NameStr);
3419 if (FI != ForwardRefVals.end()) {
3420 Value *Sentinel = FI->second.first;
3421 if (Sentinel->getType() != Inst->getType())
3422 return P.error(NameLoc, "instruction forward referenced with type '" +
3423 getTypeString(FI->second.first->getType()) +
3424 "'");
3425
3426 Sentinel->replaceAllUsesWith(Inst);
3427 Sentinel->deleteValue();
3428 ForwardRefVals.erase(FI);
3429 }
3430
3431 // Set the name on the instruction.
3432 Inst->setName(NameStr);
3433
3434 if (Inst->getName() != NameStr)
3435 return P.error(NameLoc, "multiple definition of local value named '" +
3436 NameStr + "'");
3437 return false;
3438}
3439
3440/// getBB - Get a basic block with the specified name or ID, creating a
3441/// forward reference record if needed.
3442BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3443 LocTy Loc) {
3444 return dyn_cast_or_null<BasicBlock>(
3445 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3446}
3447
3448BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3449 return dyn_cast_or_null<BasicBlock>(
3450 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3451}
3452
3453/// defineBB - Define the specified basic block, which is either named or
3454/// unnamed. If there is an error, this returns null otherwise it returns
3455/// the block being defined.
3456BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3457 int NameID, LocTy Loc) {
3458 BasicBlock *BB;
3459 if (Name.empty()) {
3460 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3461 P.error(Loc, "label expected to be numbered '" +
3462 Twine(NumberedVals.size()) + "'");
3463 return nullptr;
3464 }
3465 BB = getBB(NumberedVals.size(), Loc);
3466 if (!BB) {
3467 P.error(Loc, "unable to create block numbered '" +
3468 Twine(NumberedVals.size()) + "'");
3469 return nullptr;
3470 }
3471 } else {
3472 BB = getBB(Name, Loc);
3473 if (!BB) {
3474 P.error(Loc, "unable to create block named '" + Name + "'");
3475 return nullptr;
3476 }
3477 }
3478
3479 // Move the block to the end of the function. Forward ref'd blocks are
3480 // inserted wherever they happen to be referenced.
3481 F.splice(F.end(), &F, BB->getIterator());
3482
3483 // Remove the block from forward ref sets.
3484 if (Name.empty()) {
3485 ForwardRefValIDs.erase(NumberedVals.size());
3486 NumberedVals.push_back(BB);
3487 } else {
3488 // BB forward references are already in the function symbol table.
3489 ForwardRefVals.erase(Name);
3490 }
3491
3492 return BB;
3493}
3494
3495//===----------------------------------------------------------------------===//
3496// Constants.
3497//===----------------------------------------------------------------------===//
3498
3499/// parseValID - parse an abstract value that doesn't necessarily have a
3500/// type implied. For example, if we parse "4" we don't know what integer type
3501/// it has. The value will later be combined with its type and checked for
3502/// basic correctness. PFS is used to convert function-local operands of
3503/// metadata (since metadata operands are not just parsed here but also
3504/// converted to values). PFS can be null when we are not parsing metadata
3505/// values inside a function.
3506bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3507 ID.Loc = Lex.getLoc();
3508 switch (Lex.getKind()) {
3509 default:
3510 return tokError("expected value token");
3511 case lltok::GlobalID: // @42
3512 ID.UIntVal = Lex.getUIntVal();
3513 ID.Kind = ValID::t_GlobalID;
3514 break;
3515 case lltok::GlobalVar: // @foo
3516 ID.StrVal = Lex.getStrVal();
3517 ID.Kind = ValID::t_GlobalName;
3518 break;
3519 case lltok::LocalVarID: // %42
3520 ID.UIntVal = Lex.getUIntVal();
3521 ID.Kind = ValID::t_LocalID;
3522 break;
3523 case lltok::LocalVar: // %foo
3524 ID.StrVal = Lex.getStrVal();
3525 ID.Kind = ValID::t_LocalName;
3526 break;
3527 case lltok::APSInt:
3528 ID.APSIntVal = Lex.getAPSIntVal();
3529 ID.Kind = ValID::t_APSInt;
3530 break;
3531 case lltok::APFloat:
3532 ID.APFloatVal = Lex.getAPFloatVal();
3533 ID.Kind = ValID::t_APFloat;
3534 break;
3535 case lltok::kw_true:
3536 ID.ConstantVal = ConstantInt::getTrue(Context);
3537 ID.Kind = ValID::t_Constant;
3538 break;
3539 case lltok::kw_false:
3540 ID.ConstantVal = ConstantInt::getFalse(Context);
3541 ID.Kind = ValID::t_Constant;
3542 break;
3543 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3544 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3545 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3546 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3547 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3548
3549 case lltok::lbrace: {
3550 // ValID ::= '{' ConstVector '}'
3551 Lex.Lex();
3553 if (parseGlobalValueVector(Elts) ||
3554 parseToken(lltok::rbrace, "expected end of struct constant"))
3555 return true;
3556
3557 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3558 ID.UIntVal = Elts.size();
3559 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3560 Elts.size() * sizeof(Elts[0]));
3562 return false;
3563 }
3564 case lltok::less: {
3565 // ValID ::= '<' ConstVector '>' --> Vector.
3566 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3567 Lex.Lex();
3568 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3569
3571 LocTy FirstEltLoc = Lex.getLoc();
3572 if (parseGlobalValueVector(Elts) ||
3573 (isPackedStruct &&
3574 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3575 parseToken(lltok::greater, "expected end of constant"))
3576 return true;
3577
3578 if (isPackedStruct) {
3579 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3580 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3581 Elts.size() * sizeof(Elts[0]));
3582 ID.UIntVal = Elts.size();
3584 return false;
3585 }
3586
3587 if (Elts.empty())
3588 return error(ID.Loc, "constant vector must not be empty");
3589
3590 if (!Elts[0]->getType()->isIntegerTy() &&
3591 !Elts[0]->getType()->isFloatingPointTy() &&
3592 !Elts[0]->getType()->isPointerTy())
3593 return error(
3594 FirstEltLoc,
3595 "vector elements must have integer, pointer or floating point type");
3596
3597 // Verify that all the vector elements have the same type.
3598 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3599 if (Elts[i]->getType() != Elts[0]->getType())
3600 return error(FirstEltLoc, "vector element #" + Twine(i) +
3601 " is not of type '" +
3602 getTypeString(Elts[0]->getType()));
3603
3604 ID.ConstantVal = ConstantVector::get(Elts);
3605 ID.Kind = ValID::t_Constant;
3606 return false;
3607 }
3608 case lltok::lsquare: { // Array Constant
3609 Lex.Lex();
3611 LocTy FirstEltLoc = Lex.getLoc();
3612 if (parseGlobalValueVector(Elts) ||
3613 parseToken(lltok::rsquare, "expected end of array constant"))
3614 return true;
3615
3616 // Handle empty element.
3617 if (Elts.empty()) {
3618 // Use undef instead of an array because it's inconvenient to determine
3619 // the element type at this point, there being no elements to examine.
3620 ID.Kind = ValID::t_EmptyArray;
3621 return false;
3622 }
3623
3624 if (!Elts[0]->getType()->isFirstClassType())
3625 return error(FirstEltLoc, "invalid array element type: " +
3626 getTypeString(Elts[0]->getType()));
3627
3628 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3629
3630 // Verify all elements are correct type!
3631 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3632 if (Elts[i]->getType() != Elts[0]->getType())
3633 return error(FirstEltLoc, "array element #" + Twine(i) +
3634 " is not of type '" +
3635 getTypeString(Elts[0]->getType()));
3636 }
3637
3638 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3639 ID.Kind = ValID::t_Constant;
3640 return false;
3641 }
3642 case lltok::kw_c: // c "foo"
3643 Lex.Lex();
3644 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3645 false);
3646 if (parseToken(lltok::StringConstant, "expected string"))
3647 return true;
3648 ID.Kind = ValID::t_Constant;
3649 return false;
3650
3651 case lltok::kw_asm: {
3652 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3653 // STRINGCONSTANT
3654 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3655 Lex.Lex();
3656 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3657 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3658 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3659 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3660 parseStringConstant(ID.StrVal) ||
3661 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3662 parseToken(lltok::StringConstant, "expected constraint string"))
3663 return true;
3664 ID.StrVal2 = Lex.getStrVal();
3665 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3666 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3667 ID.Kind = ValID::t_InlineAsm;
3668 return false;
3669 }
3670
3672 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3673 Lex.Lex();
3674
3675 ValID Fn, Label;
3676
3677 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3678 parseValID(Fn, PFS) ||
3679 parseToken(lltok::comma,
3680 "expected comma in block address expression") ||
3681 parseValID(Label, PFS) ||
3682 parseToken(lltok::rparen, "expected ')' in block address expression"))
3683 return true;
3684
3686 return error(Fn.Loc, "expected function name in blockaddress");
3687 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3688 return error(Label.Loc, "expected basic block name in blockaddress");
3689
3690 // Try to find the function (but skip it if it's forward-referenced).
3691 GlobalValue *GV = nullptr;
3692 if (Fn.Kind == ValID::t_GlobalID) {
3693 if (Fn.UIntVal < NumberedVals.size())
3694 GV = NumberedVals[Fn.UIntVal];
3695 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3696 GV = M->getNamedValue(Fn.StrVal);
3697 }
3698 Function *F = nullptr;
3699 if (GV) {
3700 // Confirm that it's actually a function with a definition.
3701 if (!isa<Function>(GV))
3702 return error(Fn.Loc, "expected function name in blockaddress");
3703 F = cast<Function>(GV);
3704 if (F->isDeclaration())
3705 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3706 }
3707
3708 if (!F) {
3709 // Make a global variable as a placeholder for this reference.
3710 GlobalValue *&FwdRef =
3711 ForwardRefBlockAddresses.insert(std::make_pair(
3712 std::move(Fn),
3713 std::map<ValID, GlobalValue *>()))
3714 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3715 .first->second;
3716 if (!FwdRef) {
3717 unsigned FwdDeclAS;
3718 if (ExpectedTy) {
3719 // If we know the type that the blockaddress is being assigned to,
3720 // we can use the address space of that type.
3721 if (!ExpectedTy->isPointerTy())
3722 return error(ID.Loc,
3723 "type of blockaddress must be a pointer and not '" +
3724 getTypeString(ExpectedTy) + "'");
3725 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3726 } else if (PFS) {
3727 // Otherwise, we default the address space of the current function.
3728 FwdDeclAS = PFS->getFunction().getAddressSpace();
3729 } else {
3730 llvm_unreachable("Unknown address space for blockaddress");
3731 }
3732 FwdRef = new GlobalVariable(
3733 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3734 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3735 }
3736
3737 ID.ConstantVal = FwdRef;
3738 ID.Kind = ValID::t_Constant;
3739 return false;
3740 }
3741
3742 // We found the function; now find the basic block. Don't use PFS, since we
3743 // might be inside a constant expression.
3744 BasicBlock *BB;
3745 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3746 if (Label.Kind == ValID::t_LocalID)
3747 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3748 else
3749 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3750 if (!BB)
3751 return error(Label.Loc, "referenced value is not a basic block");
3752 } else {
3753 if (Label.Kind == ValID::t_LocalID)
3754 return error(Label.Loc, "cannot take address of numeric label after "
3755 "the function is defined");
3756 BB = dyn_cast_or_null<BasicBlock>(
3757 F->getValueSymbolTable()->lookup(Label.StrVal));
3758 if (!BB)
3759 return error(Label.Loc, "referenced value is not a basic block");
3760 }
3761
3762 ID.ConstantVal = BlockAddress::get(F, BB);
3763 ID.Kind = ValID::t_Constant;
3764 return false;
3765 }
3766
3768 // ValID ::= 'dso_local_equivalent' @foo
3769 Lex.Lex();
3770
3771 ValID Fn;
3772
3773 if (parseValID(Fn, PFS))
3774 return true;
3775
3777 return error(Fn.Loc,
3778 "expected global value name in dso_local_equivalent");
3779
3780 // Try to find the function (but skip it if it's forward-referenced).
3781 GlobalValue *GV = nullptr;
3782 if (Fn.Kind == ValID::t_GlobalID) {
3783 if (Fn.UIntVal < NumberedVals.size())
3784 GV = NumberedVals[Fn.UIntVal];
3785 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3786 GV = M->getNamedValue(Fn.StrVal);
3787 }
3788
3789 if (!GV) {
3790 // Make a placeholder global variable as a placeholder for this reference.
3791 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
3792 ? ForwardRefDSOLocalEquivalentIDs
3793 : ForwardRefDSOLocalEquivalentNames;
3794 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;
3795 if (!FwdRef) {
3796 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3797 GlobalValue::InternalLinkage, nullptr, "",
3799 }
3800
3801 ID.ConstantVal = FwdRef;
3802 ID.Kind = ValID::t_Constant;
3803 return false;
3804 }
3805
3806 if (!GV->getValueType()->isFunctionTy())
3807 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3808 "in dso_local_equivalent");
3809
3810 ID.ConstantVal = DSOLocalEquivalent::get(GV);
3811 ID.Kind = ValID::t_Constant;
3812 return false;
3813 }
3814
3815 case lltok::kw_no_cfi: {
3816 // ValID ::= 'no_cfi' @foo
3817 Lex.Lex();
3818
3819 if (parseValID(ID, PFS))
3820 return true;
3821
3822 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
3823 return error(ID.Loc, "expected global value name in no_cfi");
3824
3825 ID.NoCFI = true;
3826 return false;
3827 }
3828
3829 case lltok::kw_trunc:
3830 case lltok::kw_zext:
3831 case lltok::kw_sext:
3832 case lltok::kw_fptrunc:
3833 case lltok::kw_fpext:
3834 case lltok::kw_bitcast:
3836 case lltok::kw_uitofp:
3837 case lltok::kw_sitofp:
3838 case lltok::kw_fptoui:
3839 case lltok::kw_fptosi:
3840 case lltok::kw_inttoptr:
3841 case lltok::kw_ptrtoint: {
3842 unsigned Opc = Lex.getUIntVal();
3843 Type *DestTy = nullptr;
3844 Constant *SrcVal;
3845 Lex.Lex();
3846 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3847 parseGlobalTypeAndValue(SrcVal) ||
3848 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3849 parseType(DestTy) ||
3850 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3851 return true;
3852 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3853 return error(ID.Loc, "invalid cast opcode for cast from '" +
3854 getTypeString(SrcVal->getType()) + "' to '" +
3855 getTypeString(DestTy) + "'");
3857 SrcVal, DestTy);
3858 ID.Kind = ValID::t_Constant;
3859 return false;
3860 }
3862 return error(ID.Loc, "extractvalue constexprs are no longer supported");
3864 return error(ID.Loc, "insertvalue constexprs are no longer supported");
3865 case lltok::kw_udiv:
3866 return error(ID.Loc, "udiv constexprs are no longer supported");
3867 case lltok::kw_sdiv:
3868 return error(ID.Loc, "sdiv constexprs are no longer supported");
3869 case lltok::kw_urem:
3870 return error(ID.Loc, "urem constexprs are no longer supported");
3871 case lltok::kw_srem:
3872 return error(ID.Loc, "srem constexprs are no longer supported");
3873 case lltok::kw_fadd:
3874 return error(ID.Loc, "fadd constexprs are no longer supported");
3875 case lltok::kw_fsub:
3876 return error(ID.Loc, "fsub constexprs are no longer supported");
3877 case lltok::kw_fmul:
3878 return error(ID.Loc, "fmul constexprs are no longer supported");
3879 case lltok::kw_fdiv:
3880 return error(ID.Loc, "fdiv constexprs are no longer supported");
3881 case lltok::kw_frem:
3882 return error(ID.Loc, "frem constexprs are no longer supported");
3883 case lltok::kw_fneg:
3884 return error(ID.Loc, "fneg constexprs are no longer supported");
3885 case lltok::kw_select:
3886 return error(ID.Loc, "select constexprs are no longer supported");
3887 case lltok::kw_icmp:
3888 case lltok::kw_fcmp: {
3889 unsigned PredVal, Opc = Lex.getUIntVal();
3890 Constant *Val0, *Val1;
3891 Lex.Lex();
3892 if (parseCmpPredicate(PredVal, Opc) ||
3893 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3894 parseGlobalTypeAndValue(Val0) ||
3895 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3896 parseGlobalTypeAndValue(Val1) ||
3897 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3898 return true;
3899
3900 if (Val0->getType() != Val1->getType())
3901 return error(ID.Loc, "compare operands must have the same type");
3902
3903 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3904
3905 if (Opc == Instruction::FCmp) {
3906 if (!Val0->getType()->isFPOrFPVectorTy())
3907 return error(ID.Loc, "fcmp requires floating point operands");
3908 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3909 } else {
3910 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3911 if (!Val0->getType()->isIntOrIntVectorTy() &&
3912 !Val0->getType()->isPtrOrPtrVectorTy())
3913 return error(ID.Loc, "icmp requires pointer or integer operands");
3914 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3915 }
3916 ID.Kind = ValID::t_Constant;
3917 return false;
3918 }
3919
3920 // Binary Operators.
3921 case lltok::kw_add:
3922 case lltok::kw_sub:
3923 case lltok::kw_mul:
3924 case lltok::kw_shl:
3925 case lltok::kw_lshr:
3926 case lltok::kw_ashr: {
3927 bool NUW = false;
3928 bool NSW = false;
3929 bool Exact = false;
3930 unsigned Opc = Lex.getUIntVal();
3931 Constant *Val0, *Val1;
3932 Lex.Lex();
3933 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3934 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3935 if (EatIfPresent(lltok::kw_nuw))
3936 NUW = true;
3937 if (EatIfPresent(lltok::kw_nsw)) {
3938 NSW = true;
3939 if (EatIfPresent(lltok::kw_nuw))
3940 NUW = true;
3941 }
3942 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3943 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3944 if (EatIfPresent(lltok::kw_exact))
3945 Exact = true;
3946 }
3947 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3948 parseGlobalTypeAndValue(Val0) ||
3949 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3950 parseGlobalTypeAndValue(Val1) ||
3951 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3952 return true;
3953 if (Val0->getType() != Val1->getType())
3954 return error(ID.Loc, "operands of constexpr must have same type");
3955 // Check that the type is valid for the operator.
3956 switch (Opc) {
3957 case Instruction::Add:
3958 case Instruction::Sub:
3959 case Instruction::Mul:
3960 case Instruction::UDiv:
3961 case Instruction::SDiv:
3962 case Instruction::URem:
3963 case Instruction::SRem:
3964 case Instruction::Shl:
3965 case Instruction::AShr:
3966 case Instruction::LShr:
3967 if (!Val0->getType()->isIntOrIntVectorTy())
3968 return error(ID.Loc, "constexpr requires integer operands");
3969 break;
3970 case Instruction::FAdd:
3971 case Instruction::FSub:
3972 case Instruction::FMul:
3973 case Instruction::FDiv:
3974 case Instruction::FRem:
3975 if (!Val0->getType()->isFPOrFPVectorTy())
3976 return error(ID.Loc, "constexpr requires fp operands");
3977 break;
3978 default: llvm_unreachable("Unknown binary operator!");
3979 }
3980 unsigned Flags = 0;
3984 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3985 ID.ConstantVal = C;
3986 ID.Kind = ValID::t_Constant;
3987 return false;
3988 }
3989
3990 // Logical Operations
3991 case lltok::kw_and:
3992 case lltok::kw_or:
3993 case lltok::kw_xor: {
3994 unsigned Opc = Lex.getUIntVal();
3995 Constant *Val0, *Val1;
3996 Lex.Lex();
3997 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3998 parseGlobalTypeAndValue(Val0) ||
3999 parseToken(lltok::comma, "expected comma in logical constantexpr") ||
4000 parseGlobalTypeAndValue(Val1) ||
4001 parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
4002 return true;
4003 if (Val0->getType() != Val1->getType())
4004 return error(ID.Loc, "operands of constexpr must have same type");
4005 if (!Val0->getType()->isIntOrIntVectorTy())
4006 return error(ID.Loc,
4007 "constexpr requires integer or integer vector operands");
4008 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
4009 ID.Kind = ValID::t_Constant;
4010 return false;
4011 }
4012
4017 unsigned Opc = Lex.getUIntVal();
4019 bool InBounds = false;
4020 Type *Ty;
4021 Lex.Lex();
4022
4023 if (Opc == Instruction::GetElementPtr)
4024 InBounds = EatIfPresent(lltok::kw_inbounds);
4025
4026 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4027 return true;
4028
4029 LocTy ExplicitTypeLoc = Lex.getLoc();
4030 if (Opc == Instruction::GetElementPtr) {
4031 if (parseType(Ty) ||
4032 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4033 return true;
4034 }
4035
4036 std::optional<unsigned> InRangeOp;
4037 if (parseGlobalValueVector(
4038 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
4039 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4040 return true;
4041
4042 if (Opc == Instruction::GetElementPtr) {
4043 if (Elts.size() == 0 ||
4044 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4045 return error(ID.Loc, "base of getelementptr must be a pointer");
4046
4047 Type *BaseType = Elts[0]->getType();
4048 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
4049 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
4050 return error(
4051 ExplicitTypeLoc,
4053 "explicit pointee type doesn't match operand's pointee type",
4054 Ty, BasePointerType->getNonOpaquePointerElementType()));
4055 }
4056
4057 unsigned GEPWidth =
4058 BaseType->isVectorTy()
4059 ? cast<FixedVectorType>(BaseType)->getNumElements()
4060 : 0;
4061
4062 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4063 for (Constant *Val : Indices) {
4064 Type *ValTy = Val->getType();
4065 if (!ValTy->isIntOrIntVectorTy())
4066 return error(ID.Loc, "getelementptr index must be an integer");
4067 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4068 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4069 if (GEPWidth && (ValNumEl != GEPWidth))
4070 return error(
4071 ID.Loc,
4072 "getelementptr vector index has a wrong number of elements");
4073 // GEPWidth may have been unknown because the base is a scalar,
4074 // but it is known now.
4075 GEPWidth = ValNumEl;
4076 }
4077 }
4078
4079 SmallPtrSet<Type*, 4> Visited;
4080 if (!Indices.empty() && !Ty->isSized(&Visited))
4081 return error(ID.Loc, "base element of getelementptr must be sized");
4082
4083 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4084 return error(ID.Loc, "invalid getelementptr indices");
4085
4086 if (InRangeOp) {
4087 if (*InRangeOp == 0)
4088 return error(ID.Loc,
4089 "inrange keyword may not appear on pointer operand");
4090 --*InRangeOp;
4091 }
4092
4093 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
4094 InBounds, InRangeOp);
4095 } else if (Opc == Instruction::ShuffleVector) {
4096 if (Elts.size() != 3)
4097 return error(ID.Loc, "expected three operands to shufflevector");
4098 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4099 return error(ID.Loc, "invalid operands to shufflevector");
4101 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
4102 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4103 } else if (Opc == Instruction::ExtractElement) {
4104 if (Elts.size() != 2)
4105 return error(ID.Loc, "expected two operands to extractelement");
4106 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4107 return error(ID.Loc, "invalid extractelement operands");
4108 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4109 } else {
4110 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4111 if (Elts.size() != 3)
4112 return error(ID.Loc, "expected three operands to insertelement");
4113 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4114 return error(ID.Loc, "invalid insertelement operands");
4115 ID.ConstantVal =
4116 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4117 }
4118
4119 ID.Kind = ValID::t_Constant;
4120 return false;
4121 }
4122 }
4123
4124 Lex.Lex();
4125 return false;
4126}
4127
4128/// parseGlobalValue - parse a global value with the specified type.
4129bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4130 C = nullptr;
4131 ValID ID;
4132 Value *V = nullptr;
4133 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4134 convertValIDToValue(Ty, ID, V, nullptr);
4135 if (V && !(C = dyn_cast<Constant>(V)))
4136 return error(ID.Loc, "global values must be constants");
4137 return Parsed;
4138}
4139
4140bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4141 Type *Ty = nullptr;
4142 return parseType(Ty) || parseGlobalValue(Ty, V);
4143}
4144
4145bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4146 C = nullptr;
4147
4148 LocTy KwLoc = Lex.getLoc();
4149 if (!EatIfPresent(lltok::kw_comdat))
4150 return false;
4151
4152 if (EatIfPresent(lltok::lparen)) {
4153 if (Lex.getKind() != lltok::ComdatVar)
4154 return tokError("expected comdat variable");
4155 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4156 Lex.Lex();
4157 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4158 return true;
4159 } else {
4160 if (GlobalName.empty())
4161 return tokError("comdat cannot be unnamed");
4162 C = getComdat(std::string(GlobalName), KwLoc);
4163 }
4164
4165 return false;
4166}
4167
4168/// parseGlobalValueVector
4169/// ::= /*empty*/
4170/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
4171bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
4172 std::optional<unsigned> *InRangeOp) {
4173 // Empty list.
4174 if (Lex.getKind() == lltok::rbrace ||
4175 Lex.getKind() == lltok::rsquare ||
4176 Lex.getKind() == lltok::greater ||
4177 Lex.getKind() == lltok::rparen)
4178 return false;
4179
4180 do {
4181 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
4182 *InRangeOp = Elts.size();
4183
4184 Constant *C;
4185 if (parseGlobalTypeAndValue(C))
4186 return true;
4187 Elts.push_back(C);
4188 } while (EatIfPresent(lltok::comma));
4189
4190 return false;
4191}
4192
4193bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4195 if (parseMDNodeVector(Elts))
4196 return true;
4197
4198 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4199 return false;
4200}
4201
4202/// MDNode:
4203/// ::= !{ ... }
4204/// ::= !7
4205/// ::= !DILocation(...)
4206bool LLParser::parseMDNode(MDNode *&N) {
4207 if (Lex.getKind() == lltok::MetadataVar)
4208 return parseSpecializedMDNode(N);
4209
4210 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4211}
4212
4213bool LLParser::parseMDNodeTail(MDNode *&N) {
4214 // !{ ... }
4215 if (Lex.getKind() == lltok::lbrace)
4216 return parseMDTuple(N);
4217
4218 // !42
4219 return parseMDNodeID(N);
4220}
4221
4222namespace {
4223
4224/// Structure to represent an optional metadata field.
4225template <class FieldTy> struct MDFieldImpl {
4226 typedef MDFieldImpl ImplTy;
4227 FieldTy Val;
4228 bool Seen;
4229
4230 void assign(FieldTy Val) {
4231 Seen = true;
4232 this->Val = std::move(Val);
4233 }
4234
4235 explicit MDFieldImpl(FieldTy Default)
4236 : Val(std::move(Default)), Seen(false) {}
4237};
4238
4239/// Structure to represent an optional metadata field that
4240/// can be of either type (A or B) and encapsulates the
4241/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4242/// to reimplement the specifics for representing each Field.
4243template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4244 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4245 FieldTypeA A;
4246 FieldTypeB B;
4247 bool Seen;
4248
4249 enum {
4250 IsInvalid = 0,
4251 IsTypeA = 1,
4252 IsTypeB = 2
4253 } WhatIs;
4254
4255 void assign(FieldTypeA A) {
4256 Seen = true;
4257 this->A = std::move(A);
4258 WhatIs = IsTypeA;
4259 }
4260
4261 void assign(FieldTypeB B) {
4262 Seen = true;
4263 this->B = std::move(B);
4264 WhatIs = IsTypeB;
4265 }
4266
4267 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4268 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4269 WhatIs(IsInvalid) {}
4270};
4271
4272struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4273 uint64_t Max;
4274
4275 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4276 : ImplTy(Default), Max(Max) {}
4277};
4278
4279struct LineField : public MDUnsignedField {
4280 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4281};
4282
4283struct ColumnField : public MDUnsignedField {
4284 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4285};
4286
4287struct DwarfTagField : public MDUnsignedField {
4288 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4289 DwarfTagField(dwarf::Tag DefaultTag)
4290 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4291};
4292
4293struct DwarfMacinfoTypeField : public MDUnsignedField {
4294 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4295 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4296 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4297};
4298
4299struct DwarfAttEncodingField : public MDUnsignedField {
4300 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4301};
4302
4303struct DwarfVirtualityField : public MDUnsignedField {
4304 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4305};
4306
4307struct DwarfLangField : public MDUnsignedField {
4308 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4309};
4310
4311struct DwarfCCField : public MDUnsignedField {
4312 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4313};
4314
4315struct EmissionKindField : public MDUnsignedField {
4316 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4317};
4318
4319struct NameTableKindField : public MDUnsignedField {
4320 NameTableKindField()
4321 : MDUnsignedField(
4322 0, (unsigned)
4323 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4324};
4325
4326struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4327 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4328};
4329
4330struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4331 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4332};
4333
4334struct MDAPSIntField : public MDFieldImpl<APSInt> {
4335 MDAPSIntField() : ImplTy(APSInt()) {}
4336};
4337
4338struct MDSignedField : public MDFieldImpl<int64_t> {
4339 int64_t Min = INT64_MIN;
4340 int64_t Max = INT64_MAX;
4341
4342 MDSignedField(int64_t Default = 0)
4343 : ImplTy(Default) {}
4344 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4345 : ImplTy(Default), Min(Min), Max(Max) {}
4346};
4347
4348struct MDBoolField : public MDFieldImpl<bool> {
4349 MDBoolField(bool Default = false) : ImplTy(Default) {}
4350};
4351
4352struct MDField : public MDFieldImpl<Metadata *> {
4353 bool AllowNull;
4354
4355 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4356};
4357
4358struct MDStringField : public MDFieldImpl<MDString *> {
4359 bool AllowEmpty;
4360 MDStringField(bool AllowEmpty = true)
4361 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4362};
4363
4364struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4365 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4366};
4367
4368struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4369 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4370};
4371
4372struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4373 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4374 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4375
4376 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4377 bool AllowNull = true)
4378 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4379
4380 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4381 bool isMDField() const { return WhatIs == IsTypeB; }
4382 int64_t getMDSignedValue() const {
4383 assert(isMDSignedField() && "Wrong field type");
4384 return A.Val;
4385 }
4386 Metadata *getMDFieldValue() const {
4387 assert(isMDField() && "Wrong field type");
4388 return B.Val;
4389 }
4390};
4391
4392} // end anonymous namespace
4393
4394namespace llvm {
4395
4396template <>
4397bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4398 if (Lex.getKind() != lltok::APSInt)
4399 return tokError("expected integer");
4400
4401 Result.assign(Lex.getAPSIntVal());
4402 Lex.Lex();
4403 return false;
4404}
4405
4406template <>
4407bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4408 MDUnsignedField &Result) {
4409 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4410 return tokError("expected unsigned integer");
4411
4412 auto &U = Lex.getAPSIntVal();
4413 if (U.ugt(Result.Max))
4414 return tokError("value for '" + Name + "' too large, limit is " +
4415 Twine(Result.Max));
4416 Result.assign(U.getZExtValue());
4417 assert(Result.Val <= Result.Max && "Expected value in range");
4418 Lex.Lex();
4419 return false;
4420}
4421
4422template <>
4423bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4424 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4425}
4426template <>
4427bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4428 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4429}
4430
4431template <>
4432bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4433 if (Lex.getKind() == lltok::APSInt)
4434 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4435
4436 if (Lex.getKind() != lltok::DwarfTag)
4437 return tokError("expected DWARF tag");
4438
4439 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4441 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4442 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4443
4444 Result.assign(Tag);
4445 Lex.Lex();
4446 return false;
4447}
4448
4449template <>
4450bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4451 DwarfMacinfoTypeField &Result) {
4452 if (Lex.getKind() == lltok::APSInt)
4453 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4454
4455 if (Lex.getKind() != lltok::DwarfMacinfo)
4456 return tokError("expected DWARF macinfo type");
4457
4458 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4459 if (Macinfo == dwarf::DW_MACINFO_invalid)
4460 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4461 Lex.getStrVal() + "'");
4462 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4463
4464 Result.assign(Macinfo);
4465 Lex.Lex();
4466 return false;
4467}
4468
4469template <>
4470bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4471 DwarfVirtualityField &Result) {
4472 if (Lex.getKind() == lltok::APSInt)
4473 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4474
4475 if (Lex.getKind() != lltok::DwarfVirtuality)
4476 return tokError("expected DWARF virtuality code");
4477
4478 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4479 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4480 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4481 Lex.getStrVal() + "'");
4482 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4483 Result.assign(Virtuality);
4484 Lex.Lex();
4485 return false;
4486}
4487
4488template <>
4489bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4490 if (Lex.getKind() == lltok::APSInt)
4491 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4492
4493 if (Lex.getKind() != lltok::DwarfLang)
4494 return tokError("expected DWARF language");
4495
4496 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4497 if (!Lang)
4498 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4499 "'");
4500 assert(Lang <= Result.Max && "Expected valid DWARF language");
4501 Result.assign(Lang);
4502 Lex.Lex();
4503 return false;
4504}
4505
4506template <>
4507bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4508 if (Lex.getKind() == lltok::APSInt)
4509 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4510
4511 if (Lex.getKind() != lltok::DwarfCC)
4512 return tokError("expected DWARF calling convention");
4513
4514 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4515 if (!CC)
4516 return tokError("invalid DWARF calling convention" + Twine(" '") +
4517 Lex.getStrVal() + "'");
4518 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4519 Result.assign(CC);
4520 Lex.Lex();
4521 return false;
4522}
4523
4524template <>
4525bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4526 EmissionKindField &Result) {
4527 if (Lex.getKind() == lltok::APSInt)
4528 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4529
4530 if (Lex.getKind() != lltok::EmissionKind)
4531 return tokError("expected emission kind");
4532
4533 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4534 if (!Kind)
4535 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4536 "'");
4537 assert(*Kind <= Result.Max && "Expected valid emission kind");
4538 Result.assign(*Kind);
4539 Lex.Lex();
4540 return false;
4541}
4542
4543template <>
4544bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4545 NameTableKindField &Result) {
4546 if (Lex.getKind() == lltok::APSInt)
4547 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4548
4549 if (Lex.getKind() != lltok::NameTableKind)
4550 return tokError("expected nameTable kind");
4551
4552 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4553 if (!Kind)
4554 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4555 "'");
4556 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4557 Result.assign((unsigned)*Kind);
4558 Lex.Lex();
4559 return false;
4560}
4561
4562template <>
4563bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4564 DwarfAttEncodingField &Result) {
4565 if (Lex.getKind() == lltok::APSInt)
4566 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4567
4568 if (Lex.getKind() != lltok::DwarfAttEncoding)
4569 return tokError("expected DWARF type attribute encoding");
4570
4571 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4572 if (!Encoding)
4573 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4574 Lex.getStrVal() + "'");
4575 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4576 Result.assign(Encoding);
4577 Lex.Lex();
4578 return false;
4579}
4580
4581/// DIFlagField
4582/// ::= uint32
4583/// ::= DIFlagVector
4584/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4585template <>
4586bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4587
4588 // parser for a single flag.
4589 auto parseFlag = [&](DINode::DIFlags &Val) {
4590 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4591 uint32_t TempVal = static_cast<uint32_t>(Val);
4592 bool Res = parseUInt32(TempVal);
4593 Val = static_cast<DINode::DIFlags>(TempVal);
4594 return Res;
4595 }
4596
4597 if (Lex.getKind() != lltok::DIFlag)
4598 return tokError("expected debug info flag");
4599
4600 Val = DINode::getFlag(Lex.getStrVal());
4601 if (!Val)
4602 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4603 "'");
4604 Lex.Lex();
4605 return false;
4606 };
4607
4608 // parse the flags and combine them together.
4609 DINode::DIFlags Combined = DINode::FlagZero;
4610 do {
4611 DINode::DIFlags Val;
4612 if (parseFlag(Val))
4613 return true;
4614 Combined |= Val;
4615 } while (EatIfPresent(lltok::bar));
4616
4617 Result.assign(Combined);
4618 return false;
4619}
4620
4621/// DISPFlagField
4622/// ::= uint32
4623/// ::= DISPFlagVector
4624/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4625template <>
4626bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4627
4628 // parser for a single flag.
4629 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4630 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4631 uint32_t TempVal = static_cast<uint32_t>(Val);
4632 bool Res = parseUInt32(TempVal);
4633 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4634 return Res;
4635 }
4636
4637 if (Lex.getKind() != lltok::DISPFlag)
4638 return tokError("expected debug info flag");
4639
4640 Val = DISubprogram::getFlag(Lex.getStrVal());
4641 if (!Val)
4642 return tokError(Twine("invalid subprogram debug info flag '") +
4643 Lex.getStrVal() + "'");
4644 Lex.Lex();
4645 return false;
4646 };
4647
4648 // parse the flags and combine them together.
4649 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4650 do {
4652 if (parseFlag(Val))
4653 return true;
4654 Combined |= Val;
4655 } while (EatIfPresent(lltok::bar));
4656
4657 Result.assign(Combined);
4658 return false;
4659}
4660
4661template <>
4662bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4663 if (Lex.getKind() != lltok::APSInt)
4664 return tokError("expected signed integer");
4665
4666 auto &S = Lex.getAPSIntVal();
4667 if (S < Result.Min)
4668 return tokError("value for '" + Name + "' too small, limit is " +
4669 Twine(Result.Min));
4670 if (S > Result.Max)
4671 return tokError("value for '" + Name + "' too large, limit is " +
4672 Twine(Result.Max));
4673 Result.assign(S.getExtValue());
4674 assert(Result.Val >= Result.Min && "Expected value in range");
4675 assert(Result.Val <= Result.Max && "Expected value in range");
4676 Lex.Lex();
4677 return false;
4678}
4679
4680template <>
4681bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4682 switch (Lex.getKind()) {
4683 default:
4684 return tokError("expected 'true' or 'false'");
4685 case lltok::kw_true:
4686 Result.assign(true);
4687 break;
4688 case lltok::kw_false:
4689 Result.assign(false);
4690 break;
4691 }
4692 Lex.Lex();
4693 return false;
4694}
4695
4696template <>
4697bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4698 if (Lex.getKind() == lltok::kw_null) {
4699 if (!Result.AllowNull)
4700 return tokError("'" + Name + "' cannot be null");
4701 Lex.Lex();
4702 Result.assign(nullptr);
4703 return false;
4704 }
4705
4706 Metadata *MD;
4707 if (parseMetadata(MD, nullptr))
4708 return true;
4709
4710 Result.assign(MD);
4711 return false;
4712}
4713
4714template <>
4715bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4716 MDSignedOrMDField &Result) {
4717 // Try to parse a signed int.
4718 if (Lex.getKind() == lltok::APSInt) {
4719 MDSignedField Res = Result.A;
4720 if (!parseMDField(Loc, Name, Res)) {
4721 Result.assign(Res);
4722 return false;
4723 }
4724 return true;
4725 }
4726
4727 // Otherwise, try to parse as an MDField.
4728 MDField Res = Result.B;
4729 if (!parseMDField(Loc, Name, Res)) {
4730 Result.assign(Res);
4731 return false;
4732 }
4733
4734 return true;
4735}
4736
4737template <>
4738bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4739 LocTy ValueLoc = Lex.getLoc();
4740 std::string S;
4741 if (parseStringConstant(S))
4742 return true;
4743
4744 if (!Result.AllowEmpty && S.empty())
4745 return error(ValueLoc, "'" + Name + "' cannot be empty");
4746
4747 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4748 return false;
4749}
4750
4751template <>
4752bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4754 if (parseMDNodeVector(MDs))
4755 return true;
4756
4757 Result.assign(std::move(MDs));
4758 return false;
4759}
4760
4761template <>
4762bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4763 ChecksumKindField &Result) {
4764 std::optional<DIFile::ChecksumKind> CSKind =
4766
4767 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4768 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4769 "'");
4770
4771 Result.assign(*CSKind);
4772 Lex.Lex();
4773 return false;
4774}
4775
4776} // end namespace llvm
4777
4778template <class ParserTy>
4779bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4780 do {
4781 if (Lex.getKind() != lltok::LabelStr)
4782 return tokError("expected field label here");
4783
4784 if (ParseField())
4785 return true;
4786 } while (EatIfPresent(lltok::comma));
4787
4788 return false;
4789}
4790
4791template <class ParserTy>
4792bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4793 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4794 Lex.Lex();
4795
4796 if (parseToken(lltok::lparen, "expected '(' here"))
4797 return true;
4798 if (Lex.getKind() != lltok::rparen)
4799 if (parseMDFieldsImplBody(ParseField))
4800 return true;
4801
4802 ClosingLoc = Lex.getLoc();
4803 return parseToken(lltok::rparen, "expected ')' here");
4804}
4805
4806template <class FieldTy>
4807bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4808 if (Result.Seen)
4809 return tokError("field '" + Name + "' cannot be specified more than once");
4810
4811 LocTy Loc = Lex.getLoc();
4812 Lex.Lex();
4813 return parseMDField(Loc, Name, Result);
4814}
4815
4816bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4817 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4818
4819#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4820 if (Lex.getStrVal() == #CLASS) \
4821 return parse##CLASS(N, IsDistinct);
4822#include "llvm/IR/Metadata.def"
4823
4824 return tokError("expected metadata type");
4825}
4826
4827#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4828#define NOP_FIELD(NAME, TYPE, INIT)
4829#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4830 if (!NAME.Seen) \
4831 return error(ClosingLoc, "missing required field '" #NAME "'");
4832#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4833 if (Lex.getStrVal() == #NAME) \
4834 return parseMDField(#NAME, NAME);
4835#define PARSE_MD_FIELDS() \
4836 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4837 do { \
4838 LocTy ClosingLoc; \
4839 if (parseMDFieldsImpl( \
4840 [&]() -> bool { \
4841 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4842 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4843 "'"); \
4844 }, \
4845 ClosingLoc)) \
4846 return true; \
4847 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4848 } while (false)
4849#define GET_OR_DISTINCT(CLASS, ARGS) \
4850 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4851
4852/// parseDILocationFields:
4853/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4854/// isImplicitCode: true)
4855bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4856#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4857 OPTIONAL(line, LineField, ); \
4858 OPTIONAL(column, ColumnField, ); \
4859 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4860 OPTIONAL(inlinedAt, MDField, ); \
4861 OPTIONAL(isImplicitCode, MDBoolField, (false));
4863#undef VISIT_MD_FIELDS
4864
4865 Result =
4866 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4867 inlinedAt.Val, isImplicitCode.Val));
4868 return false;
4869}
4870
4871/// parseDIAssignID:
4872/// ::= distinct !DIAssignID()
4873bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
4874 if (!IsDistinct)
4875 return Lex.Error("missing 'distinct', required for !DIAssignID()");
4876
4877 Lex.Lex();
4878
4879 // Now eat the parens.
4880 if (parseToken(lltok::lparen, "expected '(' here"))
4881 return true;
4882 if (parseToken(lltok::rparen, "expected ')' here"))
4883 return true;
4884
4886 return false;
4887}
4888
4889/// parseGenericDINode:
4890/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4891bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4892#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4893 REQUIRED(tag, DwarfTagField, ); \
4894 OPTIONAL(header, MDStringField, ); \
4895 OPTIONAL(operands, MDFieldList, );
4897#undef VISIT_MD_FIELDS
4898
4900 (Context, tag.Val, header.Val, operands.Val));
4901 return false;
4902}
4903
4904/// parseDISubrange:
4905/// ::= !DISubrange(count: 30, lowerBound: 2)
4906/// ::= !DISubrange(count: !node, lowerBound: 2)
4907/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4908bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4909#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4910 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4911 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4912 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4913 OPTIONAL(stride, MDSignedOrMDField, );
4915#undef VISIT_MD_FIELDS
4916
4917 Metadata *Count = nullptr;
4918 Metadata *LowerBound = nullptr;
4919 Metadata *UpperBound = nullptr;
4920 Metadata *Stride = nullptr;
4921
4922 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4923 if (Bound.isMDSignedField())
4925 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4926 if (Bound.isMDField())
4927 return Bound.getMDFieldValue();
4928 return nullptr;
4929 };
4930
4931 Count = convToMetadata(count);
4932 LowerBound = convToMetadata(lowerBound);
4933 UpperBound = convToMetadata(upperBound);
4934 Stride = convToMetadata(stride);
4935
4937 (Context, Count, LowerBound, UpperBound, Stride));
4938
4939 return false;
4940}
4941
4942/// parseDIGenericSubrange:
4943/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4944/// !node3)
4945bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4946#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4947 OPTIONAL(count, MDSignedOrMDField, ); \