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