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