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