LLVM 22.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
50#include "llvm/Support/ModRef.h"
53#include <algorithm>
54#include <cassert>
55#include <cstring>
56#include <optional>
57#include <vector>
58
59using namespace llvm;
60
62 "allow-incomplete-ir", cl::init(false), cl::Hidden,
64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
66
67static std::string getTypeString(Type *T) {
68 std::string Result;
69 raw_string_ostream Tmp(Result);
70 Tmp << *T;
71 return Tmp.str();
72}
73
74/// Run: module ::= toplevelentity*
75bool LLParser::Run(bool UpgradeDebugInfo,
76 DataLayoutCallbackTy DataLayoutCallback) {
77 // Prime the lexer.
78 Lex.Lex();
79
80 if (Context.shouldDiscardValueNames())
81 return error(
82 Lex.getLoc(),
83 "Can't read textual IR with a Context that discards named Values");
84
85 if (M) {
86 if (parseTargetDefinitions(DataLayoutCallback))
87 return true;
88 }
89
90 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
91 validateEndOfIndex();
92}
93
95 const SlotMapping *Slots) {
96 restoreParsingState(Slots);
97 Lex.Lex();
98
99 Type *Ty = nullptr;
100 if (parseType(Ty) || parseConstantValue(Ty, C))
101 return true;
102 if (Lex.getKind() != lltok::Eof)
103 return error(Lex.getLoc(), "expected end of string");
104 return false;
105}
106
108 const SlotMapping *Slots) {
109 restoreParsingState(Slots);
110 Lex.Lex();
111
112 Read = 0;
113 SMLoc Start = Lex.getLoc();
114 Ty = nullptr;
115 if (parseType(Ty))
116 return true;
117 SMLoc End = Lex.getLoc();
118 Read = End.getPointer() - Start.getPointer();
119
120 return false;
121}
122
124 const SlotMapping *Slots) {
125 restoreParsingState(Slots);
126 Lex.Lex();
127
128 Read = 0;
129 SMLoc Start = Lex.getLoc();
130 Result = nullptr;
131 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
132 SMLoc End = Lex.getLoc();
133 Read = End.getPointer() - Start.getPointer();
134
135 return Status;
136}
137
138void LLParser::restoreParsingState(const SlotMapping *Slots) {
139 if (!Slots)
140 return;
141 NumberedVals = Slots->GlobalValues;
142 NumberedMetadata = Slots->MetadataNodes;
143 for (const auto &I : Slots->NamedTypes)
144 NamedTypes.insert(
145 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
146 for (const auto &I : Slots->Types)
147 NumberedTypes.insert(
148 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
149}
150
152 // White-list intrinsics that are safe to drop.
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
155 return;
156
158 for (Value *V : II->args())
159 if (auto *MV = dyn_cast<MetadataAsValue>(V))
160 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
161 if (MD->isTemporary())
162 MVs.push_back(MV);
163
164 if (!MVs.empty()) {
165 assert(II->use_empty() && "Cannot have uses");
166 II->eraseFromParent();
167
168 // Also remove no longer used MetadataAsValue wrappers.
169 for (MetadataAsValue *MV : MVs)
170 if (MV->use_empty())
171 delete MV;
172 }
173}
174
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
177 for (Function &F : *M) {
178 F.eraseMetadataIf(Pred);
179 for (Instruction &I : make_early_inc_range(instructions(F))) {
180 I.eraseMetadataIf(Pred);
181
182 if (auto *II = dyn_cast<IntrinsicInst>(&I))
184 }
185 }
186
187 for (GlobalVariable &GV : M->globals())
188 GV.eraseMetadataIf(Pred);
189
190 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
191 // Check whether there is only a single use left, which would be in our
192 // own NumberedMetadata.
193 if (Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(ID);
195 ForwardRefMDNodes.erase(ID);
196 }
197 }
198}
199
200/// validateEndOfModule - Do final validity and basic correctness checks at the
201/// end of the module.
202bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
203 if (!M)
204 return false;
205
206 // We should have already returned an error if we observed both intrinsics and
207 // records in this IR.
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
210
211 // Handle any function attribute group forward references.
212 for (const auto &RAG : ForwardRefAttrGroups) {
213 Value *V = RAG.first;
214 const std::vector<unsigned> &Attrs = RAG.second;
215 AttrBuilder B(Context);
216
217 for (const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
220 B.merge(R->second);
221 }
222
223 if (Function *Fn = dyn_cast<Function>(V)) {
224 AttributeList AS = Fn->getAttributes();
225 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
226 AS = AS.removeFnAttributes(Context);
227
228 FnAttrs.merge(B);
229
230 // If the alignment was parsed as an attribute, move to the alignment
231 // field.
232 if (MaybeAlign A = FnAttrs.getAlignment()) {
233 Fn->setAlignment(*A);
234 FnAttrs.removeAttribute(Attribute::Alignment);
235 }
236
237 AS = AS.addFnAttributes(Context, FnAttrs);
238 Fn->setAttributes(AS);
239 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
240 AttributeList AS = CI->getAttributes();
241 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
242 AS = AS.removeFnAttributes(Context);
243 FnAttrs.merge(B);
244 AS = AS.addFnAttributes(Context, FnAttrs);
245 CI->setAttributes(AS);
246 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
247 AttributeList AS = II->getAttributes();
248 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
249 AS = AS.removeFnAttributes(Context);
250 FnAttrs.merge(B);
251 AS = AS.addFnAttributes(Context, FnAttrs);
252 II->setAttributes(AS);
253 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
254 AttributeList AS = CBI->getAttributes();
255 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
256 AS = AS.removeFnAttributes(Context);
257 FnAttrs.merge(B);
258 AS = AS.addFnAttributes(Context, FnAttrs);
259 CBI->setAttributes(AS);
260 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
261 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
262 Attrs.merge(B);
263 GV->setAttributes(AttributeSet::get(Context,Attrs));
264 } else {
265 llvm_unreachable("invalid object with forward attribute group reference");
266 }
267 }
268
269 // If there are entries in ForwardRefBlockAddresses at this point, the
270 // function was never defined.
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
274
275 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
276 GlobalValue *FwdRef) {
277 GlobalValue *GV = nullptr;
278 if (GVRef.Kind == ValID::t_GlobalName) {
279 GV = M->getNamedValue(GVRef.StrVal);
280 } else {
281 GV = NumberedVals.get(GVRef.UIntVal);
282 }
283
284 if (!GV)
285 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
286 "' referenced by dso_local_equivalent");
287
288 if (!GV->getValueType()->isFunctionTy())
289 return error(GVRef.Loc,
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
292
293 auto *Equiv = DSOLocalEquivalent::get(GV);
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
296 return false;
297 };
298
299 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
300 // point, they are references after the function was defined. Resolve those
301 // now.
302 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
304 return true;
305 }
306 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
308 return true;
309 }
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
312
313 for (const auto &NT : NumberedTypes)
314 if (NT.second.second.isValid())
315 return error(NT.second.second,
316 "use of undefined type '%" + Twine(NT.first) + "'");
317
318 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
319 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
320 if (I->second.second.isValid())
321 return error(I->second.second,
322 "use of undefined type named '" + I->getKey() + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 // Automatically create declarations for intrinsics. Intrinsics can only
333 // be called directly, so the call function type directly determines the
334 // declaration function type.
335 //
336 // Additionally, automatically add the required mangling suffix to the
337 // intrinsic name. This means that we may replace a single forward
338 // declaration with multiple functions here.
339 for (Use &U : make_early_inc_range(Info.first->uses())) {
340 auto *CB = dyn_cast<CallBase>(U.getUser());
341 if (!CB || !CB->isCallee(&U))
342 return error(Info.second, "intrinsic can only be used as callee");
343
344 SmallVector<Type *> OverloadTys;
345 if (IID != Intrinsic::not_intrinsic &&
346 Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
347 OverloadTys)) {
348 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
349 } else {
350 // Try to upgrade the intrinsic.
351 Function *TmpF = Function::Create(CB->getFunctionType(),
353 Function *NewF = nullptr;
354 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
355 if (IID == Intrinsic::not_intrinsic)
356 return error(Info.second, "unknown intrinsic '" + Name + "'");
357 return error(Info.second, "invalid intrinsic signature");
358 }
359
360 U.set(TmpF);
361 UpgradeIntrinsicCall(CB, NewF);
362 if (TmpF->use_empty())
363 TmpF->eraseFromParent();
364 }
365 }
366
367 Info.first->eraseFromParent();
368 ForwardRefVals.erase(Name);
369 continue;
370 }
371
372 // If incomplete IR is allowed, also add declarations for
373 // non-intrinsics.
375 continue;
376
377 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
378 FunctionType *FTy = nullptr;
379 for (Use &U : V->uses()) {
380 auto *CB = dyn_cast<CallBase>(U.getUser());
381 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
382 return nullptr;
383 FTy = CB->getFunctionType();
384 }
385 return FTy;
386 };
387
388 // First check whether this global is only used in calls with the same
389 // type, in which case we'll insert a function. Otherwise, fall back to
390 // using a dummy i8 type.
391 Type *Ty = GetCommonFunctionType(Info.first);
392 if (!Ty)
393 Ty = Type::getInt8Ty(Context);
394
395 GlobalValue *GV;
396 if (auto *FTy = dyn_cast<FunctionType>(Ty))
398 else
399 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
401 /*Initializer*/ nullptr, Name);
402 Info.first->replaceAllUsesWith(GV);
403 Info.first->eraseFromParent();
404 ForwardRefVals.erase(Name);
405 }
406
407 if (!ForwardRefVals.empty())
408 return error(ForwardRefVals.begin()->second.second,
409 "use of undefined value '@" + ForwardRefVals.begin()->first +
410 "'");
411
412 if (!ForwardRefValIDs.empty())
413 return error(ForwardRefValIDs.begin()->second.second,
414 "use of undefined value '@" +
415 Twine(ForwardRefValIDs.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 // Resolve metadata cycles.
426 for (auto &N : NumberedMetadata) {
427 if (N.second && !N.second->isResolved())
428 N.second->resolveCycles();
429 }
430
431 for (auto *Inst : InstsWithTBAATag) {
432 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
433 // With incomplete IR, the tbaa metadata may have been dropped.
435 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
436 if (MD) {
437 auto *UpgradedMD = UpgradeTBAANode(*MD);
438 if (MD != UpgradedMD)
439 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
440 }
441 }
442
443 // Look for intrinsic functions and CallInst that need to be upgraded. We use
444 // make_early_inc_range here because we may remove some functions.
445 for (Function &F : llvm::make_early_inc_range(*M))
447
448 if (UpgradeDebugInfo)
450
454
455 if (!Slots)
456 return false;
457 // Initialize the slot mapping.
458 // Because by this point we've parsed and validated everything, we can "steal"
459 // the mapping from LLParser as it doesn't need it anymore.
460 Slots->GlobalValues = std::move(NumberedVals);
461 Slots->MetadataNodes = std::move(NumberedMetadata);
462 for (const auto &I : NamedTypes)
463 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
464 for (const auto &I : NumberedTypes)
465 Slots->Types.insert(std::make_pair(I.first, I.second.first));
466
467 return false;
468}
469
470/// Do final validity and basic correctness checks at the end of the index.
471bool LLParser::validateEndOfIndex() {
472 if (!Index)
473 return false;
474
475 if (!ForwardRefValueInfos.empty())
476 return error(ForwardRefValueInfos.begin()->second.front().second,
477 "use of undefined summary '^" +
478 Twine(ForwardRefValueInfos.begin()->first) + "'");
479
480 if (!ForwardRefAliasees.empty())
481 return error(ForwardRefAliasees.begin()->second.front().second,
482 "use of undefined summary '^" +
483 Twine(ForwardRefAliasees.begin()->first) + "'");
484
485 if (!ForwardRefTypeIds.empty())
486 return error(ForwardRefTypeIds.begin()->second.front().second,
487 "use of undefined type id summary '^" +
488 Twine(ForwardRefTypeIds.begin()->first) + "'");
489
490 return false;
491}
492
493//===----------------------------------------------------------------------===//
494// Top-Level Entities
495//===----------------------------------------------------------------------===//
496
497bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
498 // Delay parsing of the data layout string until the target triple is known.
499 // Then, pass both the the target triple and the tentative data layout string
500 // to DataLayoutCallback, allowing to override the DL string.
501 // This enables importing modules with invalid DL strings.
502 std::string TentativeDLStr = M->getDataLayoutStr();
503 LocTy DLStrLoc;
504
505 bool Done = false;
506 while (!Done) {
507 switch (Lex.getKind()) {
508 case lltok::kw_target:
509 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
510 return true;
511 break;
513 if (parseSourceFileName())
514 return true;
515 break;
516 default:
517 Done = true;
518 }
519 }
520 // Run the override callback to potentially change the data layout string, and
521 // parse the data layout string.
522 if (auto LayoutOverride =
523 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
524 TentativeDLStr = *LayoutOverride;
525 DLStrLoc = {};
526 }
527 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
528 if (!MaybeDL)
529 return error(DLStrLoc, toString(MaybeDL.takeError()));
530 M->setDataLayout(MaybeDL.get());
531 return false;
532}
533
534bool LLParser::parseTopLevelEntities() {
535 // If there is no Module, then parse just the summary index entries.
536 if (!M) {
537 while (true) {
538 switch (Lex.getKind()) {
539 case lltok::Eof:
540 return false;
541 case lltok::SummaryID:
542 if (parseSummaryEntry())
543 return true;
544 break;
546 if (parseSourceFileName())
547 return true;
548 break;
549 default:
550 // Skip everything else
551 Lex.Lex();
552 }
553 }
554 }
555 while (true) {
556 switch (Lex.getKind()) {
557 default:
558 return tokError("expected top-level entity");
559 case lltok::Eof: return false;
561 if (parseDeclare())
562 return true;
563 break;
564 case lltok::kw_define:
565 if (parseDefine())
566 return true;
567 break;
568 case lltok::kw_module:
569 if (parseModuleAsm())
570 return true;
571 break;
573 if (parseUnnamedType())
574 return true;
575 break;
576 case lltok::LocalVar:
577 if (parseNamedType())
578 return true;
579 break;
580 case lltok::GlobalID:
581 if (parseUnnamedGlobal())
582 return true;
583 break;
584 case lltok::GlobalVar:
585 if (parseNamedGlobal())
586 return true;
587 break;
588 case lltok::ComdatVar: if (parseComdat()) return true; break;
589 case lltok::exclaim:
590 if (parseStandaloneMetadata())
591 return true;
592 break;
593 case lltok::SummaryID:
594 if (parseSummaryEntry())
595 return true;
596 break;
598 if (parseNamedMetadata())
599 return true;
600 break;
602 if (parseUnnamedAttrGrp())
603 return true;
604 break;
606 if (parseUseListOrder())
607 return true;
608 break;
610 if (parseUseListOrderBB())
611 return true;
612 break;
613 }
614 }
615}
616
617/// toplevelentity
618/// ::= 'module' 'asm' STRINGCONSTANT
619bool LLParser::parseModuleAsm() {
620 assert(Lex.getKind() == lltok::kw_module);
621 Lex.Lex();
622
623 std::string AsmStr;
624 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
625 parseStringConstant(AsmStr))
626 return true;
627
628 M->appendModuleInlineAsm(AsmStr);
629 return false;
630}
631
632/// toplevelentity
633/// ::= 'target' 'triple' '=' STRINGCONSTANT
634/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
635bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
636 LocTy &DLStrLoc) {
637 assert(Lex.getKind() == lltok::kw_target);
638 std::string Str;
639 switch (Lex.Lex()) {
640 default:
641 return tokError("unknown target property");
642 case lltok::kw_triple:
643 Lex.Lex();
644 if (parseToken(lltok::equal, "expected '=' after target triple") ||
645 parseStringConstant(Str))
646 return true;
647 M->setTargetTriple(Triple(std::move(Str)));
648 return false;
650 Lex.Lex();
651 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
652 return true;
653 DLStrLoc = Lex.getLoc();
654 if (parseStringConstant(TentativeDLStr))
655 return true;
656 return false;
657 }
658}
659
660/// toplevelentity
661/// ::= 'source_filename' '=' STRINGCONSTANT
662bool LLParser::parseSourceFileName() {
663 assert(Lex.getKind() == lltok::kw_source_filename);
664 Lex.Lex();
665 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
666 parseStringConstant(SourceFileName))
667 return true;
668 if (M)
669 M->setSourceFileName(SourceFileName);
670 return false;
671}
672
673/// parseUnnamedType:
674/// ::= LocalVarID '=' 'type' type
675bool LLParser::parseUnnamedType() {
676 LocTy TypeLoc = Lex.getLoc();
677 unsigned TypeID = Lex.getUIntVal();
678 Lex.Lex(); // eat LocalVarID;
679
680 if (parseToken(lltok::equal, "expected '=' after name") ||
681 parseToken(lltok::kw_type, "expected 'type' after '='"))
682 return true;
683
684 Type *Result = nullptr;
685 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
686 return true;
687
688 if (!isa<StructType>(Result)) {
689 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
690 if (Entry.first)
691 return error(TypeLoc, "non-struct types may not be recursive");
692 Entry.first = Result;
693 Entry.second = SMLoc();
694 }
695
696 return false;
697}
698
699/// toplevelentity
700/// ::= LocalVar '=' 'type' type
701bool LLParser::parseNamedType() {
702 std::string Name = Lex.getStrVal();
703 LocTy NameLoc = Lex.getLoc();
704 Lex.Lex(); // eat LocalVar.
705
706 if (parseToken(lltok::equal, "expected '=' after name") ||
707 parseToken(lltok::kw_type, "expected 'type' after name"))
708 return true;
709
710 Type *Result = nullptr;
711 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
712 return true;
713
714 if (!isa<StructType>(Result)) {
715 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
716 if (Entry.first)
717 return error(NameLoc, "non-struct types may not be recursive");
718 Entry.first = Result;
719 Entry.second = SMLoc();
720 }
721
722 return false;
723}
724
725/// toplevelentity
726/// ::= 'declare' FunctionHeader
727bool LLParser::parseDeclare() {
728 assert(Lex.getKind() == lltok::kw_declare);
729 Lex.Lex();
730
731 std::vector<std::pair<unsigned, MDNode *>> MDs;
732 while (Lex.getKind() == lltok::MetadataVar) {
733 unsigned MDK;
734 MDNode *N;
735 if (parseMetadataAttachment(MDK, N))
736 return true;
737 MDs.push_back({MDK, N});
738 }
739
740 Function *F;
741 unsigned FunctionNumber = -1;
742 SmallVector<unsigned> UnnamedArgNums;
743 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
744 return true;
745 for (auto &MD : MDs)
746 F->addMetadata(MD.first, *MD.second);
747 return false;
748}
749
750/// toplevelentity
751/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
752bool LLParser::parseDefine() {
753 assert(Lex.getKind() == lltok::kw_define);
754 Lex.Lex();
755
756 Function *F;
757 unsigned FunctionNumber = -1;
758 SmallVector<unsigned> UnnamedArgNums;
759 return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
760 parseOptionalFunctionMetadata(*F) ||
761 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
762}
763
764/// parseGlobalType
765/// ::= 'constant'
766/// ::= 'global'
767bool LLParser::parseGlobalType(bool &IsConstant) {
768 if (Lex.getKind() == lltok::kw_constant)
769 IsConstant = true;
770 else if (Lex.getKind() == lltok::kw_global)
771 IsConstant = false;
772 else {
773 IsConstant = false;
774 return tokError("expected 'global' or 'constant'");
775 }
776 Lex.Lex();
777 return false;
778}
779
780bool LLParser::parseOptionalUnnamedAddr(
781 GlobalVariable::UnnamedAddr &UnnamedAddr) {
782 if (EatIfPresent(lltok::kw_unnamed_addr))
784 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
786 else
787 UnnamedAddr = GlobalValue::UnnamedAddr::None;
788 return false;
789}
790
791/// parseUnnamedGlobal:
792/// OptionalVisibility (ALIAS | IFUNC) ...
793/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
794/// OptionalDLLStorageClass
795/// ... -> global variable
796/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
797/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
798/// OptionalVisibility
799/// OptionalDLLStorageClass
800/// ... -> global variable
801bool LLParser::parseUnnamedGlobal() {
802 unsigned VarID;
803 std::string Name;
804 LocTy NameLoc = Lex.getLoc();
805
806 // Handle the GlobalID form.
807 if (Lex.getKind() == lltok::GlobalID) {
808 VarID = Lex.getUIntVal();
809 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
810 return true;
811
812 Lex.Lex(); // eat GlobalID;
813 if (parseToken(lltok::equal, "expected '=' after name"))
814 return true;
815 } else {
816 VarID = NumberedVals.getNext();
817 }
818
819 bool HasLinkage;
820 unsigned Linkage, Visibility, DLLStorageClass;
821 bool DSOLocal;
823 GlobalVariable::UnnamedAddr UnnamedAddr;
824 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
825 DSOLocal) ||
826 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
827 return true;
828
829 switch (Lex.getKind()) {
830 default:
831 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
832 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
833 case lltok::kw_alias:
834 case lltok::kw_ifunc:
835 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
836 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
837 }
838}
839
840/// parseNamedGlobal:
841/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
842/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
843/// OptionalVisibility OptionalDLLStorageClass
844/// ... -> global variable
845bool LLParser::parseNamedGlobal() {
846 assert(Lex.getKind() == lltok::GlobalVar);
847 LocTy NameLoc = Lex.getLoc();
848 std::string Name = Lex.getStrVal();
849 Lex.Lex();
850
851 bool HasLinkage;
852 unsigned Linkage, Visibility, DLLStorageClass;
853 bool DSOLocal;
855 GlobalVariable::UnnamedAddr UnnamedAddr;
856 if (parseToken(lltok::equal, "expected '=' in global variable") ||
857 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
858 DSOLocal) ||
859 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
860 return true;
861
862 switch (Lex.getKind()) {
863 default:
864 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
865 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
866 case lltok::kw_alias:
867 case lltok::kw_ifunc:
868 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
869 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
870 }
871}
872
873bool LLParser::parseComdat() {
874 assert(Lex.getKind() == lltok::ComdatVar);
875 std::string Name = Lex.getStrVal();
876 LocTy NameLoc = Lex.getLoc();
877 Lex.Lex();
878
879 if (parseToken(lltok::equal, "expected '=' here"))
880 return true;
881
882 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
883 return tokError("expected comdat type");
884
886 switch (Lex.getKind()) {
887 default:
888 return tokError("unknown selection kind");
889 case lltok::kw_any:
890 SK = Comdat::Any;
891 break;
894 break;
896 SK = Comdat::Largest;
897 break;
900 break;
902 SK = Comdat::SameSize;
903 break;
904 }
905 Lex.Lex();
906
907 // See if the comdat was forward referenced, if so, use the comdat.
908 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
909 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
910 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
911 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
912
913 Comdat *C;
914 if (I != ComdatSymTab.end())
915 C = &I->second;
916 else
917 C = M->getOrInsertComdat(Name);
918 C->setSelectionKind(SK);
919
920 return false;
921}
922
923// MDString:
924// ::= '!' STRINGCONSTANT
925bool LLParser::parseMDString(MDString *&Result) {
926 std::string Str;
927 if (parseStringConstant(Str))
928 return true;
929 Result = MDString::get(Context, Str);
930 return false;
931}
932
933// MDNode:
934// ::= '!' MDNodeNumber
935bool LLParser::parseMDNodeID(MDNode *&Result) {
936 // !{ ..., !42, ... }
937 LocTy IDLoc = Lex.getLoc();
938 unsigned MID = 0;
939 if (parseUInt32(MID))
940 return true;
941
942 // If not a forward reference, just return it now.
943 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
944 if (!Inserted) {
945 Result = It->second;
946 return false;
947 }
948
949 // Otherwise, create MDNode forward reference.
950 auto &FwdRef = ForwardRefMDNodes[MID];
951 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
952
953 Result = FwdRef.first.get();
954 It->second.reset(Result);
955 return false;
956}
957
958/// parseNamedMetadata:
959/// !foo = !{ !1, !2 }
960bool LLParser::parseNamedMetadata() {
961 assert(Lex.getKind() == lltok::MetadataVar);
962 std::string Name = Lex.getStrVal();
963 Lex.Lex();
964
965 if (parseToken(lltok::equal, "expected '=' here") ||
966 parseToken(lltok::exclaim, "Expected '!' here") ||
967 parseToken(lltok::lbrace, "Expected '{' here"))
968 return true;
969
970 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
971 if (Lex.getKind() != lltok::rbrace)
972 do {
973 MDNode *N = nullptr;
974 // parse DIExpressions inline as a special case. They are still MDNodes,
975 // so they can still appear in named metadata. Remove this logic if they
976 // become plain Metadata.
977 if (Lex.getKind() == lltok::MetadataVar &&
978 Lex.getStrVal() == "DIExpression") {
979 if (parseDIExpression(N, /*IsDistinct=*/false))
980 return true;
981 // DIArgLists should only appear inline in a function, as they may
982 // contain LocalAsMetadata arguments which require a function context.
983 } else if (Lex.getKind() == lltok::MetadataVar &&
984 Lex.getStrVal() == "DIArgList") {
985 return tokError("found DIArgList outside of function");
986 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
987 parseMDNodeID(N)) {
988 return true;
989 }
990 NMD->addOperand(N);
991 } while (EatIfPresent(lltok::comma));
992
993 return parseToken(lltok::rbrace, "expected end of metadata node");
994}
995
996/// parseStandaloneMetadata:
997/// !42 = !{...}
998bool LLParser::parseStandaloneMetadata() {
999 assert(Lex.getKind() == lltok::exclaim);
1000 Lex.Lex();
1001 unsigned MetadataID = 0;
1002
1003 MDNode *Init;
1004 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1005 return true;
1006
1007 // Detect common error, from old metadata syntax.
1008 if (Lex.getKind() == lltok::Type)
1009 return tokError("unexpected type in metadata definition");
1010
1011 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1012 if (Lex.getKind() == lltok::MetadataVar) {
1013 if (parseSpecializedMDNode(Init, IsDistinct))
1014 return true;
1015 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1016 parseMDTuple(Init, IsDistinct))
1017 return true;
1018
1019 // See if this was forward referenced, if so, handle it.
1020 auto FI = ForwardRefMDNodes.find(MetadataID);
1021 if (FI != ForwardRefMDNodes.end()) {
1022 auto *ToReplace = FI->second.first.get();
1023 // DIAssignID has its own special forward-reference "replacement" for
1024 // attachments (the temporary attachments are never actually attached).
1025 if (isa<DIAssignID>(Init)) {
1026 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1027 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1028 "Inst unexpectedly already has DIAssignID attachment");
1029 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1030 }
1031 }
1032
1033 ToReplace->replaceAllUsesWith(Init);
1034 ForwardRefMDNodes.erase(FI);
1035
1036 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1037 } else {
1038 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1039 if (!Inserted)
1040 return tokError("Metadata id is already used");
1041 It->second.reset(Init);
1042 }
1043
1044 return false;
1045}
1046
1047// Skips a single module summary entry.
1048bool LLParser::skipModuleSummaryEntry() {
1049 // Each module summary entry consists of a tag for the entry
1050 // type, followed by a colon, then the fields which may be surrounded by
1051 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1052 // support is in place we will look for the tokens corresponding to the
1053 // expected tags.
1054 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1055 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1056 Lex.getKind() != lltok::kw_blockcount)
1057 return tokError(
1058 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1059 "start of summary entry");
1060 if (Lex.getKind() == lltok::kw_flags)
1061 return parseSummaryIndexFlags();
1062 if (Lex.getKind() == lltok::kw_blockcount)
1063 return parseBlockCount();
1064 Lex.Lex();
1065 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1066 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1067 return true;
1068 // Now walk through the parenthesized entry, until the number of open
1069 // parentheses goes back down to 0 (the first '(' was parsed above).
1070 unsigned NumOpenParen = 1;
1071 do {
1072 switch (Lex.getKind()) {
1073 case lltok::lparen:
1074 NumOpenParen++;
1075 break;
1076 case lltok::rparen:
1077 NumOpenParen--;
1078 break;
1079 case lltok::Eof:
1080 return tokError("found end of file while parsing summary entry");
1081 default:
1082 // Skip everything in between parentheses.
1083 break;
1084 }
1085 Lex.Lex();
1086 } while (NumOpenParen > 0);
1087 return false;
1088}
1089
1090/// SummaryEntry
1091/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1092bool LLParser::parseSummaryEntry() {
1093 assert(Lex.getKind() == lltok::SummaryID);
1094 unsigned SummaryID = Lex.getUIntVal();
1095
1096 // For summary entries, colons should be treated as distinct tokens,
1097 // not an indication of the end of a label token.
1098 Lex.setIgnoreColonInIdentifiers(true);
1099
1100 Lex.Lex();
1101 if (parseToken(lltok::equal, "expected '=' here"))
1102 return true;
1103
1104 // If we don't have an index object, skip the summary entry.
1105 if (!Index)
1106 return skipModuleSummaryEntry();
1107
1108 bool result = false;
1109 switch (Lex.getKind()) {
1110 case lltok::kw_gv:
1111 result = parseGVEntry(SummaryID);
1112 break;
1113 case lltok::kw_module:
1114 result = parseModuleEntry(SummaryID);
1115 break;
1116 case lltok::kw_typeid:
1117 result = parseTypeIdEntry(SummaryID);
1118 break;
1120 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1121 break;
1122 case lltok::kw_flags:
1123 result = parseSummaryIndexFlags();
1124 break;
1126 result = parseBlockCount();
1127 break;
1128 default:
1129 result = error(Lex.getLoc(), "unexpected summary kind");
1130 break;
1131 }
1132 Lex.setIgnoreColonInIdentifiers(false);
1133 return result;
1134}
1135
1144
1145// If there was an explicit dso_local, update GV. In the absence of an explicit
1146// dso_local we keep the default value.
1147static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1148 if (DSOLocal)
1149 GV.setDSOLocal(true);
1150}
1151
1152/// parseAliasOrIFunc:
1153/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1154/// OptionalVisibility OptionalDLLStorageClass
1155/// OptionalThreadLocal OptionalUnnamedAddr
1156/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1157///
1158/// AliaseeOrResolver
1159/// ::= TypeAndValue
1160///
1161/// SymbolAttrs
1162/// ::= ',' 'partition' StringConstant
1163///
1164/// Everything through OptionalUnnamedAddr has already been parsed.
1165///
1166bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1167 LocTy NameLoc, unsigned L, unsigned Visibility,
1168 unsigned DLLStorageClass, bool DSOLocal,
1170 GlobalVariable::UnnamedAddr UnnamedAddr) {
1171 bool IsAlias;
1172 if (Lex.getKind() == lltok::kw_alias)
1173 IsAlias = true;
1174 else if (Lex.getKind() == lltok::kw_ifunc)
1175 IsAlias = false;
1176 else
1177 llvm_unreachable("Not an alias or ifunc!");
1178 Lex.Lex();
1179
1181
1182 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1183 return error(NameLoc, "invalid linkage type for alias");
1184
1185 if (!isValidVisibilityForLinkage(Visibility, L))
1186 return error(NameLoc,
1187 "symbol with local linkage must have default visibility");
1188
1189 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1190 return error(NameLoc,
1191 "symbol with local linkage cannot have a DLL storage class");
1192
1193 Type *Ty;
1194 LocTy ExplicitTypeLoc = Lex.getLoc();
1195 if (parseType(Ty) ||
1196 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1197 return true;
1198
1199 Constant *Aliasee;
1200 LocTy AliaseeLoc = Lex.getLoc();
1201 if (Lex.getKind() != lltok::kw_bitcast &&
1202 Lex.getKind() != lltok::kw_getelementptr &&
1203 Lex.getKind() != lltok::kw_addrspacecast &&
1204 Lex.getKind() != lltok::kw_inttoptr) {
1205 if (parseGlobalTypeAndValue(Aliasee))
1206 return true;
1207 } else {
1208 // The bitcast dest type is not present, it is implied by the dest type.
1209 ValID ID;
1210 if (parseValID(ID, /*PFS=*/nullptr))
1211 return true;
1212 if (ID.Kind != ValID::t_Constant)
1213 return error(AliaseeLoc, "invalid aliasee");
1214 Aliasee = ID.ConstantVal;
1215 }
1216
1217 Type *AliaseeType = Aliasee->getType();
1218 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1219 if (!PTy)
1220 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1221 unsigned AddrSpace = PTy->getAddressSpace();
1222
1223 GlobalValue *GVal = nullptr;
1224
1225 // See if the alias was forward referenced, if so, prepare to replace the
1226 // forward reference.
1227 if (!Name.empty()) {
1228 auto I = ForwardRefVals.find(Name);
1229 if (I != ForwardRefVals.end()) {
1230 GVal = I->second.first;
1231 ForwardRefVals.erase(Name);
1232 } else if (M->getNamedValue(Name)) {
1233 return error(NameLoc, "redefinition of global '@" + Name + "'");
1234 }
1235 } else {
1236 auto I = ForwardRefValIDs.find(NameID);
1237 if (I != ForwardRefValIDs.end()) {
1238 GVal = I->second.first;
1239 ForwardRefValIDs.erase(I);
1240 }
1241 }
1242
1243 // Okay, create the alias/ifunc but do not insert it into the module yet.
1244 std::unique_ptr<GlobalAlias> GA;
1245 std::unique_ptr<GlobalIFunc> GI;
1246 GlobalValue *GV;
1247 if (IsAlias) {
1248 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1249 /*Parent=*/nullptr));
1250 GV = GA.get();
1251 } else {
1252 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1253 /*Parent=*/nullptr));
1254 GV = GI.get();
1255 }
1256 GV->setThreadLocalMode(TLM);
1259 GV->setUnnamedAddr(UnnamedAddr);
1260 maybeSetDSOLocal(DSOLocal, *GV);
1261
1262 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1263 // Now parse them if there are any.
1264 while (Lex.getKind() == lltok::comma) {
1265 Lex.Lex();
1266
1267 if (Lex.getKind() == lltok::kw_partition) {
1268 Lex.Lex();
1269 GV->setPartition(Lex.getStrVal());
1270 if (parseToken(lltok::StringConstant, "expected partition string"))
1271 return true;
1272 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1273 if (parseGlobalObjectMetadataAttachment(*GI.get()))
1274 return true;
1275 } else {
1276 return tokError("unknown alias or ifunc property!");
1277 }
1278 }
1279
1280 if (Name.empty())
1281 NumberedVals.add(NameID, GV);
1282
1283 if (GVal) {
1284 // Verify that types agree.
1285 if (GVal->getType() != GV->getType())
1286 return error(
1287 ExplicitTypeLoc,
1288 "forward reference and definition of alias have different types");
1289
1290 // If they agree, just RAUW the old value with the alias and remove the
1291 // forward ref info.
1292 GVal->replaceAllUsesWith(GV);
1293 GVal->eraseFromParent();
1294 }
1295
1296 // Insert into the module, we know its name won't collide now.
1297 if (IsAlias)
1298 M->insertAlias(GA.release());
1299 else
1300 M->insertIFunc(GI.release());
1301 assert(GV->getName() == Name && "Should not be a name conflict!");
1302
1303 return false;
1304}
1305
1306static bool isSanitizer(lltok::Kind Kind) {
1307 switch (Kind) {
1310 case lltok::kw_sanitize_memtag:
1312 return true;
1313 default:
1314 return false;
1315 }
1316}
1317
1318bool LLParser::parseSanitizer(GlobalVariable *GV) {
1319 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1321 if (GV->hasSanitizerMetadata())
1322 Meta = GV->getSanitizerMetadata();
1323
1324 switch (Lex.getKind()) {
1326 Meta.NoAddress = true;
1327 break;
1329 Meta.NoHWAddress = true;
1330 break;
1331 case lltok::kw_sanitize_memtag:
1332 Meta.Memtag = true;
1333 break;
1335 Meta.IsDynInit = true;
1336 break;
1337 default:
1338 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1339 }
1340 GV->setSanitizerMetadata(Meta);
1341 Lex.Lex();
1342 return false;
1343}
1344
1345/// parseGlobal
1346/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1347/// OptionalVisibility OptionalDLLStorageClass
1348/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1349/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1350/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1351/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1352/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1353/// Const OptionalAttrs
1354///
1355/// Everything up to and including OptionalUnnamedAddr has been parsed
1356/// already.
1357///
1358bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1359 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1360 unsigned Visibility, unsigned DLLStorageClass,
1361 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1362 GlobalVariable::UnnamedAddr UnnamedAddr) {
1363 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1364 return error(NameLoc,
1365 "symbol with local linkage must have default visibility");
1366
1367 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1368 return error(NameLoc,
1369 "symbol with local linkage cannot have a DLL storage class");
1370
1371 unsigned AddrSpace;
1372 bool IsConstant, IsExternallyInitialized;
1373 LocTy IsExternallyInitializedLoc;
1374 LocTy TyLoc;
1375
1376 Type *Ty = nullptr;
1377 if (parseOptionalAddrSpace(AddrSpace) ||
1378 parseOptionalToken(lltok::kw_externally_initialized,
1379 IsExternallyInitialized,
1380 &IsExternallyInitializedLoc) ||
1381 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1382 return true;
1383
1384 // If the linkage is specified and is external, then no initializer is
1385 // present.
1386 Constant *Init = nullptr;
1387 if (!HasLinkage ||
1390 if (parseGlobalValue(Ty, Init))
1391 return true;
1392 }
1393
1395 return error(TyLoc, "invalid type for global variable");
1396
1397 GlobalValue *GVal = nullptr;
1398
1399 // See if the global was forward referenced, if so, use the global.
1400 if (!Name.empty()) {
1401 auto I = ForwardRefVals.find(Name);
1402 if (I != ForwardRefVals.end()) {
1403 GVal = I->second.first;
1404 ForwardRefVals.erase(I);
1405 } else if (M->getNamedValue(Name)) {
1406 return error(NameLoc, "redefinition of global '@" + Name + "'");
1407 }
1408 } else {
1409 // Handle @"", where a name is syntactically specified, but semantically
1410 // missing.
1411 if (NameID == (unsigned)-1)
1412 NameID = NumberedVals.getNext();
1413
1414 auto I = ForwardRefValIDs.find(NameID);
1415 if (I != ForwardRefValIDs.end()) {
1416 GVal = I->second.first;
1417 ForwardRefValIDs.erase(I);
1418 }
1419 }
1420
1421 GlobalVariable *GV = new GlobalVariable(
1422 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1424
1425 if (Name.empty())
1426 NumberedVals.add(NameID, GV);
1427
1428 // Set the parsed properties on the global.
1429 if (Init)
1430 GV->setInitializer(Init);
1431 GV->setConstant(IsConstant);
1433 maybeSetDSOLocal(DSOLocal, *GV);
1436 GV->setExternallyInitialized(IsExternallyInitialized);
1437 GV->setThreadLocalMode(TLM);
1438 GV->setUnnamedAddr(UnnamedAddr);
1439
1440 if (GVal) {
1441 if (GVal->getAddressSpace() != AddrSpace)
1442 return error(
1443 TyLoc,
1444 "forward reference and definition of global have different types");
1445
1446 GVal->replaceAllUsesWith(GV);
1447 GVal->eraseFromParent();
1448 }
1449
1450 // parse attributes on the global.
1451 while (Lex.getKind() == lltok::comma) {
1452 Lex.Lex();
1453
1454 if (Lex.getKind() == lltok::kw_section) {
1455 Lex.Lex();
1456 GV->setSection(Lex.getStrVal());
1457 if (parseToken(lltok::StringConstant, "expected global section string"))
1458 return true;
1459 } else if (Lex.getKind() == lltok::kw_partition) {
1460 Lex.Lex();
1461 GV->setPartition(Lex.getStrVal());
1462 if (parseToken(lltok::StringConstant, "expected partition string"))
1463 return true;
1464 } else if (Lex.getKind() == lltok::kw_align) {
1465 MaybeAlign Alignment;
1466 if (parseOptionalAlignment(Alignment))
1467 return true;
1468 if (Alignment)
1469 GV->setAlignment(*Alignment);
1470 } else if (Lex.getKind() == lltok::kw_code_model) {
1472 if (parseOptionalCodeModel(CodeModel))
1473 return true;
1474 GV->setCodeModel(CodeModel);
1475 } else if (Lex.getKind() == lltok::MetadataVar) {
1476 if (parseGlobalObjectMetadataAttachment(*GV))
1477 return true;
1478 } else if (isSanitizer(Lex.getKind())) {
1479 if (parseSanitizer(GV))
1480 return true;
1481 } else {
1482 Comdat *C;
1483 if (parseOptionalComdat(Name, C))
1484 return true;
1485 if (C)
1486 GV->setComdat(C);
1487 else
1488 return tokError("unknown global variable property!");
1489 }
1490 }
1491
1492 AttrBuilder Attrs(M->getContext());
1493 LocTy BuiltinLoc;
1494 std::vector<unsigned> FwdRefAttrGrps;
1495 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1496 return true;
1497 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1498 GV->setAttributes(AttributeSet::get(Context, Attrs));
1499 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1500 }
1501
1502 return false;
1503}
1504
1505/// parseUnnamedAttrGrp
1506/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1507bool LLParser::parseUnnamedAttrGrp() {
1508 assert(Lex.getKind() == lltok::kw_attributes);
1509 LocTy AttrGrpLoc = Lex.getLoc();
1510 Lex.Lex();
1511
1512 if (Lex.getKind() != lltok::AttrGrpID)
1513 return tokError("expected attribute group id");
1514
1515 unsigned VarID = Lex.getUIntVal();
1516 std::vector<unsigned> unused;
1517 LocTy BuiltinLoc;
1518 Lex.Lex();
1519
1520 if (parseToken(lltok::equal, "expected '=' here") ||
1521 parseToken(lltok::lbrace, "expected '{' here"))
1522 return true;
1523
1524 auto R = NumberedAttrBuilders.find(VarID);
1525 if (R == NumberedAttrBuilders.end())
1526 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1527
1528 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1529 parseToken(lltok::rbrace, "expected end of attribute group"))
1530 return true;
1531
1532 if (!R->second.hasAttributes())
1533 return error(AttrGrpLoc, "attribute group has no attributes");
1534
1535 return false;
1536}
1537
1539 switch (Kind) {
1540#define GET_ATTR_NAMES
1541#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1542 case lltok::kw_##DISPLAY_NAME: \
1543 return Attribute::ENUM_NAME;
1544#include "llvm/IR/Attributes.inc"
1545 default:
1546 return Attribute::None;
1547 }
1548}
1549
1550bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1551 bool InAttrGroup) {
1552 if (Attribute::isTypeAttrKind(Attr))
1553 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1554
1555 switch (Attr) {
1556 case Attribute::Alignment: {
1557 MaybeAlign Alignment;
1558 if (InAttrGroup) {
1559 uint32_t Value = 0;
1560 Lex.Lex();
1561 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1562 return true;
1563 Alignment = Align(Value);
1564 } else {
1565 if (parseOptionalAlignment(Alignment, true))
1566 return true;
1567 }
1568 B.addAlignmentAttr(Alignment);
1569 return false;
1570 }
1571 case Attribute::StackAlignment: {
1572 unsigned Alignment;
1573 if (InAttrGroup) {
1574 Lex.Lex();
1575 if (parseToken(lltok::equal, "expected '=' here") ||
1576 parseUInt32(Alignment))
1577 return true;
1578 } else {
1579 if (parseOptionalStackAlignment(Alignment))
1580 return true;
1581 }
1582 B.addStackAlignmentAttr(Alignment);
1583 return false;
1584 }
1585 case Attribute::AllocSize: {
1586 unsigned ElemSizeArg;
1587 std::optional<unsigned> NumElemsArg;
1588 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1589 return true;
1590 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1591 return false;
1592 }
1593 case Attribute::VScaleRange: {
1594 unsigned MinValue, MaxValue;
1595 if (parseVScaleRangeArguments(MinValue, MaxValue))
1596 return true;
1597 B.addVScaleRangeAttr(MinValue,
1598 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1599 return false;
1600 }
1601 case Attribute::Dereferenceable: {
1602 uint64_t Bytes;
1603 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1604 return true;
1605 B.addDereferenceableAttr(Bytes);
1606 return false;
1607 }
1608 case Attribute::DereferenceableOrNull: {
1609 uint64_t Bytes;
1610 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1611 return true;
1612 B.addDereferenceableOrNullAttr(Bytes);
1613 return false;
1614 }
1615 case Attribute::UWTable: {
1617 if (parseOptionalUWTableKind(Kind))
1618 return true;
1619 B.addUWTableAttr(Kind);
1620 return false;
1621 }
1622 case Attribute::AllocKind: {
1624 if (parseAllocKind(Kind))
1625 return true;
1626 B.addAllocKindAttr(Kind);
1627 return false;
1628 }
1629 case Attribute::Memory: {
1630 std::optional<MemoryEffects> ME = parseMemoryAttr();
1631 if (!ME)
1632 return true;
1633 B.addMemoryAttr(*ME);
1634 return false;
1635 }
1636 case Attribute::NoFPClass: {
1637 if (FPClassTest NoFPClass =
1638 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1639 B.addNoFPClassAttr(NoFPClass);
1640 return false;
1641 }
1642
1643 return true;
1644 }
1645 case Attribute::Range:
1646 return parseRangeAttr(B);
1647 case Attribute::Initializes:
1648 return parseInitializesAttr(B);
1649 case Attribute::Captures:
1650 return parseCapturesAttr(B);
1651 default:
1652 B.addAttribute(Attr);
1653 Lex.Lex();
1654 return false;
1655 }
1656}
1657
1659 switch (Kind) {
1660 case lltok::kw_readnone:
1661 ME &= MemoryEffects::none();
1662 return true;
1663 case lltok::kw_readonly:
1665 return true;
1666 case lltok::kw_writeonly:
1668 return true;
1671 return true;
1674 return true;
1677 return true;
1678 default:
1679 return false;
1680 }
1681}
1682
1683/// parseFnAttributeValuePairs
1684/// ::= <attr> | <attr> '=' <value>
1685bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1686 std::vector<unsigned> &FwdRefAttrGrps,
1687 bool InAttrGrp, LocTy &BuiltinLoc) {
1688 bool HaveError = false;
1689
1690 B.clear();
1691
1693 while (true) {
1694 lltok::Kind Token = Lex.getKind();
1695 if (Token == lltok::rbrace)
1696 break; // Finished.
1697
1698 if (Token == lltok::StringConstant) {
1699 if (parseStringAttribute(B))
1700 return true;
1701 continue;
1702 }
1703
1704 if (Token == lltok::AttrGrpID) {
1705 // Allow a function to reference an attribute group:
1706 //
1707 // define void @foo() #1 { ... }
1708 if (InAttrGrp) {
1709 HaveError |= error(
1710 Lex.getLoc(),
1711 "cannot have an attribute group reference in an attribute group");
1712 } else {
1713 // Save the reference to the attribute group. We'll fill it in later.
1714 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1715 }
1716 Lex.Lex();
1717 continue;
1718 }
1719
1720 SMLoc Loc = Lex.getLoc();
1721 if (Token == lltok::kw_builtin)
1722 BuiltinLoc = Loc;
1723
1724 if (upgradeMemoryAttr(ME, Token)) {
1725 Lex.Lex();
1726 continue;
1727 }
1728
1730 if (Attr == Attribute::None) {
1731 if (!InAttrGrp)
1732 break;
1733 return error(Lex.getLoc(), "unterminated attribute group");
1734 }
1735
1736 if (parseEnumAttribute(Attr, B, InAttrGrp))
1737 return true;
1738
1739 // As a hack, we allow function alignment to be initially parsed as an
1740 // attribute on a function declaration/definition or added to an attribute
1741 // group and later moved to the alignment field.
1742 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1743 HaveError |= error(Loc, "this attribute does not apply to functions");
1744 }
1745
1746 if (ME != MemoryEffects::unknown())
1747 B.addMemoryAttr(ME);
1748 return HaveError;
1749}
1750
1751//===----------------------------------------------------------------------===//
1752// GlobalValue Reference/Resolution Routines.
1753//===----------------------------------------------------------------------===//
1754
1756 // The used global type does not matter. We will later RAUW it with a
1757 // global/function of the correct type.
1758 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1761 PTy->getAddressSpace());
1762}
1763
1764Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1765 Value *Val) {
1766 Type *ValTy = Val->getType();
1767 if (ValTy == Ty)
1768 return Val;
1769 if (Ty->isLabelTy())
1770 error(Loc, "'" + Name + "' is not a basic block");
1771 else
1772 error(Loc, "'" + Name + "' defined with type '" +
1773 getTypeString(Val->getType()) + "' but expected '" +
1774 getTypeString(Ty) + "'");
1775 return nullptr;
1776}
1777
1778/// getGlobalVal - Get a value with the specified name or ID, creating a
1779/// forward reference record if needed. This can return null if the value
1780/// exists but does not have the right type.
1781GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1782 LocTy Loc) {
1784 if (!PTy) {
1785 error(Loc, "global variable reference must have pointer type");
1786 return nullptr;
1787 }
1788
1789 // Look this name up in the normal function symbol table.
1790 GlobalValue *Val =
1791 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1792
1793 // If this is a forward reference for the value, see if we already created a
1794 // forward ref record.
1795 if (!Val) {
1796 auto I = ForwardRefVals.find(Name);
1797 if (I != ForwardRefVals.end())
1798 Val = I->second.first;
1799 }
1800
1801 // If we have the value in the symbol table or fwd-ref table, return it.
1802 if (Val)
1804 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1805
1806 // Otherwise, create a new forward reference for this value and remember it.
1807 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1808 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1809 return FwdVal;
1810}
1811
1812GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1814 if (!PTy) {
1815 error(Loc, "global variable reference must have pointer type");
1816 return nullptr;
1817 }
1818
1819 GlobalValue *Val = NumberedVals.get(ID);
1820
1821 // If this is a forward reference for the value, see if we already created a
1822 // forward ref record.
1823 if (!Val) {
1824 auto I = ForwardRefValIDs.find(ID);
1825 if (I != ForwardRefValIDs.end())
1826 Val = I->second.first;
1827 }
1828
1829 // If we have the value in the symbol table or fwd-ref table, return it.
1830 if (Val)
1832 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1833
1834 // Otherwise, create a new forward reference for this value and remember it.
1835 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1836 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1837 return FwdVal;
1838}
1839
1840//===----------------------------------------------------------------------===//
1841// Comdat Reference/Resolution Routines.
1842//===----------------------------------------------------------------------===//
1843
1844Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1845 // Look this name up in the comdat symbol table.
1846 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1847 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1848 if (I != ComdatSymTab.end())
1849 return &I->second;
1850
1851 // Otherwise, create a new forward reference for this value and remember it.
1852 Comdat *C = M->getOrInsertComdat(Name);
1853 ForwardRefComdats[Name] = Loc;
1854 return C;
1855}
1856
1857//===----------------------------------------------------------------------===//
1858// Helper Routines.
1859//===----------------------------------------------------------------------===//
1860
1861/// parseToken - If the current token has the specified kind, eat it and return
1862/// success. Otherwise, emit the specified error and return failure.
1863bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1864 if (Lex.getKind() != T)
1865 return tokError(ErrMsg);
1866 Lex.Lex();
1867 return false;
1868}
1869
1870/// parseStringConstant
1871/// ::= StringConstant
1872bool LLParser::parseStringConstant(std::string &Result) {
1873 if (Lex.getKind() != lltok::StringConstant)
1874 return tokError("expected string constant");
1875 Result = Lex.getStrVal();
1876 Lex.Lex();
1877 return false;
1878}
1879
1880/// parseUInt32
1881/// ::= uint32
1882bool LLParser::parseUInt32(uint32_t &Val) {
1883 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1884 return tokError("expected integer");
1885 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1886 if (Val64 != unsigned(Val64))
1887 return tokError("expected 32-bit integer (too large)");
1888 Val = Val64;
1889 Lex.Lex();
1890 return false;
1891}
1892
1893/// parseUInt64
1894/// ::= uint64
1895bool LLParser::parseUInt64(uint64_t &Val) {
1896 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1897 return tokError("expected integer");
1898 Val = Lex.getAPSIntVal().getLimitedValue();
1899 Lex.Lex();
1900 return false;
1901}
1902
1903/// parseTLSModel
1904/// := 'localdynamic'
1905/// := 'initialexec'
1906/// := 'localexec'
1907bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1908 switch (Lex.getKind()) {
1909 default:
1910 return tokError("expected localdynamic, initialexec or localexec");
1913 break;
1916 break;
1919 break;
1920 }
1921
1922 Lex.Lex();
1923 return false;
1924}
1925
1926/// parseOptionalThreadLocal
1927/// := /*empty*/
1928/// := 'thread_local'
1929/// := 'thread_local' '(' tlsmodel ')'
1930bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1932 if (!EatIfPresent(lltok::kw_thread_local))
1933 return false;
1934
1936 if (Lex.getKind() == lltok::lparen) {
1937 Lex.Lex();
1938 return parseTLSModel(TLM) ||
1939 parseToken(lltok::rparen, "expected ')' after thread local model");
1940 }
1941 return false;
1942}
1943
1944/// parseOptionalAddrSpace
1945/// := /*empty*/
1946/// := 'addrspace' '(' uint32 ')'
1947bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1948 AddrSpace = DefaultAS;
1949 if (!EatIfPresent(lltok::kw_addrspace))
1950 return false;
1951
1952 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1953 if (Lex.getKind() == lltok::StringConstant) {
1954 auto AddrSpaceStr = Lex.getStrVal();
1955 if (AddrSpaceStr == "A") {
1956 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1957 } else if (AddrSpaceStr == "G") {
1958 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1959 } else if (AddrSpaceStr == "P") {
1960 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1961 } else {
1962 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1963 }
1964 Lex.Lex();
1965 return false;
1966 }
1967 if (Lex.getKind() != lltok::APSInt)
1968 return tokError("expected integer or string constant");
1969 SMLoc Loc = Lex.getLoc();
1970 if (parseUInt32(AddrSpace))
1971 return true;
1972 if (!isUInt<24>(AddrSpace))
1973 return error(Loc, "invalid address space, must be a 24-bit integer");
1974 return false;
1975 };
1976
1977 return parseToken(lltok::lparen, "expected '(' in address space") ||
1978 ParseAddrspaceValue(AddrSpace) ||
1979 parseToken(lltok::rparen, "expected ')' in address space");
1980}
1981
1982/// parseStringAttribute
1983/// := StringConstant
1984/// := StringConstant '=' StringConstant
1985bool LLParser::parseStringAttribute(AttrBuilder &B) {
1986 std::string Attr = Lex.getStrVal();
1987 Lex.Lex();
1988 std::string Val;
1989 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1990 return true;
1991 B.addAttribute(Attr, Val);
1992 return false;
1993}
1994
1995/// Parse a potentially empty list of parameter or return attributes.
1996bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1997 bool HaveError = false;
1998
1999 B.clear();
2000
2001 while (true) {
2002 lltok::Kind Token = Lex.getKind();
2003 if (Token == lltok::StringConstant) {
2004 if (parseStringAttribute(B))
2005 return true;
2006 continue;
2007 }
2008
2009 if (Token == lltok::kw_nocapture) {
2010 Lex.Lex();
2011 B.addCapturesAttr(CaptureInfo::none());
2012 continue;
2013 }
2014
2015 SMLoc Loc = Lex.getLoc();
2017 if (Attr == Attribute::None)
2018 return HaveError;
2019
2020 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2021 return true;
2022
2023 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2024 HaveError |= error(Loc, "this attribute does not apply to parameters");
2025 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2026 HaveError |= error(Loc, "this attribute does not apply to return values");
2027 }
2028}
2029
2030static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2031 HasLinkage = true;
2032 switch (Kind) {
2033 default:
2034 HasLinkage = false;
2036 case lltok::kw_private:
2038 case lltok::kw_internal:
2040 case lltok::kw_weak:
2042 case lltok::kw_weak_odr:
2044 case lltok::kw_linkonce:
2052 case lltok::kw_common:
2056 case lltok::kw_external:
2058 }
2059}
2060
2061/// parseOptionalLinkage
2062/// ::= /*empty*/
2063/// ::= 'private'
2064/// ::= 'internal'
2065/// ::= 'weak'
2066/// ::= 'weak_odr'
2067/// ::= 'linkonce'
2068/// ::= 'linkonce_odr'
2069/// ::= 'available_externally'
2070/// ::= 'appending'
2071/// ::= 'common'
2072/// ::= 'extern_weak'
2073/// ::= 'external'
2074bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2075 unsigned &Visibility,
2076 unsigned &DLLStorageClass, bool &DSOLocal) {
2077 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2078 if (HasLinkage)
2079 Lex.Lex();
2080 parseOptionalDSOLocal(DSOLocal);
2081 parseOptionalVisibility(Visibility);
2082 parseOptionalDLLStorageClass(DLLStorageClass);
2083
2084 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2085 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2086 }
2087
2088 return false;
2089}
2090
2091void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2092 switch (Lex.getKind()) {
2093 default:
2094 DSOLocal = false;
2095 break;
2097 DSOLocal = true;
2098 Lex.Lex();
2099 break;
2101 DSOLocal = false;
2102 Lex.Lex();
2103 break;
2104 }
2105}
2106
2107/// parseOptionalVisibility
2108/// ::= /*empty*/
2109/// ::= 'default'
2110/// ::= 'hidden'
2111/// ::= 'protected'
2112///
2113void LLParser::parseOptionalVisibility(unsigned &Res) {
2114 switch (Lex.getKind()) {
2115 default:
2117 return;
2118 case lltok::kw_default:
2120 break;
2121 case lltok::kw_hidden:
2123 break;
2126 break;
2127 }
2128 Lex.Lex();
2129}
2130
2131bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2133 switch (Kind) {
2134 default:
2135 return tokError("unknown import kind. Expect definition or declaration.");
2138 return false;
2141 return false;
2142 }
2143}
2144
2145/// parseOptionalDLLStorageClass
2146/// ::= /*empty*/
2147/// ::= 'dllimport'
2148/// ::= 'dllexport'
2149///
2150void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2151 switch (Lex.getKind()) {
2152 default:
2154 return;
2157 break;
2160 break;
2161 }
2162 Lex.Lex();
2163}
2164
2165/// parseOptionalCallingConv
2166/// ::= /*empty*/
2167/// ::= 'ccc'
2168/// ::= 'fastcc'
2169/// ::= 'intel_ocl_bicc'
2170/// ::= 'coldcc'
2171/// ::= 'cfguard_checkcc'
2172/// ::= 'x86_stdcallcc'
2173/// ::= 'x86_fastcallcc'
2174/// ::= 'x86_thiscallcc'
2175/// ::= 'x86_vectorcallcc'
2176/// ::= 'arm_apcscc'
2177/// ::= 'arm_aapcscc'
2178/// ::= 'arm_aapcs_vfpcc'
2179/// ::= 'aarch64_vector_pcs'
2180/// ::= 'aarch64_sve_vector_pcs'
2181/// ::= 'aarch64_sme_preservemost_from_x0'
2182/// ::= 'aarch64_sme_preservemost_from_x1'
2183/// ::= 'aarch64_sme_preservemost_from_x2'
2184/// ::= 'msp430_intrcc'
2185/// ::= 'avr_intrcc'
2186/// ::= 'avr_signalcc'
2187/// ::= 'ptx_kernel'
2188/// ::= 'ptx_device'
2189/// ::= 'spir_func'
2190/// ::= 'spir_kernel'
2191/// ::= 'x86_64_sysvcc'
2192/// ::= 'win64cc'
2193/// ::= 'anyregcc'
2194/// ::= 'preserve_mostcc'
2195/// ::= 'preserve_allcc'
2196/// ::= 'preserve_nonecc'
2197/// ::= 'ghccc'
2198/// ::= 'swiftcc'
2199/// ::= 'swifttailcc'
2200/// ::= 'x86_intrcc'
2201/// ::= 'hhvmcc'
2202/// ::= 'hhvm_ccc'
2203/// ::= 'cxx_fast_tlscc'
2204/// ::= 'amdgpu_vs'
2205/// ::= 'amdgpu_ls'
2206/// ::= 'amdgpu_hs'
2207/// ::= 'amdgpu_es'
2208/// ::= 'amdgpu_gs'
2209/// ::= 'amdgpu_ps'
2210/// ::= 'amdgpu_cs'
2211/// ::= 'amdgpu_cs_chain'
2212/// ::= 'amdgpu_cs_chain_preserve'
2213/// ::= 'amdgpu_kernel'
2214/// ::= 'tailcc'
2215/// ::= 'm68k_rtdcc'
2216/// ::= 'graalcc'
2217/// ::= 'riscv_vector_cc'
2218/// ::= 'riscv_vls_cc'
2219/// ::= 'cc' UINT
2220///
2221bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2222 switch (Lex.getKind()) {
2223 default: CC = CallingConv::C; return false;
2224 case lltok::kw_ccc: CC = CallingConv::C; break;
2225 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2226 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2239 break;
2242 break;
2245 break;
2248 break;
2258 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2259 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2263 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2264 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2267 case lltok::kw_hhvmcc:
2269 break;
2270 case lltok::kw_hhvm_ccc:
2272 break;
2284 break;
2287 break;
2291 break;
2292 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2294 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2297 break;
2299 // Default ABI_VLEN
2301 Lex.Lex();
2302 if (!EatIfPresent(lltok::lparen))
2303 break;
2304 uint32_t ABIVlen;
2305 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2306 return true;
2307 switch (ABIVlen) {
2308 default:
2309 return tokError("unknown RISC-V ABI VLEN");
2310#define CC_VLS_CASE(ABIVlen) \
2311 case ABIVlen: \
2312 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2313 break;
2314 CC_VLS_CASE(32)
2315 CC_VLS_CASE(64)
2316 CC_VLS_CASE(128)
2317 CC_VLS_CASE(256)
2318 CC_VLS_CASE(512)
2319 CC_VLS_CASE(1024)
2320 CC_VLS_CASE(2048)
2321 CC_VLS_CASE(4096)
2322 CC_VLS_CASE(8192)
2323 CC_VLS_CASE(16384)
2324 CC_VLS_CASE(32768)
2325 CC_VLS_CASE(65536)
2326#undef CC_VLS_CASE
2327 }
2328 return false;
2331 break;
2334 break;
2337 break;
2338 case lltok::kw_cc: {
2339 Lex.Lex();
2340 return parseUInt32(CC);
2341 }
2342 }
2343
2344 Lex.Lex();
2345 return false;
2346}
2347
2348/// parseMetadataAttachment
2349/// ::= !dbg !42
2350bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2351 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2352
2353 std::string Name = Lex.getStrVal();
2354 Kind = M->getMDKindID(Name);
2355 Lex.Lex();
2356
2357 return parseMDNode(MD);
2358}
2359
2360/// parseInstructionMetadata
2361/// ::= !dbg !42 (',' !dbg !57)*
2362bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2363 do {
2364 if (Lex.getKind() != lltok::MetadataVar)
2365 return tokError("expected metadata after comma");
2366
2367 unsigned MDK;
2368 MDNode *N;
2369 if (parseMetadataAttachment(MDK, N))
2370 return true;
2371
2372 if (MDK == LLVMContext::MD_DIAssignID)
2373 TempDIAssignIDAttachments[N].push_back(&Inst);
2374 else
2375 Inst.setMetadata(MDK, N);
2376
2377 if (MDK == LLVMContext::MD_tbaa)
2378 InstsWithTBAATag.push_back(&Inst);
2379
2380 // If this is the end of the list, we're done.
2381 } while (EatIfPresent(lltok::comma));
2382 return false;
2383}
2384
2385/// parseGlobalObjectMetadataAttachment
2386/// ::= !dbg !57
2387bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2388 unsigned MDK;
2389 MDNode *N;
2390 if (parseMetadataAttachment(MDK, N))
2391 return true;
2392
2393 GO.addMetadata(MDK, *N);
2394 return false;
2395}
2396
2397/// parseOptionalFunctionMetadata
2398/// ::= (!dbg !57)*
2399bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2400 while (Lex.getKind() == lltok::MetadataVar)
2401 if (parseGlobalObjectMetadataAttachment(F))
2402 return true;
2403 return false;
2404}
2405
2406/// parseOptionalAlignment
2407/// ::= /* empty */
2408/// ::= 'align' 4
2409bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2410 Alignment = std::nullopt;
2411 if (!EatIfPresent(lltok::kw_align))
2412 return false;
2413 LocTy AlignLoc = Lex.getLoc();
2414 uint64_t Value = 0;
2415
2416 LocTy ParenLoc = Lex.getLoc();
2417 bool HaveParens = false;
2418 if (AllowParens) {
2419 if (EatIfPresent(lltok::lparen))
2420 HaveParens = true;
2421 }
2422
2423 if (parseUInt64(Value))
2424 return true;
2425
2426 if (HaveParens && !EatIfPresent(lltok::rparen))
2427 return error(ParenLoc, "expected ')'");
2428
2429 if (!isPowerOf2_64(Value))
2430 return error(AlignLoc, "alignment is not a power of two");
2432 return error(AlignLoc, "huge alignments are not supported yet");
2433 Alignment = Align(Value);
2434 return false;
2435}
2436
2437/// parseOptionalCodeModel
2438/// ::= /* empty */
2439/// ::= 'code_model' "large"
2440bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2441 Lex.Lex();
2442 auto StrVal = Lex.getStrVal();
2443 auto ErrMsg = "expected global code model string";
2444 if (StrVal == "tiny")
2445 model = CodeModel::Tiny;
2446 else if (StrVal == "small")
2447 model = CodeModel::Small;
2448 else if (StrVal == "kernel")
2449 model = CodeModel::Kernel;
2450 else if (StrVal == "medium")
2451 model = CodeModel::Medium;
2452 else if (StrVal == "large")
2453 model = CodeModel::Large;
2454 else
2455 return tokError(ErrMsg);
2456 if (parseToken(lltok::StringConstant, ErrMsg))
2457 return true;
2458 return false;
2459}
2460
2461/// parseOptionalDerefAttrBytes
2462/// ::= /* empty */
2463/// ::= AttrKind '(' 4 ')'
2464///
2465/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2466bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2467 uint64_t &Bytes) {
2468 assert((AttrKind == lltok::kw_dereferenceable ||
2469 AttrKind == lltok::kw_dereferenceable_or_null) &&
2470 "contract!");
2471
2472 Bytes = 0;
2473 if (!EatIfPresent(AttrKind))
2474 return false;
2475 LocTy ParenLoc = Lex.getLoc();
2476 if (!EatIfPresent(lltok::lparen))
2477 return error(ParenLoc, "expected '('");
2478 LocTy DerefLoc = Lex.getLoc();
2479 if (parseUInt64(Bytes))
2480 return true;
2481 ParenLoc = Lex.getLoc();
2482 if (!EatIfPresent(lltok::rparen))
2483 return error(ParenLoc, "expected ')'");
2484 if (!Bytes)
2485 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2486 return false;
2487}
2488
2489bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2490 Lex.Lex();
2492 if (!EatIfPresent(lltok::lparen))
2493 return false;
2494 LocTy KindLoc = Lex.getLoc();
2495 if (Lex.getKind() == lltok::kw_sync)
2497 else if (Lex.getKind() == lltok::kw_async)
2499 else
2500 return error(KindLoc, "expected unwind table kind");
2501 Lex.Lex();
2502 return parseToken(lltok::rparen, "expected ')'");
2503}
2504
2505bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2506 Lex.Lex();
2507 LocTy ParenLoc = Lex.getLoc();
2508 if (!EatIfPresent(lltok::lparen))
2509 return error(ParenLoc, "expected '('");
2510 LocTy KindLoc = Lex.getLoc();
2511 std::string Arg;
2512 if (parseStringConstant(Arg))
2513 return error(KindLoc, "expected allockind value");
2514 for (StringRef A : llvm::split(Arg, ",")) {
2515 if (A == "alloc") {
2517 } else if (A == "realloc") {
2519 } else if (A == "free") {
2521 } else if (A == "uninitialized") {
2523 } else if (A == "zeroed") {
2525 } else if (A == "aligned") {
2527 } else {
2528 return error(KindLoc, Twine("unknown allockind ") + A);
2529 }
2530 }
2531 ParenLoc = Lex.getLoc();
2532 if (!EatIfPresent(lltok::rparen))
2533 return error(ParenLoc, "expected ')'");
2534 if (Kind == AllocFnKind::Unknown)
2535 return error(KindLoc, "expected allockind value");
2536 return false;
2537}
2538
2539static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2540 switch (Tok) {
2541 case lltok::kw_argmem:
2542 return IRMemLocation::ArgMem;
2545 case lltok::kw_errnomem:
2547 default:
2548 return std::nullopt;
2549 }
2550}
2551
2552static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2553 switch (Tok) {
2554 case lltok::kw_none:
2555 return ModRefInfo::NoModRef;
2556 case lltok::kw_read:
2557 return ModRefInfo::Ref;
2558 case lltok::kw_write:
2559 return ModRefInfo::Mod;
2561 return ModRefInfo::ModRef;
2562 default:
2563 return std::nullopt;
2564 }
2565}
2566
2567std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2569
2570 // We use syntax like memory(argmem: read), so the colon should not be
2571 // interpreted as a label terminator.
2572 Lex.setIgnoreColonInIdentifiers(true);
2573 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2574
2575 Lex.Lex();
2576 if (!EatIfPresent(lltok::lparen)) {
2577 tokError("expected '('");
2578 return std::nullopt;
2579 }
2580
2581 bool SeenLoc = false;
2582 do {
2583 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2584 if (Loc) {
2585 Lex.Lex();
2586 if (!EatIfPresent(lltok::colon)) {
2587 tokError("expected ':' after location");
2588 return std::nullopt;
2589 }
2590 }
2591
2592 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2593 if (!MR) {
2594 if (!Loc)
2595 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2596 "or access kind (none, read, write, readwrite)");
2597 else
2598 tokError("expected access kind (none, read, write, readwrite)");
2599 return std::nullopt;
2600 }
2601
2602 Lex.Lex();
2603 if (Loc) {
2604 SeenLoc = true;
2605 ME = ME.getWithModRef(*Loc, *MR);
2606 } else {
2607 if (SeenLoc) {
2608 tokError("default access kind must be specified first");
2609 return std::nullopt;
2610 }
2611 ME = MemoryEffects(*MR);
2612 }
2613
2614 if (EatIfPresent(lltok::rparen))
2615 return ME;
2616 } while (EatIfPresent(lltok::comma));
2617
2618 tokError("unterminated memory attribute");
2619 return std::nullopt;
2620}
2621
2622static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2623 switch (Tok) {
2624 case lltok::kw_all:
2625 return fcAllFlags;
2626 case lltok::kw_nan:
2627 return fcNan;
2628 case lltok::kw_snan:
2629 return fcSNan;
2630 case lltok::kw_qnan:
2631 return fcQNan;
2632 case lltok::kw_inf:
2633 return fcInf;
2634 case lltok::kw_ninf:
2635 return fcNegInf;
2636 case lltok::kw_pinf:
2637 return fcPosInf;
2638 case lltok::kw_norm:
2639 return fcNormal;
2640 case lltok::kw_nnorm:
2641 return fcNegNormal;
2642 case lltok::kw_pnorm:
2643 return fcPosNormal;
2644 case lltok::kw_sub:
2645 return fcSubnormal;
2646 case lltok::kw_nsub:
2647 return fcNegSubnormal;
2648 case lltok::kw_psub:
2649 return fcPosSubnormal;
2650 case lltok::kw_zero:
2651 return fcZero;
2652 case lltok::kw_nzero:
2653 return fcNegZero;
2654 case lltok::kw_pzero:
2655 return fcPosZero;
2656 default:
2657 return 0;
2658 }
2659}
2660
2661unsigned LLParser::parseNoFPClassAttr() {
2662 unsigned Mask = fcNone;
2663
2664 Lex.Lex();
2665 if (!EatIfPresent(lltok::lparen)) {
2666 tokError("expected '('");
2667 return 0;
2668 }
2669
2670 do {
2671 uint64_t Value = 0;
2672 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2673 if (TestMask != 0) {
2674 Mask |= TestMask;
2675 // TODO: Disallow overlapping masks to avoid copy paste errors
2676 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2677 !parseUInt64(Value)) {
2678 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2679 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2680 return 0;
2681 }
2682
2683 if (!EatIfPresent(lltok::rparen)) {
2684 error(Lex.getLoc(), "expected ')'");
2685 return 0;
2686 }
2687
2688 return Value;
2689 } else {
2690 error(Lex.getLoc(), "expected nofpclass test mask");
2691 return 0;
2692 }
2693
2694 Lex.Lex();
2695 if (EatIfPresent(lltok::rparen))
2696 return Mask;
2697 } while (1);
2698
2699 llvm_unreachable("unterminated nofpclass attribute");
2700}
2701
2702/// parseOptionalCommaAlign
2703/// ::=
2704/// ::= ',' align 4
2705///
2706/// This returns with AteExtraComma set to true if it ate an excess comma at the
2707/// end.
2708bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2709 bool &AteExtraComma) {
2710 AteExtraComma = false;
2711 while (EatIfPresent(lltok::comma)) {
2712 // Metadata at the end is an early exit.
2713 if (Lex.getKind() == lltok::MetadataVar) {
2714 AteExtraComma = true;
2715 return false;
2716 }
2717
2718 if (Lex.getKind() != lltok::kw_align)
2719 return error(Lex.getLoc(), "expected metadata or 'align'");
2720
2721 if (parseOptionalAlignment(Alignment))
2722 return true;
2723 }
2724
2725 return false;
2726}
2727
2728/// parseOptionalCommaAddrSpace
2729/// ::=
2730/// ::= ',' addrspace(1)
2731///
2732/// This returns with AteExtraComma set to true if it ate an excess comma at the
2733/// end.
2734bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2735 bool &AteExtraComma) {
2736 AteExtraComma = false;
2737 while (EatIfPresent(lltok::comma)) {
2738 // Metadata at the end is an early exit.
2739 if (Lex.getKind() == lltok::MetadataVar) {
2740 AteExtraComma = true;
2741 return false;
2742 }
2743
2744 Loc = Lex.getLoc();
2745 if (Lex.getKind() != lltok::kw_addrspace)
2746 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2747
2748 if (parseOptionalAddrSpace(AddrSpace))
2749 return true;
2750 }
2751
2752 return false;
2753}
2754
2755bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2756 std::optional<unsigned> &HowManyArg) {
2757 Lex.Lex();
2758
2759 auto StartParen = Lex.getLoc();
2760 if (!EatIfPresent(lltok::lparen))
2761 return error(StartParen, "expected '('");
2762
2763 if (parseUInt32(BaseSizeArg))
2764 return true;
2765
2766 if (EatIfPresent(lltok::comma)) {
2767 auto HowManyAt = Lex.getLoc();
2768 unsigned HowMany;
2769 if (parseUInt32(HowMany))
2770 return true;
2771 if (HowMany == BaseSizeArg)
2772 return error(HowManyAt,
2773 "'allocsize' indices can't refer to the same parameter");
2774 HowManyArg = HowMany;
2775 } else
2776 HowManyArg = std::nullopt;
2777
2778 auto EndParen = Lex.getLoc();
2779 if (!EatIfPresent(lltok::rparen))
2780 return error(EndParen, "expected ')'");
2781 return false;
2782}
2783
2784bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2785 unsigned &MaxValue) {
2786 Lex.Lex();
2787
2788 auto StartParen = Lex.getLoc();
2789 if (!EatIfPresent(lltok::lparen))
2790 return error(StartParen, "expected '('");
2791
2792 if (parseUInt32(MinValue))
2793 return true;
2794
2795 if (EatIfPresent(lltok::comma)) {
2796 if (parseUInt32(MaxValue))
2797 return true;
2798 } else
2799 MaxValue = MinValue;
2800
2801 auto EndParen = Lex.getLoc();
2802 if (!EatIfPresent(lltok::rparen))
2803 return error(EndParen, "expected ')'");
2804 return false;
2805}
2806
2807/// parseScopeAndOrdering
2808/// if isAtomic: ::= SyncScope? AtomicOrdering
2809/// else: ::=
2810///
2811/// This sets Scope and Ordering to the parsed values.
2812bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2813 AtomicOrdering &Ordering) {
2814 if (!IsAtomic)
2815 return false;
2816
2817 return parseScope(SSID) || parseOrdering(Ordering);
2818}
2819
2820/// parseScope
2821/// ::= syncscope("singlethread" | "<target scope>")?
2822///
2823/// This sets synchronization scope ID to the ID of the parsed value.
2824bool LLParser::parseScope(SyncScope::ID &SSID) {
2825 SSID = SyncScope::System;
2826 if (EatIfPresent(lltok::kw_syncscope)) {
2827 auto StartParenAt = Lex.getLoc();
2828 if (!EatIfPresent(lltok::lparen))
2829 return error(StartParenAt, "Expected '(' in syncscope");
2830
2831 std::string SSN;
2832 auto SSNAt = Lex.getLoc();
2833 if (parseStringConstant(SSN))
2834 return error(SSNAt, "Expected synchronization scope name");
2835
2836 auto EndParenAt = Lex.getLoc();
2837 if (!EatIfPresent(lltok::rparen))
2838 return error(EndParenAt, "Expected ')' in syncscope");
2839
2840 SSID = Context.getOrInsertSyncScopeID(SSN);
2841 }
2842
2843 return false;
2844}
2845
2846/// parseOrdering
2847/// ::= AtomicOrdering
2848///
2849/// This sets Ordering to the parsed value.
2850bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2851 switch (Lex.getKind()) {
2852 default:
2853 return tokError("Expected ordering on atomic instruction");
2856 // Not specified yet:
2857 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2861 case lltok::kw_seq_cst:
2863 break;
2864 }
2865 Lex.Lex();
2866 return false;
2867}
2868
2869/// parseOptionalStackAlignment
2870/// ::= /* empty */
2871/// ::= 'alignstack' '(' 4 ')'
2872bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2873 Alignment = 0;
2874 if (!EatIfPresent(lltok::kw_alignstack))
2875 return false;
2876 LocTy ParenLoc = Lex.getLoc();
2877 if (!EatIfPresent(lltok::lparen))
2878 return error(ParenLoc, "expected '('");
2879 LocTy AlignLoc = Lex.getLoc();
2880 if (parseUInt32(Alignment))
2881 return true;
2882 ParenLoc = Lex.getLoc();
2883 if (!EatIfPresent(lltok::rparen))
2884 return error(ParenLoc, "expected ')'");
2885 if (!isPowerOf2_32(Alignment))
2886 return error(AlignLoc, "stack alignment is not a power of two");
2887 return false;
2888}
2889
2890/// parseIndexList - This parses the index list for an insert/extractvalue
2891/// instruction. This sets AteExtraComma in the case where we eat an extra
2892/// comma at the end of the line and find that it is followed by metadata.
2893/// Clients that don't allow metadata can call the version of this function that
2894/// only takes one argument.
2895///
2896/// parseIndexList
2897/// ::= (',' uint32)+
2898///
2899bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2900 bool &AteExtraComma) {
2901 AteExtraComma = false;
2902
2903 if (Lex.getKind() != lltok::comma)
2904 return tokError("expected ',' as start of index list");
2905
2906 while (EatIfPresent(lltok::comma)) {
2907 if (Lex.getKind() == lltok::MetadataVar) {
2908 if (Indices.empty())
2909 return tokError("expected index");
2910 AteExtraComma = true;
2911 return false;
2912 }
2913 unsigned Idx = 0;
2914 if (parseUInt32(Idx))
2915 return true;
2916 Indices.push_back(Idx);
2917 }
2918
2919 return false;
2920}
2921
2922//===----------------------------------------------------------------------===//
2923// Type Parsing.
2924//===----------------------------------------------------------------------===//
2925
2926/// parseType - parse a type.
2927bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2928 SMLoc TypeLoc = Lex.getLoc();
2929 switch (Lex.getKind()) {
2930 default:
2931 return tokError(Msg);
2932 case lltok::Type:
2933 // Type ::= 'float' | 'void' (etc)
2934 Result = Lex.getTyVal();
2935 Lex.Lex();
2936
2937 // Handle "ptr" opaque pointer type.
2938 //
2939 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2940 if (Result->isPointerTy()) {
2941 unsigned AddrSpace;
2942 if (parseOptionalAddrSpace(AddrSpace))
2943 return true;
2944 Result = PointerType::get(getContext(), AddrSpace);
2945
2946 // Give a nice error for 'ptr*'.
2947 if (Lex.getKind() == lltok::star)
2948 return tokError("ptr* is invalid - use ptr instead");
2949
2950 // Fall through to parsing the type suffixes only if this 'ptr' is a
2951 // function return. Otherwise, return success, implicitly rejecting other
2952 // suffixes.
2953 if (Lex.getKind() != lltok::lparen)
2954 return false;
2955 }
2956 break;
2957 case lltok::kw_target: {
2958 // Type ::= TargetExtType
2959 if (parseTargetExtType(Result))
2960 return true;
2961 break;
2962 }
2963 case lltok::lbrace:
2964 // Type ::= StructType
2965 if (parseAnonStructType(Result, false))
2966 return true;
2967 break;
2968 case lltok::lsquare:
2969 // Type ::= '[' ... ']'
2970 Lex.Lex(); // eat the lsquare.
2971 if (parseArrayVectorType(Result, false))
2972 return true;
2973 break;
2974 case lltok::less: // Either vector or packed struct.
2975 // Type ::= '<' ... '>'
2976 Lex.Lex();
2977 if (Lex.getKind() == lltok::lbrace) {
2978 if (parseAnonStructType(Result, true) ||
2979 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2980 return true;
2981 } else if (parseArrayVectorType(Result, true))
2982 return true;
2983 break;
2984 case lltok::LocalVar: {
2985 // Type ::= %foo
2986 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2987
2988 // If the type hasn't been defined yet, create a forward definition and
2989 // remember where that forward def'n was seen (in case it never is defined).
2990 if (!Entry.first) {
2991 Entry.first = StructType::create(Context, Lex.getStrVal());
2992 Entry.second = Lex.getLoc();
2993 }
2994 Result = Entry.first;
2995 Lex.Lex();
2996 break;
2997 }
2998
2999 case lltok::LocalVarID: {
3000 // Type ::= %4
3001 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3002
3003 // If the type hasn't been defined yet, create a forward definition and
3004 // remember where that forward def'n was seen (in case it never is defined).
3005 if (!Entry.first) {
3006 Entry.first = StructType::create(Context);
3007 Entry.second = Lex.getLoc();
3008 }
3009 Result = Entry.first;
3010 Lex.Lex();
3011 break;
3012 }
3013 }
3014
3015 // parse the type suffixes.
3016 while (true) {
3017 switch (Lex.getKind()) {
3018 // End of type.
3019 default:
3020 if (!AllowVoid && Result->isVoidTy())
3021 return error(TypeLoc, "void type only allowed for function results");
3022 return false;
3023
3024 // Type ::= Type '*'
3025 case lltok::star:
3026 if (Result->isLabelTy())
3027 return tokError("basic block pointers are invalid");
3028 if (Result->isVoidTy())
3029 return tokError("pointers to void are invalid - use i8* instead");
3031 return tokError("pointer to this type is invalid");
3032 Result = PointerType::getUnqual(Context);
3033 Lex.Lex();
3034 break;
3035
3036 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3037 case lltok::kw_addrspace: {
3038 if (Result->isLabelTy())
3039 return tokError("basic block pointers are invalid");
3040 if (Result->isVoidTy())
3041 return tokError("pointers to void are invalid; use i8* instead");
3043 return tokError("pointer to this type is invalid");
3044 unsigned AddrSpace;
3045 if (parseOptionalAddrSpace(AddrSpace) ||
3046 parseToken(lltok::star, "expected '*' in address space"))
3047 return true;
3048
3049 Result = PointerType::get(Context, AddrSpace);
3050 break;
3051 }
3052
3053 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3054 case lltok::lparen:
3055 if (parseFunctionType(Result))
3056 return true;
3057 break;
3058 }
3059 }
3060}
3061
3062/// parseParameterList
3063/// ::= '(' ')'
3064/// ::= '(' Arg (',' Arg)* ')'
3065/// Arg
3066/// ::= Type OptionalAttributes Value OptionalAttributes
3067bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3068 PerFunctionState &PFS, bool IsMustTailCall,
3069 bool InVarArgsFunc) {
3070 if (parseToken(lltok::lparen, "expected '(' in call"))
3071 return true;
3072
3073 while (Lex.getKind() != lltok::rparen) {
3074 // If this isn't the first argument, we need a comma.
3075 if (!ArgList.empty() &&
3076 parseToken(lltok::comma, "expected ',' in argument list"))
3077 return true;
3078
3079 // parse an ellipsis if this is a musttail call in a variadic function.
3080 if (Lex.getKind() == lltok::dotdotdot) {
3081 const char *Msg = "unexpected ellipsis in argument list for ";
3082 if (!IsMustTailCall)
3083 return tokError(Twine(Msg) + "non-musttail call");
3084 if (!InVarArgsFunc)
3085 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3086 Lex.Lex(); // Lex the '...', it is purely for readability.
3087 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3088 }
3089
3090 // parse the argument.
3091 LocTy ArgLoc;
3092 Type *ArgTy = nullptr;
3093 Value *V;
3094 if (parseType(ArgTy, ArgLoc))
3095 return true;
3097 return error(ArgLoc, "invalid type for function argument");
3098
3099 AttrBuilder ArgAttrs(M->getContext());
3100
3101 if (ArgTy->isMetadataTy()) {
3102 if (parseMetadataAsValue(V, PFS))
3103 return true;
3104 } else {
3105 // Otherwise, handle normal operands.
3106 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3107 return true;
3108 }
3109 ArgList.push_back(ParamInfo(
3110 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3111 }
3112
3113 if (IsMustTailCall && InVarArgsFunc)
3114 return tokError("expected '...' at end of argument list for musttail call "
3115 "in varargs function");
3116
3117 Lex.Lex(); // Lex the ')'.
3118 return false;
3119}
3120
3121/// parseRequiredTypeAttr
3122/// ::= attrname(<ty>)
3123bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3124 Attribute::AttrKind AttrKind) {
3125 Type *Ty = nullptr;
3126 if (!EatIfPresent(AttrToken))
3127 return true;
3128 if (!EatIfPresent(lltok::lparen))
3129 return error(Lex.getLoc(), "expected '('");
3130 if (parseType(Ty))
3131 return true;
3132 if (!EatIfPresent(lltok::rparen))
3133 return error(Lex.getLoc(), "expected ')'");
3134
3135 B.addTypeAttr(AttrKind, Ty);
3136 return false;
3137}
3138
3139/// parseRangeAttr
3140/// ::= range(<ty> <n>,<n>)
3141bool LLParser::parseRangeAttr(AttrBuilder &B) {
3142 Lex.Lex();
3143
3144 APInt Lower;
3145 APInt Upper;
3146 Type *Ty = nullptr;
3147 LocTy TyLoc;
3148
3149 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3150 if (Lex.getKind() != lltok::APSInt)
3151 return tokError("expected integer");
3152 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3153 return tokError(
3154 "integer is too large for the bit width of specified type");
3155 Val = Lex.getAPSIntVal().extend(BitWidth);
3156 Lex.Lex();
3157 return false;
3158 };
3159
3160 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3161 return true;
3162 if (!Ty->isIntegerTy())
3163 return error(TyLoc, "the range must have integer type!");
3164
3165 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3166
3167 if (ParseAPSInt(BitWidth, Lower) ||
3168 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3169 return true;
3170 if (Lower == Upper && !Lower.isZero())
3171 return tokError("the range represent the empty set but limits aren't 0!");
3172
3173 if (parseToken(lltok::rparen, "expected ')'"))
3174 return true;
3175
3176 B.addRangeAttr(ConstantRange(Lower, Upper));
3177 return false;
3178}
3179
3180/// parseInitializesAttr
3181/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3182bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3183 Lex.Lex();
3184
3185 auto ParseAPSInt = [&](APInt &Val) {
3186 if (Lex.getKind() != lltok::APSInt)
3187 return tokError("expected integer");
3188 Val = Lex.getAPSIntVal().extend(64);
3189 Lex.Lex();
3190 return false;
3191 };
3192
3193 if (parseToken(lltok::lparen, "expected '('"))
3194 return true;
3195
3197 // Parse each constant range.
3198 do {
3199 APInt Lower, Upper;
3200 if (parseToken(lltok::lparen, "expected '('"))
3201 return true;
3202
3203 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3204 ParseAPSInt(Upper))
3205 return true;
3206
3207 if (Lower == Upper)
3208 return tokError("the range should not represent the full or empty set!");
3209
3210 if (parseToken(lltok::rparen, "expected ')'"))
3211 return true;
3212
3213 RangeList.push_back(ConstantRange(Lower, Upper));
3214 } while (EatIfPresent(lltok::comma));
3215
3216 if (parseToken(lltok::rparen, "expected ')'"))
3217 return true;
3218
3219 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3220 if (!CRLOrNull.has_value())
3221 return tokError("Invalid (unordered or overlapping) range list");
3222 B.addInitializesAttr(*CRLOrNull);
3223 return false;
3224}
3225
3226bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3228 std::optional<CaptureComponents> Ret;
3229
3230 // We use syntax like captures(ret: address, provenance), so the colon
3231 // should not be interpreted as a label terminator.
3232 Lex.setIgnoreColonInIdentifiers(true);
3233 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
3234
3235 Lex.Lex();
3236 if (parseToken(lltok::lparen, "expected '('"))
3237 return true;
3238
3239 CaptureComponents *Current = &Other;
3240 bool SeenComponent = false;
3241 while (true) {
3242 if (EatIfPresent(lltok::kw_ret)) {
3243 if (parseToken(lltok::colon, "expected ':'"))
3244 return true;
3245 if (Ret)
3246 return tokError("duplicate 'ret' location");
3248 Current = &*Ret;
3249 SeenComponent = false;
3250 }
3251
3252 if (EatIfPresent(lltok::kw_none)) {
3253 if (SeenComponent)
3254 return tokError("cannot use 'none' with other component");
3255 *Current = CaptureComponents::None;
3256 } else {
3257 if (SeenComponent && capturesNothing(*Current))
3258 return tokError("cannot use 'none' with other component");
3259
3260 if (EatIfPresent(lltok::kw_address_is_null))
3262 else if (EatIfPresent(lltok::kw_address))
3263 *Current |= CaptureComponents::Address;
3264 else if (EatIfPresent(lltok::kw_provenance))
3266 else if (EatIfPresent(lltok::kw_read_provenance))
3268 else
3269 return tokError("expected one of 'none', 'address', 'address_is_null', "
3270 "'provenance' or 'read_provenance'");
3271 }
3272
3273 SeenComponent = true;
3274 if (EatIfPresent(lltok::rparen))
3275 break;
3276
3277 if (parseToken(lltok::comma, "expected ',' or ')'"))
3278 return true;
3279 }
3280
3281 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3282 return false;
3283}
3284
3285/// parseOptionalOperandBundles
3286/// ::= /*empty*/
3287/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3288///
3289/// OperandBundle
3290/// ::= bundle-tag '(' ')'
3291/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3292///
3293/// bundle-tag ::= String Constant
3294bool LLParser::parseOptionalOperandBundles(
3295 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3296 LocTy BeginLoc = Lex.getLoc();
3297 if (!EatIfPresent(lltok::lsquare))
3298 return false;
3299
3300 while (Lex.getKind() != lltok::rsquare) {
3301 // If this isn't the first operand bundle, we need a comma.
3302 if (!BundleList.empty() &&
3303 parseToken(lltok::comma, "expected ',' in input list"))
3304 return true;
3305
3306 std::string Tag;
3307 if (parseStringConstant(Tag))
3308 return true;
3309
3310 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3311 return true;
3312
3313 std::vector<Value *> Inputs;
3314 while (Lex.getKind() != lltok::rparen) {
3315 // If this isn't the first input, we need a comma.
3316 if (!Inputs.empty() &&
3317 parseToken(lltok::comma, "expected ',' in input list"))
3318 return true;
3319
3320 Type *Ty = nullptr;
3321 Value *Input = nullptr;
3322 if (parseType(Ty))
3323 return true;
3324 if (Ty->isMetadataTy()) {
3325 if (parseMetadataAsValue(Input, PFS))
3326 return true;
3327 } else if (parseValue(Ty, Input, PFS)) {
3328 return true;
3329 }
3330 Inputs.push_back(Input);
3331 }
3332
3333 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3334
3335 Lex.Lex(); // Lex the ')'.
3336 }
3337
3338 if (BundleList.empty())
3339 return error(BeginLoc, "operand bundle set must not be empty");
3340
3341 Lex.Lex(); // Lex the ']'.
3342 return false;
3343}
3344
3345bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3346 unsigned NextID, unsigned ID) {
3347 if (ID < NextID)
3348 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3349 Twine(NextID) + "' or greater");
3350
3351 return false;
3352}
3353
3354/// parseArgumentList - parse the argument list for a function type or function
3355/// prototype.
3356/// ::= '(' ArgTypeListI ')'
3357/// ArgTypeListI
3358/// ::= /*empty*/
3359/// ::= '...'
3360/// ::= ArgTypeList ',' '...'
3361/// ::= ArgType (',' ArgType)*
3362///
3363bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3364 SmallVectorImpl<unsigned> &UnnamedArgNums,
3365 bool &IsVarArg) {
3366 unsigned CurValID = 0;
3367 IsVarArg = false;
3368 assert(Lex.getKind() == lltok::lparen);
3369 Lex.Lex(); // eat the (.
3370
3371 if (Lex.getKind() != lltok::rparen) {
3372 do {
3373 // Handle ... at end of arg list.
3374 if (EatIfPresent(lltok::dotdotdot)) {
3375 IsVarArg = true;
3376 break;
3377 }
3378
3379 // Otherwise must be an argument type.
3380 LocTy TypeLoc = Lex.getLoc();
3381 Type *ArgTy = nullptr;
3382 AttrBuilder Attrs(M->getContext());
3383 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3384 return true;
3385
3386 if (ArgTy->isVoidTy())
3387 return error(TypeLoc, "argument can not have void type");
3388
3389 std::string Name;
3390 if (Lex.getKind() == lltok::LocalVar) {
3391 Name = Lex.getStrVal();
3392 Lex.Lex();
3393 } else {
3394 unsigned ArgID;
3395 if (Lex.getKind() == lltok::LocalVarID) {
3396 ArgID = Lex.getUIntVal();
3397 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3398 return true;
3399 Lex.Lex();
3400 } else {
3401 ArgID = CurValID;
3402 }
3403 UnnamedArgNums.push_back(ArgID);
3404 CurValID = ArgID + 1;
3405 }
3406
3408 return error(TypeLoc, "invalid type for function argument");
3409
3410 ArgList.emplace_back(TypeLoc, ArgTy,
3411 AttributeSet::get(ArgTy->getContext(), Attrs),
3412 std::move(Name));
3413 } while (EatIfPresent(lltok::comma));
3414 }
3415
3416 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3417}
3418
3419/// parseFunctionType
3420/// ::= Type ArgumentList OptionalAttrs
3421bool LLParser::parseFunctionType(Type *&Result) {
3422 assert(Lex.getKind() == lltok::lparen);
3423
3425 return tokError("invalid function return type");
3426
3428 bool IsVarArg;
3429 SmallVector<unsigned> UnnamedArgNums;
3430 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3431 return true;
3432
3433 // Reject names on the arguments lists.
3434 for (const ArgInfo &Arg : ArgList) {
3435 if (!Arg.Name.empty())
3436 return error(Arg.Loc, "argument name invalid in function type");
3437 if (Arg.Attrs.hasAttributes())
3438 return error(Arg.Loc, "argument attributes invalid in function type");
3439 }
3440
3441 SmallVector<Type*, 16> ArgListTy;
3442 for (const ArgInfo &Arg : ArgList)
3443 ArgListTy.push_back(Arg.Ty);
3444
3445 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3446 return false;
3447}
3448
3449/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3450/// other structs.
3451bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3453 if (parseStructBody(Elts))
3454 return true;
3455
3456 Result = StructType::get(Context, Elts, Packed);
3457 return false;
3458}
3459
3460/// parseStructDefinition - parse a struct in a 'type' definition.
3461bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3462 std::pair<Type *, LocTy> &Entry,
3463 Type *&ResultTy) {
3464 // If the type was already defined, diagnose the redefinition.
3465 if (Entry.first && !Entry.second.isValid())
3466 return error(TypeLoc, "redefinition of type");
3467
3468 // If we have opaque, just return without filling in the definition for the
3469 // struct. This counts as a definition as far as the .ll file goes.
3470 if (EatIfPresent(lltok::kw_opaque)) {
3471 // This type is being defined, so clear the location to indicate this.
3472 Entry.second = SMLoc();
3473
3474 // If this type number has never been uttered, create it.
3475 if (!Entry.first)
3476 Entry.first = StructType::create(Context, Name);
3477 ResultTy = Entry.first;
3478 return false;
3479 }
3480
3481 // If the type starts with '<', then it is either a packed struct or a vector.
3482 bool isPacked = EatIfPresent(lltok::less);
3483
3484 // If we don't have a struct, then we have a random type alias, which we
3485 // accept for compatibility with old files. These types are not allowed to be
3486 // forward referenced and not allowed to be recursive.
3487 if (Lex.getKind() != lltok::lbrace) {
3488 if (Entry.first)
3489 return error(TypeLoc, "forward references to non-struct type");
3490
3491 ResultTy = nullptr;
3492 if (isPacked)
3493 return parseArrayVectorType(ResultTy, true);
3494 return parseType(ResultTy);
3495 }
3496
3497 // This type is being defined, so clear the location to indicate this.
3498 Entry.second = SMLoc();
3499
3500 // If this type number has never been uttered, create it.
3501 if (!Entry.first)
3502 Entry.first = StructType::create(Context, Name);
3503
3504 StructType *STy = cast<StructType>(Entry.first);
3505
3507 if (parseStructBody(Body) ||
3508 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3509 return true;
3510
3511 if (auto E = STy->setBodyOrError(Body, isPacked))
3512 return tokError(toString(std::move(E)));
3513
3514 ResultTy = STy;
3515 return false;
3516}
3517
3518/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3519/// StructType
3520/// ::= '{' '}'
3521/// ::= '{' Type (',' Type)* '}'
3522/// ::= '<' '{' '}' '>'
3523/// ::= '<' '{' Type (',' Type)* '}' '>'
3524bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3525 assert(Lex.getKind() == lltok::lbrace);
3526 Lex.Lex(); // Consume the '{'
3527
3528 // Handle the empty struct.
3529 if (EatIfPresent(lltok::rbrace))
3530 return false;
3531
3532 LocTy EltTyLoc = Lex.getLoc();
3533 Type *Ty = nullptr;
3534 if (parseType(Ty))
3535 return true;
3536 Body.push_back(Ty);
3537
3539 return error(EltTyLoc, "invalid element type for struct");
3540
3541 while (EatIfPresent(lltok::comma)) {
3542 EltTyLoc = Lex.getLoc();
3543 if (parseType(Ty))
3544 return true;
3545
3547 return error(EltTyLoc, "invalid element type for struct");
3548
3549 Body.push_back(Ty);
3550 }
3551
3552 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3553}
3554
3555/// parseArrayVectorType - parse an array or vector type, assuming the first
3556/// token has already been consumed.
3557/// Type
3558/// ::= '[' APSINTVAL 'x' Types ']'
3559/// ::= '<' APSINTVAL 'x' Types '>'
3560/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3561bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3562 bool Scalable = false;
3563
3564 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3565 Lex.Lex(); // consume the 'vscale'
3566 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3567 return true;
3568
3569 Scalable = true;
3570 }
3571
3572 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3573 Lex.getAPSIntVal().getBitWidth() > 64)
3574 return tokError("expected number in address space");
3575
3576 LocTy SizeLoc = Lex.getLoc();
3577 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3578 Lex.Lex();
3579
3580 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3581 return true;
3582
3583 LocTy TypeLoc = Lex.getLoc();
3584 Type *EltTy = nullptr;
3585 if (parseType(EltTy))
3586 return true;
3587
3588 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3589 "expected end of sequential type"))
3590 return true;
3591
3592 if (IsVector) {
3593 if (Size == 0)
3594 return error(SizeLoc, "zero element vector is illegal");
3595 if ((unsigned)Size != Size)
3596 return error(SizeLoc, "size too large for vector");
3598 return error(TypeLoc, "invalid vector element type");
3599 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3600 } else {
3602 return error(TypeLoc, "invalid array element type");
3603 Result = ArrayType::get(EltTy, Size);
3604 }
3605 return false;
3606}
3607
3608/// parseTargetExtType - handle target extension type syntax
3609/// TargetExtType
3610/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3611///
3612/// TargetExtTypeParams
3613/// ::= /*empty*/
3614/// ::= ',' Type TargetExtTypeParams
3615///
3616/// TargetExtIntParams
3617/// ::= /*empty*/
3618/// ::= ',' uint32 TargetExtIntParams
3619bool LLParser::parseTargetExtType(Type *&Result) {
3620 Lex.Lex(); // Eat the 'target' keyword.
3621
3622 // Get the mandatory type name.
3623 std::string TypeName;
3624 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3625 parseStringConstant(TypeName))
3626 return true;
3627
3628 // Parse all of the integer and type parameters at the same time; the use of
3629 // SeenInt will allow us to catch cases where type parameters follow integer
3630 // parameters.
3631 SmallVector<Type *> TypeParams;
3632 SmallVector<unsigned> IntParams;
3633 bool SeenInt = false;
3634 while (Lex.getKind() == lltok::comma) {
3635 Lex.Lex(); // Eat the comma.
3636
3637 if (Lex.getKind() == lltok::APSInt) {
3638 SeenInt = true;
3639 unsigned IntVal;
3640 if (parseUInt32(IntVal))
3641 return true;
3642 IntParams.push_back(IntVal);
3643 } else if (SeenInt) {
3644 // The only other kind of parameter we support is type parameters, which
3645 // must precede the integer parameters. This is therefore an error.
3646 return tokError("expected uint32 param");
3647 } else {
3648 Type *TypeParam;
3649 if (parseType(TypeParam, /*AllowVoid=*/true))
3650 return true;
3651 TypeParams.push_back(TypeParam);
3652 }
3653 }
3654
3655 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3656 return true;
3657
3658 auto TTy =
3659 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3660 if (auto E = TTy.takeError())
3661 return tokError(toString(std::move(E)));
3662
3663 Result = *TTy;
3664 return false;
3665}
3666
3667//===----------------------------------------------------------------------===//
3668// Function Semantic Analysis.
3669//===----------------------------------------------------------------------===//
3670
3671LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3672 int functionNumber,
3673 ArrayRef<unsigned> UnnamedArgNums)
3674 : P(p), F(f), FunctionNumber(functionNumber) {
3675
3676 // Insert unnamed arguments into the NumberedVals list.
3677 auto It = UnnamedArgNums.begin();
3678 for (Argument &A : F.args()) {
3679 if (!A.hasName()) {
3680 unsigned ArgNum = *It++;
3681 NumberedVals.add(ArgNum, &A);
3682 }
3683 }
3684}
3685
3686LLParser::PerFunctionState::~PerFunctionState() {
3687 // If there were any forward referenced non-basicblock values, delete them.
3688
3689 for (const auto &P : ForwardRefVals) {
3690 if (isa<BasicBlock>(P.second.first))
3691 continue;
3692 P.second.first->replaceAllUsesWith(
3693 PoisonValue::get(P.second.first->getType()));
3694 P.second.first->deleteValue();
3695 }
3696
3697 for (const auto &P : ForwardRefValIDs) {
3698 if (isa<BasicBlock>(P.second.first))
3699 continue;
3700 P.second.first->replaceAllUsesWith(
3701 PoisonValue::get(P.second.first->getType()));
3702 P.second.first->deleteValue();
3703 }
3704}
3705
3706bool LLParser::PerFunctionState::finishFunction() {
3707 if (!ForwardRefVals.empty())
3708 return P.error(ForwardRefVals.begin()->second.second,
3709 "use of undefined value '%" + ForwardRefVals.begin()->first +
3710 "'");
3711 if (!ForwardRefValIDs.empty())
3712 return P.error(ForwardRefValIDs.begin()->second.second,
3713 "use of undefined value '%" +
3714 Twine(ForwardRefValIDs.begin()->first) + "'");
3715 return false;
3716}
3717
3718/// getVal - Get a value with the specified name or ID, creating a
3719/// forward reference record if needed. This can return null if the value
3720/// exists but does not have the right type.
3721Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3722 LocTy Loc) {
3723 // Look this name up in the normal function symbol table.
3724 Value *Val = F.getValueSymbolTable()->lookup(Name);
3725
3726 // If this is a forward reference for the value, see if we already created a
3727 // forward ref record.
3728 if (!Val) {
3729 auto I = ForwardRefVals.find(Name);
3730 if (I != ForwardRefVals.end())
3731 Val = I->second.first;
3732 }
3733
3734 // If we have the value in the symbol table or fwd-ref table, return it.
3735 if (Val)
3736 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3737
3738 // Don't make placeholders with invalid type.
3739 if (!Ty->isFirstClassType()) {
3740 P.error(Loc, "invalid use of a non-first-class type");
3741 return nullptr;
3742 }
3743
3744 // Otherwise, create a new forward reference for this value and remember it.
3745 Value *FwdVal;
3746 if (Ty->isLabelTy()) {
3747 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3748 } else {
3749 FwdVal = new Argument(Ty, Name);
3750 }
3751 if (FwdVal->getName() != Name) {
3752 P.error(Loc, "name is too long which can result in name collisions, "
3753 "consider making the name shorter or "
3754 "increasing -non-global-value-max-name-size");
3755 return nullptr;
3756 }
3757
3758 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3759 return FwdVal;
3760}
3761
3762Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3763 // Look this name up in the normal function symbol table.
3764 Value *Val = NumberedVals.get(ID);
3765
3766 // If this is a forward reference for the value, see if we already created a
3767 // forward ref record.
3768 if (!Val) {
3769 auto I = ForwardRefValIDs.find(ID);
3770 if (I != ForwardRefValIDs.end())
3771 Val = I->second.first;
3772 }
3773
3774 // If we have the value in the symbol table or fwd-ref table, return it.
3775 if (Val)
3776 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3777
3778 if (!Ty->isFirstClassType()) {
3779 P.error(Loc, "invalid use of a non-first-class type");
3780 return nullptr;
3781 }
3782
3783 // Otherwise, create a new forward reference for this value and remember it.
3784 Value *FwdVal;
3785 if (Ty->isLabelTy()) {
3786 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3787 } else {
3788 FwdVal = new Argument(Ty);
3789 }
3790
3791 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3792 return FwdVal;
3793}
3794
3795/// setInstName - After an instruction is parsed and inserted into its
3796/// basic block, this installs its name.
3797bool LLParser::PerFunctionState::setInstName(int NameID,
3798 const std::string &NameStr,
3799 LocTy NameLoc, Instruction *Inst) {
3800 // If this instruction has void type, it cannot have a name or ID specified.
3801 if (Inst->getType()->isVoidTy()) {
3802 if (NameID != -1 || !NameStr.empty())
3803 return P.error(NameLoc, "instructions returning void cannot have a name");
3804 return false;
3805 }
3806
3807 // If this was a numbered instruction, verify that the instruction is the
3808 // expected value and resolve any forward references.
3809 if (NameStr.empty()) {
3810 // If neither a name nor an ID was specified, just use the next ID.
3811 if (NameID == -1)
3812 NameID = NumberedVals.getNext();
3813
3814 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3815 NameID))
3816 return true;
3817
3818 auto FI = ForwardRefValIDs.find(NameID);
3819 if (FI != ForwardRefValIDs.end()) {
3820 Value *Sentinel = FI->second.first;
3821 if (Sentinel->getType() != Inst->getType())
3822 return P.error(NameLoc, "instruction forward referenced with type '" +
3823 getTypeString(FI->second.first->getType()) +
3824 "'");
3825
3826 Sentinel->replaceAllUsesWith(Inst);
3827 Sentinel->deleteValue();
3828 ForwardRefValIDs.erase(FI);
3829 }
3830
3831 NumberedVals.add(NameID, Inst);
3832 return false;
3833 }
3834
3835 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3836 auto FI = ForwardRefVals.find(NameStr);
3837 if (FI != ForwardRefVals.end()) {
3838 Value *Sentinel = FI->second.first;
3839 if (Sentinel->getType() != Inst->getType())
3840 return P.error(NameLoc, "instruction forward referenced with type '" +
3841 getTypeString(FI->second.first->getType()) +
3842 "'");
3843
3844 Sentinel->replaceAllUsesWith(Inst);
3845 Sentinel->deleteValue();
3846 ForwardRefVals.erase(FI);
3847 }
3848
3849 // Set the name on the instruction.
3850 Inst->setName(NameStr);
3851
3852 if (Inst->getName() != NameStr)
3853 return P.error(NameLoc, "multiple definition of local value named '" +
3854 NameStr + "'");
3855 return false;
3856}
3857
3858/// getBB - Get a basic block with the specified name or ID, creating a
3859/// forward reference record if needed.
3860BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3861 LocTy Loc) {
3863 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3864}
3865
3866BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3868 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3869}
3870
3871/// defineBB - Define the specified basic block, which is either named or
3872/// unnamed. If there is an error, this returns null otherwise it returns
3873/// the block being defined.
3874BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3875 int NameID, LocTy Loc) {
3876 BasicBlock *BB;
3877 if (Name.empty()) {
3878 if (NameID != -1) {
3879 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3880 return nullptr;
3881 } else {
3882 NameID = NumberedVals.getNext();
3883 }
3884 BB = getBB(NameID, Loc);
3885 if (!BB) {
3886 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3887 return nullptr;
3888 }
3889 } else {
3890 BB = getBB(Name, Loc);
3891 if (!BB) {
3892 P.error(Loc, "unable to create block named '" + Name + "'");
3893 return nullptr;
3894 }
3895 }
3896
3897 // Move the block to the end of the function. Forward ref'd blocks are
3898 // inserted wherever they happen to be referenced.
3899 F.splice(F.end(), &F, BB->getIterator());
3900
3901 // Remove the block from forward ref sets.
3902 if (Name.empty()) {
3903 ForwardRefValIDs.erase(NameID);
3904 NumberedVals.add(NameID, BB);
3905 } else {
3906 // BB forward references are already in the function symbol table.
3907 ForwardRefVals.erase(Name);
3908 }
3909
3910 return BB;
3911}
3912
3913//===----------------------------------------------------------------------===//
3914// Constants.
3915//===----------------------------------------------------------------------===//
3916
3917/// parseValID - parse an abstract value that doesn't necessarily have a
3918/// type implied. For example, if we parse "4" we don't know what integer type
3919/// it has. The value will later be combined with its type and checked for
3920/// basic correctness. PFS is used to convert function-local operands of
3921/// metadata (since metadata operands are not just parsed here but also
3922/// converted to values). PFS can be null when we are not parsing metadata
3923/// values inside a function.
3924bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3925 ID.Loc = Lex.getLoc();
3926 switch (Lex.getKind()) {
3927 default:
3928 return tokError("expected value token");
3929 case lltok::GlobalID: // @42
3930 ID.UIntVal = Lex.getUIntVal();
3931 ID.Kind = ValID::t_GlobalID;
3932 break;
3933 case lltok::GlobalVar: // @foo
3934 ID.StrVal = Lex.getStrVal();
3935 ID.Kind = ValID::t_GlobalName;
3936 break;
3937 case lltok::LocalVarID: // %42
3938 ID.UIntVal = Lex.getUIntVal();
3939 ID.Kind = ValID::t_LocalID;
3940 break;
3941 case lltok::LocalVar: // %foo
3942 ID.StrVal = Lex.getStrVal();
3943 ID.Kind = ValID::t_LocalName;
3944 break;
3945 case lltok::APSInt:
3946 ID.APSIntVal = Lex.getAPSIntVal();
3947 ID.Kind = ValID::t_APSInt;
3948 break;
3949 case lltok::APFloat:
3950 ID.APFloatVal = Lex.getAPFloatVal();
3951 ID.Kind = ValID::t_APFloat;
3952 break;
3953 case lltok::kw_true:
3954 ID.ConstantVal = ConstantInt::getTrue(Context);
3955 ID.Kind = ValID::t_Constant;
3956 break;
3957 case lltok::kw_false:
3958 ID.ConstantVal = ConstantInt::getFalse(Context);
3959 ID.Kind = ValID::t_Constant;
3960 break;
3961 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3962 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3963 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3964 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3965 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3966
3967 case lltok::lbrace: {
3968 // ValID ::= '{' ConstVector '}'
3969 Lex.Lex();
3971 if (parseGlobalValueVector(Elts) ||
3972 parseToken(lltok::rbrace, "expected end of struct constant"))
3973 return true;
3974
3975 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3976 ID.UIntVal = Elts.size();
3977 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3978 Elts.size() * sizeof(Elts[0]));
3980 return false;
3981 }
3982 case lltok::less: {
3983 // ValID ::= '<' ConstVector '>' --> Vector.
3984 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3985 Lex.Lex();
3986 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3987
3989 LocTy FirstEltLoc = Lex.getLoc();
3990 if (parseGlobalValueVector(Elts) ||
3991 (isPackedStruct &&
3992 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3993 parseToken(lltok::greater, "expected end of constant"))
3994 return true;
3995
3996 if (isPackedStruct) {
3997 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3998 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3999 Elts.size() * sizeof(Elts[0]));
4000 ID.UIntVal = Elts.size();
4002 return false;
4003 }
4004
4005 if (Elts.empty())
4006 return error(ID.Loc, "constant vector must not be empty");
4007
4008 if (!Elts[0]->getType()->isIntegerTy() &&
4009 !Elts[0]->getType()->isFloatingPointTy() &&
4010 !Elts[0]->getType()->isPointerTy())
4011 return error(
4012 FirstEltLoc,
4013 "vector elements must have integer, pointer or floating point type");
4014
4015 // Verify that all the vector elements have the same type.
4016 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4017 if (Elts[i]->getType() != Elts[0]->getType())
4018 return error(FirstEltLoc, "vector element #" + Twine(i) +
4019 " is not of type '" +
4020 getTypeString(Elts[0]->getType()));
4021
4022 ID.ConstantVal = ConstantVector::get(Elts);
4023 ID.Kind = ValID::t_Constant;
4024 return false;
4025 }
4026 case lltok::lsquare: { // Array Constant
4027 Lex.Lex();
4029 LocTy FirstEltLoc = Lex.getLoc();
4030 if (parseGlobalValueVector(Elts) ||
4031 parseToken(lltok::rsquare, "expected end of array constant"))
4032 return true;
4033
4034 // Handle empty element.
4035 if (Elts.empty()) {
4036 // Use undef instead of an array because it's inconvenient to determine
4037 // the element type at this point, there being no elements to examine.
4038 ID.Kind = ValID::t_EmptyArray;
4039 return false;
4040 }
4041
4042 if (!Elts[0]->getType()->isFirstClassType())
4043 return error(FirstEltLoc, "invalid array element type: " +
4044 getTypeString(Elts[0]->getType()));
4045
4046 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4047
4048 // Verify all elements are correct type!
4049 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4050 if (Elts[i]->getType() != Elts[0]->getType())
4051 return error(FirstEltLoc, "array element #" + Twine(i) +
4052 " is not of type '" +
4053 getTypeString(Elts[0]->getType()));
4054 }
4055
4056 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4057 ID.Kind = ValID::t_Constant;
4058 return false;
4059 }
4060 case lltok::kw_c: // c "foo"
4061 Lex.Lex();
4062 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4063 false);
4064 if (parseToken(lltok::StringConstant, "expected string"))
4065 return true;
4066 ID.Kind = ValID::t_Constant;
4067 return false;
4068
4069 case lltok::kw_asm: {
4070 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4071 // STRINGCONSTANT
4072 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4073 Lex.Lex();
4074 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4075 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4076 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4077 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4078 parseStringConstant(ID.StrVal) ||
4079 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4080 parseToken(lltok::StringConstant, "expected constraint string"))
4081 return true;
4082 ID.StrVal2 = Lex.getStrVal();
4083 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4084 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4085 ID.Kind = ValID::t_InlineAsm;
4086 return false;
4087 }
4088
4090 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4091 Lex.Lex();
4092
4093 ValID Fn, Label;
4094
4095 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4096 parseValID(Fn, PFS) ||
4097 parseToken(lltok::comma,
4098 "expected comma in block address expression") ||
4099 parseValID(Label, PFS) ||
4100 parseToken(lltok::rparen, "expected ')' in block address expression"))
4101 return true;
4102
4104 return error(Fn.Loc, "expected function name in blockaddress");
4105 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4106 return error(Label.Loc, "expected basic block name in blockaddress");
4107
4108 // Try to find the function (but skip it if it's forward-referenced).
4109 GlobalValue *GV = nullptr;
4110 if (Fn.Kind == ValID::t_GlobalID) {
4111 GV = NumberedVals.get(Fn.UIntVal);
4112 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4113 GV = M->getNamedValue(Fn.StrVal);
4114 }
4115 Function *F = nullptr;
4116 if (GV) {
4117 // Confirm that it's actually a function with a definition.
4118 if (!isa<Function>(GV))
4119 return error(Fn.Loc, "expected function name in blockaddress");
4120 F = cast<Function>(GV);
4121 if (F->isDeclaration())
4122 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4123 }
4124
4125 if (!F) {
4126 // Make a global variable as a placeholder for this reference.
4127 GlobalValue *&FwdRef =
4128 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4129 if (!FwdRef) {
4130 unsigned FwdDeclAS;
4131 if (ExpectedTy) {
4132 // If we know the type that the blockaddress is being assigned to,
4133 // we can use the address space of that type.
4134 if (!ExpectedTy->isPointerTy())
4135 return error(ID.Loc,
4136 "type of blockaddress must be a pointer and not '" +
4137 getTypeString(ExpectedTy) + "'");
4138 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4139 } else if (PFS) {
4140 // Otherwise, we default the address space of the current function.
4141 FwdDeclAS = PFS->getFunction().getAddressSpace();
4142 } else {
4143 llvm_unreachable("Unknown address space for blockaddress");
4144 }
4145 FwdRef = new GlobalVariable(
4146 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4147 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4148 }
4149
4150 ID.ConstantVal = FwdRef;
4151 ID.Kind = ValID::t_Constant;
4152 return false;
4153 }
4154
4155 // We found the function; now find the basic block. Don't use PFS, since we
4156 // might be inside a constant expression.
4157 BasicBlock *BB;
4158 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4159 if (Label.Kind == ValID::t_LocalID)
4160 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4161 else
4162 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4163 if (!BB)
4164 return error(Label.Loc, "referenced value is not a basic block");
4165 } else {
4166 if (Label.Kind == ValID::t_LocalID)
4167 return error(Label.Loc, "cannot take address of numeric label after "
4168 "the function is defined");
4170 F->getValueSymbolTable()->lookup(Label.StrVal));
4171 if (!BB)
4172 return error(Label.Loc, "referenced value is not a basic block");
4173 }
4174
4175 ID.ConstantVal = BlockAddress::get(F, BB);
4176 ID.Kind = ValID::t_Constant;
4177 return false;
4178 }
4179
4181 // ValID ::= 'dso_local_equivalent' @foo
4182 Lex.Lex();
4183
4184 ValID Fn;
4185
4186 if (parseValID(Fn, PFS))
4187 return true;
4188
4190 return error(Fn.Loc,
4191 "expected global value name in dso_local_equivalent");
4192
4193 // Try to find the function (but skip it if it's forward-referenced).
4194 GlobalValue *GV = nullptr;
4195 if (Fn.Kind == ValID::t_GlobalID) {
4196 GV = NumberedVals.get(Fn.UIntVal);
4197 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4198 GV = M->getNamedValue(Fn.StrVal);
4199 }
4200
4201 if (!GV) {
4202 // Make a placeholder global variable as a placeholder for this reference.
4203 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4204 ? ForwardRefDSOLocalEquivalentIDs
4205 : ForwardRefDSOLocalEquivalentNames;
4206 GlobalValue *&FwdRef = FwdRefMap[Fn];
4207 if (!FwdRef) {
4208 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4209 GlobalValue::InternalLinkage, nullptr, "",
4211 }
4212
4213 ID.ConstantVal = FwdRef;
4214 ID.Kind = ValID::t_Constant;
4215 return false;
4216 }
4217
4218 if (!GV->getValueType()->isFunctionTy())
4219 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4220 "in dso_local_equivalent");
4221
4222 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4223 ID.Kind = ValID::t_Constant;
4224 return false;
4225 }
4226
4227 case lltok::kw_no_cfi: {
4228 // ValID ::= 'no_cfi' @foo
4229 Lex.Lex();
4230
4231 if (parseValID(ID, PFS))
4232 return true;
4233
4234 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4235 return error(ID.Loc, "expected global value name in no_cfi");
4236
4237 ID.NoCFI = true;
4238 return false;
4239 }
4240 case lltok::kw_ptrauth: {
4241 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4242 // (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4243 Lex.Lex();
4244
4245 Constant *Ptr, *Key;
4246 Constant *Disc = nullptr, *AddrDisc = nullptr;
4247
4248 if (parseToken(lltok::lparen,
4249 "expected '(' in constant ptrauth expression") ||
4250 parseGlobalTypeAndValue(Ptr) ||
4251 parseToken(lltok::comma,
4252 "expected comma in constant ptrauth expression") ||
4253 parseGlobalTypeAndValue(Key))
4254 return true;
4255 // If present, parse the optional disc/addrdisc.
4256 if (EatIfPresent(lltok::comma))
4257 if (parseGlobalTypeAndValue(Disc) ||
4258 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4259 return true;
4260 if (parseToken(lltok::rparen,
4261 "expected ')' in constant ptrauth expression"))
4262 return true;
4263
4264 if (!Ptr->getType()->isPointerTy())
4265 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4266
4267 auto *KeyC = dyn_cast<ConstantInt>(Key);
4268 if (!KeyC || KeyC->getBitWidth() != 32)
4269 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4270
4271 ConstantInt *DiscC = nullptr;
4272 if (Disc) {
4273 DiscC = dyn_cast<ConstantInt>(Disc);
4274 if (!DiscC || DiscC->getBitWidth() != 64)
4275 return error(
4276 ID.Loc,
4277 "constant ptrauth integer discriminator must be i64 constant");
4278 } else {
4279 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4280 }
4281
4282 if (AddrDisc) {
4283 if (!AddrDisc->getType()->isPointerTy())
4284 return error(
4285 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4286 } else {
4287 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4288 }
4289
4290 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4291 ID.Kind = ValID::t_Constant;
4292 return false;
4293 }
4294
4295 case lltok::kw_trunc:
4296 case lltok::kw_bitcast:
4298 case lltok::kw_inttoptr:
4300 case lltok::kw_ptrtoint: {
4301 unsigned Opc = Lex.getUIntVal();
4302 Type *DestTy = nullptr;
4303 Constant *SrcVal;
4304 Lex.Lex();
4305 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4306 parseGlobalTypeAndValue(SrcVal) ||
4307 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4308 parseType(DestTy) ||
4309 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4310 return true;
4311 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4312 return error(ID.Loc, "invalid cast opcode for cast from '" +
4313 getTypeString(SrcVal->getType()) + "' to '" +
4314 getTypeString(DestTy) + "'");
4316 SrcVal, DestTy);
4317 ID.Kind = ValID::t_Constant;
4318 return false;
4319 }
4321 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4323 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4324 case lltok::kw_udiv:
4325 return error(ID.Loc, "udiv constexprs are no longer supported");
4326 case lltok::kw_sdiv:
4327 return error(ID.Loc, "sdiv constexprs are no longer supported");
4328 case lltok::kw_urem:
4329 return error(ID.Loc, "urem constexprs are no longer supported");
4330 case lltok::kw_srem:
4331 return error(ID.Loc, "srem constexprs are no longer supported");
4332 case lltok::kw_fadd:
4333 return error(ID.Loc, "fadd constexprs are no longer supported");
4334 case lltok::kw_fsub:
4335 return error(ID.Loc, "fsub constexprs are no longer supported");
4336 case lltok::kw_fmul:
4337 return error(ID.Loc, "fmul constexprs are no longer supported");
4338 case lltok::kw_fdiv:
4339 return error(ID.Loc, "fdiv constexprs are no longer supported");
4340 case lltok::kw_frem:
4341 return error(ID.Loc, "frem constexprs are no longer supported");
4342 case lltok::kw_and:
4343 return error(ID.Loc, "and constexprs are no longer supported");
4344 case lltok::kw_or:
4345 return error(ID.Loc, "or constexprs are no longer supported");
4346 case lltok::kw_lshr:
4347 return error(ID.Loc, "lshr constexprs are no longer supported");
4348 case lltok::kw_ashr:
4349 return error(ID.Loc, "ashr constexprs are no longer supported");
4350 case lltok::kw_shl:
4351 return error(ID.Loc, "shl constexprs are no longer supported");
4352 case lltok::kw_mul:
4353 return error(ID.Loc, "mul constexprs are no longer supported");
4354 case lltok::kw_fneg:
4355 return error(ID.Loc, "fneg constexprs are no longer supported");
4356 case lltok::kw_select:
4357 return error(ID.Loc, "select constexprs are no longer supported");
4358 case lltok::kw_zext:
4359 return error(ID.Loc, "zext constexprs are no longer supported");
4360 case lltok::kw_sext:
4361 return error(ID.Loc, "sext constexprs are no longer supported");
4362 case lltok::kw_fptrunc:
4363 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4364 case lltok::kw_fpext:
4365 return error(ID.Loc, "fpext constexprs are no longer supported");
4366 case lltok::kw_uitofp:
4367 return error(ID.Loc, "uitofp constexprs are no longer supported");
4368 case lltok::kw_sitofp:
4369 return error(ID.Loc, "sitofp constexprs are no longer supported");
4370 case lltok::kw_fptoui:
4371 return error(ID.Loc, "fptoui constexprs are no longer supported");
4372 case lltok::kw_fptosi:
4373 return error(ID.Loc, "fptosi constexprs are no longer supported");
4374 case lltok::kw_icmp:
4375 return error(ID.Loc, "icmp constexprs are no longer supported");
4376 case lltok::kw_fcmp:
4377 return error(ID.Loc, "fcmp constexprs are no longer supported");
4378
4379 // Binary Operators.
4380 case lltok::kw_add:
4381 case lltok::kw_sub:
4382 case lltok::kw_xor: {
4383 bool NUW = false;
4384 bool NSW = false;
4385 unsigned Opc = Lex.getUIntVal();
4386 Constant *Val0, *Val1;
4387 Lex.Lex();
4388 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4389 Opc == Instruction::Mul) {
4390 if (EatIfPresent(lltok::kw_nuw))
4391 NUW = true;
4392 if (EatIfPresent(lltok::kw_nsw)) {
4393 NSW = true;
4394 if (EatIfPresent(lltok::kw_nuw))
4395 NUW = true;
4396 }
4397 }
4398 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4399 parseGlobalTypeAndValue(Val0) ||
4400 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4401 parseGlobalTypeAndValue(Val1) ||
4402 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4403 return true;
4404 if (Val0->getType() != Val1->getType())
4405 return error(ID.Loc, "operands of constexpr must have same type");
4406 // Check that the type is valid for the operator.
4407 if (!Val0->getType()->isIntOrIntVectorTy())
4408 return error(ID.Loc,
4409 "constexpr requires integer or integer vector operands");
4410 unsigned Flags = 0;
4413 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4414 ID.Kind = ValID::t_Constant;
4415 return false;
4416 }
4417
4418 case lltok::kw_splat: {
4419 Lex.Lex();
4420 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4421 return true;
4422 Constant *C;
4423 if (parseGlobalTypeAndValue(C))
4424 return true;
4425 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4426 return true;
4427
4428 ID.ConstantVal = C;
4430 return false;
4431 }
4432
4437 unsigned Opc = Lex.getUIntVal();
4439 GEPNoWrapFlags NW;
4440 bool HasInRange = false;
4441 APSInt InRangeStart;
4442 APSInt InRangeEnd;
4443 Type *Ty;
4444 Lex.Lex();
4445
4446 if (Opc == Instruction::GetElementPtr) {
4447 while (true) {
4448 if (EatIfPresent(lltok::kw_inbounds))
4450 else if (EatIfPresent(lltok::kw_nusw))
4452 else if (EatIfPresent(lltok::kw_nuw))
4454 else
4455 break;
4456 }
4457
4458 if (EatIfPresent(lltok::kw_inrange)) {
4459 if (parseToken(lltok::lparen, "expected '('"))
4460 return true;
4461 if (Lex.getKind() != lltok::APSInt)
4462 return tokError("expected integer");
4463 InRangeStart = Lex.getAPSIntVal();
4464 Lex.Lex();
4465 if (parseToken(lltok::comma, "expected ','"))
4466 return true;
4467 if (Lex.getKind() != lltok::APSInt)
4468 return tokError("expected integer");
4469 InRangeEnd = Lex.getAPSIntVal();
4470 Lex.Lex();
4471 if (parseToken(lltok::rparen, "expected ')'"))
4472 return true;
4473 HasInRange = true;
4474 }
4475 }
4476
4477 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4478 return true;
4479
4480 if (Opc == Instruction::GetElementPtr) {
4481 if (parseType(Ty) ||
4482 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4483 return true;
4484 }
4485
4486 if (parseGlobalValueVector(Elts) ||
4487 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4488 return true;
4489
4490 if (Opc == Instruction::GetElementPtr) {
4491 if (Elts.size() == 0 ||
4492 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4493 return error(ID.Loc, "base of getelementptr must be a pointer");
4494
4495 Type *BaseType = Elts[0]->getType();
4496 std::optional<ConstantRange> InRange;
4497 if (HasInRange) {
4498 unsigned IndexWidth =
4499 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4500 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4501 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4502 if (InRangeStart.sge(InRangeEnd))
4503 return error(ID.Loc, "expected end to be larger than start");
4504 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4505 }
4506
4507 unsigned GEPWidth =
4508 BaseType->isVectorTy()
4509 ? cast<FixedVectorType>(BaseType)->getNumElements()
4510 : 0;
4511
4512 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4513 for (Constant *Val : Indices) {
4514 Type *ValTy = Val->getType();
4515 if (!ValTy->isIntOrIntVectorTy())
4516 return error(ID.Loc, "getelementptr index must be an integer");
4517 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4518 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4519 if (GEPWidth && (ValNumEl != GEPWidth))
4520 return error(
4521 ID.Loc,
4522 "getelementptr vector index has a wrong number of elements");
4523 // GEPWidth may have been unknown because the base is a scalar,
4524 // but it is known now.
4525 GEPWidth = ValNumEl;
4526 }
4527 }
4528
4529 SmallPtrSet<Type*, 4> Visited;
4530 if (!Indices.empty() && !Ty->isSized(&Visited))
4531 return error(ID.Loc, "base element of getelementptr must be sized");
4532
4533 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4534 return error(ID.Loc, "invalid getelementptr indices");
4535
4536 ID.ConstantVal =
4537 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4538 } else if (Opc == Instruction::ShuffleVector) {
4539 if (Elts.size() != 3)
4540 return error(ID.Loc, "expected three operands to shufflevector");
4541 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4542 return error(ID.Loc, "invalid operands to shufflevector");
4543 SmallVector<int, 16> Mask;
4545 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4546 } else if (Opc == Instruction::ExtractElement) {
4547 if (Elts.size() != 2)
4548 return error(ID.Loc, "expected two operands to extractelement");
4549 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4550 return error(ID.Loc, "invalid extractelement operands");
4551 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4552 } else {
4553 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4554 if (Elts.size() != 3)
4555 return error(ID.Loc, "expected three operands to insertelement");
4556 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4557 return error(ID.Loc, "invalid insertelement operands");
4558 ID.ConstantVal =
4559 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4560 }
4561
4562 ID.Kind = ValID::t_Constant;
4563 return false;
4564 }
4565 }
4566
4567 Lex.Lex();
4568 return false;
4569}
4570
4571/// parseGlobalValue - parse a global value with the specified type.
4572bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4573 C = nullptr;
4574 ValID ID;
4575 Value *V = nullptr;
4576 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4577 convertValIDToValue(Ty, ID, V, nullptr);
4578 if (V && !(C = dyn_cast<Constant>(V)))
4579 return error(ID.Loc, "global values must be constants");
4580 return Parsed;
4581}
4582
4583bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4584 Type *Ty = nullptr;
4585 return parseType(Ty) || parseGlobalValue(Ty, V);
4586}
4587
4588bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4589 C = nullptr;
4590
4591 LocTy KwLoc = Lex.getLoc();
4592 if (!EatIfPresent(lltok::kw_comdat))
4593 return false;
4594
4595 if (EatIfPresent(lltok::lparen)) {
4596 if (Lex.getKind() != lltok::ComdatVar)
4597 return tokError("expected comdat variable");
4598 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4599 Lex.Lex();
4600 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4601 return true;
4602 } else {
4603 if (GlobalName.empty())
4604 return tokError("comdat cannot be unnamed");
4605 C = getComdat(std::string(GlobalName), KwLoc);
4606 }
4607
4608 return false;
4609}
4610
4611/// parseGlobalValueVector
4612/// ::= /*empty*/
4613/// ::= TypeAndValue (',' TypeAndValue)*
4614bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4615 // Empty list.
4616 if (Lex.getKind() == lltok::rbrace ||
4617 Lex.getKind() == lltok::rsquare ||
4618 Lex.getKind() == lltok::greater ||
4619 Lex.getKind() == lltok::rparen)
4620 return false;
4621
4622 do {
4623 // Let the caller deal with inrange.
4624 if (Lex.getKind() == lltok::kw_inrange)
4625 return false;
4626
4627 Constant *C;
4628 if (parseGlobalTypeAndValue(C))
4629 return true;
4630 Elts.push_back(C);
4631 } while (EatIfPresent(lltok::comma));
4632
4633 return false;
4634}
4635
4636bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4638 if (parseMDNodeVector(Elts))
4639 return true;
4640
4641 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4642 return false;
4643}
4644
4645/// MDNode:
4646/// ::= !{ ... }
4647/// ::= !7
4648/// ::= !DILocation(...)
4649bool LLParser::parseMDNode(MDNode *&N) {
4650 if (Lex.getKind() == lltok::MetadataVar)
4651 return parseSpecializedMDNode(N);
4652
4653 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4654}
4655
4656bool LLParser::parseMDNodeTail(MDNode *&N) {
4657 // !{ ... }
4658 if (Lex.getKind() == lltok::lbrace)
4659 return parseMDTuple(N);
4660
4661 // !42
4662 return parseMDNodeID(N);
4663}
4664
4665namespace {
4666
4667/// Structure to represent an optional metadata field.
4668template <class FieldTy> struct MDFieldImpl {
4669 typedef MDFieldImpl ImplTy;
4670 FieldTy Val;
4671 bool Seen;
4672
4673 void assign(FieldTy Val) {
4674 Seen = true;
4675 this->Val = std::move(Val);
4676 }
4677
4678 explicit MDFieldImpl(FieldTy Default)
4679 : Val(std::move(Default)), Seen(false) {}
4680};
4681
4682/// Structure to represent an optional metadata field that
4683/// can be of either type (A or B) and encapsulates the
4684/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4685/// to reimplement the specifics for representing each Field.
4686template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4687 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4688 FieldTypeA A;
4689 FieldTypeB B;
4690 bool Seen;
4691
4692 enum {
4693 IsInvalid = 0,
4694 IsTypeA = 1,
4695 IsTypeB = 2
4696 } WhatIs;
4697
4698 void assign(FieldTypeA A) {
4699 Seen = true;
4700 this->A = std::move(A);
4701 WhatIs = IsTypeA;
4702 }
4703
4704 void assign(FieldTypeB B) {
4705 Seen = true;
4706 this->B = std::move(B);
4707 WhatIs = IsTypeB;
4708 }
4709
4710 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4711 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4712 WhatIs(IsInvalid) {}
4713};
4714
4715struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4716 uint64_t Max;
4717
4718 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4719 : ImplTy(Default), Max(Max) {}
4720};
4721
4722struct LineField : public MDUnsignedField {
4723 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4724};
4725
4726struct ColumnField : public MDUnsignedField {
4727 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4728};
4729
4730struct DwarfTagField : public MDUnsignedField {
4731 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4732 DwarfTagField(dwarf::Tag DefaultTag)
4733 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4734};
4735
4736struct DwarfMacinfoTypeField : public MDUnsignedField {
4737 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4738 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4739 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4740};
4741
4742struct DwarfAttEncodingField : public MDUnsignedField {
4743 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4744};
4745
4746struct DwarfVirtualityField : public MDUnsignedField {
4747 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4748};
4749
4750struct DwarfLangField : public MDUnsignedField {
4751 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4752};
4753
4754struct DwarfSourceLangNameField : public MDUnsignedField {
4755 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4756};
4757
4758struct DwarfCCField : public MDUnsignedField {
4759 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4760};
4761
4762struct DwarfEnumKindField : public MDUnsignedField {
4763 DwarfEnumKindField()
4764 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4765 dwarf::DW_APPLE_ENUM_KIND_max) {}
4766};
4767
4768struct EmissionKindField : public MDUnsignedField {
4769 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4770};
4771
4772struct FixedPointKindField : public MDUnsignedField {
4773 FixedPointKindField()
4774 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4775};
4776
4777struct NameTableKindField : public MDUnsignedField {
4778 NameTableKindField()
4779 : MDUnsignedField(
4780 0, (unsigned)
4781 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4782};
4783
4784struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4785 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4786};
4787
4788struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4789 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4790};
4791
4792struct MDAPSIntField : public MDFieldImpl<APSInt> {
4793 MDAPSIntField() : ImplTy(APSInt()) {}
4794};
4795
4796struct MDSignedField : public MDFieldImpl<int64_t> {
4797 int64_t Min = INT64_MIN;
4798 int64_t Max = INT64_MAX;
4799
4800 MDSignedField(int64_t Default = 0)
4801 : ImplTy(Default) {}
4802 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4803 : ImplTy(Default), Min(Min), Max(Max) {}
4804};
4805
4806struct MDBoolField : public MDFieldImpl<bool> {
4807 MDBoolField(bool Default = false) : ImplTy(Default) {}
4808};
4809
4810struct MDField : public MDFieldImpl<Metadata *> {
4811 bool AllowNull;
4812
4813 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4814};
4815
4816struct MDStringField : public MDFieldImpl<MDString *> {
4817 enum class EmptyIs {
4818 Null, //< Allow empty input string, map to nullptr
4819 Empty, //< Allow empty input string, map to an empty MDString
4820 Error, //< Disallow empty string, map to an error
4821 } EmptyIs;
4822 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
4823 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4824};
4825
4826struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4827 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4828};
4829
4830struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4831 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4832};
4833
4834struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4835 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4836 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4837
4838 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4839 bool AllowNull = true)
4840 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4841
4842 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4843 bool isMDField() const { return WhatIs == IsTypeB; }
4844 int64_t getMDSignedValue() const {
4845 assert(isMDSignedField() && "Wrong field type");
4846 return A.Val;
4847 }
4848 Metadata *getMDFieldValue() const {
4849 assert(isMDField() && "Wrong field type");
4850 return B.Val;
4851 }
4852};
4853
4854struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4855 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
4856 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
4857
4858 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
4859 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
4860
4861 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
4862 bool isMDField() const { return WhatIs == IsTypeB; }
4863 uint64_t getMDUnsignedValue() const {
4864 assert(isMDUnsignedField() && "Wrong field type");
4865 return A.Val;
4866 }
4867 Metadata *getMDFieldValue() const {
4868 assert(isMDField() && "Wrong field type");
4869 return B.Val;
4870 }
4871
4872 Metadata *getValueAsMetadata(LLVMContext &Context) const {
4873 if (isMDUnsignedField())
4875 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
4876 if (isMDField())
4877 return getMDFieldValue();
4878 return nullptr;
4879 }
4880};
4881
4882} // end anonymous namespace
4883
4884namespace llvm {
4885
4886template <>
4887bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4888 if (Lex.getKind() != lltok::APSInt)
4889 return tokError("expected integer");
4890
4891 Result.assign(Lex.getAPSIntVal());
4892 Lex.Lex();
4893 return false;
4894}
4895
4896template <>
4897bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4898 MDUnsignedField &Result) {
4899 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4900 return tokError("expected unsigned integer");
4901
4902 auto &U = Lex.getAPSIntVal();
4903 if (U.ugt(Result.Max))
4904 return tokError("value for '" + Name + "' too large, limit is " +
4905 Twine(Result.Max));
4906 Result.assign(U.getZExtValue());
4907 assert(Result.Val <= Result.Max && "Expected value in range");
4908 Lex.Lex();
4909 return false;
4910}
4911
4912template <>
4913bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4914 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4915}
4916template <>
4917bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4918 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4919}
4920
4921template <>
4922bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4923 if (Lex.getKind() == lltok::APSInt)
4924 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4925
4926 if (Lex.getKind() != lltok::DwarfTag)
4927 return tokError("expected DWARF tag");
4928
4929 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4931 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4932 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4933
4934 Result.assign(Tag);
4935 Lex.Lex();
4936 return false;
4937}
4938
4939template <>
4940bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4941 DwarfMacinfoTypeField &Result) {
4942 if (Lex.getKind() == lltok::APSInt)
4943 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4944
4945 if (Lex.getKind() != lltok::DwarfMacinfo)
4946 return tokError("expected DWARF macinfo type");
4947
4948 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4949 if (Macinfo == dwarf::DW_MACINFO_invalid)
4950 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4951 Lex.getStrVal() + "'");
4952 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4953
4954 Result.assign(Macinfo);
4955 Lex.Lex();
4956 return false;
4957}
4958
4959template <>
4960bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4961 DwarfVirtualityField &Result) {
4962 if (Lex.getKind() == lltok::APSInt)
4963 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4964
4965 if (Lex.getKind() != lltok::DwarfVirtuality)
4966 return tokError("expected DWARF virtuality code");
4967
4968 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4969 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4970 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4971 Lex.getStrVal() + "'");
4972 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4973 Result.assign(Virtuality);
4974 Lex.Lex();
4975 return false;
4976}
4977
4978template <>
4979bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4980 DwarfEnumKindField &Result) {
4981 if (Lex.getKind() == lltok::APSInt)
4982 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4983
4984 if (Lex.getKind() != lltok::DwarfEnumKind)
4985 return tokError("expected DWARF enum kind code");
4986
4987 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
4988 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
4989 return tokError("invalid DWARF enum kind code" + Twine(" '") +
4990 Lex.getStrVal() + "'");
4991 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
4992 Result.assign(EnumKind);
4993 Lex.Lex();
4994 return false;
4995}
4996
4997template <>
4998bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4999 if (Lex.getKind() == lltok::APSInt)
5000 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5001
5002 if (Lex.getKind() != lltok::DwarfLang)
5003 return tokError("expected DWARF language");
5004
5005 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5006 if (!Lang)
5007 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5008 "'");
5009 assert(Lang <= Result.Max && "Expected valid DWARF language");
5010 Result.assign(Lang);
5011 Lex.Lex();
5012 return false;
5013}
5014
5015template <>
5016bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5017 DwarfSourceLangNameField &Result) {
5018 if (Lex.getKind() == lltok::APSInt)
5019 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5020
5021 if (Lex.getKind() != lltok::DwarfSourceLangName)
5022 return tokError("expected DWARF source language name");
5023
5024 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5025 if (!Lang)
5026 return tokError("invalid DWARF source language name" + Twine(" '") +
5027 Lex.getStrVal() + "'");
5028 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5029 Result.assign(Lang);
5030 Lex.Lex();
5031 return false;
5032}
5033
5034template <>
5035bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5036 if (Lex.getKind() == lltok::APSInt)
5037 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5038
5039 if (Lex.getKind() != lltok::DwarfCC)
5040 return tokError("expected DWARF calling convention");
5041
5042 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5043 if (!CC)
5044 return tokError("invalid DWARF calling convention" + Twine(" '") +
5045 Lex.getStrVal() + "'");
5046 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5047 Result.assign(CC);
5048 Lex.Lex();
5049 return false;
5050}
5051
5052template <>
5053bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5054 EmissionKindField &Result) {
5055 if (Lex.getKind() == lltok::APSInt)
5056 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5057
5058 if (Lex.getKind() != lltok::EmissionKind)
5059 return tokError("expected emission kind");
5060
5061 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5062 if (!Kind)
5063 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5064 "'");
5065 assert(*Kind <= Result.Max && "Expected valid emission kind");
5066 Result.assign(*Kind);
5067 Lex.Lex();
5068 return false;
5069}
5070
5071template <>
5072bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5073 FixedPointKindField &Result) {
5074 if (Lex.getKind() == lltok::APSInt)
5075 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5076
5077 if (Lex.getKind() != lltok::FixedPointKind)
5078 return tokError("expected fixed-point kind");
5079
5080 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5081 if (!Kind)
5082 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5083 "'");
5084 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5085 Result.assign(*Kind);
5086 Lex.Lex();
5087 return false;
5088}
5089
5090template <>
5091bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5092 NameTableKindField &Result) {
5093 if (Lex.getKind() == lltok::APSInt)
5094 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5095
5096 if (Lex.getKind() != lltok::NameTableKind)
5097 return tokError("expected nameTable kind");
5098
5099 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5100 if (!Kind)
5101 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5102 "'");
5103 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5104 Result.assign((unsigned)*Kind);
5105 Lex.Lex();
5106 return false;
5107}
5108
5109template <>
5110bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5111 DwarfAttEncodingField &Result) {
5112 if (Lex.getKind() == lltok::APSInt)
5113 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5114
5115 if (Lex.getKind() != lltok::DwarfAttEncoding)
5116 return tokError("expected DWARF type attribute encoding");
5117
5118 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5119 if (!Encoding)
5120 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5121 Lex.getStrVal() + "'");
5122 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5123 Result.assign(Encoding);
5124 Lex.Lex();
5125 return false;
5126}
5127
5128/// DIFlagField
5129/// ::= uint32
5130/// ::= DIFlagVector
5131/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5132template <>
5133bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5134
5135 // parser for a single flag.
5136 auto parseFlag = [&](DINode::DIFlags &Val) {
5137 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5138 uint32_t TempVal = static_cast<uint32_t>(Val);
5139 bool Res = parseUInt32(TempVal);
5140 Val = static_cast<DINode::DIFlags>(TempVal);
5141 return Res;
5142 }
5143
5144 if (Lex.getKind() != lltok::DIFlag)
5145 return tokError("expected debug info flag");
5146
5147 Val = DINode::getFlag(Lex.getStrVal());
5148 if (!Val)
5149 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5150 "'");
5151 Lex.Lex();
5152 return false;
5153 };
5154
5155 // parse the flags and combine them together.
5156 DINode::DIFlags Combined = DINode::FlagZero;
5157 do {
5158 DINode::DIFlags Val;
5159 if (parseFlag(Val))
5160 return true;
5161 Combined |= Val;
5162 } while (EatIfPresent(lltok::bar));
5163
5164 Result.assign(Combined);
5165 return false;
5166}
5167
5168/// DISPFlagField
5169/// ::= uint32
5170/// ::= DISPFlagVector
5171/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5172template <>
5173bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5174
5175 // parser for a single flag.
5176 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5177 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5178 uint32_t TempVal = static_cast<uint32_t>(Val);
5179 bool Res = parseUInt32(TempVal);
5180 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5181 return Res;
5182 }
5183
5184 if (Lex.getKind() != lltok::DISPFlag)
5185 return tokError("expected debug info flag");
5186
5187 Val = DISubprogram::getFlag(Lex.getStrVal());
5188 if (!Val)
5189 return tokError(Twine("invalid subprogram debug info flag '") +
5190 Lex.getStrVal() + "'");
5191 Lex.Lex();
5192 return false;
5193 };
5194
5195 // parse the flags and combine them together.
5196 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5197 do {
5199 if (parseFlag(Val))
5200 return true;
5201 Combined |= Val;
5202 } while (EatIfPresent(lltok::bar));
5203
5204 Result.assign(Combined);
5205 return false;
5206}
5207
5208template <>
5209bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5210 if (Lex.getKind() != lltok::APSInt)
5211 return tokError("expected signed integer");
5212
5213 auto &S = Lex.getAPSIntVal();
5214 if (S < Result.Min)
5215 return tokError("value for '" + Name + "' too small, limit is " +
5216 Twine(Result.Min));
5217 if (S > Result.Max)
5218 return tokError("value for '" + Name + "' too large, limit is " +
5219 Twine(Result.Max));
5220 Result.assign(S.getExtValue());
5221 assert(Result.Val >= Result.Min && "Expected value in range");
5222 assert(Result.Val <= Result.Max && "Expected value in range");
5223 Lex.Lex();
5224 return false;
5225}
5226
5227template <>
5228bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5229 switch (Lex.getKind()) {
5230 default:
5231 return tokError("expected 'true' or 'false'");
5232 case lltok::kw_true:
5233 Result.assign(true);
5234 break;
5235 case lltok::kw_false:
5236 Result.assign(false);
5237 break;
5238 }
5239 Lex.Lex();
5240 return false;
5241}
5242
5243template <>
5244bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5245 if (Lex.getKind() == lltok::kw_null) {
5246 if (!Result.AllowNull)
5247 return tokError("'" + Name + "' cannot be null");
5248 Lex.Lex();
5249 Result.assign(nullptr);
5250 return false;
5251 }
5252
5253 Metadata *MD;
5254 if (parseMetadata(MD, nullptr))
5255 return true;
5256
5257 Result.assign(MD);
5258 return false;
5259}
5260
5261template <>
5262bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5263 MDSignedOrMDField &Result) {
5264 // Try to parse a signed int.
5265 if (Lex.getKind() == lltok::APSInt) {
5266 MDSignedField Res = Result.A;
5267 if (!parseMDField(Loc, Name, Res)) {
5268 Result.assign(Res);
5269 return false;
5270 }
5271 return true;
5272 }
5273
5274 // Otherwise, try to parse as an MDField.
5275 MDField Res = Result.B;
5276 if (!parseMDField(Loc, Name, Res)) {
5277 Result.assign(Res);
5278 return false;
5279 }
5280
5281 return true;
5282}
5283
5284template <>
5285bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5286 MDUnsignedOrMDField &Result) {
5287 // Try to parse an unsigned int.
5288 if (Lex.getKind() == lltok::APSInt) {
5289 MDUnsignedField Res = Result.A;
5290 if (!parseMDField(Loc, Name, Res)) {
5291 Result.assign(Res);
5292 return false;
5293 }
5294 return true;
5295 }
5296
5297 // Otherwise, try to parse as an MDField.
5298 MDField Res = Result.B;
5299 if (!parseMDField(Loc, Name, Res)) {
5300 Result.assign(Res);
5301 return false;
5302 }
5303
5304 return true;
5305}
5306
5307template <>
5308bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5309 LocTy ValueLoc = Lex.getLoc();
5310 std::string S;
5311 if (parseStringConstant(S))
5312 return true;
5313
5314 if (S.empty()) {
5315 switch (Result.EmptyIs) {
5316 case MDStringField::EmptyIs::Null:
5317 Result.assign(nullptr);
5318 return false;
5319 case MDStringField::EmptyIs::Empty:
5320 break;
5321 case MDStringField::EmptyIs::Error:
5322 return error(ValueLoc, "'" + Name + "' cannot be empty");
5323 }
5324 }
5325
5326 Result.assign(MDString::get(Context, S));
5327 return false;
5328}
5329
5330template <>
5331bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5333 if (parseMDNodeVector(MDs))
5334 return true;
5335
5336 Result.assign(std::move(MDs));
5337 return false;
5338}
5339
5340template <>
5341bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5342 ChecksumKindField &Result) {
5343 std::optional<DIFile::ChecksumKind> CSKind =
5344 DIFile::getChecksumKind(Lex.getStrVal());
5345
5346 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5347 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5348 "'");
5349
5350 Result.assign(*CSKind);
5351 Lex.Lex();
5352 return false;
5353}
5354
5355} // end namespace llvm
5356
5357template <class ParserTy>
5358bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5359 do {
5360 if (Lex.getKind() != lltok::LabelStr)
5361 return tokError("expected field label here");
5362
5363 if (ParseField())
5364 return true;
5365 } while (EatIfPresent(lltok::comma));
5366
5367 return false;
5368}
5369
5370template <class ParserTy>
5371bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5372 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5373 Lex.Lex();
5374
5375 if (parseToken(lltok::lparen, "expected '(' here"))
5376 return true;
5377 if (Lex.getKind() != lltok::rparen)
5378 if (parseMDFieldsImplBody(ParseField))
5379 return true;
5380
5381 ClosingLoc = Lex.getLoc();
5382 return parseToken(lltok::rparen, "expected ')' here");
5383}
5384
5385template <class FieldTy>
5386bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5387 if (Result.Seen)
5388 return tokError("field '" + Name + "' cannot be specified more than once");
5389
5390 LocTy Loc = Lex.getLoc();
5391 Lex.Lex();
5392 return parseMDField(Loc, Name, Result);
5393}
5394
5395bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5396 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5397
5398#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5399 if (Lex.getStrVal() == #CLASS) \
5400 return parse##CLASS(N, IsDistinct);
5401#include "llvm/IR/Metadata.def"
5402
5403 return tokError("expected metadata type");
5404}
5405
5406#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5407#define NOP_FIELD(NAME, TYPE, INIT)
5408#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5409 if (!NAME.Seen) \
5410 return error(ClosingLoc, "missing required field '" #NAME "'");
5411#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5412 if (Lex.getStrVal() == #NAME) \
5413 return parseMDField(#NAME, NAME);
5414#define PARSE_MD_FIELDS() \
5415 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5416 do { \
5417 LocTy ClosingLoc; \
5418 if (parseMDFieldsImpl( \
5419 [&]() -> bool { \
5420 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5421 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5422 "'"); \
5423 }, \
5424 ClosingLoc)) \
5425 return true; \
5426 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5427 } while (false)
5428#define GET_OR_DISTINCT(CLASS, ARGS) \
5429 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5430
5431/// parseDILocationFields:
5432/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5433/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5434bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5435#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5436 OPTIONAL(line, LineField, ); \
5437 OPTIONAL(column, ColumnField, ); \
5438 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5439 OPTIONAL(inlinedAt, MDField, ); \
5440 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5441 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5442 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5444#undef VISIT_MD_FIELDS
5445
5446 Result = GET_OR_DISTINCT(
5447 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5448 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5449 return false;
5450}
5451
5452/// parseDIAssignID:
5453/// ::= distinct !DIAssignID()
5454bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5455 if (!IsDistinct)
5456 return tokError("missing 'distinct', required for !DIAssignID()");
5457
5458 Lex.Lex();
5459
5460 // Now eat the parens.
5461 if (parseToken(lltok::lparen, "expected '(' here"))
5462 return true;
5463 if (parseToken(lltok::rparen, "expected ')' here"))
5464 return true;
5465
5467 return false;
5468}
5469
5470/// parseGenericDINode:
5471/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5472bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5473#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5474 REQUIRED(tag, DwarfTagField, ); \
5475 OPTIONAL(header, MDStringField, ); \
5476 OPTIONAL(operands, MDFieldList, );
5478#undef VISIT_MD_FIELDS
5479
5480 Result = GET_OR_DISTINCT(GenericDINode,
5481 (Context, tag.Val, header.Val, operands.Val));
5482 return false;
5483}
5484
5485/// parseDISubrangeType:
5486/// ::= !DISubrangeType(name: "whatever", file: !0,
5487/// line: 7, scope: !1, baseType: !2, size: 32,
5488/// align: 32, flags: 0, lowerBound: !3
5489/// upperBound: !4, stride: !5, bias: !6)
5490bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5491#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5492 OPTIONAL(name, MDStringField, ); \
5493 OPTIONAL(file, MDField, ); \
5494 OPTIONAL(line, LineField, ); \
5495 OPTIONAL(scope, MDField, ); \
5496 OPTIONAL(baseType, MDField, ); \
5497 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5498 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5499 OPTIONAL(flags, DIFlagField, ); \
5500 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5501 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5502 OPTIONAL(stride, MDSignedOrMDField, ); \
5503 OPTIONAL(bias, MDSignedOrMDField, );
5505#undef VISIT_MD_FIELDS
5506
5507 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5508 if (Bound.isMDSignedField())
5510 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5511 if (Bound.isMDField())
5512 return Bound.getMDFieldValue();
5513 return nullptr;
5514 };
5515
5516 Metadata *LowerBound = convToMetadata(lowerBound);
5517 Metadata *UpperBound = convToMetadata(upperBound);
5518 Metadata *Stride = convToMetadata(stride);
5519 Metadata *Bias = convToMetadata(bias);
5520
5522 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5523 size.getValueAsMetadata(Context), align.Val, flags.Val,
5524 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5525
5526 return false;
5527}
5528
5529/// parseDISubrange:
5530/// ::= !DISubrange(count: 30, lowerBound: 2)
5531/// ::= !DISubrange(count: !node, lowerBound: 2)
5532/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5533bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5534#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5535 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5536 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5537 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5538 OPTIONAL(stride, MDSignedOrMDField, );
5540#undef VISIT_MD_FIELDS
5541
5542 Metadata *Count = nullptr;
5543 Metadata *LowerBound = nullptr;
5544 Metadata *UpperBound = nullptr;
5545 Metadata *Stride = nullptr;
5546
5547 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5548 if (Bound.isMDSignedField())
5550 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5551 if (Bound.isMDField())
5552 return Bound.getMDFieldValue();
5553 return nullptr;
5554 };
5555
5556 Count = convToMetadata(count);
5557 LowerBound = convToMetadata(lowerBound);
5558 UpperBound = convToMetadata(upperBound);
5559 Stride = convToMetadata(stride);
5560
5561 Result = GET_OR_DISTINCT(DISubrange,
5562 (Context, Count, LowerBound, UpperBound, Stride));
5563
5564 return false;
5565}
5566
5567/// parseDIGenericSubrange:
5568/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5569/// !node3)
5570bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5571#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5572 OPTIONAL(count, MDSignedOrMDField, ); \
5573 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5574 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5575 OPTIONAL(stride, MDSignedOrMDField, );
5577#undef VISIT_MD_FIELDS
5578
5579 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5580 if (Bound.isMDSignedField())
5581 return DIExpression::get(
5582 Context, {dwarf::DW_OP_consts,
5583 static_cast<uint64_t>(Bound.getMDSignedValue())});
5584 if (Bound.isMDField())
5585 return Bound.getMDFieldValue();
5586 return nullptr;
5587 };
5588
5589 Metadata *Count = ConvToMetadata(count);
5590 Metadata *LowerBound = ConvToMetadata(lowerBound);
5591 Metadata *UpperBound = ConvToMetadata(upperBound);
5592 Metadata *Stride = ConvToMetadata(stride);
5593
5594 Result = GET_OR_DISTINCT(DIGenericSubrange,
5595 (Context, Count, LowerBound, UpperBound, Stride));
5596
5597 return false;
5598}
5599
5600/// parseDIEnumerator:
5601/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5602bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5603#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5604 REQUIRED(name, MDStringField, ); \
5605 REQUIRED(value, MDAPSIntField, ); \
5606 OPTIONAL(isUnsigned, MDBoolField, (false));
5608#undef VISIT_MD_FIELDS
5609
5610 if (isUnsigned.Val && value.Val.isNegative())
5611 return tokError("unsigned enumerator with negative value");
5612
5613 APSInt Value(value.Val);
5614 // Add a leading zero so that unsigned values with the msb set are not
5615 // mistaken for negative values when used for signed enumerators.
5616 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5617 Value = Value.zext(Value.getBitWidth() + 1);
5618
5619 Result =
5620 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5621
5622 return false;
5623}
5624
5625/// parseDIBasicType:
5626/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5627/// encoding: DW_ATE_encoding, flags: 0)
5628bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5629#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5630 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5631 OPTIONAL(name, MDStringField, ); \
5632 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5633 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5634 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5635 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5636 OPTIONAL(flags, DIFlagField, );
5638#undef VISIT_MD_FIELDS
5639
5640 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val,
5641 size.getValueAsMetadata(Context),
5642 align.Val, encoding.Val,
5643 num_extra_inhabitants.Val, flags.Val));
5644 return false;
5645}
5646
5647/// parseDIFixedPointType:
5648/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5649/// align: 32, encoding: DW_ATE_signed_fixed,
5650/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5651/// denominator: 8)
5652bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5653#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5654 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5655 OPTIONAL(name, MDStringField, ); \
5656 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5657 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5658 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5659 OPTIONAL(flags, DIFlagField, ); \
5660 OPTIONAL(kind, FixedPointKindField, ); \
5661 OPTIONAL(factor, MDSignedField, ); \
5662 OPTIONAL(numerator, MDAPSIntField, ); \
5663 OPTIONAL(denominator, MDAPSIntField, );
5665#undef VISIT_MD_FIELDS
5666
5667 Result = GET_OR_DISTINCT(DIFixedPointType,
5668 (Context, tag.Val, name.Val,
5669 size.getValueAsMetadata(Context), align.Val,
5670 encoding.Val, flags.Val, kind.Val, factor.Val,
5671 numerator.Val, denominator.Val));
5672 return false;
5673}
5674
5675/// parseDIStringType:
5676/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5677bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5678#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5679 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5680 OPTIONAL(name, MDStringField, ); \
5681 OPTIONAL(stringLength, MDField, ); \
5682 OPTIONAL(stringLengthExpression, MDField, ); \
5683 OPTIONAL(stringLocationExpression, MDField, ); \
5684 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5685 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5686 OPTIONAL(encoding, DwarfAttEncodingField, );
5688#undef VISIT_MD_FIELDS
5689
5691 DIStringType,
5692 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5693 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5694 align.Val, encoding.Val));
5695 return false;
5696}
5697
5698/// parseDIDerivedType:
5699/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5700/// line: 7, scope: !1, baseType: !2, size: 32,
5701/// align: 32, offset: 0, flags: 0, extraData: !3,
5702/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5703/// ptrAuthIsAddressDiscriminated: true,
5704/// ptrAuthExtraDiscriminator: 0x1234,
5705/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5706/// )
5707bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5708#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5709 REQUIRED(tag, DwarfTagField, ); \
5710 OPTIONAL(name, MDStringField, ); \
5711 OPTIONAL(file, MDField, ); \
5712 OPTIONAL(line, LineField, ); \
5713 OPTIONAL(scope, MDField, ); \
5714 REQUIRED(baseType, MDField, ); \
5715 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5716 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5717 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5718 OPTIONAL(flags, DIFlagField, ); \
5719 OPTIONAL(extraData, MDField, ); \
5720 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5721 OPTIONAL(annotations, MDField, ); \
5722 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5723 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5724 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5725 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5726 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5728#undef VISIT_MD_FIELDS
5729
5730 std::optional<unsigned> DWARFAddressSpace;
5731 if (dwarfAddressSpace.Val != UINT32_MAX)
5732 DWARFAddressSpace = dwarfAddressSpace.Val;
5733 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5734 if (ptrAuthKey.Val)
5735 PtrAuthData.emplace(
5736 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5737 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5738 ptrAuthAuthenticatesNullValues.Val);
5739
5741 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5742 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5743 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5744 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5745 return false;
5746}
5747
5748bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5749#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5750 REQUIRED(tag, DwarfTagField, ); \
5751 OPTIONAL(name, MDStringField, ); \
5752 OPTIONAL(file, MDField, ); \
5753 OPTIONAL(line, LineField, ); \
5754 OPTIONAL(scope, MDField, ); \
5755 OPTIONAL(baseType, MDField, ); \
5756 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5757 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5758 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5759 OPTIONAL(flags, DIFlagField, ); \
5760 OPTIONAL(elements, MDField, ); \
5761 OPTIONAL(runtimeLang, DwarfLangField, ); \
5762 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5763 OPTIONAL(vtableHolder, MDField, ); \
5764 OPTIONAL(templateParams, MDField, ); \
5765 OPTIONAL(identifier, MDStringField, ); \
5766 OPTIONAL(discriminator, MDField, ); \
5767 OPTIONAL(dataLocation, MDField, ); \
5768 OPTIONAL(associated, MDField, ); \
5769 OPTIONAL(allocated, MDField, ); \
5770 OPTIONAL(rank, MDSignedOrMDField, ); \
5771 OPTIONAL(annotations, MDField, ); \
5772 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5773 OPTIONAL(specification, MDField, ); \
5774 OPTIONAL(bitStride, MDField, );
5776#undef VISIT_MD_FIELDS
5777
5778 Metadata *Rank = nullptr;
5779 if (rank.isMDSignedField())
5781 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5782 else if (rank.isMDField())
5783 Rank = rank.getMDFieldValue();
5784
5785 std::optional<unsigned> EnumKind;
5786 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5787 EnumKind = enumKind.Val;
5788
5789 // If this has an identifier try to build an ODR type.
5790 if (identifier.Val)
5791 if (auto *CT = DICompositeType::buildODRType(
5792 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5793 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
5794 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5795 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5796 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5797 dataLocation.Val, associated.Val, allocated.Val, Rank,
5798 annotations.Val, bitStride.Val)) {
5799 Result = CT;
5800 return false;
5801 }
5802
5803 // Create a new node, and save it in the context if it belongs in the type
5804 // map.
5806 DICompositeType,
5807 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5808 size.getValueAsMetadata(Context), align.Val,
5809 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5810 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5811 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5812 allocated.Val, Rank, annotations.Val, specification.Val,
5813 num_extra_inhabitants.Val, bitStride.Val));
5814 return false;
5815}
5816
5817bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5818#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5819 OPTIONAL(flags, DIFlagField, ); \
5820 OPTIONAL(cc, DwarfCCField, ); \
5821 REQUIRED(types, MDField, );
5823#undef VISIT_MD_FIELDS
5824
5825 Result = GET_OR_DISTINCT(DISubroutineType,
5826 (Context, flags.Val, cc.Val, types.Val));
5827 return false;
5828}
5829
5830/// parseDIFileType:
5831/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5832/// checksumkind: CSK_MD5,
5833/// checksum: "000102030405060708090a0b0c0d0e0f",
5834/// source: "source file contents")
5835bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5836 // The default constructed value for checksumkind is required, but will never
5837 // be used, as the parser checks if the field was actually Seen before using
5838 // the Val.
5839#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5840 REQUIRED(filename, MDStringField, ); \
5841 REQUIRED(directory, MDStringField, ); \
5842 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5843 OPTIONAL(checksum, MDStringField, ); \
5844 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5846#undef VISIT_MD_FIELDS
5847
5848 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5849 if (checksumkind.Seen && checksum.Seen)
5850 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5851 else if (checksumkind.Seen || checksum.Seen)
5852 return tokError("'checksumkind' and 'checksum' must be provided together");
5853
5854 MDString *Source = nullptr;
5855 if (source.Seen)
5856 Source = source.Val;
5858 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5859 return false;
5860}
5861
5862/// parseDICompileUnit:
5863/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5864/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5865/// splitDebugFilename: "abc.debug",
5866/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5867/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5868/// sysroot: "/", sdk: "MacOSX.sdk")
5869bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5870 if (!IsDistinct)
5871 return tokError("missing 'distinct', required for !DICompileUnit");
5872
5873 LocTy Loc = Lex.getLoc();
5874
5875#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5876 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5877 OPTIONAL(language, DwarfLangField, ); \
5878 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
5879 OPTIONAL(producer, MDStringField, ); \
5880 OPTIONAL(isOptimized, MDBoolField, ); \
5881 OPTIONAL(flags, MDStringField, ); \
5882 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5883 OPTIONAL(splitDebugFilename, MDStringField, ); \
5884 OPTIONAL(emissionKind, EmissionKindField, ); \
5885 OPTIONAL(enums, MDField, ); \
5886 OPTIONAL(retainedTypes, MDField, ); \
5887 OPTIONAL(globals, MDField, ); \
5888 OPTIONAL(imports, MDField, ); \
5889 OPTIONAL(macros, MDField, ); \
5890 OPTIONAL(dwoId, MDUnsignedField, ); \
5891 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5892 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5893 OPTIONAL(nameTableKind, NameTableKindField, ); \
5894 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5895 OPTIONAL(sysroot, MDStringField, ); \
5896 OPTIONAL(sdk, MDStringField, );
5898#undef VISIT_MD_FIELDS
5899
5900 if (!language.Seen && !sourceLanguageName.Seen)
5901 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
5902 "required for !DICompileUnit");
5903
5904 if (language.Seen && sourceLanguageName.Seen)
5905 return error(Loc, "can only specify one of 'language' and "
5906 "'sourceLanguageName' on !DICompileUnit");
5907
5909 Context,
5910 language.Seen ? DISourceLanguageName(language.Val)
5911 : DISourceLanguageName(sourceLanguageName.Val, 0),
5912 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
5913 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
5914 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
5915 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
5916 sysroot.Val, sdk.Val);
5917 return false;
5918}
5919
5920/// parseDISubprogram:
5921/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5922/// file: !1, line: 7, type: !2, isLocal: false,
5923/// isDefinition: true, scopeLine: 8, containingType: !3,
5924/// virtuality: DW_VIRTUALTIY_pure_virtual,
5925/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5926/// spFlags: 10, isOptimized: false, templateParams: !4,
5927/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5928/// annotations: !8)
5929bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5930 auto Loc = Lex.getLoc();
5931#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5932 OPTIONAL(scope, MDField, ); \
5933 OPTIONAL(name, MDStringField, ); \
5934 OPTIONAL(linkageName, MDStringField, ); \
5935 OPTIONAL(file, MDField, ); \
5936 OPTIONAL(line, LineField, ); \
5937 OPTIONAL(type, MDField, ); \
5938 OPTIONAL(isLocal, MDBoolField, ); \
5939 OPTIONAL(isDefinition, MDBoolField, (true)); \
5940 OPTIONAL(scopeLine, LineField, ); \
5941 OPTIONAL(containingType, MDField, ); \
5942 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5943 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5944 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5945 OPTIONAL(flags, DIFlagField, ); \
5946 OPTIONAL(spFlags, DISPFlagField, ); \
5947 OPTIONAL(isOptimized, MDBoolField, ); \
5948 OPTIONAL(unit, MDField, ); \
5949 OPTIONAL(templateParams, MDField, ); \
5950 OPTIONAL(declaration, MDField, ); \
5951 OPTIONAL(retainedNodes, MDField, ); \
5952 OPTIONAL(thrownTypes, MDField, ); \
5953 OPTIONAL(annotations, MDField, ); \
5954 OPTIONAL(targetFuncName, MDStringField, ); \
5955 OPTIONAL(keyInstructions, MDBoolField, );
5957#undef VISIT_MD_FIELDS
5958
5959 // An explicit spFlags field takes precedence over individual fields in
5960 // older IR versions.
5961 DISubprogram::DISPFlags SPFlags =
5962 spFlags.Seen ? spFlags.Val
5963 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5964 isOptimized.Val, virtuality.Val);
5965 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5966 return error(
5967 Loc,
5968 "missing 'distinct', required for !DISubprogram that is a Definition");
5970 DISubprogram,
5971 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5972 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5973 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5974 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5975 targetFuncName.Val, keyInstructions.Val));
5976 return false;
5977}
5978
5979/// parseDILexicalBlock:
5980/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5981bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5982#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5983 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5984 OPTIONAL(file, MDField, ); \
5985 OPTIONAL(line, LineField, ); \
5986 OPTIONAL(column, ColumnField, );
5988#undef VISIT_MD_FIELDS
5989
5991 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5992 return false;
5993}
5994
5995/// parseDILexicalBlockFile:
5996/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5997bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5998#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5999 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6000 OPTIONAL(file, MDField, ); \
6001 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6003#undef VISIT_MD_FIELDS
6004
6005 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6006 (Context, scope.Val, file.Val, discriminator.Val));
6007 return false;
6008}
6009
6010/// parseDICommonBlock:
6011/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6012bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6013#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6014 REQUIRED(scope, MDField, ); \
6015 OPTIONAL(declaration, MDField, ); \
6016 OPTIONAL(name, MDStringField, ); \
6017 OPTIONAL(file, MDField, ); \
6018 OPTIONAL(line, LineField, );
6020#undef VISIT_MD_FIELDS
6021
6022 Result = GET_OR_DISTINCT(DICommonBlock,
6023 (Context, scope.Val, declaration.Val, name.Val,
6024 file.Val, line.Val));
6025 return false;
6026}
6027
6028/// parseDINamespace:
6029/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6030bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6031#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6032 REQUIRED(scope, MDField, ); \
6033 OPTIONAL(name, MDStringField, ); \
6034 OPTIONAL(exportSymbols, MDBoolField, );
6036#undef VISIT_MD_FIELDS
6037
6038 Result = GET_OR_DISTINCT(DINamespace,
6039 (Context, scope.Val, name.Val, exportSymbols.Val));
6040 return false;
6041}
6042
6043/// parseDIMacro:
6044/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6045/// "SomeValue")
6046bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6047#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6048 REQUIRED(type, DwarfMacinfoTypeField, ); \
6049 OPTIONAL(line, LineField, ); \
6050 REQUIRED(name, MDStringField, ); \
6051 OPTIONAL(value, MDStringField, );
6053#undef VISIT_MD_FIELDS
6054
6055 Result = GET_OR_DISTINCT(DIMacro,
6056 (Context, type.Val, line.Val, name.Val, value.Val));
6057 return false;
6058}
6059
6060/// parseDIMacroFile:
6061/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6062bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6063#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6064 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6065 OPTIONAL(line, LineField, ); \
6066 REQUIRED(file, MDField, ); \
6067 OPTIONAL(nodes, MDField, );
6069#undef VISIT_MD_FIELDS
6070
6071 Result = GET_OR_DISTINCT(DIMacroFile,
6072 (Context, type.Val, line.Val, file.Val, nodes.Val));
6073 return false;
6074}
6075
6076/// parseDIModule:
6077/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6078/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6079/// file: !1, line: 4, isDecl: false)
6080bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6081#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6082 REQUIRED(scope, MDField, ); \
6083 REQUIRED(name, MDStringField, ); \
6084 OPTIONAL(configMacros, MDStringField, ); \
6085 OPTIONAL(includePath, MDStringField, ); \
6086 OPTIONAL(apinotes, MDStringField, ); \
6087 OPTIONAL(file, MDField, ); \
6088 OPTIONAL(line, LineField, ); \
6089 OPTIONAL(isDecl, MDBoolField, );
6091#undef VISIT_MD_FIELDS
6092
6093 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6094 configMacros.Val, includePath.Val,
6095 apinotes.Val, line.Val, isDecl.Val));
6096 return false;
6097}
6098
6099/// parseDITemplateTypeParameter:
6100/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6101bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6102#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6103 OPTIONAL(name, MDStringField, ); \
6104 REQUIRED(type, MDField, ); \
6105 OPTIONAL(defaulted, MDBoolField, );
6107#undef VISIT_MD_FIELDS
6108
6109 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6110 (Context, name.Val, type.Val, defaulted.Val));
6111 return false;
6112}
6113
6114/// parseDITemplateValueParameter:
6115/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6116/// name: "V", type: !1, defaulted: false,
6117/// value: i32 7)
6118bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6119#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6120 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6121 OPTIONAL(name, MDStringField, ); \
6122 OPTIONAL(type, MDField, ); \
6123 OPTIONAL(defaulted, MDBoolField, ); \
6124 REQUIRED(value, MDField, );
6125
6127#undef VISIT_MD_FIELDS
6128
6130 DITemplateValueParameter,
6131 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6132 return false;
6133}
6134
6135/// parseDIGlobalVariable:
6136/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6137/// file: !1, line: 7, type: !2, isLocal: false,
6138/// isDefinition: true, templateParams: !3,
6139/// declaration: !4, align: 8)
6140bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6141#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6142 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6143 OPTIONAL(scope, MDField, ); \
6144 OPTIONAL(linkageName, MDStringField, ); \
6145 OPTIONAL(file, MDField, ); \
6146 OPTIONAL(line, LineField, ); \
6147 OPTIONAL(type, MDField, ); \
6148 OPTIONAL(isLocal, MDBoolField, ); \
6149 OPTIONAL(isDefinition, MDBoolField, (true)); \
6150 OPTIONAL(templateParams, MDField, ); \
6151 OPTIONAL(declaration, MDField, ); \
6152 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6153 OPTIONAL(annotations, MDField, );
6155#undef VISIT_MD_FIELDS
6156
6157 Result =
6158 GET_OR_DISTINCT(DIGlobalVariable,
6159 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6160 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6161 declaration.Val, templateParams.Val, align.Val,
6162 annotations.Val));
6163 return false;
6164}
6165
6166/// parseDILocalVariable:
6167/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6168/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6169/// align: 8)
6170/// ::= !DILocalVariable(scope: !0, name: "foo",
6171/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6172/// align: 8)
6173bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6174#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6175 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6176 OPTIONAL(name, MDStringField, ); \
6177 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6178 OPTIONAL(file, MDField, ); \
6179 OPTIONAL(line, LineField, ); \
6180 OPTIONAL(type, MDField, ); \
6181 OPTIONAL(flags, DIFlagField, ); \
6182 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6183 OPTIONAL(annotations, MDField, );
6185#undef VISIT_MD_FIELDS
6186
6187 Result = GET_OR_DISTINCT(DILocalVariable,
6188 (Context, scope.Val, name.Val, file.Val, line.Val,
6189 type.Val, arg.Val, flags.Val, align.Val,
6190 annotations.Val));
6191 return false;
6192}
6193
6194/// parseDILabel:
6195/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6196bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6197#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6198 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6199 REQUIRED(name, MDStringField, ); \
6200 REQUIRED(file, MDField, ); \
6201 REQUIRED(line, LineField, ); \
6202 OPTIONAL(column, ColumnField, ); \
6203 OPTIONAL(isArtificial, MDBoolField, ); \
6204 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6206#undef VISIT_MD_FIELDS
6207
6208 std::optional<unsigned> CoroSuspendIdx =
6209 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6210 : std::nullopt;
6211
6212 Result = GET_OR_DISTINCT(DILabel,
6213 (Context, scope.Val, name.Val, file.Val, line.Val,
6214 column.Val, isArtificial.Val, CoroSuspendIdx));
6215 return false;
6216}
6217
6218/// parseDIExpressionBody:
6219/// ::= (0, 7, -1)
6220bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6221 if (parseToken(lltok::lparen, "expected '(' here"))
6222 return true;
6223
6224 SmallVector<uint64_t, 8> Elements;
6225 if (Lex.getKind() != lltok::rparen)
6226 do {
6227 if (Lex.getKind() == lltok::DwarfOp) {
6228 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6229 Lex.Lex();
6230 Elements.push_back(Op);
6231 continue;
6232 }
6233 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6234 }
6235
6236 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6237 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6238 Lex.Lex();
6239 Elements.push_back(Op);
6240 continue;
6241 }
6242 return tokError(Twine("invalid DWARF attribute encoding '") +
6243 Lex.getStrVal() + "'");
6244 }
6245
6246 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6247 return tokError("expected unsigned integer");
6248
6249 auto &U = Lex.getAPSIntVal();
6250 if (U.ugt(UINT64_MAX))
6251 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6252 Elements.push_back(U.getZExtValue());
6253 Lex.Lex();
6254 } while (EatIfPresent(lltok::comma));
6255
6256 if (parseToken(lltok::rparen, "expected ')' here"))
6257 return true;
6258
6259 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6260 return false;
6261}
6262
6263/// parseDIExpression:
6264/// ::= !DIExpression(0, 7, -1)
6265bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6266 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6267 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6268 Lex.Lex();
6269
6270 return parseDIExpressionBody(Result, IsDistinct);
6271}
6272
6273/// ParseDIArgList:
6274/// ::= !DIArgList(i32 7, i64 %0)
6275bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6276 assert(PFS && "Expected valid function state");
6277 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6278 Lex.Lex();
6279
6280 if (parseToken(lltok::lparen, "expected '(' here"))
6281 return true;
6282
6284 if (Lex.getKind() != lltok::rparen)
6285 do {
6286 Metadata *MD;
6287 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6288 return true;
6289 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6290 } while (EatIfPresent(lltok::comma));
6291
6292 if (parseToken(lltok::rparen, "expected ')' here"))
6293 return true;
6294
6295 MD = DIArgList::get(Context, Args);
6296 return false;
6297}
6298
6299/// parseDIGlobalVariableExpression:
6300/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6301bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6302 bool IsDistinct) {
6303#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6304 REQUIRED(var, MDField, ); \
6305 REQUIRED(expr, MDField, );
6307#undef VISIT_MD_FIELDS
6308
6309 Result =
6310 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6311 return false;
6312}
6313
6314/// parseDIObjCProperty:
6315/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6316/// getter: "getFoo", attributes: 7, type: !2)
6317bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6318#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6319 OPTIONAL(name, MDStringField, ); \
6320 OPTIONAL(file, MDField, ); \
6321 OPTIONAL(line, LineField, ); \
6322 OPTIONAL(setter, MDStringField, ); \
6323 OPTIONAL(getter, MDStringField, ); \
6324 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6325 OPTIONAL(type, MDField, );
6327#undef VISIT_MD_FIELDS
6328
6329 Result = GET_OR_DISTINCT(DIObjCProperty,
6330 (Context, name.Val, file.Val, line.Val, setter.Val,
6331 getter.Val, attributes.Val, type.Val));
6332 return false;
6333}
6334
6335/// parseDIImportedEntity:
6336/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6337/// line: 7, name: "foo", elements: !2)
6338bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6339#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6340 REQUIRED(tag, DwarfTagField, ); \
6341 REQUIRED(scope, MDField, ); \
6342 OPTIONAL(entity, MDField, ); \
6343 OPTIONAL(file, MDField, ); \
6344 OPTIONAL(line, LineField, ); \
6345 OPTIONAL(name, MDStringField, ); \
6346 OPTIONAL(elements, MDField, );
6348#undef VISIT_MD_FIELDS
6349
6350 Result = GET_OR_DISTINCT(DIImportedEntity,
6351 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6352 line.Val, name.Val, elements.Val));
6353 return false;
6354}
6355
6356#undef PARSE_MD_FIELD
6357#undef NOP_FIELD
6358#undef REQUIRE_FIELD
6359#undef DECLARE_FIELD
6360
6361/// parseMetadataAsValue
6362/// ::= metadata i32 %local
6363/// ::= metadata i32 @global
6364/// ::= metadata i32 7
6365/// ::= metadata !0
6366/// ::= metadata !{...}
6367/// ::= metadata !"string"
6368bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6369 // Note: the type 'metadata' has already been parsed.
6370 Metadata *MD;
6371 if (parseMetadata(MD, &PFS))
6372 return true;
6373
6374 V = MetadataAsValue::get(Context, MD);
6375 return false;
6376}
6377
6378/// parseValueAsMetadata
6379/// ::= i32 %local
6380/// ::= i32 @global
6381/// ::= i32 7
6382bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6383 PerFunctionState *PFS) {
6384 Type *Ty;
6385 LocTy Loc;
6386 if (parseType(Ty, TypeMsg, Loc))
6387 return true;
6388 if (Ty->isMetadataTy())
6389 return error(Loc, "invalid metadata-value-metadata roundtrip");
6390
6391 Value *V;
6392 if (parseValue(Ty, V, PFS))
6393 return true;
6394
6395 MD = ValueAsMetadata::get(V);
6396 return false;
6397}
6398
6399/// parseMetadata
6400/// ::= i32 %local
6401/// ::= i32 @global
6402/// ::= i32 7
6403/// ::= !42
6404/// ::= !{...}
6405/// ::= !"string"
6406/// ::= !DILocation(...)
6407bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6408 if (Lex.getKind() == lltok::MetadataVar) {
6409 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6410 // so parsing this requires a Function State.
6411 if (Lex.getStrVal() == "DIArgList") {
6412 Metadata *AL;
6413 if (parseDIArgList(AL, PFS))
6414 return true;
6415 MD = AL;
6416 return false;
6417 }
6418 MDNode *N;
6419 if (parseSpecializedMDNode(N)) {
6420 return true;
6421 }
6422 MD = N;
6423 return false;
6424 }
6425
6426 // ValueAsMetadata:
6427 // <type> <value>
6428 if (Lex.getKind() != lltok::exclaim)
6429 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6430
6431 // '!'.
6432 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6433 Lex.Lex();
6434
6435 // MDString:
6436 // ::= '!' STRINGCONSTANT
6437 if (Lex.getKind() == lltok::StringConstant) {
6438 MDString *S;
6439 if (parseMDString(S))
6440 return true;
6441 MD = S;
6442 return false;
6443 }
6444
6445 // MDNode:
6446 // !{ ... }
6447 // !7
6448 MDNode *N;
6449 if (parseMDNodeTail(N))
6450 return true;
6451 MD = N;
6452 return false;
6453}
6454
6455//===----------------------------------------------------------------------===//
6456// Function Parsing.
6457//===----------------------------------------------------------------------===//
6458
6459bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6460 PerFunctionState *PFS) {
6461 if (Ty->isFunctionTy())
6462 return error(ID.Loc, "functions are not values, refer to them as pointers");
6463
6464 switch (ID.Kind) {
6465 case ValID::t_LocalID:
6466 if (!PFS)
6467 return error(ID.Loc, "invalid use of function-local name");
6468 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6469 return V == nullptr;
6470 case ValID::t_LocalName:
6471 if (!PFS)
6472 return error(ID.Loc, "invalid use of function-local name");
6473 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6474 return V == nullptr;
6475 case ValID::t_InlineAsm: {
6476 if (!ID.FTy)
6477 return error(ID.Loc, "invalid type for inline asm constraint string");
6478 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6479 return error(ID.Loc, toString(std::move(Err)));
6480 V = InlineAsm::get(
6481 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6482 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6483 return false;
6484 }
6486 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6487 if (V && ID.NoCFI)
6489 return V == nullptr;
6490 case ValID::t_GlobalID:
6491 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6492 if (V && ID.NoCFI)
6494 return V == nullptr;
6495 case ValID::t_APSInt:
6496 if (!Ty->isIntegerTy())
6497 return error(ID.Loc, "integer constant must have integer type");
6498 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6499 V = ConstantInt::get(Context, ID.APSIntVal);
6500 return false;
6501 case ValID::t_APFloat:
6502 if (!Ty->isFloatingPointTy() ||
6503 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6504 return error(ID.Loc, "floating point constant invalid for type");
6505
6506 // The lexer has no type info, so builds all half, bfloat, float, and double
6507 // FP constants as double. Fix this here. Long double does not need this.
6508 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6509 // Check for signaling before potentially converting and losing that info.
6510 bool IsSNAN = ID.APFloatVal.isSignaling();
6511 bool Ignored;
6512 if (Ty->isHalfTy())
6514 &Ignored);
6515 else if (Ty->isBFloatTy())
6516 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6517 &Ignored);
6518 else if (Ty->isFloatTy())
6520 &Ignored);
6521 if (IsSNAN) {
6522 // The convert call above may quiet an SNaN, so manufacture another
6523 // SNaN. The bitcast works because the payload (significand) parameter
6524 // is truncated to fit.
6525 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6526 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6527 ID.APFloatVal.isNegative(), &Payload);
6528 }
6529 }
6530 V = ConstantFP::get(Context, ID.APFloatVal);
6531
6532 if (V->getType() != Ty)
6533 return error(ID.Loc, "floating point constant does not have type '" +
6534 getTypeString(Ty) + "'");
6535
6536 return false;
6537 case ValID::t_Null:
6538 if (!Ty->isPointerTy())
6539 return error(ID.Loc, "null must be a pointer type");
6541 return false;
6542 case ValID::t_Undef:
6543 // FIXME: LabelTy should not be a first-class type.
6544 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6545 return error(ID.Loc, "invalid type for undef constant");
6546 V = UndefValue::get(Ty);
6547 return false;
6549 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6550 return error(ID.Loc, "invalid empty array initializer");
6551 V = PoisonValue::get(Ty);
6552 return false;
6553 case ValID::t_Zero:
6554 // FIXME: LabelTy should not be a first-class type.
6555 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6556 return error(ID.Loc, "invalid type for null constant");
6557 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6558 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6559 return error(ID.Loc, "invalid type for null constant");
6561 return false;
6562 case ValID::t_None:
6563 if (!Ty->isTokenTy())
6564 return error(ID.Loc, "invalid type for none constant");
6566 return false;
6567 case ValID::t_Poison:
6568 // FIXME: LabelTy should not be a first-class type.
6569 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6570 return error(ID.Loc, "invalid type for poison constant");
6571 V = PoisonValue::get(Ty);
6572 return false;
6573 case ValID::t_Constant:
6574 if (ID.ConstantVal->getType() != Ty)
6575 return error(ID.Loc, "constant expression type mismatch: got type '" +
6576 getTypeString(ID.ConstantVal->getType()) +
6577 "' but expected '" + getTypeString(Ty) + "'");
6578 V = ID.ConstantVal;
6579 return false;
6581 if (!Ty->isVectorTy())
6582 return error(ID.Loc, "vector constant must have vector type");
6583 if (ID.ConstantVal->getType() != Ty->getScalarType())
6584 return error(ID.Loc, "constant expression type mismatch: got type '" +
6585 getTypeString(ID.ConstantVal->getType()) +
6586 "' but expected '" +
6587 getTypeString(Ty->getScalarType()) + "'");
6588 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6589 ID.ConstantVal);
6590 return false;
6593 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6594 if (ST->getNumElements() != ID.UIntVal)
6595 return error(ID.Loc,
6596 "initializer with struct type has wrong # elements");
6597 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6598 return error(ID.Loc, "packed'ness of initializer and type don't match");
6599
6600 // Verify that the elements are compatible with the structtype.
6601 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6602 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6603 return error(
6604 ID.Loc,
6605 "element " + Twine(i) +
6606 " of struct initializer doesn't match struct element type");
6607
6609 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6610 } else
6611 return error(ID.Loc, "constant expression type mismatch");
6612 return false;
6613 }
6614 llvm_unreachable("Invalid ValID");
6615}
6616
6617bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6618 C = nullptr;
6619 ValID ID;
6620 auto Loc = Lex.getLoc();
6621 if (parseValID(ID, /*PFS=*/nullptr))
6622 return true;
6623 switch (ID.Kind) {
6624 case ValID::t_APSInt:
6625 case ValID::t_APFloat:
6626 case ValID::t_Undef:
6627 case ValID::t_Poison:
6628 case ValID::t_Zero:
6629 case ValID::t_Constant:
6633 Value *V;
6634 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6635 return true;
6636 assert(isa<Constant>(V) && "Expected a constant value");
6637 C = cast<Constant>(V);
6638 return false;
6639 }
6640 case ValID::t_Null:
6642 return false;
6643 default:
6644 return error(Loc, "expected a constant value");
6645 }
6646}
6647
6648bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6649 V = nullptr;
6650 ValID ID;
6651 return parseValID(ID, PFS, Ty) ||
6652 convertValIDToValue(Ty, ID, V, PFS);
6653}
6654
6655bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6656 Type *Ty = nullptr;
6657 return parseType(Ty) || parseValue(Ty, V, PFS);
6658}
6659
6660bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6661 PerFunctionState &PFS) {
6662 Value *V;
6663 Loc = Lex.getLoc();
6664 if (parseTypeAndValue(V, PFS))
6665 return true;
6666 if (!isa<BasicBlock>(V))
6667 return error(Loc, "expected a basic block");
6668 BB = cast<BasicBlock>(V);
6669 return false;
6670}
6671
6673 // Exit early for the common (non-debug-intrinsic) case.
6674 // We can make this the only check when we begin supporting all "llvm.dbg"
6675 // intrinsics in the new debug info format.
6676 if (!Name.starts_with("llvm.dbg."))
6677 return false;
6679 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6680 FnID == Intrinsic::dbg_assign;
6681}
6682
6683/// FunctionHeader
6684/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6685/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6686/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6687/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6688bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6689 unsigned &FunctionNumber,
6690 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6691 // parse the linkage.
6692 LocTy LinkageLoc = Lex.getLoc();
6693 unsigned Linkage;
6694 unsigned Visibility;
6695 unsigned DLLStorageClass;
6696 bool DSOLocal;
6697 AttrBuilder RetAttrs(M->getContext());
6698 unsigned CC;
6699 bool HasLinkage;
6700 Type *RetType = nullptr;
6701 LocTy RetTypeLoc = Lex.getLoc();
6702 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6703 DSOLocal) ||
6704 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6705 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6706 return true;
6707
6708 // Verify that the linkage is ok.
6711 break; // always ok.
6713 if (IsDefine)
6714 return error(LinkageLoc, "invalid linkage for function definition");
6715 break;
6723 if (!IsDefine)
6724 return error(LinkageLoc, "invalid linkage for function declaration");
6725 break;
6728 return error(LinkageLoc, "invalid function linkage type");
6729 }
6730
6731 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6732 return error(LinkageLoc,
6733 "symbol with local linkage must have default visibility");
6734
6735 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6736 return error(LinkageLoc,
6737 "symbol with local linkage cannot have a DLL storage class");
6738
6739 if (!FunctionType::isValidReturnType(RetType))
6740 return error(RetTypeLoc, "invalid function return type");
6741
6742 LocTy NameLoc = Lex.getLoc();
6743
6744 std::string FunctionName;
6745 if (Lex.getKind() == lltok::GlobalVar) {
6746 FunctionName = Lex.getStrVal();
6747 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6748 FunctionNumber = Lex.getUIntVal();
6749 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6750 FunctionNumber))
6751 return true;
6752 } else {
6753 return tokError("expected function name");
6754 }
6755
6756 Lex.Lex();
6757
6758 if (Lex.getKind() != lltok::lparen)
6759 return tokError("expected '(' in function argument list");
6760
6762 bool IsVarArg;
6763 AttrBuilder FuncAttrs(M->getContext());
6764 std::vector<unsigned> FwdRefAttrGrps;
6765 LocTy BuiltinLoc;
6766 std::string Section;
6767 std::string Partition;
6768 MaybeAlign Alignment;
6769 std::string GC;
6771 unsigned AddrSpace = 0;
6772 Constant *Prefix = nullptr;
6773 Constant *Prologue = nullptr;
6774 Constant *PersonalityFn = nullptr;
6775 Comdat *C;
6776
6777 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6778 parseOptionalUnnamedAddr(UnnamedAddr) ||
6779 parseOptionalProgramAddrSpace(AddrSpace) ||
6780 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6781 BuiltinLoc) ||
6782 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6783 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6784 parseOptionalComdat(FunctionName, C) ||
6785 parseOptionalAlignment(Alignment) ||
6786 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6787 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6788 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6789 (EatIfPresent(lltok::kw_personality) &&
6790 parseGlobalTypeAndValue(PersonalityFn)))
6791 return true;
6792
6793 if (FuncAttrs.contains(Attribute::Builtin))
6794 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6795
6796 // If the alignment was parsed as an attribute, move to the alignment field.
6797 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6798 Alignment = A;
6799 FuncAttrs.removeAttribute(Attribute::Alignment);
6800 }
6801
6802 // Okay, if we got here, the function is syntactically valid. Convert types
6803 // and do semantic checks.
6804 std::vector<Type*> ParamTypeList;
6806
6807 for (const ArgInfo &Arg : ArgList) {
6808 ParamTypeList.push_back(Arg.Ty);
6809 Attrs.push_back(Arg.Attrs);
6810 }
6811
6812 AttributeList PAL =
6813 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6814 AttributeSet::get(Context, RetAttrs), Attrs);
6815
6816 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6817 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6818
6819 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6820 PointerType *PFT = PointerType::get(Context, AddrSpace);
6821
6822 Fn = nullptr;
6823 GlobalValue *FwdFn = nullptr;
6824 if (!FunctionName.empty()) {
6825 // If this was a definition of a forward reference, remove the definition
6826 // from the forward reference table and fill in the forward ref.
6827 auto FRVI = ForwardRefVals.find(FunctionName);
6828 if (FRVI != ForwardRefVals.end()) {
6829 FwdFn = FRVI->second.first;
6830 if (FwdFn->getType() != PFT)
6831 return error(FRVI->second.second,
6832 "invalid forward reference to "
6833 "function '" +
6834 FunctionName +
6835 "' with wrong type: "
6836 "expected '" +
6837 getTypeString(PFT) + "' but was '" +
6838 getTypeString(FwdFn->getType()) + "'");
6839 ForwardRefVals.erase(FRVI);
6840 } else if ((Fn = M->getFunction(FunctionName))) {
6841 // Reject redefinitions.
6842 return error(NameLoc,
6843 "invalid redefinition of function '" + FunctionName + "'");
6844 } else if (M->getNamedValue(FunctionName)) {
6845 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6846 }
6847
6848 } else {
6849 // Handle @"", where a name is syntactically specified, but semantically
6850 // missing.
6851 if (FunctionNumber == (unsigned)-1)
6852 FunctionNumber = NumberedVals.getNext();
6853
6854 // If this is a definition of a forward referenced function, make sure the
6855 // types agree.
6856 auto I = ForwardRefValIDs.find(FunctionNumber);
6857 if (I != ForwardRefValIDs.end()) {
6858 FwdFn = I->second.first;
6859 if (FwdFn->getType() != PFT)
6860 return error(NameLoc, "type of definition and forward reference of '@" +
6861 Twine(FunctionNumber) +
6862 "' disagree: "
6863 "expected '" +
6864 getTypeString(PFT) + "' but was '" +
6865 getTypeString(FwdFn->getType()) + "'");
6866 ForwardRefValIDs.erase(I);
6867 }
6868 }
6869
6871 FunctionName, M);
6872
6873 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6874
6875 if (FunctionName.empty())
6876 NumberedVals.add(FunctionNumber, Fn);
6877
6879 maybeSetDSOLocal(DSOLocal, *Fn);
6882 Fn->setCallingConv(CC);
6883 Fn->setAttributes(PAL);
6884 Fn->setUnnamedAddr(UnnamedAddr);
6885 if (Alignment)
6886 Fn->setAlignment(*Alignment);
6887 Fn->setSection(Section);
6888 Fn->setPartition(Partition);
6889 Fn->setComdat(C);
6890 Fn->setPersonalityFn(PersonalityFn);
6891 if (!GC.empty()) Fn->setGC(GC);
6892 Fn->setPrefixData(Prefix);
6893 Fn->setPrologueData(Prologue);
6894 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6895
6896 // Add all of the arguments we parsed to the function.
6897 Function::arg_iterator ArgIt = Fn->arg_begin();
6898 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6899 // If the argument has a name, insert it into the argument symbol table.
6900 if (ArgList[i].Name.empty()) continue;
6901
6902 // Set the name, if it conflicted, it will be auto-renamed.
6903 ArgIt->setName(ArgList[i].Name);
6904
6905 if (ArgIt->getName() != ArgList[i].Name)
6906 return error(ArgList[i].Loc,
6907 "redefinition of argument '%" + ArgList[i].Name + "'");
6908 }
6909
6910 if (FwdFn) {
6911 FwdFn->replaceAllUsesWith(Fn);
6912 FwdFn->eraseFromParent();
6913 }
6914
6915 if (IsDefine)
6916 return false;
6917
6918 // Check the declaration has no block address forward references.
6919 ValID ID;
6920 if (FunctionName.empty()) {
6921 ID.Kind = ValID::t_GlobalID;
6922 ID.UIntVal = FunctionNumber;
6923 } else {
6924 ID.Kind = ValID::t_GlobalName;
6925 ID.StrVal = FunctionName;
6926 }
6927 auto Blocks = ForwardRefBlockAddresses.find(ID);
6928 if (Blocks != ForwardRefBlockAddresses.end())
6929 return error(Blocks->first.Loc,
6930 "cannot take blockaddress inside a declaration");
6931 return false;
6932}
6933
6934bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6935 ValID ID;
6936 if (FunctionNumber == -1) {
6937 ID.Kind = ValID::t_GlobalName;
6938 ID.StrVal = std::string(F.getName());
6939 } else {
6940 ID.Kind = ValID::t_GlobalID;
6941 ID.UIntVal = FunctionNumber;
6942 }
6943
6944 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6945 if (Blocks == P.ForwardRefBlockAddresses.end())
6946 return false;
6947
6948 for (const auto &I : Blocks->second) {
6949 const ValID &BBID = I.first;
6950 GlobalValue *GV = I.second;
6951
6952 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6953 "Expected local id or name");
6954 BasicBlock *BB;
6955 if (BBID.Kind == ValID::t_LocalName)
6956 BB = getBB(BBID.StrVal, BBID.Loc);
6957 else
6958 BB = getBB(BBID.UIntVal, BBID.Loc);
6959 if (!BB)
6960 return P.error(BBID.Loc, "referenced value is not a basic block");
6961
6962 Value *ResolvedVal = BlockAddress::get(&F, BB);
6963 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6964 ResolvedVal);
6965 if (!ResolvedVal)
6966 return true;
6967 GV->replaceAllUsesWith(ResolvedVal);
6968 GV->eraseFromParent();
6969 }
6970
6971 P.ForwardRefBlockAddresses.erase(Blocks);
6972 return false;
6973}
6974
6975/// parseFunctionBody
6976/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6977bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6978 ArrayRef<unsigned> UnnamedArgNums) {
6979 if (Lex.getKind() != lltok::lbrace)
6980 return tokError("expected '{' in function body");
6981 Lex.Lex(); // eat the {.
6982
6983 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
6984
6985 // Resolve block addresses and allow basic blocks to be forward-declared
6986 // within this function.
6987 if (PFS.resolveForwardRefBlockAddresses())
6988 return true;
6989 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6990
6991 // We need at least one basic block.
6992 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6993 return tokError("function body requires at least one basic block");
6994
6995 while (Lex.getKind() != lltok::rbrace &&
6996 Lex.getKind() != lltok::kw_uselistorder)
6997 if (parseBasicBlock(PFS))
6998 return true;
6999
7000 while (Lex.getKind() != lltok::rbrace)
7001 if (parseUseListOrder(&PFS))
7002 return true;
7003
7004 // Eat the }.
7005 Lex.Lex();
7006
7007 // Verify function is ok.
7008 return PFS.finishFunction();
7009}
7010
7011/// parseBasicBlock
7012/// ::= (LabelStr|LabelID)? Instruction*
7013bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7014 // If this basic block starts out with a name, remember it.
7015 std::string Name;
7016 int NameID = -1;
7017 LocTy NameLoc = Lex.getLoc();
7018 if (Lex.getKind() == lltok::LabelStr) {
7019 Name = Lex.getStrVal();
7020 Lex.Lex();
7021 } else if (Lex.getKind() == lltok::LabelID) {
7022 NameID = Lex.getUIntVal();
7023 Lex.Lex();
7024 }
7025
7026 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7027 if (!BB)
7028 return true;
7029
7030 std::string NameStr;
7031
7032 // Parse the instructions and debug values in this block until we get a
7033 // terminator.
7034 Instruction *Inst;
7035 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7036 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7037 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7038 do {
7039 // Handle debug records first - there should always be an instruction
7040 // following the debug records, i.e. they cannot appear after the block
7041 // terminator.
7042 while (Lex.getKind() == lltok::hash) {
7043 if (SeenOldDbgInfoFormat)
7044 return error(Lex.getLoc(), "debug record should not appear in a module "
7045 "containing debug info intrinsics");
7046 SeenNewDbgInfoFormat = true;
7047 Lex.Lex();
7048
7049 DbgRecord *DR;
7050 if (parseDebugRecord(DR, PFS))
7051 return true;
7052 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7053 }
7054
7055 // This instruction may have three possibilities for a name: a) none
7056 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7057 LocTy NameLoc = Lex.getLoc();
7058 int NameID = -1;
7059 NameStr = "";
7060
7061 if (Lex.getKind() == lltok::LocalVarID) {
7062 NameID = Lex.getUIntVal();
7063 Lex.Lex();
7064 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7065 return true;
7066 } else if (Lex.getKind() == lltok::LocalVar) {
7067 NameStr = Lex.getStrVal();
7068 Lex.Lex();
7069 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7070 return true;
7071 }
7072
7073 switch (parseInstruction(Inst, BB, PFS)) {
7074 default:
7075 llvm_unreachable("Unknown parseInstruction result!");
7076 case InstError: return true;
7077 case InstNormal:
7078 Inst->insertInto(BB, BB->end());
7079
7080 // With a normal result, we check to see if the instruction is followed by
7081 // a comma and metadata.
7082 if (EatIfPresent(lltok::comma))
7083 if (parseInstructionMetadata(*Inst))
7084 return true;
7085 break;
7086 case InstExtraComma:
7087 Inst->insertInto(BB, BB->end());
7088
7089 // If the instruction parser ate an extra comma at the end of it, it
7090 // *must* be followed by metadata.
7091 if (parseInstructionMetadata(*Inst))
7092 return true;
7093 break;
7094 }
7095
7096 // Set the name on the instruction.
7097 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7098 return true;
7099
7100 // Attach any preceding debug values to this instruction.
7101 for (DbgRecordPtr &DR : TrailingDbgRecord)
7102 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7103 TrailingDbgRecord.clear();
7104 } while (!Inst->isTerminator());
7105
7106 assert(TrailingDbgRecord.empty() &&
7107 "All debug values should have been attached to an instruction.");
7108
7109 return false;
7110}
7111
7112/// parseDebugRecord
7113/// ::= #dbg_label '(' MDNode ')'
7114/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7115/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7116bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7117 using RecordKind = DbgRecord::Kind;
7118 using LocType = DbgVariableRecord::LocationType;
7119 LocTy DVRLoc = Lex.getLoc();
7120 if (Lex.getKind() != lltok::DbgRecordType)
7121 return error(DVRLoc, "expected debug record type here");
7122 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7123 .Case("declare", RecordKind::ValueKind)
7124 .Case("value", RecordKind::ValueKind)
7125 .Case("assign", RecordKind::ValueKind)
7126 .Case("label", RecordKind::LabelKind);
7127
7128 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7129 // full DbgVariableRecord processing stage.
7130 if (RecordType == RecordKind::LabelKind) {
7131 Lex.Lex();
7132 if (parseToken(lltok::lparen, "Expected '(' here"))
7133 return true;
7134 MDNode *Label;
7135 if (parseMDNode(Label))
7136 return true;
7137 if (parseToken(lltok::comma, "Expected ',' here"))
7138 return true;
7139 MDNode *DbgLoc;
7140 if (parseMDNode(DbgLoc))
7141 return true;
7142 if (parseToken(lltok::rparen, "Expected ')' here"))
7143 return true;
7145 return false;
7146 }
7147
7148 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7149 .Case("declare", LocType::Declare)
7150 .Case("value", LocType::Value)
7151 .Case("assign", LocType::Assign);
7152
7153 Lex.Lex();
7154 if (parseToken(lltok::lparen, "Expected '(' here"))
7155 return true;
7156
7157 // Parse Value field.
7158 Metadata *ValLocMD;
7159 if (parseMetadata(ValLocMD, &PFS))
7160 return true;
7161 if (parseToken(lltok::comma, "Expected ',' here"))
7162 return true;
7163
7164 // Parse Variable field.
7165 MDNode *Variable;
7166 if (parseMDNode(Variable))
7167 return true;
7168 if (parseToken(lltok::comma, "Expected ',' here"))
7169 return true;
7170
7171 // Parse Expression field.
7172 MDNode *Expression;
7173 if (parseMDNode(Expression))
7174 return true;
7175 if (parseToken(lltok::comma, "Expected ',' here"))
7176 return true;
7177
7178 // Parse additional fields for #dbg_assign.
7179 MDNode *AssignID = nullptr;
7180 Metadata *AddressLocation = nullptr;
7181 MDNode *AddressExpression = nullptr;
7182 if (ValueType == LocType::Assign) {
7183 // Parse DIAssignID.
7184 if (parseMDNode(AssignID))
7185 return true;
7186 if (parseToken(lltok::comma, "Expected ',' here"))
7187 return true;
7188
7189 // Parse address ValueAsMetadata.
7190 if (parseMetadata(AddressLocation, &PFS))
7191 return true;
7192 if (parseToken(lltok::comma, "Expected ',' here"))
7193 return true;
7194
7195 // Parse address DIExpression.
7196 if (parseMDNode(AddressExpression))
7197 return true;
7198 if (parseToken(lltok::comma, "Expected ',' here"))
7199 return true;
7200 }
7201
7202 /// Parse DILocation.
7203 MDNode *DebugLoc;
7204 if (parseMDNode(DebugLoc))
7205 return true;
7206
7207 if (parseToken(lltok::rparen, "Expected ')' here"))
7208 return true;
7210 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7211 AddressExpression, DebugLoc);
7212 return false;
7213}
7214//===----------------------------------------------------------------------===//
7215// Instruction Parsing.
7216//===----------------------------------------------------------------------===//
7217
7218/// parseInstruction - parse one of the many different instructions.
7219///
7220int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7221 PerFunctionState &PFS) {
7222 lltok::Kind Token = Lex.getKind();
7223 if (Token == lltok::Eof)
7224 return tokError("found end of file when expecting more instructions");
7225 LocTy Loc = Lex.getLoc();
7226 unsigned KeywordVal = Lex.getUIntVal();
7227 Lex.Lex(); // Eat the keyword.
7228
7229 switch (Token) {
7230 default:
7231 return error(Loc, "expected instruction opcode");
7232 // Terminator Instructions.
7233 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7234 case lltok::kw_ret:
7235 return parseRet(Inst, BB, PFS);
7236 case lltok::kw_br:
7237 return parseBr(Inst, PFS);
7238 case lltok::kw_switch:
7239 return parseSwitch(Inst, PFS);
7241 return parseIndirectBr(Inst, PFS);
7242 case lltok::kw_invoke:
7243 return parseInvoke(Inst, PFS);
7244 case lltok::kw_resume:
7245 return parseResume(Inst, PFS);
7247 return parseCleanupRet(Inst, PFS);
7248 case lltok::kw_catchret:
7249 return parseCatchRet(Inst, PFS);
7251 return parseCatchSwitch(Inst, PFS);
7252 case lltok::kw_catchpad:
7253 return parseCatchPad(Inst, PFS);
7255 return parseCleanupPad(Inst, PFS);
7256 case lltok::kw_callbr:
7257 return parseCallBr(Inst, PFS);
7258 // Unary Operators.
7259 case lltok::kw_fneg: {
7260 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7261 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7262 if (Res != 0)
7263 return Res;
7264 if (FMF.any())
7265 Inst->setFastMathFlags(FMF);
7266 return false;
7267 }
7268 // Binary Operators.
7269 case lltok::kw_add:
7270 case lltok::kw_sub:
7271 case lltok::kw_mul:
7272 case lltok::kw_shl: {
7273 bool NUW = EatIfPresent(lltok::kw_nuw);
7274 bool NSW = EatIfPresent(lltok::kw_nsw);
7275 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7276
7277 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7278 return true;
7279
7280 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7281 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7282 return false;
7283 }
7284 case lltok::kw_fadd:
7285 case lltok::kw_fsub:
7286 case lltok::kw_fmul:
7287 case lltok::kw_fdiv:
7288 case lltok::kw_frem: {
7289 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7290 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7291 if (Res != 0)
7292 return Res;
7293 if (FMF.any())
7294 Inst->setFastMathFlags(FMF);
7295 return 0;
7296 }
7297
7298 case lltok::kw_sdiv:
7299 case lltok::kw_udiv:
7300 case lltok::kw_lshr:
7301 case lltok::kw_ashr: {
7302 bool Exact = EatIfPresent(lltok::kw_exact);
7303
7304 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7305 return true;
7306 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7307 return false;
7308 }
7309
7310 case lltok::kw_urem:
7311 case lltok::kw_srem:
7312 return parseArithmetic(Inst, PFS, KeywordVal,
7313 /*IsFP*/ false);
7314 case lltok::kw_or: {
7315 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7316 if (parseLogical(Inst, PFS, KeywordVal))
7317 return true;
7318 if (Disjoint)
7319 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7320 return false;
7321 }
7322 case lltok::kw_and:
7323 case lltok::kw_xor:
7324 return parseLogical(Inst, PFS, KeywordVal);
7325 case lltok::kw_icmp: {
7326 bool SameSign = EatIfPresent(lltok::kw_samesign);
7327 if (parseCompare(Inst, PFS, KeywordVal))
7328 return true;
7329 if (SameSign)
7330 cast<ICmpInst>(Inst)->setSameSign();
7331 return false;
7332 }
7333 case lltok::kw_fcmp: {
7334 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7335 int Res = parseCompare(Inst, PFS, KeywordVal);
7336 if (Res != 0)
7337 return Res;
7338 if (FMF.any())
7339 Inst->setFastMathFlags(FMF);
7340 return 0;
7341 }
7342
7343 // Casts.
7344 case lltok::kw_uitofp:
7345 case lltok::kw_zext: {
7346 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7347 bool Res = parseCast(Inst, PFS, KeywordVal);
7348 if (Res != 0)
7349 return Res;
7350 if (NonNeg)
7351 Inst->setNonNeg();
7352 return 0;
7353 }
7354 case lltok::kw_trunc: {
7355 bool NUW = EatIfPresent(lltok::kw_nuw);
7356 bool NSW = EatIfPresent(lltok::kw_nsw);
7357 if (!NUW)
7358 NUW = EatIfPresent(lltok::kw_nuw);
7359 if (parseCast(Inst, PFS, KeywordVal))
7360 return true;
7361 if (NUW)
7362 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7363 if (NSW)
7364 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7365 return false;
7366 }
7367 case lltok::kw_sext:
7368 case lltok::kw_bitcast:
7370 case lltok::kw_sitofp:
7371 case lltok::kw_fptoui:
7372 case lltok::kw_fptosi:
7373 case lltok::kw_inttoptr:
7375 case lltok::kw_ptrtoint:
7376 return parseCast(Inst, PFS, KeywordVal);
7377 case lltok::kw_fptrunc:
7378 case lltok::kw_fpext: {
7379 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7380 if (parseCast(Inst, PFS, KeywordVal))
7381 return true;
7382 if (FMF.any())
7383 Inst->setFastMathFlags(FMF);
7384 return false;
7385 }
7386
7387 // Other.
7388 case lltok::kw_select: {
7389 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7390 int Res = parseSelect(Inst, PFS);
7391 if (Res != 0)
7392 return Res;
7393 if (FMF.any()) {
7394 if (!isa<FPMathOperator>(Inst))
7395 return error(Loc, "fast-math-flags specified for select without "
7396 "floating-point scalar or vector return type");
7397 Inst->setFastMathFlags(FMF);
7398 }
7399 return 0;
7400 }
7401 case lltok::kw_va_arg:
7402 return parseVAArg(Inst, PFS);
7404 return parseExtractElement(Inst, PFS);
7406 return parseInsertElement(Inst, PFS);
7408 return parseShuffleVector(Inst, PFS);
7409 case lltok::kw_phi: {
7410 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7411 int Res = parsePHI(Inst, PFS);
7412 if (Res != 0)
7413 return Res;
7414 if (FMF.any()) {
7415 if (!isa<FPMathOperator>(Inst))
7416 return error(Loc, "fast-math-flags specified for phi without "
7417 "floating-point scalar or vector return type");
7418 Inst->setFastMathFlags(FMF);
7419 }
7420 return 0;
7421 }
7423 return parseLandingPad(Inst, PFS);
7424 case lltok::kw_freeze:
7425 return parseFreeze(Inst, PFS);
7426 // Call.
7427 case lltok::kw_call:
7428 return parseCall(Inst, PFS, CallInst::TCK_None);
7429 case lltok::kw_tail:
7430 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7431 case lltok::kw_musttail:
7432 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7433 case lltok::kw_notail:
7434 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7435 // Memory.
7436 case lltok::kw_alloca:
7437 return parseAlloc(Inst, PFS);
7438 case lltok::kw_load:
7439 return parseLoad(Inst, PFS);
7440 case lltok::kw_store:
7441 return parseStore(Inst, PFS);
7442 case lltok::kw_cmpxchg:
7443 return parseCmpXchg(Inst, PFS);
7445 return parseAtomicRMW(Inst, PFS);
7446 case lltok::kw_fence:
7447 return parseFence(Inst, PFS);
7449 return parseGetElementPtr(Inst, PFS);
7451 return parseExtractValue(Inst, PFS);
7453 return parseInsertValue(Inst, PFS);
7454 }
7455}
7456
7457/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7458bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7459 if (Opc == Instruction::FCmp) {
7460 switch (Lex.getKind()) {
7461 default:
7462 return tokError("expected fcmp predicate (e.g. 'oeq')");
7463 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7464 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7465 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7466 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7467 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7468 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7469 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7470 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7471 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7472 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7473 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7474 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7475 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7476 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7477 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7478 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7479 }
7480 } else {
7481 switch (Lex.getKind()) {
7482 default:
7483 return tokError("expected icmp predicate (e.g. 'eq')");
7484 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7485 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7486 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7487 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7488 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7489 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7490 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7491 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7492 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7493 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7494 }
7495 }
7496 Lex.Lex();
7497 return false;
7498}
7499
7500//===----------------------------------------------------------------------===//
7501// Terminator Instructions.
7502//===----------------------------------------------------------------------===//
7503
7504/// parseRet - parse a return instruction.
7505/// ::= 'ret' void (',' !dbg, !1)*
7506/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7507bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7508 PerFunctionState &PFS) {
7509 SMLoc TypeLoc = Lex.getLoc();
7510 Type *Ty = nullptr;
7511 if (parseType(Ty, true /*void allowed*/))
7512 return true;
7513
7514 Type *ResType = PFS.getFunction().getReturnType();
7515
7516 if (Ty->isVoidTy()) {
7517 if (!ResType->isVoidTy())
7518 return error(TypeLoc, "value doesn't match function result type '" +
7519 getTypeString(ResType) + "'");
7520
7521 Inst = ReturnInst::Create(Context);
7522 return false;
7523 }
7524
7525 Value *RV;
7526 if (parseValue(Ty, RV, PFS))
7527 return true;
7528
7529 if (ResType != RV->getType())
7530 return error(TypeLoc, "value doesn't match function result type '" +
7531 getTypeString(ResType) + "'");
7532
7533 Inst = ReturnInst::Create(Context, RV);
7534 return false;
7535}
7536
7537/// parseBr
7538/// ::= 'br' TypeAndValue
7539/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7540bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7541 LocTy Loc, Loc2;
7542 Value *Op0;
7543 BasicBlock *Op1, *Op2;
7544 if (parseTypeAndValue(Op0, Loc, PFS))
7545 return true;
7546
7547 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7548 Inst = BranchInst::Create(BB);
7549 return false;
7550 }
7551
7552 if (Op0->getType() != Type::getInt1Ty(Context))
7553 return error(Loc, "branch condition must have 'i1' type");
7554
7555 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7556 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7557 parseToken(lltok::comma, "expected ',' after true destination") ||
7558 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7559 return true;
7560
7561 Inst = BranchInst::Create(Op1, Op2, Op0);
7562 return false;
7563}
7564
7565/// parseSwitch
7566/// Instruction
7567/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7568/// JumpTable
7569/// ::= (TypeAndValue ',' TypeAndValue)*
7570bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7571 LocTy CondLoc, BBLoc;
7572 Value *Cond;
7573 BasicBlock *DefaultBB;
7574 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7575 parseToken(lltok::comma, "expected ',' after switch condition") ||
7576 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7577 parseToken(lltok::lsquare, "expected '[' with switch table"))
7578 return true;
7579
7580 if (!Cond->getType()->isIntegerTy())
7581 return error(CondLoc, "switch condition must have integer type");
7582
7583 // parse the jump table pairs.
7584 SmallPtrSet<Value*, 32> SeenCases;
7586 while (Lex.getKind() != lltok::rsquare) {
7587 Value *Constant;
7588 BasicBlock *DestBB;
7589
7590 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7591 parseToken(lltok::comma, "expected ',' after case value") ||
7592 parseTypeAndBasicBlock(DestBB, PFS))
7593 return true;
7594
7595 if (!SeenCases.insert(Constant).second)
7596 return error(CondLoc, "duplicate case value in switch");
7597 if (!isa<ConstantInt>(Constant))
7598 return error(CondLoc, "case value is not a constant integer");
7599
7600 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7601 }
7602
7603 Lex.Lex(); // Eat the ']'.
7604
7605 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7606 for (const auto &[OnVal, Dest] : Table)
7607 SI->addCase(OnVal, Dest);
7608 Inst = SI;
7609 return false;
7610}
7611
7612/// parseIndirectBr
7613/// Instruction
7614/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7615bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7616 LocTy AddrLoc;
7617 Value *Address;
7618 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7619 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7620 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7621 return true;
7622
7623 if (!Address->getType()->isPointerTy())
7624 return error(AddrLoc, "indirectbr address must have pointer type");
7625
7626 // parse the destination list.
7627 SmallVector<BasicBlock*, 16> DestList;
7628
7629 if (Lex.getKind() != lltok::rsquare) {
7630 BasicBlock *DestBB;
7631 if (parseTypeAndBasicBlock(DestBB, PFS))
7632 return true;
7633 DestList.push_back(DestBB);
7634
7635 while (EatIfPresent(lltok::comma)) {
7636 if (parseTypeAndBasicBlock(DestBB, PFS))
7637 return true;
7638 DestList.push_back(DestBB);
7639 }
7640 }
7641
7642 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7643 return true;
7644
7645 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7646 for (BasicBlock *Dest : DestList)
7647 IBI->addDestination(Dest);
7648 Inst = IBI;
7649 return false;
7650}
7651
7652// If RetType is a non-function pointer type, then this is the short syntax
7653// for the call, which means that RetType is just the return type. Infer the
7654// rest of the function argument types from the arguments that are present.
7655bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7656 FunctionType *&FuncTy) {
7657 FuncTy = dyn_cast<FunctionType>(RetType);
7658 if (!FuncTy) {
7659 // Pull out the types of all of the arguments...
7660 SmallVector<Type *, 8> ParamTypes;
7661 ParamTypes.reserve(ArgList.size());
7662 for (const ParamInfo &Arg : ArgList)
7663 ParamTypes.push_back(Arg.V->getType());
7664
7665 if (!FunctionType::isValidReturnType(RetType))
7666 return true;
7667
7668 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7669 }
7670 return false;
7671}
7672
7673/// parseInvoke
7674/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7675/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7676bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7677 LocTy CallLoc = Lex.getLoc();
7678 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7679 std::vector<unsigned> FwdRefAttrGrps;
7680 LocTy NoBuiltinLoc;
7681 unsigned CC;
7682 unsigned InvokeAddrSpace;
7683 Type *RetType = nullptr;
7684 LocTy RetTypeLoc;
7685 ValID CalleeID;
7688
7689 BasicBlock *NormalBB, *UnwindBB;
7690 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7691 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7692 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7693 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7694 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7695 NoBuiltinLoc) ||
7696 parseOptionalOperandBundles(BundleList, PFS) ||
7697 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7698 parseTypeAndBasicBlock(NormalBB, PFS) ||
7699 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7700 parseTypeAndBasicBlock(UnwindBB, PFS))
7701 return true;
7702
7703 // If RetType is a non-function pointer type, then this is the short syntax
7704 // for the call, which means that RetType is just the return type. Infer the
7705 // rest of the function argument types from the arguments that are present.
7706 FunctionType *Ty;
7707 if (resolveFunctionType(RetType, ArgList, Ty))
7708 return error(RetTypeLoc, "Invalid result type for LLVM function");
7709
7710 CalleeID.FTy = Ty;
7711
7712 // Look up the callee.
7713 Value *Callee;
7714 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7715 Callee, &PFS))
7716 return true;
7717
7718 // Set up the Attribute for the function.
7719 SmallVector<Value *, 8> Args;
7721
7722 // Loop through FunctionType's arguments and ensure they are specified
7723 // correctly. Also, gather any parameter attributes.
7724 FunctionType::param_iterator I = Ty->param_begin();
7725 FunctionType::param_iterator E = Ty->param_end();
7726 for (const ParamInfo &Arg : ArgList) {
7727 Type *ExpectedTy = nullptr;
7728 if (I != E) {
7729 ExpectedTy = *I++;
7730 } else if (!Ty->isVarArg()) {
7731 return error(Arg.Loc, "too many arguments specified");
7732 }
7733
7734 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7735 return error(Arg.Loc, "argument is not of expected type '" +
7736 getTypeString(ExpectedTy) + "'");
7737 Args.push_back(Arg.V);
7738 ArgAttrs.push_back(Arg.Attrs);
7739 }
7740
7741 if (I != E)
7742 return error(CallLoc, "not enough parameters specified for call");
7743
7744 // Finish off the Attribute and check them
7745 AttributeList PAL =
7746 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7747 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7748
7749 InvokeInst *II =
7750 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7751 II->setCallingConv(CC);
7752 II->setAttributes(PAL);
7753 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7754 Inst = II;
7755 return false;
7756}
7757
7758/// parseResume
7759/// ::= 'resume' TypeAndValue
7760bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7761 Value *Exn; LocTy ExnLoc;
7762 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7763 return true;
7764
7765 ResumeInst *RI = ResumeInst::Create(Exn);
7766 Inst = RI;
7767 return false;
7768}
7769
7770bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7771 PerFunctionState &PFS) {
7772 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7773 return true;
7774
7775 while (Lex.getKind() != lltok::rsquare) {
7776 // If this isn't the first argument, we need a comma.
7777 if (!Args.empty() &&
7778 parseToken(lltok::comma, "expected ',' in argument list"))
7779 return true;
7780
7781 // parse the argument.
7782 LocTy ArgLoc;
7783 Type *ArgTy = nullptr;
7784 if (parseType(ArgTy, ArgLoc))
7785 return true;
7786
7787 Value *V;
7788 if (ArgTy->isMetadataTy()) {
7789 if (parseMetadataAsValue(V, PFS))
7790 return true;
7791 } else {
7792 if (parseValue(ArgTy, V, PFS))
7793 return true;
7794 }
7795 Args.push_back(V);
7796 }
7797
7798 Lex.Lex(); // Lex the ']'.
7799 return false;
7800}
7801
7802/// parseCleanupRet
7803/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7804bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7805 Value *CleanupPad = nullptr;
7806
7807 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7808 return true;
7809
7810 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7811 return true;
7812
7813 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7814 return true;
7815
7816 BasicBlock *UnwindBB = nullptr;
7817 if (Lex.getKind() == lltok::kw_to) {
7818 Lex.Lex();
7819 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7820 return true;
7821 } else {
7822 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7823 return true;
7824 }
7825 }
7826
7827 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7828 return false;
7829}
7830
7831/// parseCatchRet
7832/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7833bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7834 Value *CatchPad = nullptr;
7835
7836 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7837 return true;
7838
7839 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7840 return true;
7841
7842 BasicBlock *BB;
7843 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7844 parseTypeAndBasicBlock(BB, PFS))
7845 return true;
7846
7847 Inst = CatchReturnInst::Create(CatchPad, BB);
7848 return false;
7849}
7850
7851/// parseCatchSwitch
7852/// ::= 'catchswitch' within Parent
7853bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7854 Value *ParentPad;
7855
7856 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7857 return true;
7858
7859 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7860 Lex.getKind() != lltok::LocalVarID)
7861 return tokError("expected scope value for catchswitch");
7862
7863 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7864 return true;
7865
7866 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7867 return true;
7868
7870 do {
7871 BasicBlock *DestBB;
7872 if (parseTypeAndBasicBlock(DestBB, PFS))
7873 return true;
7874 Table.push_back(DestBB);
7875 } while (EatIfPresent(lltok::comma));
7876
7877 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7878 return true;
7879
7880 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7881 return true;
7882
7883 BasicBlock *UnwindBB = nullptr;
7884 if (EatIfPresent(lltok::kw_to)) {
7885 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7886 return true;
7887 } else {
7888 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7889 return true;
7890 }
7891
7892 auto *CatchSwitch =
7893 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7894 for (BasicBlock *DestBB : Table)
7895 CatchSwitch->addHandler(DestBB);
7896 Inst = CatchSwitch;
7897 return false;
7898}
7899
7900/// parseCatchPad
7901/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7902bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7903 Value *CatchSwitch = nullptr;
7904
7905 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7906 return true;
7907
7908 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7909 return tokError("expected scope value for catchpad");
7910
7911 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7912 return true;
7913
7914 SmallVector<Value *, 8> Args;
7915 if (parseExceptionArgs(Args, PFS))
7916 return true;
7917
7918 Inst = CatchPadInst::Create(CatchSwitch, Args);
7919 return false;
7920}
7921
7922/// parseCleanupPad
7923/// ::= 'cleanuppad' within Parent ParamList
7924bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7925 Value *ParentPad = nullptr;
7926
7927 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7928 return true;
7929
7930 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7931 Lex.getKind() != lltok::LocalVarID)
7932 return tokError("expected scope value for cleanuppad");
7933
7934 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7935 return true;
7936
7937 SmallVector<Value *, 8> Args;
7938 if (parseExceptionArgs(Args, PFS))
7939 return true;
7940
7941 Inst = CleanupPadInst::Create(ParentPad, Args);
7942 return false;
7943}
7944
7945//===----------------------------------------------------------------------===//
7946// Unary Operators.
7947//===----------------------------------------------------------------------===//
7948
7949/// parseUnaryOp
7950/// ::= UnaryOp TypeAndValue ',' Value
7951///
7952/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7953/// operand is allowed.
7954bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7955 unsigned Opc, bool IsFP) {
7956 LocTy Loc; Value *LHS;
7957 if (parseTypeAndValue(LHS, Loc, PFS))
7958 return true;
7959
7960 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7962
7963 if (!Valid)
7964 return error(Loc, "invalid operand type for instruction");
7965
7967 return false;
7968}
7969
7970/// parseCallBr
7971/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7972/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7973/// '[' LabelList ']'
7974bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7975 LocTy CallLoc = Lex.getLoc();
7976 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7977 std::vector<unsigned> FwdRefAttrGrps;
7978 LocTy NoBuiltinLoc;
7979 unsigned CC;
7980 Type *RetType = nullptr;
7981 LocTy RetTypeLoc;
7982 ValID CalleeID;
7985
7986 BasicBlock *DefaultDest;
7987 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7988 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7989 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7990 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7991 NoBuiltinLoc) ||
7992 parseOptionalOperandBundles(BundleList, PFS) ||
7993 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7994 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7995 parseToken(lltok::lsquare, "expected '[' in callbr"))
7996 return true;
7997
7998 // parse the destination list.
7999 SmallVector<BasicBlock *, 16> IndirectDests;
8000
8001 if (Lex.getKind() != lltok::rsquare) {
8002 BasicBlock *DestBB;
8003 if (parseTypeAndBasicBlock(DestBB, PFS))
8004 return true;
8005 IndirectDests.push_back(DestBB);
8006
8007 while (EatIfPresent(lltok::comma)) {
8008 if (parseTypeAndBasicBlock(DestBB, PFS))
8009 return true;
8010 IndirectDests.push_back(DestBB);
8011 }
8012 }
8013
8014 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8015 return true;
8016
8017 // If RetType is a non-function pointer type, then this is the short syntax
8018 // for the call, which means that RetType is just the return type. Infer the
8019 // rest of the function argument types from the arguments that are present.
8020 FunctionType *Ty;
8021 if (resolveFunctionType(RetType, ArgList, Ty))
8022 return error(RetTypeLoc, "Invalid result type for LLVM function");
8023
8024 CalleeID.FTy = Ty;
8025
8026 // Look up the callee.
8027 Value *Callee;
8028 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8029 &PFS))
8030 return true;
8031
8032 // Set up the Attribute for the function.
8033 SmallVector<Value *, 8> Args;
8035
8036 // Loop through FunctionType's arguments and ensure they are specified
8037 // correctly. Also, gather any parameter attributes.
8038 FunctionType::param_iterator I = Ty->param_begin();
8039 FunctionType::param_iterator E = Ty->param_end();
8040 for (const ParamInfo &Arg : ArgList) {
8041 Type *ExpectedTy = nullptr;
8042 if (I != E) {
8043 ExpectedTy = *I++;
8044 } else if (!Ty->isVarArg()) {
8045 return error(Arg.Loc, "too many arguments specified");
8046 }
8047
8048 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8049 return error(Arg.Loc, "argument is not of expected type '" +
8050 getTypeString(ExpectedTy) + "'");
8051 Args.push_back(Arg.V);
8052 ArgAttrs.push_back(Arg.Attrs);
8053 }
8054
8055 if (I != E)
8056 return error(CallLoc, "not enough parameters specified for call");
8057
8058 // Finish off the Attribute and check them
8059 AttributeList PAL =
8060 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8061 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8062
8063 CallBrInst *CBI =
8064 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8065 BundleList);
8066 CBI->setCallingConv(CC);
8067 CBI->setAttributes(PAL);
8068 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8069 Inst = CBI;
8070 return false;
8071}
8072
8073//===----------------------------------------------------------------------===//
8074// Binary Operators.
8075//===----------------------------------------------------------------------===//
8076
8077/// parseArithmetic
8078/// ::= ArithmeticOps TypeAndValue ',' Value
8079///
8080/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8081/// operand is allowed.
8082bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8083 unsigned Opc, bool IsFP) {
8084 LocTy Loc; Value *LHS, *RHS;
8085 if (parseTypeAndValue(LHS, Loc, PFS) ||
8086 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8087 parseValue(LHS->getType(), RHS, PFS))
8088 return true;
8089
8090 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8092
8093 if (!Valid)
8094 return error(Loc, "invalid operand type for instruction");
8095
8097 return false;
8098}
8099
8100/// parseLogical
8101/// ::= ArithmeticOps TypeAndValue ',' Value {
8102bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8103 unsigned Opc) {
8104 LocTy Loc; Value *LHS, *RHS;
8105 if (parseTypeAndValue(LHS, Loc, PFS) ||
8106 parseToken(lltok::comma, "expected ',' in logical operation") ||
8107 parseValue(LHS->getType(), RHS, PFS))
8108 return true;
8109
8110 if (!LHS->getType()->isIntOrIntVectorTy())
8111 return error(Loc,
8112 "instruction requires integer or integer vector operands");
8113
8115 return false;
8116}
8117
8118/// parseCompare
8119/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8120/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8121bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8122 unsigned Opc) {
8123 // parse the integer/fp comparison predicate.
8124 LocTy Loc;
8125 unsigned Pred;
8126 Value *LHS, *RHS;
8127 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8128 parseToken(lltok::comma, "expected ',' after compare value") ||
8129 parseValue(LHS->getType(), RHS, PFS))
8130 return true;
8131
8132 if (Opc == Instruction::FCmp) {
8133 if (!LHS->getType()->isFPOrFPVectorTy())
8134 return error(Loc, "fcmp requires floating point operands");
8135 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8136 } else {
8137 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8138 if (!LHS->getType()->isIntOrIntVectorTy() &&
8140 return error(Loc, "icmp requires integer operands");
8141 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8142 }
8143 return false;
8144}
8145
8146//===----------------------------------------------------------------------===//
8147// Other Instructions.
8148//===----------------------------------------------------------------------===//
8149
8150/// parseCast
8151/// ::= CastOpc TypeAndValue 'to' Type
8152bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8153 unsigned Opc) {
8154 LocTy Loc;
8155 Value *Op;
8156 Type *DestTy = nullptr;
8157 if (parseTypeAndValue(Op, Loc, PFS) ||
8158 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8159 parseType(DestTy))
8160 return true;
8161
8163 return error(Loc, "invalid cast opcode for cast from '" +
8164 getTypeString(Op->getType()) + "' to '" +
8165 getTypeString(DestTy) + "'");
8166 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8167 return false;
8168}
8169
8170/// parseSelect
8171/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8172bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8173 LocTy Loc;
8174 Value *Op0, *Op1, *Op2;
8175 if (parseTypeAndValue(Op0, Loc, PFS) ||
8176 parseToken(lltok::comma, "expected ',' after select condition") ||
8177 parseTypeAndValue(Op1, PFS) ||
8178 parseToken(lltok::comma, "expected ',' after select value") ||
8179 parseTypeAndValue(Op2, PFS))
8180 return true;
8181
8182 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8183 return error(Loc, Reason);
8184
8185 Inst = SelectInst::Create(Op0, Op1, Op2);
8186 return false;
8187}
8188
8189/// parseVAArg
8190/// ::= 'va_arg' TypeAndValue ',' Type
8191bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8192 Value *Op;
8193 Type *EltTy = nullptr;
8194 LocTy TypeLoc;
8195 if (parseTypeAndValue(Op, PFS) ||
8196 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8197 parseType(EltTy, TypeLoc))
8198 return true;
8199
8200 if (!EltTy->isFirstClassType())
8201 return error(TypeLoc, "va_arg requires operand with first class type");
8202
8203 Inst = new VAArgInst(Op, EltTy);
8204 return false;
8205}
8206
8207/// parseExtractElement
8208/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8209bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8210 LocTy Loc;
8211 Value *Op0, *Op1;
8212 if (parseTypeAndValue(Op0, Loc, PFS) ||
8213 parseToken(lltok::comma, "expected ',' after extract value") ||
8214 parseTypeAndValue(Op1, PFS))
8215 return true;
8216
8218 return error(Loc, "invalid extractelement operands");
8219
8220 Inst = ExtractElementInst::Create(Op0, Op1);
8221 return false;
8222}
8223
8224/// parseInsertElement
8225/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8226bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8227 LocTy Loc;
8228 Value *Op0, *Op1, *Op2;
8229 if (parseTypeAndValue(Op0, Loc, PFS) ||
8230 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8231 parseTypeAndValue(Op1, PFS) ||
8232 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8233 parseTypeAndValue(Op2, PFS))
8234 return true;
8235
8236 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8237 return error(Loc, "invalid insertelement operands");
8238
8239 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8240 return false;
8241}
8242
8243/// parseShuffleVector
8244/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8245bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8246 LocTy Loc;
8247 Value *Op0, *Op1, *Op2;
8248 if (parseTypeAndValue(Op0, Loc, PFS) ||
8249 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8250 parseTypeAndValue(Op1, PFS) ||
8251 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8252 parseTypeAndValue(Op2, PFS))
8253 return true;
8254
8255 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8256 return error(Loc, "invalid shufflevector operands");
8257
8258 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8259 return false;
8260}
8261
8262/// parsePHI
8263/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8264int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8265 Type *Ty = nullptr; LocTy TypeLoc;
8266 Value *Op0, *Op1;
8267
8268 if (parseType(Ty, TypeLoc))
8269 return true;
8270
8271 if (!Ty->isFirstClassType())
8272 return error(TypeLoc, "phi node must have first class type");
8273
8274 bool First = true;
8275 bool AteExtraComma = false;
8277
8278 while (true) {
8279 if (First) {
8280 if (Lex.getKind() != lltok::lsquare)
8281 break;
8282 First = false;
8283 } else if (!EatIfPresent(lltok::comma))
8284 break;
8285
8286 if (Lex.getKind() == lltok::MetadataVar) {
8287 AteExtraComma = true;
8288 break;
8289 }
8290
8291 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8292 parseValue(Ty, Op0, PFS) ||
8293 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8294 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8295 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8296 return true;
8297
8298 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8299 }
8300
8301 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8302 for (const auto &[Val, BB] : PHIVals)
8303 PN->addIncoming(Val, BB);
8304 Inst = PN;
8305 return AteExtraComma ? InstExtraComma : InstNormal;
8306}
8307
8308/// parseLandingPad
8309/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8310/// Clause
8311/// ::= 'catch' TypeAndValue
8312/// ::= 'filter'
8313/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8314bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8315 Type *Ty = nullptr; LocTy TyLoc;
8316
8317 if (parseType(Ty, TyLoc))
8318 return true;
8319
8320 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8321 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8322
8323 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8325 if (EatIfPresent(lltok::kw_catch))
8327 else if (EatIfPresent(lltok::kw_filter))
8329 else
8330 return tokError("expected 'catch' or 'filter' clause type");
8331
8332 Value *V;
8333 LocTy VLoc;
8334 if (parseTypeAndValue(V, VLoc, PFS))
8335 return true;
8336
8337 // A 'catch' type expects a non-array constant. A filter clause expects an
8338 // array constant.
8339 if (CT == LandingPadInst::Catch) {
8340 if (isa<ArrayType>(V->getType()))
8341 return error(VLoc, "'catch' clause has an invalid type");
8342 } else {
8343 if (!isa<ArrayType>(V->getType()))
8344 return error(VLoc, "'filter' clause has an invalid type");
8345 }
8346
8348 if (!CV)
8349 return error(VLoc, "clause argument must be a constant");
8350 LP->addClause(CV);
8351 }
8352
8353 Inst = LP.release();
8354 return false;
8355}
8356
8357/// parseFreeze
8358/// ::= 'freeze' Type Value
8359bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8360 LocTy Loc;
8361 Value *Op;
8362 if (parseTypeAndValue(Op, Loc, PFS))
8363 return true;
8364
8365 Inst = new FreezeInst(Op);
8366 return false;
8367}
8368
8369/// parseCall
8370/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8371/// OptionalAttrs Type Value ParameterList OptionalAttrs
8372/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8373/// OptionalAttrs Type Value ParameterList OptionalAttrs
8374/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8375/// OptionalAttrs Type Value ParameterList OptionalAttrs
8376/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8377/// OptionalAttrs Type Value ParameterList OptionalAttrs
8378bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8380 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8381 std::vector<unsigned> FwdRefAttrGrps;
8382 LocTy BuiltinLoc;
8383 unsigned CallAddrSpace;
8384 unsigned CC;
8385 Type *RetType = nullptr;
8386 LocTy RetTypeLoc;
8387 ValID CalleeID;
8390 LocTy CallLoc = Lex.getLoc();
8391
8392 if (TCK != CallInst::TCK_None &&
8393 parseToken(lltok::kw_call,
8394 "expected 'tail call', 'musttail call', or 'notail call'"))
8395 return true;
8396
8397 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8398
8399 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8400 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8401 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8402 parseValID(CalleeID, &PFS) ||
8403 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8404 PFS.getFunction().isVarArg()) ||
8405 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8406 parseOptionalOperandBundles(BundleList, PFS))
8407 return true;
8408
8409 // If RetType is a non-function pointer type, then this is the short syntax
8410 // for the call, which means that RetType is just the return type. Infer the
8411 // rest of the function argument types from the arguments that are present.
8412 FunctionType *Ty;
8413 if (resolveFunctionType(RetType, ArgList, Ty))
8414 return error(RetTypeLoc, "Invalid result type for LLVM function");
8415
8416 CalleeID.FTy = Ty;
8417
8418 // Look up the callee.
8419 Value *Callee;
8420 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8421 Callee, &PFS))
8422 return true;
8423
8424 // Set up the Attribute for the function.
8426
8427 SmallVector<Value*, 8> Args;
8428
8429 // Loop through FunctionType's arguments and ensure they are specified
8430 // correctly. Also, gather any parameter attributes.
8431 FunctionType::param_iterator I = Ty->param_begin();
8432 FunctionType::param_iterator E = Ty->param_end();
8433 for (const ParamInfo &Arg : ArgList) {
8434 Type *ExpectedTy = nullptr;
8435 if (I != E) {
8436 ExpectedTy = *I++;
8437 } else if (!Ty->isVarArg()) {
8438 return error(Arg.Loc, "too many arguments specified");
8439 }
8440
8441 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8442 return error(Arg.Loc, "argument is not of expected type '" +
8443 getTypeString(ExpectedTy) + "'");
8444 Args.push_back(Arg.V);
8445 Attrs.push_back(Arg.Attrs);
8446 }
8447
8448 if (I != E)
8449 return error(CallLoc, "not enough parameters specified for call");
8450
8451 // Finish off the Attribute and check them
8452 AttributeList PAL =
8453 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8454 AttributeSet::get(Context, RetAttrs), Attrs);
8455
8456 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8457 CI->setTailCallKind(TCK);
8458 CI->setCallingConv(CC);
8459 if (FMF.any()) {
8460 if (!isa<FPMathOperator>(CI)) {
8461 CI->deleteValue();
8462 return error(CallLoc, "fast-math-flags specified for call without "
8463 "floating-point scalar or vector return type");
8464 }
8465 CI->setFastMathFlags(FMF);
8466 }
8467
8468 if (CalleeID.Kind == ValID::t_GlobalName &&
8469 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8470 if (SeenNewDbgInfoFormat) {
8471 CI->deleteValue();
8472 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8473 "using non-intrinsic debug info");
8474 }
8475 SeenOldDbgInfoFormat = true;
8476 }
8477 CI->setAttributes(PAL);
8478 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8479 Inst = CI;
8480 return false;
8481}
8482
8483//===----------------------------------------------------------------------===//
8484// Memory Instructions.
8485//===----------------------------------------------------------------------===//
8486
8487/// parseAlloc
8488/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8489/// (',' 'align' i32)? (',', 'addrspace(n))?
8490int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8491 Value *Size = nullptr;
8492 LocTy SizeLoc, TyLoc, ASLoc;
8493 MaybeAlign Alignment;
8494 unsigned AddrSpace = 0;
8495 Type *Ty = nullptr;
8496
8497 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8498 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8499
8500 if (parseType(Ty, TyLoc))
8501 return true;
8502
8504 return error(TyLoc, "invalid type for alloca");
8505
8506 bool AteExtraComma = false;
8507 if (EatIfPresent(lltok::comma)) {
8508 if (Lex.getKind() == lltok::kw_align) {
8509 if (parseOptionalAlignment(Alignment))
8510 return true;
8511 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8512 return true;
8513 } else if (Lex.getKind() == lltok::kw_addrspace) {
8514 ASLoc = Lex.getLoc();
8515 if (parseOptionalAddrSpace(AddrSpace))
8516 return true;
8517 } else if (Lex.getKind() == lltok::MetadataVar) {
8518 AteExtraComma = true;
8519 } else {
8520 if (parseTypeAndValue(Size, SizeLoc, PFS))
8521 return true;
8522 if (EatIfPresent(lltok::comma)) {
8523 if (Lex.getKind() == lltok::kw_align) {
8524 if (parseOptionalAlignment(Alignment))
8525 return true;
8526 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8527 return true;
8528 } else if (Lex.getKind() == lltok::kw_addrspace) {
8529 ASLoc = Lex.getLoc();
8530 if (parseOptionalAddrSpace(AddrSpace))
8531 return true;
8532 } else if (Lex.getKind() == lltok::MetadataVar) {
8533 AteExtraComma = true;
8534 }
8535 }
8536 }
8537 }
8538
8539 if (Size && !Size->getType()->isIntegerTy())
8540 return error(SizeLoc, "element count must have integer type");
8541
8542 SmallPtrSet<Type *, 4> Visited;
8543 if (!Alignment && !Ty->isSized(&Visited))
8544 return error(TyLoc, "Cannot allocate unsized type");
8545 if (!Alignment)
8546 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8547 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8548 AI->setUsedWithInAlloca(IsInAlloca);
8549 AI->setSwiftError(IsSwiftError);
8550 Inst = AI;
8551 return AteExtraComma ? InstExtraComma : InstNormal;
8552}
8553
8554/// parseLoad
8555/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8556/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8557/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8558int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8559 Value *Val; LocTy Loc;
8560 MaybeAlign Alignment;
8561 bool AteExtraComma = false;
8562 bool isAtomic = false;
8565
8566 if (Lex.getKind() == lltok::kw_atomic) {
8567 isAtomic = true;
8568 Lex.Lex();
8569 }
8570
8571 bool isVolatile = false;
8572 if (Lex.getKind() == lltok::kw_volatile) {
8573 isVolatile = true;
8574 Lex.Lex();
8575 }
8576
8577 Type *Ty;
8578 LocTy ExplicitTypeLoc = Lex.getLoc();
8579 if (parseType(Ty) ||
8580 parseToken(lltok::comma, "expected comma after load's type") ||
8581 parseTypeAndValue(Val, Loc, PFS) ||
8582 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8583 parseOptionalCommaAlign(Alignment, AteExtraComma))
8584 return true;
8585
8586 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8587 return error(Loc, "load operand must be a pointer to a first class type");
8588 if (isAtomic && !Alignment)
8589 return error(Loc, "atomic load must have explicit non-zero alignment");
8590 if (Ordering == AtomicOrdering::Release ||
8592 return error(Loc, "atomic load cannot use Release ordering");
8593
8594 SmallPtrSet<Type *, 4> Visited;
8595 if (!Alignment && !Ty->isSized(&Visited))
8596 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8597 if (!Alignment)
8598 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8599 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8600 return AteExtraComma ? InstExtraComma : InstNormal;
8601}
8602
8603/// parseStore
8604
8605/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8606/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8607/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8608int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8609 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8610 MaybeAlign Alignment;
8611 bool AteExtraComma = false;
8612 bool isAtomic = false;
8615
8616 if (Lex.getKind() == lltok::kw_atomic) {
8617 isAtomic = true;
8618 Lex.Lex();
8619 }
8620
8621 bool isVolatile = false;
8622 if (Lex.getKind() == lltok::kw_volatile) {
8623 isVolatile = true;
8624 Lex.Lex();
8625 }
8626
8627 if (parseTypeAndValue(Val, Loc, PFS) ||
8628 parseToken(lltok::comma, "expected ',' after store operand") ||
8629 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8630 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8631 parseOptionalCommaAlign(Alignment, AteExtraComma))
8632 return true;
8633
8634 if (!Ptr->getType()->isPointerTy())
8635 return error(PtrLoc, "store operand must be a pointer");
8636 if (!Val->getType()->isFirstClassType())
8637 return error(Loc, "store operand must be a first class value");
8638 if (isAtomic && !Alignment)
8639 return error(Loc, "atomic store must have explicit non-zero alignment");
8640 if (Ordering == AtomicOrdering::Acquire ||
8642 return error(Loc, "atomic store cannot use Acquire ordering");
8643 SmallPtrSet<Type *, 4> Visited;
8644 if (!Alignment && !Val->getType()->isSized(&Visited))
8645 return error(Loc, "storing unsized types is not allowed");
8646 if (!Alignment)
8647 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8648
8649 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8650 return AteExtraComma ? InstExtraComma : InstNormal;
8651}
8652
8653/// parseCmpXchg
8654/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8655/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8656/// 'Align'?
8657int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8658 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8659 bool AteExtraComma = false;
8660 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8661 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8663 bool isVolatile = false;
8664 bool isWeak = false;
8665 MaybeAlign Alignment;
8666
8667 if (EatIfPresent(lltok::kw_weak))
8668 isWeak = true;
8669
8670 if (EatIfPresent(lltok::kw_volatile))
8671 isVolatile = true;
8672
8673 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8674 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8675 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8676 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8677 parseTypeAndValue(New, NewLoc, PFS) ||
8678 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8679 parseOrdering(FailureOrdering) ||
8680 parseOptionalCommaAlign(Alignment, AteExtraComma))
8681 return true;
8682
8683 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8684 return tokError("invalid cmpxchg success ordering");
8685 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8686 return tokError("invalid cmpxchg failure ordering");
8687 if (!Ptr->getType()->isPointerTy())
8688 return error(PtrLoc, "cmpxchg operand must be a pointer");
8689 if (Cmp->getType() != New->getType())
8690 return error(NewLoc, "compare value and new value type do not match");
8691 if (!New->getType()->isFirstClassType())
8692 return error(NewLoc, "cmpxchg operand must be a first class value");
8693
8694 const Align DefaultAlignment(
8695 PFS.getFunction().getDataLayout().getTypeStoreSize(
8696 Cmp->getType()));
8697
8698 AtomicCmpXchgInst *CXI =
8699 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8700 SuccessOrdering, FailureOrdering, SSID);
8701 CXI->setVolatile(isVolatile);
8702 CXI->setWeak(isWeak);
8703
8704 Inst = CXI;
8705 return AteExtraComma ? InstExtraComma : InstNormal;
8706}
8707
8708/// parseAtomicRMW
8709/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8710/// 'singlethread'? AtomicOrdering
8711int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8712 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8713 bool AteExtraComma = false;
8716 bool isVolatile = false;
8717 bool IsFP = false;
8719 MaybeAlign Alignment;
8720
8721 if (EatIfPresent(lltok::kw_volatile))
8722 isVolatile = true;
8723
8724 switch (Lex.getKind()) {
8725 default:
8726 return tokError("expected binary operation in atomicrmw");
8740 break;
8743 break;
8746 break;
8747 case lltok::kw_usub_sat:
8749 break;
8750 case lltok::kw_fadd:
8752 IsFP = true;
8753 break;
8754 case lltok::kw_fsub:
8756 IsFP = true;
8757 break;
8758 case lltok::kw_fmax:
8760 IsFP = true;
8761 break;
8762 case lltok::kw_fmin:
8764 IsFP = true;
8765 break;
8766 case lltok::kw_fmaximum:
8768 IsFP = true;
8769 break;
8770 case lltok::kw_fminimum:
8772 IsFP = true;
8773 break;
8774 }
8775 Lex.Lex(); // Eat the operation.
8776
8777 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8778 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8779 parseTypeAndValue(Val, ValLoc, PFS) ||
8780 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8781 parseOptionalCommaAlign(Alignment, AteExtraComma))
8782 return true;
8783
8784 if (Ordering == AtomicOrdering::Unordered)
8785 return tokError("atomicrmw cannot be unordered");
8786 if (!Ptr->getType()->isPointerTy())
8787 return error(PtrLoc, "atomicrmw operand must be a pointer");
8788 if (Val->getType()->isScalableTy())
8789 return error(ValLoc, "atomicrmw operand may not be scalable");
8790
8792 if (!Val->getType()->isIntegerTy() &&
8793 !Val->getType()->isFloatingPointTy() &&
8794 !Val->getType()->isPointerTy()) {
8795 return error(
8796 ValLoc,
8798 " operand must be an integer, floating point, or pointer type");
8799 }
8800 } else if (IsFP) {
8801 if (!Val->getType()->isFPOrFPVectorTy()) {
8802 return error(ValLoc, "atomicrmw " +
8804 " operand must be a floating point type");
8805 }
8806 } else {
8807 if (!Val->getType()->isIntegerTy()) {
8808 return error(ValLoc, "atomicrmw " +
8810 " operand must be an integer");
8811 }
8812 }
8813
8814 unsigned Size =
8815 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8816 Val->getType());
8817 if (Size < 8 || (Size & (Size - 1)))
8818 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8819 " integer");
8820 const Align DefaultAlignment(
8821 PFS.getFunction().getDataLayout().getTypeStoreSize(
8822 Val->getType()));
8823 AtomicRMWInst *RMWI =
8824 new AtomicRMWInst(Operation, Ptr, Val,
8825 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8826 RMWI->setVolatile(isVolatile);
8827 Inst = RMWI;
8828 return AteExtraComma ? InstExtraComma : InstNormal;
8829}
8830
8831/// parseFence
8832/// ::= 'fence' 'singlethread'? AtomicOrdering
8833int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8836 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8837 return true;
8838
8839 if (Ordering == AtomicOrdering::Unordered)
8840 return tokError("fence cannot be unordered");
8841 if (Ordering == AtomicOrdering::Monotonic)
8842 return tokError("fence cannot be monotonic");
8843
8844 Inst = new FenceInst(Context, Ordering, SSID);
8845 return InstNormal;
8846}
8847
8848/// parseGetElementPtr
8849/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8850int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8851 Value *Ptr = nullptr;
8852 Value *Val = nullptr;
8853 LocTy Loc, EltLoc;
8854 GEPNoWrapFlags NW;
8855
8856 while (true) {
8857 if (EatIfPresent(lltok::kw_inbounds))
8859 else if (EatIfPresent(lltok::kw_nusw))
8861 else if (EatIfPresent(lltok::kw_nuw))
8863 else
8864 break;
8865 }
8866
8867 Type *Ty = nullptr;
8868 if (parseType(Ty) ||
8869 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8870 parseTypeAndValue(Ptr, Loc, PFS))
8871 return true;
8872
8873 Type *BaseType = Ptr->getType();
8874 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8875 if (!BasePointerType)
8876 return error(Loc, "base of getelementptr must be a pointer");
8877
8878 SmallVector<Value*, 16> Indices;
8879 bool AteExtraComma = false;
8880 // GEP returns a vector of pointers if at least one of parameters is a vector.
8881 // All vector parameters should have the same vector width.
8882 ElementCount GEPWidth = BaseType->isVectorTy()
8883 ? cast<VectorType>(BaseType)->getElementCount()
8885
8886 while (EatIfPresent(lltok::comma)) {
8887 if (Lex.getKind() == lltok::MetadataVar) {
8888 AteExtraComma = true;
8889 break;
8890 }
8891 if (parseTypeAndValue(Val, EltLoc, PFS))
8892 return true;
8893 if (!Val->getType()->isIntOrIntVectorTy())
8894 return error(EltLoc, "getelementptr index must be an integer");
8895
8896 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8897 ElementCount ValNumEl = ValVTy->getElementCount();
8898 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8899 return error(
8900 EltLoc,
8901 "getelementptr vector index has a wrong number of elements");
8902 GEPWidth = ValNumEl;
8903 }
8904 Indices.push_back(Val);
8905 }
8906
8907 SmallPtrSet<Type*, 4> Visited;
8908 if (!Indices.empty() && !Ty->isSized(&Visited))
8909 return error(Loc, "base element of getelementptr must be sized");
8910
8911 auto *STy = dyn_cast<StructType>(Ty);
8912 if (STy && STy->isScalableTy())
8913 return error(Loc, "getelementptr cannot target structure that contains "
8914 "scalable vector type");
8915
8916 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8917 return error(Loc, "invalid getelementptr indices");
8918 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8919 Inst = GEP;
8920 GEP->setNoWrapFlags(NW);
8921 return AteExtraComma ? InstExtraComma : InstNormal;
8922}
8923
8924/// parseExtractValue
8925/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8926int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8927 Value *Val; LocTy Loc;
8928 SmallVector<unsigned, 4> Indices;
8929 bool AteExtraComma;
8930 if (parseTypeAndValue(Val, Loc, PFS) ||
8931 parseIndexList(Indices, AteExtraComma))
8932 return true;
8933
8934 if (!Val->getType()->isAggregateType())
8935 return error(Loc, "extractvalue operand must be aggregate type");
8936
8937 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8938 return error(Loc, "invalid indices for extractvalue");
8939 Inst = ExtractValueInst::Create(Val, Indices);
8940 return AteExtraComma ? InstExtraComma : InstNormal;
8941}
8942
8943/// parseInsertValue
8944/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8945int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8946 Value *Val0, *Val1; LocTy Loc0, Loc1;
8947 SmallVector<unsigned, 4> Indices;
8948 bool AteExtraComma;
8949 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8950 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8951 parseTypeAndValue(Val1, Loc1, PFS) ||
8952 parseIndexList(Indices, AteExtraComma))
8953 return true;
8954
8955 if (!Val0->getType()->isAggregateType())
8956 return error(Loc0, "insertvalue operand must be aggregate type");
8957
8958 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8959 if (!IndexedType)
8960 return error(Loc0, "invalid indices for insertvalue");
8961 if (IndexedType != Val1->getType())
8962 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8963 getTypeString(Val1->getType()) + "' instead of '" +
8964 getTypeString(IndexedType) + "'");
8965 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8966 return AteExtraComma ? InstExtraComma : InstNormal;
8967}
8968
8969//===----------------------------------------------------------------------===//
8970// Embedded metadata.
8971//===----------------------------------------------------------------------===//
8972
8973/// parseMDNodeVector
8974/// ::= { Element (',' Element)* }
8975/// Element
8976/// ::= 'null' | Metadata
8977bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8978 if (parseToken(lltok::lbrace, "expected '{' here"))
8979 return true;
8980
8981 // Check for an empty list.
8982 if (EatIfPresent(lltok::rbrace))
8983 return false;
8984
8985 do {
8986 if (EatIfPresent(lltok::kw_null)) {
8987 Elts.push_back(nullptr);
8988 continue;
8989 }
8990
8991 Metadata *MD;
8992 if (parseMetadata(MD, nullptr))
8993 return true;
8994 Elts.push_back(MD);
8995 } while (EatIfPresent(lltok::comma));
8996
8997 return parseToken(lltok::rbrace, "expected end of metadata node");
8998}
8999
9000//===----------------------------------------------------------------------===//
9001// Use-list order directives.
9002//===----------------------------------------------------------------------===//
9003bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9004 SMLoc Loc) {
9005 if (!V->hasUseList())
9006 return false;
9007 if (V->use_empty())
9008 return error(Loc, "value has no uses");
9009
9010 unsigned NumUses = 0;
9011 SmallDenseMap<const Use *, unsigned, 16> Order;
9012 for (const Use &U : V->uses()) {
9013 if (++NumUses > Indexes.size())
9014 break;
9015 Order[&U] = Indexes[NumUses - 1];
9016 }
9017 if (NumUses < 2)
9018 return error(Loc, "value only has one use");
9019 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9020 return error(Loc,
9021 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9022
9023 V->sortUseList([&](const Use &L, const Use &R) {
9024 return Order.lookup(&L) < Order.lookup(&R);
9025 });
9026 return false;
9027}
9028
9029/// parseUseListOrderIndexes
9030/// ::= '{' uint32 (',' uint32)+ '}'
9031bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9032 SMLoc Loc = Lex.getLoc();
9033 if (parseToken(lltok::lbrace, "expected '{' here"))
9034 return true;
9035 if (Lex.getKind() == lltok::rbrace)
9036 return tokError("expected non-empty list of uselistorder indexes");
9037
9038 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9039 // indexes should be distinct numbers in the range [0, size-1], and should
9040 // not be in order.
9041 unsigned Offset = 0;
9042 unsigned Max = 0;
9043 bool IsOrdered = true;
9044 assert(Indexes.empty() && "Expected empty order vector");
9045 do {
9046 unsigned Index;
9047 if (parseUInt32(Index))
9048 return true;
9049
9050 // Update consistency checks.
9051 Offset += Index - Indexes.size();
9052 Max = std::max(Max, Index);
9053 IsOrdered &= Index == Indexes.size();
9054
9055 Indexes.push_back(Index);
9056 } while (EatIfPresent(lltok::comma));
9057
9058 if (parseToken(lltok::rbrace, "expected '}' here"))
9059 return true;
9060
9061 if (Indexes.size() < 2)
9062 return error(Loc, "expected >= 2 uselistorder indexes");
9063 if (Offset != 0 || Max >= Indexes.size())
9064 return error(Loc,
9065 "expected distinct uselistorder indexes in range [0, size)");
9066 if (IsOrdered)
9067 return error(Loc, "expected uselistorder indexes to change the order");
9068
9069 return false;
9070}
9071
9072/// parseUseListOrder
9073/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9074bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9075 SMLoc Loc = Lex.getLoc();
9076 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9077 return true;
9078
9079 Value *V;
9080 SmallVector<unsigned, 16> Indexes;
9081 if (parseTypeAndValue(V, PFS) ||
9082 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9083 parseUseListOrderIndexes(Indexes))
9084 return true;
9085
9086 return sortUseListOrder(V, Indexes, Loc);
9087}
9088
9089/// parseUseListOrderBB
9090/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9091bool LLParser::parseUseListOrderBB() {
9092 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9093 SMLoc Loc = Lex.getLoc();
9094 Lex.Lex();
9095
9096 ValID Fn, Label;
9097 SmallVector<unsigned, 16> Indexes;
9098 if (parseValID(Fn, /*PFS=*/nullptr) ||
9099 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9100 parseValID(Label, /*PFS=*/nullptr) ||
9101 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9102 parseUseListOrderIndexes(Indexes))
9103 return true;
9104
9105 // Check the function.
9106 GlobalValue *GV;
9107 if (Fn.Kind == ValID::t_GlobalName)
9108 GV = M->getNamedValue(Fn.StrVal);
9109 else if (Fn.Kind == ValID::t_GlobalID)
9110 GV = NumberedVals.get(Fn.UIntVal);
9111 else
9112 return error(Fn.Loc, "expected function name in uselistorder_bb");
9113 if (!GV)
9114 return error(Fn.Loc,
9115 "invalid function forward reference in uselistorder_bb");
9116 auto *F = dyn_cast<Function>(GV);
9117 if (!F)
9118 return error(Fn.Loc, "expected function name in uselistorder_bb");
9119 if (F->isDeclaration())
9120 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9121
9122 // Check the basic block.
9123 if (Label.Kind == ValID::t_LocalID)
9124 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9125 if (Label.Kind != ValID::t_LocalName)
9126 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9127 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9128 if (!V)
9129 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9130 if (!isa<BasicBlock>(V))
9131 return error(Label.Loc, "expected basic block in uselistorder_bb");
9132
9133 return sortUseListOrder(V, Indexes, Loc);
9134}
9135
9136/// ModuleEntry
9137/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9138/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9139bool LLParser::parseModuleEntry(unsigned ID) {
9140 assert(Lex.getKind() == lltok::kw_module);
9141 Lex.Lex();
9142
9143 std::string Path;
9144 if (parseToken(lltok::colon, "expected ':' here") ||
9145 parseToken(lltok::lparen, "expected '(' here") ||
9146 parseToken(lltok::kw_path, "expected 'path' here") ||
9147 parseToken(lltok::colon, "expected ':' here") ||
9148 parseStringConstant(Path) ||
9149 parseToken(lltok::comma, "expected ',' here") ||
9150 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9151 parseToken(lltok::colon, "expected ':' here") ||
9152 parseToken(lltok::lparen, "expected '(' here"))
9153 return true;
9154
9155 ModuleHash Hash;
9156 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9157 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9158 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9159 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9160 parseUInt32(Hash[4]))
9161 return true;
9162
9163 if (parseToken(lltok::rparen, "expected ')' here") ||
9164 parseToken(lltok::rparen, "expected ')' here"))
9165 return true;
9166
9167 auto ModuleEntry = Index->addModule(Path, Hash);
9168 ModuleIdMap[ID] = ModuleEntry->first();
9169
9170 return false;
9171}
9172
9173/// TypeIdEntry
9174/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9175bool LLParser::parseTypeIdEntry(unsigned ID) {
9176 assert(Lex.getKind() == lltok::kw_typeid);
9177 Lex.Lex();
9178
9179 std::string Name;
9180 if (parseToken(lltok::colon, "expected ':' here") ||
9181 parseToken(lltok::lparen, "expected '(' here") ||
9182 parseToken(lltok::kw_name, "expected 'name' here") ||
9183 parseToken(lltok::colon, "expected ':' here") ||
9184 parseStringConstant(Name))
9185 return true;
9186
9187 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9188 if (parseToken(lltok::comma, "expected ',' here") ||
9189 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9190 return true;
9191
9192 // Check if this ID was forward referenced, and if so, update the
9193 // corresponding GUIDs.
9194 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9195 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9196 for (auto TIDRef : FwdRefTIDs->second) {
9197 assert(!*TIDRef.first &&
9198 "Forward referenced type id GUID expected to be 0");
9199 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9200 }
9201 ForwardRefTypeIds.erase(FwdRefTIDs);
9202 }
9203
9204 return false;
9205}
9206
9207/// TypeIdSummary
9208/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9209bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9210 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9211 parseToken(lltok::colon, "expected ':' here") ||
9212 parseToken(lltok::lparen, "expected '(' here") ||
9213 parseTypeTestResolution(TIS.TTRes))
9214 return true;
9215
9216 if (EatIfPresent(lltok::comma)) {
9217 // Expect optional wpdResolutions field
9218 if (parseOptionalWpdResolutions(TIS.WPDRes))
9219 return true;
9220 }
9221
9222 if (parseToken(lltok::rparen, "expected ')' here"))
9223 return true;
9224
9225 return false;
9226}
9227
9229 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9230
9231/// TypeIdCompatibleVtableEntry
9232/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9233/// TypeIdCompatibleVtableInfo
9234/// ')'
9235bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9237 Lex.Lex();
9238
9239 std::string Name;
9240 if (parseToken(lltok::colon, "expected ':' here") ||
9241 parseToken(lltok::lparen, "expected '(' here") ||
9242 parseToken(lltok::kw_name, "expected 'name' here") ||
9243 parseToken(lltok::colon, "expected ':' here") ||
9244 parseStringConstant(Name))
9245 return true;
9246
9248 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9249 if (parseToken(lltok::comma, "expected ',' here") ||
9250 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9251 parseToken(lltok::colon, "expected ':' here") ||
9252 parseToken(lltok::lparen, "expected '(' here"))
9253 return true;
9254
9255 IdToIndexMapType IdToIndexMap;
9256 // parse each call edge
9257 do {
9259 if (parseToken(lltok::lparen, "expected '(' here") ||
9260 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9261 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9262 parseToken(lltok::comma, "expected ',' here"))
9263 return true;
9264
9265 LocTy Loc = Lex.getLoc();
9266 unsigned GVId;
9267 ValueInfo VI;
9268 if (parseGVReference(VI, GVId))
9269 return true;
9270
9271 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9272 // forward reference. We will save the location of the ValueInfo needing an
9273 // update, but can only do so once the std::vector is finalized.
9274 if (VI == EmptyVI)
9275 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9276 TI.push_back({Offset, VI});
9277
9278 if (parseToken(lltok::rparen, "expected ')' in call"))
9279 return true;
9280 } while (EatIfPresent(lltok::comma));
9281
9282 // Now that the TI vector is finalized, it is safe to save the locations
9283 // of any forward GV references that need updating later.
9284 for (auto I : IdToIndexMap) {
9285 auto &Infos = ForwardRefValueInfos[I.first];
9286 for (auto P : I.second) {
9287 assert(TI[P.first].VTableVI == EmptyVI &&
9288 "Forward referenced ValueInfo expected to be empty");
9289 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9290 }
9291 }
9292
9293 if (parseToken(lltok::rparen, "expected ')' here") ||
9294 parseToken(lltok::rparen, "expected ')' here"))
9295 return true;
9296
9297 // Check if this ID was forward referenced, and if so, update the
9298 // corresponding GUIDs.
9299 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9300 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9301 for (auto TIDRef : FwdRefTIDs->second) {
9302 assert(!*TIDRef.first &&
9303 "Forward referenced type id GUID expected to be 0");
9304 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9305 }
9306 ForwardRefTypeIds.erase(FwdRefTIDs);
9307 }
9308
9309 return false;
9310}
9311
9312/// TypeTestResolution
9313/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9314/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9315/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9316/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9317/// [',' 'inlinesBits' ':' UInt64]? ')'
9318bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9319 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9320 parseToken(lltok::colon, "expected ':' here") ||
9321 parseToken(lltok::lparen, "expected '(' here") ||
9322 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9323 parseToken(lltok::colon, "expected ':' here"))
9324 return true;
9325
9326 switch (Lex.getKind()) {
9327 case lltok::kw_unknown:
9329 break;
9330 case lltok::kw_unsat:
9332 break;
9335 break;
9336 case lltok::kw_inline:
9338 break;
9339 case lltok::kw_single:
9341 break;
9342 case lltok::kw_allOnes:
9344 break;
9345 default:
9346 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9347 }
9348 Lex.Lex();
9349
9350 if (parseToken(lltok::comma, "expected ',' here") ||
9351 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9352 parseToken(lltok::colon, "expected ':' here") ||
9353 parseUInt32(TTRes.SizeM1BitWidth))
9354 return true;
9355
9356 // parse optional fields
9357 while (EatIfPresent(lltok::comma)) {
9358 switch (Lex.getKind()) {
9360 Lex.Lex();
9361 if (parseToken(lltok::colon, "expected ':'") ||
9362 parseUInt64(TTRes.AlignLog2))
9363 return true;
9364 break;
9365 case lltok::kw_sizeM1:
9366 Lex.Lex();
9367 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9368 return true;
9369 break;
9370 case lltok::kw_bitMask: {
9371 unsigned Val;
9372 Lex.Lex();
9373 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9374 return true;
9375 assert(Val <= 0xff);
9376 TTRes.BitMask = (uint8_t)Val;
9377 break;
9378 }
9380 Lex.Lex();
9381 if (parseToken(lltok::colon, "expected ':'") ||
9382 parseUInt64(TTRes.InlineBits))
9383 return true;
9384 break;
9385 default:
9386 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9387 }
9388 }
9389
9390 if (parseToken(lltok::rparen, "expected ')' here"))
9391 return true;
9392
9393 return false;
9394}
9395
9396/// OptionalWpdResolutions
9397/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9398/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9399bool LLParser::parseOptionalWpdResolutions(
9400 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9401 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9402 parseToken(lltok::colon, "expected ':' here") ||
9403 parseToken(lltok::lparen, "expected '(' here"))
9404 return true;
9405
9406 do {
9407 uint64_t Offset;
9408 WholeProgramDevirtResolution WPDRes;
9409 if (parseToken(lltok::lparen, "expected '(' here") ||
9410 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9411 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9412 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9413 parseToken(lltok::rparen, "expected ')' here"))
9414 return true;
9415 WPDResMap[Offset] = WPDRes;
9416 } while (EatIfPresent(lltok::comma));
9417
9418 if (parseToken(lltok::rparen, "expected ')' here"))
9419 return true;
9420
9421 return false;
9422}
9423
9424/// WpdRes
9425/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9426/// [',' OptionalResByArg]? ')'
9427/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9428/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9429/// [',' OptionalResByArg]? ')'
9430/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9431/// [',' OptionalResByArg]? ')'
9432bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9433 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9434 parseToken(lltok::colon, "expected ':' here") ||
9435 parseToken(lltok::lparen, "expected '(' here") ||
9436 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9437 parseToken(lltok::colon, "expected ':' here"))
9438 return true;
9439
9440 switch (Lex.getKind()) {
9441 case lltok::kw_indir:
9443 break;
9446 break;
9449 break;
9450 default:
9451 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9452 }
9453 Lex.Lex();
9454
9455 // parse optional fields
9456 while (EatIfPresent(lltok::comma)) {
9457 switch (Lex.getKind()) {
9459 Lex.Lex();
9460 if (parseToken(lltok::colon, "expected ':' here") ||
9461 parseStringConstant(WPDRes.SingleImplName))
9462 return true;
9463 break;
9464 case lltok::kw_resByArg:
9465 if (parseOptionalResByArg(WPDRes.ResByArg))
9466 return true;
9467 break;
9468 default:
9469 return error(Lex.getLoc(),
9470 "expected optional WholeProgramDevirtResolution field");
9471 }
9472 }
9473
9474 if (parseToken(lltok::rparen, "expected ')' here"))
9475 return true;
9476
9477 return false;
9478}
9479
9480/// OptionalResByArg
9481/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9482/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9483/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9484/// 'virtualConstProp' )
9485/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9486/// [',' 'bit' ':' UInt32]? ')'
9487bool LLParser::parseOptionalResByArg(
9488 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9489 &ResByArg) {
9490 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9491 parseToken(lltok::colon, "expected ':' here") ||
9492 parseToken(lltok::lparen, "expected '(' here"))
9493 return true;
9494
9495 do {
9496 std::vector<uint64_t> Args;
9497 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9498 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9499 parseToken(lltok::colon, "expected ':' here") ||
9500 parseToken(lltok::lparen, "expected '(' here") ||
9501 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9502 parseToken(lltok::colon, "expected ':' here"))
9503 return true;
9504
9505 WholeProgramDevirtResolution::ByArg ByArg;
9506 switch (Lex.getKind()) {
9507 case lltok::kw_indir:
9509 break;
9512 break;
9515 break;
9518 break;
9519 default:
9520 return error(Lex.getLoc(),
9521 "unexpected WholeProgramDevirtResolution::ByArg kind");
9522 }
9523 Lex.Lex();
9524
9525 // parse optional fields
9526 while (EatIfPresent(lltok::comma)) {
9527 switch (Lex.getKind()) {
9528 case lltok::kw_info:
9529 Lex.Lex();
9530 if (parseToken(lltok::colon, "expected ':' here") ||
9531 parseUInt64(ByArg.Info))
9532 return true;
9533 break;
9534 case lltok::kw_byte:
9535 Lex.Lex();
9536 if (parseToken(lltok::colon, "expected ':' here") ||
9537 parseUInt32(ByArg.Byte))
9538 return true;
9539 break;
9540 case lltok::kw_bit:
9541 Lex.Lex();
9542 if (parseToken(lltok::colon, "expected ':' here") ||
9543 parseUInt32(ByArg.Bit))
9544 return true;
9545 break;
9546 default:
9547 return error(Lex.getLoc(),
9548 "expected optional whole program devirt field");
9549 }
9550 }
9551
9552 if (parseToken(lltok::rparen, "expected ')' here"))
9553 return true;
9554
9555 ResByArg[Args] = ByArg;
9556 } while (EatIfPresent(lltok::comma));
9557
9558 if (parseToken(lltok::rparen, "expected ')' here"))
9559 return true;
9560
9561 return false;
9562}
9563
9564/// OptionalResByArg
9565/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9566bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9567 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9568 parseToken(lltok::colon, "expected ':' here") ||
9569 parseToken(lltok::lparen, "expected '(' here"))
9570 return true;
9571
9572 do {
9573 uint64_t Val;
9574 if (parseUInt64(Val))
9575 return true;
9576 Args.push_back(Val);
9577 } while (EatIfPresent(lltok::comma));
9578
9579 if (parseToken(lltok::rparen, "expected ')' here"))
9580 return true;
9581
9582 return false;
9583}
9584
9585static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9586
9587static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9588 bool ReadOnly = Fwd->isReadOnly();
9589 bool WriteOnly = Fwd->isWriteOnly();
9590 assert(!(ReadOnly && WriteOnly));
9591 *Fwd = Resolved;
9592 if (ReadOnly)
9593 Fwd->setReadOnly();
9594 if (WriteOnly)
9595 Fwd->setWriteOnly();
9596}
9597
9598/// Stores the given Name/GUID and associated summary into the Index.
9599/// Also updates any forward references to the associated entry ID.
9600bool LLParser::addGlobalValueToIndex(
9601 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9602 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9603 // First create the ValueInfo utilizing the Name or GUID.
9604 ValueInfo VI;
9605 if (GUID != 0) {
9606 assert(Name.empty());
9607 VI = Index->getOrInsertValueInfo(GUID);
9608 } else {
9609 assert(!Name.empty());
9610 if (M) {
9611 auto *GV = M->getNamedValue(Name);
9612 if (!GV)
9613 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9614
9615 VI = Index->getOrInsertValueInfo(GV);
9616 } else {
9617 assert(
9618 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9619 "Need a source_filename to compute GUID for local");
9621 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9622 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9623 }
9624 }
9625
9626 // Resolve forward references from calls/refs
9627 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9628 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9629 for (auto VIRef : FwdRefVIs->second) {
9630 assert(VIRef.first->getRef() == FwdVIRef &&
9631 "Forward referenced ValueInfo expected to be empty");
9632 resolveFwdRef(VIRef.first, VI);
9633 }
9634 ForwardRefValueInfos.erase(FwdRefVIs);
9635 }
9636
9637 // Resolve forward references from aliases
9638 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9639 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9640 for (auto AliaseeRef : FwdRefAliasees->second) {
9641 assert(!AliaseeRef.first->hasAliasee() &&
9642 "Forward referencing alias already has aliasee");
9643 assert(Summary && "Aliasee must be a definition");
9644 AliaseeRef.first->setAliasee(VI, Summary.get());
9645 }
9646 ForwardRefAliasees.erase(FwdRefAliasees);
9647 }
9648
9649 // Add the summary if one was provided.
9650 if (Summary)
9651 Index->addGlobalValueSummary(VI, std::move(Summary));
9652
9653 // Save the associated ValueInfo for use in later references by ID.
9654 if (ID == NumberedValueInfos.size())
9655 NumberedValueInfos.push_back(VI);
9656 else {
9657 // Handle non-continuous numbers (to make test simplification easier).
9658 if (ID > NumberedValueInfos.size())
9659 NumberedValueInfos.resize(ID + 1);
9660 NumberedValueInfos[ID] = VI;
9661 }
9662
9663 return false;
9664}
9665
9666/// parseSummaryIndexFlags
9667/// ::= 'flags' ':' UInt64
9668bool LLParser::parseSummaryIndexFlags() {
9669 assert(Lex.getKind() == lltok::kw_flags);
9670 Lex.Lex();
9671
9672 if (parseToken(lltok::colon, "expected ':' here"))
9673 return true;
9674 uint64_t Flags;
9675 if (parseUInt64(Flags))
9676 return true;
9677 if (Index)
9678 Index->setFlags(Flags);
9679 return false;
9680}
9681
9682/// parseBlockCount
9683/// ::= 'blockcount' ':' UInt64
9684bool LLParser::parseBlockCount() {
9685 assert(Lex.getKind() == lltok::kw_blockcount);
9686 Lex.Lex();
9687
9688 if (parseToken(lltok::colon, "expected ':' here"))
9689 return true;
9690 uint64_t BlockCount;
9691 if (parseUInt64(BlockCount))
9692 return true;
9693 if (Index)
9694 Index->setBlockCount(BlockCount);
9695 return false;
9696}
9697
9698/// parseGVEntry
9699/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9700/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9701/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9702bool LLParser::parseGVEntry(unsigned ID) {
9703 assert(Lex.getKind() == lltok::kw_gv);
9704 Lex.Lex();
9705
9706 if (parseToken(lltok::colon, "expected ':' here") ||
9707 parseToken(lltok::lparen, "expected '(' here"))
9708 return true;
9709
9710 LocTy Loc = Lex.getLoc();
9711 std::string Name;
9713 switch (Lex.getKind()) {
9714 case lltok::kw_name:
9715 Lex.Lex();
9716 if (parseToken(lltok::colon, "expected ':' here") ||
9717 parseStringConstant(Name))
9718 return true;
9719 // Can't create GUID/ValueInfo until we have the linkage.
9720 break;
9721 case lltok::kw_guid:
9722 Lex.Lex();
9723 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9724 return true;
9725 break;
9726 default:
9727 return error(Lex.getLoc(), "expected name or guid tag");
9728 }
9729
9730 if (!EatIfPresent(lltok::comma)) {
9731 // No summaries. Wrap up.
9732 if (parseToken(lltok::rparen, "expected ')' here"))
9733 return true;
9734 // This was created for a call to an external or indirect target.
9735 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9736 // created for indirect calls with VP. A Name with no GUID came from
9737 // an external definition. We pass ExternalLinkage since that is only
9738 // used when the GUID must be computed from Name, and in that case
9739 // the symbol must have external linkage.
9740 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9741 nullptr, Loc);
9742 }
9743
9744 // Have a list of summaries
9745 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9746 parseToken(lltok::colon, "expected ':' here") ||
9747 parseToken(lltok::lparen, "expected '(' here"))
9748 return true;
9749 do {
9750 switch (Lex.getKind()) {
9751 case lltok::kw_function:
9752 if (parseFunctionSummary(Name, GUID, ID))
9753 return true;
9754 break;
9755 case lltok::kw_variable:
9756 if (parseVariableSummary(Name, GUID, ID))
9757 return true;
9758 break;
9759 case lltok::kw_alias:
9760 if (parseAliasSummary(Name, GUID, ID))
9761 return true;
9762 break;
9763 default:
9764 return error(Lex.getLoc(), "expected summary type");
9765 }
9766 } while (EatIfPresent(lltok::comma));
9767
9768 if (parseToken(lltok::rparen, "expected ')' here") ||
9769 parseToken(lltok::rparen, "expected ')' here"))
9770 return true;
9771
9772 return false;
9773}
9774
9775/// FunctionSummary
9776/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9777/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9778/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9779/// [',' OptionalRefs]? ')'
9780bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9781 unsigned ID) {
9782 LocTy Loc = Lex.getLoc();
9783 assert(Lex.getKind() == lltok::kw_function);
9784 Lex.Lex();
9785
9786 StringRef ModulePath;
9787 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9789 /*NotEligibleToImport=*/false,
9790 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9792 unsigned InstCount;
9794 FunctionSummary::TypeIdInfo TypeIdInfo;
9795 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9797 std::vector<CallsiteInfo> Callsites;
9798 std::vector<AllocInfo> Allocs;
9799 // Default is all-zeros (conservative values).
9800 FunctionSummary::FFlags FFlags = {};
9801 if (parseToken(lltok::colon, "expected ':' here") ||
9802 parseToken(lltok::lparen, "expected '(' here") ||
9803 parseModuleReference(ModulePath) ||
9804 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9805 parseToken(lltok::comma, "expected ',' here") ||
9806 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9807 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9808 return true;
9809
9810 // parse optional fields
9811 while (EatIfPresent(lltok::comma)) {
9812 switch (Lex.getKind()) {
9814 if (parseOptionalFFlags(FFlags))
9815 return true;
9816 break;
9817 case lltok::kw_calls:
9818 if (parseOptionalCalls(Calls))
9819 return true;
9820 break;
9822 if (parseOptionalTypeIdInfo(TypeIdInfo))
9823 return true;
9824 break;
9825 case lltok::kw_refs:
9826 if (parseOptionalRefs(Refs))
9827 return true;
9828 break;
9829 case lltok::kw_params:
9830 if (parseOptionalParamAccesses(ParamAccesses))
9831 return true;
9832 break;
9833 case lltok::kw_allocs:
9834 if (parseOptionalAllocs(Allocs))
9835 return true;
9836 break;
9838 if (parseOptionalCallsites(Callsites))
9839 return true;
9840 break;
9841 default:
9842 return error(Lex.getLoc(), "expected optional function summary field");
9843 }
9844 }
9845
9846 if (parseToken(lltok::rparen, "expected ')' here"))
9847 return true;
9848
9849 auto FS = std::make_unique<FunctionSummary>(
9850 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9851 std::move(TypeIdInfo.TypeTests),
9852 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9853 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9854 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9855 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9856 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9857
9858 FS->setModulePath(ModulePath);
9859
9860 return addGlobalValueToIndex(Name, GUID,
9862 std::move(FS), Loc);
9863}
9864
9865/// VariableSummary
9866/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9867/// [',' OptionalRefs]? ')'
9868bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9869 unsigned ID) {
9870 LocTy Loc = Lex.getLoc();
9871 assert(Lex.getKind() == lltok::kw_variable);
9872 Lex.Lex();
9873
9874 StringRef ModulePath;
9875 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9877 /*NotEligibleToImport=*/false,
9878 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9880 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9881 /* WriteOnly */ false,
9882 /* Constant */ false,
9885 VTableFuncList VTableFuncs;
9886 if (parseToken(lltok::colon, "expected ':' here") ||
9887 parseToken(lltok::lparen, "expected '(' here") ||
9888 parseModuleReference(ModulePath) ||
9889 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9890 parseToken(lltok::comma, "expected ',' here") ||
9891 parseGVarFlags(GVarFlags))
9892 return true;
9893
9894 // parse optional fields
9895 while (EatIfPresent(lltok::comma)) {
9896 switch (Lex.getKind()) {
9898 if (parseOptionalVTableFuncs(VTableFuncs))
9899 return true;
9900 break;
9901 case lltok::kw_refs:
9902 if (parseOptionalRefs(Refs))
9903 return true;
9904 break;
9905 default:
9906 return error(Lex.getLoc(), "expected optional variable summary field");
9907 }
9908 }
9909
9910 if (parseToken(lltok::rparen, "expected ')' here"))
9911 return true;
9912
9913 auto GS =
9914 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9915
9916 GS->setModulePath(ModulePath);
9917 GS->setVTableFuncs(std::move(VTableFuncs));
9918
9919 return addGlobalValueToIndex(Name, GUID,
9921 std::move(GS), Loc);
9922}
9923
9924/// AliasSummary
9925/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9926/// 'aliasee' ':' GVReference ')'
9927bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9928 unsigned ID) {
9929 assert(Lex.getKind() == lltok::kw_alias);
9930 LocTy Loc = Lex.getLoc();
9931 Lex.Lex();
9932
9933 StringRef ModulePath;
9934 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9936 /*NotEligibleToImport=*/false,
9937 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9939 if (parseToken(lltok::colon, "expected ':' here") ||
9940 parseToken(lltok::lparen, "expected '(' here") ||
9941 parseModuleReference(ModulePath) ||
9942 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9943 parseToken(lltok::comma, "expected ',' here") ||
9944 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9945 parseToken(lltok::colon, "expected ':' here"))
9946 return true;
9947
9948 ValueInfo AliaseeVI;
9949 unsigned GVId;
9950 if (parseGVReference(AliaseeVI, GVId))
9951 return true;
9952
9953 if (parseToken(lltok::rparen, "expected ')' here"))
9954 return true;
9955
9956 auto AS = std::make_unique<AliasSummary>(GVFlags);
9957
9958 AS->setModulePath(ModulePath);
9959
9960 // Record forward reference if the aliasee is not parsed yet.
9961 if (AliaseeVI.getRef() == FwdVIRef) {
9962 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9963 } else {
9964 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9965 assert(Summary && "Aliasee must be a definition");
9966 AS->setAliasee(AliaseeVI, Summary);
9967 }
9968
9969 return addGlobalValueToIndex(Name, GUID,
9971 std::move(AS), Loc);
9972}
9973
9974/// Flag
9975/// ::= [0|1]
9976bool LLParser::parseFlag(unsigned &Val) {
9977 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9978 return tokError("expected integer");
9979 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9980 Lex.Lex();
9981 return false;
9982}
9983
9984/// OptionalFFlags
9985/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9986/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9987/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9988/// [',' 'noInline' ':' Flag]? ')'
9989/// [',' 'alwaysInline' ':' Flag]? ')'
9990/// [',' 'noUnwind' ':' Flag]? ')'
9991/// [',' 'mayThrow' ':' Flag]? ')'
9992/// [',' 'hasUnknownCall' ':' Flag]? ')'
9993/// [',' 'mustBeUnreachable' ':' Flag]? ')'
9994
9995bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9996 assert(Lex.getKind() == lltok::kw_funcFlags);
9997 Lex.Lex();
9998
9999 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10000 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10001 return true;
10002
10003 do {
10004 unsigned Val = 0;
10005 switch (Lex.getKind()) {
10006 case lltok::kw_readNone:
10007 Lex.Lex();
10008 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10009 return true;
10010 FFlags.ReadNone = Val;
10011 break;
10012 case lltok::kw_readOnly:
10013 Lex.Lex();
10014 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10015 return true;
10016 FFlags.ReadOnly = Val;
10017 break;
10019 Lex.Lex();
10020 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10021 return true;
10022 FFlags.NoRecurse = Val;
10023 break;
10025 Lex.Lex();
10026 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10027 return true;
10028 FFlags.ReturnDoesNotAlias = Val;
10029 break;
10030 case lltok::kw_noInline:
10031 Lex.Lex();
10032 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10033 return true;
10034 FFlags.NoInline = Val;
10035 break;
10037 Lex.Lex();
10038 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10039 return true;
10040 FFlags.AlwaysInline = Val;
10041 break;
10042 case lltok::kw_noUnwind:
10043 Lex.Lex();
10044 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10045 return true;
10046 FFlags.NoUnwind = Val;
10047 break;
10048 case lltok::kw_mayThrow:
10049 Lex.Lex();
10050 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10051 return true;
10052 FFlags.MayThrow = Val;
10053 break;
10055 Lex.Lex();
10056 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10057 return true;
10058 FFlags.HasUnknownCall = Val;
10059 break;
10061 Lex.Lex();
10062 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10063 return true;
10064 FFlags.MustBeUnreachable = Val;
10065 break;
10066 default:
10067 return error(Lex.getLoc(), "expected function flag type");
10068 }
10069 } while (EatIfPresent(lltok::comma));
10070
10071 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10072 return true;
10073
10074 return false;
10075}
10076
10077/// OptionalCalls
10078/// := 'calls' ':' '(' Call [',' Call]* ')'
10079/// Call ::= '(' 'callee' ':' GVReference
10080/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10081/// [ ',' 'tail' ]? ')'
10082bool LLParser::parseOptionalCalls(
10083 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10084 assert(Lex.getKind() == lltok::kw_calls);
10085 Lex.Lex();
10086
10087 if (parseToken(lltok::colon, "expected ':' in calls") ||
10088 parseToken(lltok::lparen, "expected '(' in calls"))
10089 return true;
10090
10091 IdToIndexMapType IdToIndexMap;
10092 // parse each call edge
10093 do {
10094 ValueInfo VI;
10095 if (parseToken(lltok::lparen, "expected '(' in call") ||
10096 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10097 parseToken(lltok::colon, "expected ':'"))
10098 return true;
10099
10100 LocTy Loc = Lex.getLoc();
10101 unsigned GVId;
10102 if (parseGVReference(VI, GVId))
10103 return true;
10104
10106 unsigned RelBF = 0;
10107 unsigned HasTailCall = false;
10108
10109 // parse optional fields
10110 while (EatIfPresent(lltok::comma)) {
10111 switch (Lex.getKind()) {
10112 case lltok::kw_hotness:
10113 Lex.Lex();
10114 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10115 return true;
10116 break;
10117 case lltok::kw_relbf:
10118 Lex.Lex();
10119 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10120 return true;
10121 break;
10122 case lltok::kw_tail:
10123 Lex.Lex();
10124 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10125 return true;
10126 break;
10127 default:
10128 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10129 }
10130 }
10131 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
10132 return tokError("Expected only one of hotness or relbf");
10133 // Keep track of the Call array index needing a forward reference.
10134 // We will save the location of the ValueInfo needing an update, but
10135 // can only do so once the std::vector is finalized.
10136 if (VI.getRef() == FwdVIRef)
10137 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10138 Calls.push_back(
10139 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
10140
10141 if (parseToken(lltok::rparen, "expected ')' in call"))
10142 return true;
10143 } while (EatIfPresent(lltok::comma));
10144
10145 // Now that the Calls vector is finalized, it is safe to save the locations
10146 // of any forward GV references that need updating later.
10147 for (auto I : IdToIndexMap) {
10148 auto &Infos = ForwardRefValueInfos[I.first];
10149 for (auto P : I.second) {
10150 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10151 "Forward referenced ValueInfo expected to be empty");
10152 Infos.emplace_back(&Calls[P.first].first, P.second);
10153 }
10154 }
10155
10156 if (parseToken(lltok::rparen, "expected ')' in calls"))
10157 return true;
10158
10159 return false;
10160}
10161
10162/// Hotness
10163/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10164bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10165 switch (Lex.getKind()) {
10166 case lltok::kw_unknown:
10168 break;
10169 case lltok::kw_cold:
10171 break;
10172 case lltok::kw_none:
10174 break;
10175 case lltok::kw_hot:
10177 break;
10178 case lltok::kw_critical:
10180 break;
10181 default:
10182 return error(Lex.getLoc(), "invalid call edge hotness");
10183 }
10184 Lex.Lex();
10185 return false;
10186}
10187
10188/// OptionalVTableFuncs
10189/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10190/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10191bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10192 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10193 Lex.Lex();
10194
10195 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10196 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10197 return true;
10198
10199 IdToIndexMapType IdToIndexMap;
10200 // parse each virtual function pair
10201 do {
10202 ValueInfo VI;
10203 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10204 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10205 parseToken(lltok::colon, "expected ':'"))
10206 return true;
10207
10208 LocTy Loc = Lex.getLoc();
10209 unsigned GVId;
10210 if (parseGVReference(VI, GVId))
10211 return true;
10212
10213 uint64_t Offset;
10214 if (parseToken(lltok::comma, "expected comma") ||
10215 parseToken(lltok::kw_offset, "expected offset") ||
10216 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10217 return true;
10218
10219 // Keep track of the VTableFuncs array index needing a forward reference.
10220 // We will save the location of the ValueInfo needing an update, but
10221 // can only do so once the std::vector is finalized.
10222 if (VI == EmptyVI)
10223 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10224 VTableFuncs.push_back({VI, Offset});
10225
10226 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10227 return true;
10228 } while (EatIfPresent(lltok::comma));
10229
10230 // Now that the VTableFuncs vector is finalized, it is safe to save the
10231 // locations of any forward GV references that need updating later.
10232 for (auto I : IdToIndexMap) {
10233 auto &Infos = ForwardRefValueInfos[I.first];
10234 for (auto P : I.second) {
10235 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10236 "Forward referenced ValueInfo expected to be empty");
10237 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10238 }
10239 }
10240
10241 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10242 return true;
10243
10244 return false;
10245}
10246
10247/// ParamNo := 'param' ':' UInt64
10248bool LLParser::parseParamNo(uint64_t &ParamNo) {
10249 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10250 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10251 return true;
10252 return false;
10253}
10254
10255/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10256bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10257 APSInt Lower;
10258 APSInt Upper;
10259 auto ParseAPSInt = [&](APSInt &Val) {
10260 if (Lex.getKind() != lltok::APSInt)
10261 return tokError("expected integer");
10262 Val = Lex.getAPSIntVal();
10263 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10264 Val.setIsSigned(true);
10265 Lex.Lex();
10266 return false;
10267 };
10268 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10269 parseToken(lltok::colon, "expected ':' here") ||
10270 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10271 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10272 parseToken(lltok::rsquare, "expected ']' here"))
10273 return true;
10274
10275 ++Upper;
10276 Range =
10277 (Lower == Upper && !Lower.isMaxValue())
10278 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10279 : ConstantRange(Lower, Upper);
10280
10281 return false;
10282}
10283
10284/// ParamAccessCall
10285/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10286bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10287 IdLocListType &IdLocList) {
10288 if (parseToken(lltok::lparen, "expected '(' here") ||
10289 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10290 parseToken(lltok::colon, "expected ':' here"))
10291 return true;
10292
10293 unsigned GVId;
10294 ValueInfo VI;
10295 LocTy Loc = Lex.getLoc();
10296 if (parseGVReference(VI, GVId))
10297 return true;
10298
10299 Call.Callee = VI;
10300 IdLocList.emplace_back(GVId, Loc);
10301
10302 if (parseToken(lltok::comma, "expected ',' here") ||
10303 parseParamNo(Call.ParamNo) ||
10304 parseToken(lltok::comma, "expected ',' here") ||
10305 parseParamAccessOffset(Call.Offsets))
10306 return true;
10307
10308 if (parseToken(lltok::rparen, "expected ')' here"))
10309 return true;
10310
10311 return false;
10312}
10313
10314/// ParamAccess
10315/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10316/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10317bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10318 IdLocListType &IdLocList) {
10319 if (parseToken(lltok::lparen, "expected '(' here") ||
10320 parseParamNo(Param.ParamNo) ||
10321 parseToken(lltok::comma, "expected ',' here") ||
10322 parseParamAccessOffset(Param.Use))
10323 return true;
10324
10325 if (EatIfPresent(lltok::comma)) {
10326 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10327 parseToken(lltok::colon, "expected ':' here") ||
10328 parseToken(lltok::lparen, "expected '(' here"))
10329 return true;
10330 do {
10331 FunctionSummary::ParamAccess::Call Call;
10332 if (parseParamAccessCall(Call, IdLocList))
10333 return true;
10334 Param.Calls.push_back(Call);
10335 } while (EatIfPresent(lltok::comma));
10336
10337 if (parseToken(lltok::rparen, "expected ')' here"))
10338 return true;
10339 }
10340
10341 if (parseToken(lltok::rparen, "expected ')' here"))
10342 return true;
10343
10344 return false;
10345}
10346
10347/// OptionalParamAccesses
10348/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10349bool LLParser::parseOptionalParamAccesses(
10350 std::vector<FunctionSummary::ParamAccess> &Params) {
10351 assert(Lex.getKind() == lltok::kw_params);
10352 Lex.Lex();
10353
10354 if (parseToken(lltok::colon, "expected ':' here") ||
10355 parseToken(lltok::lparen, "expected '(' here"))
10356 return true;
10357
10358 IdLocListType VContexts;
10359 size_t CallsNum = 0;
10360 do {
10361 FunctionSummary::ParamAccess ParamAccess;
10362 if (parseParamAccess(ParamAccess, VContexts))
10363 return true;
10364 CallsNum += ParamAccess.Calls.size();
10365 assert(VContexts.size() == CallsNum);
10366 (void)CallsNum;
10367 Params.emplace_back(std::move(ParamAccess));
10368 } while (EatIfPresent(lltok::comma));
10369
10370 if (parseToken(lltok::rparen, "expected ')' here"))
10371 return true;
10372
10373 // Now that the Params is finalized, it is safe to save the locations
10374 // of any forward GV references that need updating later.
10375 IdLocListType::const_iterator ItContext = VContexts.begin();
10376 for (auto &PA : Params) {
10377 for (auto &C : PA.Calls) {
10378 if (C.Callee.getRef() == FwdVIRef)
10379 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10380 ItContext->second);
10381 ++ItContext;
10382 }
10383 }
10384 assert(ItContext == VContexts.end());
10385
10386 return false;
10387}
10388
10389/// OptionalRefs
10390/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10391bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10392 assert(Lex.getKind() == lltok::kw_refs);
10393 Lex.Lex();
10394
10395 if (parseToken(lltok::colon, "expected ':' in refs") ||
10396 parseToken(lltok::lparen, "expected '(' in refs"))
10397 return true;
10398
10399 struct ValueContext {
10400 ValueInfo VI;
10401 unsigned GVId;
10402 LocTy Loc;
10403 };
10404 std::vector<ValueContext> VContexts;
10405 // parse each ref edge
10406 do {
10407 ValueContext VC;
10408 VC.Loc = Lex.getLoc();
10409 if (parseGVReference(VC.VI, VC.GVId))
10410 return true;
10411 VContexts.push_back(VC);
10412 } while (EatIfPresent(lltok::comma));
10413
10414 // Sort value contexts so that ones with writeonly
10415 // and readonly ValueInfo are at the end of VContexts vector.
10416 // See FunctionSummary::specialRefCounts()
10417 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10418 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10419 });
10420
10421 IdToIndexMapType IdToIndexMap;
10422 for (auto &VC : VContexts) {
10423 // Keep track of the Refs array index needing a forward reference.
10424 // We will save the location of the ValueInfo needing an update, but
10425 // can only do so once the std::vector is finalized.
10426 if (VC.VI.getRef() == FwdVIRef)
10427 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10428 Refs.push_back(VC.VI);
10429 }
10430
10431 // Now that the Refs vector is finalized, it is safe to save the locations
10432 // of any forward GV references that need updating later.
10433 for (auto I : IdToIndexMap) {
10434 auto &Infos = ForwardRefValueInfos[I.first];
10435 for (auto P : I.second) {
10436 assert(Refs[P.first].getRef() == FwdVIRef &&
10437 "Forward referenced ValueInfo expected to be empty");
10438 Infos.emplace_back(&Refs[P.first], P.second);
10439 }
10440 }
10441
10442 if (parseToken(lltok::rparen, "expected ')' in refs"))
10443 return true;
10444
10445 return false;
10446}
10447
10448/// OptionalTypeIdInfo
10449/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10450/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10451/// [',' TypeCheckedLoadConstVCalls]? ')'
10452bool LLParser::parseOptionalTypeIdInfo(
10453 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10454 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10455 Lex.Lex();
10456
10457 if (parseToken(lltok::colon, "expected ':' here") ||
10458 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10459 return true;
10460
10461 do {
10462 switch (Lex.getKind()) {
10464 if (parseTypeTests(TypeIdInfo.TypeTests))
10465 return true;
10466 break;
10468 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10469 TypeIdInfo.TypeTestAssumeVCalls))
10470 return true;
10471 break;
10473 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10474 TypeIdInfo.TypeCheckedLoadVCalls))
10475 return true;
10476 break;
10478 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10479 TypeIdInfo.TypeTestAssumeConstVCalls))
10480 return true;
10481 break;
10483 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10484 TypeIdInfo.TypeCheckedLoadConstVCalls))
10485 return true;
10486 break;
10487 default:
10488 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10489 }
10490 } while (EatIfPresent(lltok::comma));
10491
10492 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10493 return true;
10494
10495 return false;
10496}
10497
10498/// TypeTests
10499/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10500/// [',' (SummaryID | UInt64)]* ')'
10501bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10502 assert(Lex.getKind() == lltok::kw_typeTests);
10503 Lex.Lex();
10504
10505 if (parseToken(lltok::colon, "expected ':' here") ||
10506 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10507 return true;
10508
10509 IdToIndexMapType IdToIndexMap;
10510 do {
10512 if (Lex.getKind() == lltok::SummaryID) {
10513 unsigned ID = Lex.getUIntVal();
10514 LocTy Loc = Lex.getLoc();
10515 // Keep track of the TypeTests array index needing a forward reference.
10516 // We will save the location of the GUID needing an update, but
10517 // can only do so once the std::vector is finalized.
10518 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10519 Lex.Lex();
10520 } else if (parseUInt64(GUID))
10521 return true;
10522 TypeTests.push_back(GUID);
10523 } while (EatIfPresent(lltok::comma));
10524
10525 // Now that the TypeTests vector is finalized, it is safe to save the
10526 // locations of any forward GV references that need updating later.
10527 for (auto I : IdToIndexMap) {
10528 auto &Ids = ForwardRefTypeIds[I.first];
10529 for (auto P : I.second) {
10530 assert(TypeTests[P.first] == 0 &&
10531 "Forward referenced type id GUID expected to be 0");
10532 Ids.emplace_back(&TypeTests[P.first], P.second);
10533 }
10534 }
10535
10536 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10537 return true;
10538
10539 return false;
10540}
10541
10542/// VFuncIdList
10543/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10544bool LLParser::parseVFuncIdList(
10545 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10546 assert(Lex.getKind() == Kind);
10547 Lex.Lex();
10548
10549 if (parseToken(lltok::colon, "expected ':' here") ||
10550 parseToken(lltok::lparen, "expected '(' here"))
10551 return true;
10552
10553 IdToIndexMapType IdToIndexMap;
10554 do {
10555 FunctionSummary::VFuncId VFuncId;
10556 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10557 return true;
10558 VFuncIdList.push_back(VFuncId);
10559 } while (EatIfPresent(lltok::comma));
10560
10561 if (parseToken(lltok::rparen, "expected ')' here"))
10562 return true;
10563
10564 // Now that the VFuncIdList vector is finalized, it is safe to save the
10565 // locations of any forward GV references that need updating later.
10566 for (auto I : IdToIndexMap) {
10567 auto &Ids = ForwardRefTypeIds[I.first];
10568 for (auto P : I.second) {
10569 assert(VFuncIdList[P.first].GUID == 0 &&
10570 "Forward referenced type id GUID expected to be 0");
10571 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10572 }
10573 }
10574
10575 return false;
10576}
10577
10578/// ConstVCallList
10579/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10580bool LLParser::parseConstVCallList(
10581 lltok::Kind Kind,
10582 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10583 assert(Lex.getKind() == Kind);
10584 Lex.Lex();
10585
10586 if (parseToken(lltok::colon, "expected ':' here") ||
10587 parseToken(lltok::lparen, "expected '(' here"))
10588 return true;
10589
10590 IdToIndexMapType IdToIndexMap;
10591 do {
10592 FunctionSummary::ConstVCall ConstVCall;
10593 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10594 return true;
10595 ConstVCallList.push_back(ConstVCall);
10596 } while (EatIfPresent(lltok::comma));
10597
10598 if (parseToken(lltok::rparen, "expected ')' here"))
10599 return true;
10600
10601 // Now that the ConstVCallList vector is finalized, it is safe to save the
10602 // locations of any forward GV references that need updating later.
10603 for (auto I : IdToIndexMap) {
10604 auto &Ids = ForwardRefTypeIds[I.first];
10605 for (auto P : I.second) {
10606 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10607 "Forward referenced type id GUID expected to be 0");
10608 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10609 }
10610 }
10611
10612 return false;
10613}
10614
10615/// ConstVCall
10616/// ::= '(' VFuncId ',' Args ')'
10617bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10618 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10619 if (parseToken(lltok::lparen, "expected '(' here") ||
10620 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10621 return true;
10622
10623 if (EatIfPresent(lltok::comma))
10624 if (parseArgs(ConstVCall.Args))
10625 return true;
10626
10627 if (parseToken(lltok::rparen, "expected ')' here"))
10628 return true;
10629
10630 return false;
10631}
10632
10633/// VFuncId
10634/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10635/// 'offset' ':' UInt64 ')'
10636bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10637 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10638 assert(Lex.getKind() == lltok::kw_vFuncId);
10639 Lex.Lex();
10640
10641 if (parseToken(lltok::colon, "expected ':' here") ||
10642 parseToken(lltok::lparen, "expected '(' here"))
10643 return true;
10644
10645 if (Lex.getKind() == lltok::SummaryID) {
10646 VFuncId.GUID = 0;
10647 unsigned ID = Lex.getUIntVal();
10648 LocTy Loc = Lex.getLoc();
10649 // Keep track of the array index needing a forward reference.
10650 // We will save the location of the GUID needing an update, but
10651 // can only do so once the caller's std::vector is finalized.
10652 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10653 Lex.Lex();
10654 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10655 parseToken(lltok::colon, "expected ':' here") ||
10656 parseUInt64(VFuncId.GUID))
10657 return true;
10658
10659 if (parseToken(lltok::comma, "expected ',' here") ||
10660 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10661 parseToken(lltok::colon, "expected ':' here") ||
10662 parseUInt64(VFuncId.Offset) ||
10663 parseToken(lltok::rparen, "expected ')' here"))
10664 return true;
10665
10666 return false;
10667}
10668
10669/// GVFlags
10670/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10671/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10672/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10673/// 'canAutoHide' ':' Flag ',' ')'
10674bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10675 assert(Lex.getKind() == lltok::kw_flags);
10676 Lex.Lex();
10677
10678 if (parseToken(lltok::colon, "expected ':' here") ||
10679 parseToken(lltok::lparen, "expected '(' here"))
10680 return true;
10681
10682 do {
10683 unsigned Flag = 0;
10684 switch (Lex.getKind()) {
10685 case lltok::kw_linkage:
10686 Lex.Lex();
10687 if (parseToken(lltok::colon, "expected ':'"))
10688 return true;
10689 bool HasLinkage;
10690 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10691 assert(HasLinkage && "Linkage not optional in summary entry");
10692 Lex.Lex();
10693 break;
10695 Lex.Lex();
10696 if (parseToken(lltok::colon, "expected ':'"))
10697 return true;
10698 parseOptionalVisibility(Flag);
10699 GVFlags.Visibility = Flag;
10700 break;
10702 Lex.Lex();
10703 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10704 return true;
10705 GVFlags.NotEligibleToImport = Flag;
10706 break;
10707 case lltok::kw_live:
10708 Lex.Lex();
10709 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10710 return true;
10711 GVFlags.Live = Flag;
10712 break;
10713 case lltok::kw_dsoLocal:
10714 Lex.Lex();
10715 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10716 return true;
10717 GVFlags.DSOLocal = Flag;
10718 break;
10720 Lex.Lex();
10721 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10722 return true;
10723 GVFlags.CanAutoHide = Flag;
10724 break;
10726 Lex.Lex();
10727 if (parseToken(lltok::colon, "expected ':'"))
10728 return true;
10730 if (parseOptionalImportType(Lex.getKind(), IK))
10731 return true;
10732 GVFlags.ImportType = static_cast<unsigned>(IK);
10733 Lex.Lex();
10734 break;
10735 default:
10736 return error(Lex.getLoc(), "expected gv flag type");
10737 }
10738 } while (EatIfPresent(lltok::comma));
10739
10740 if (parseToken(lltok::rparen, "expected ')' here"))
10741 return true;
10742
10743 return false;
10744}
10745
10746/// GVarFlags
10747/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10748/// ',' 'writeonly' ':' Flag
10749/// ',' 'constant' ':' Flag ')'
10750bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10751 assert(Lex.getKind() == lltok::kw_varFlags);
10752 Lex.Lex();
10753
10754 if (parseToken(lltok::colon, "expected ':' here") ||
10755 parseToken(lltok::lparen, "expected '(' here"))
10756 return true;
10757
10758 auto ParseRest = [this](unsigned int &Val) {
10759 Lex.Lex();
10760 if (parseToken(lltok::colon, "expected ':'"))
10761 return true;
10762 return parseFlag(Val);
10763 };
10764
10765 do {
10766 unsigned Flag = 0;
10767 switch (Lex.getKind()) {
10768 case lltok::kw_readonly:
10769 if (ParseRest(Flag))
10770 return true;
10771 GVarFlags.MaybeReadOnly = Flag;
10772 break;
10773 case lltok::kw_writeonly:
10774 if (ParseRest(Flag))
10775 return true;
10776 GVarFlags.MaybeWriteOnly = Flag;
10777 break;
10778 case lltok::kw_constant:
10779 if (ParseRest(Flag))
10780 return true;
10781 GVarFlags.Constant = Flag;
10782 break;
10784 if (ParseRest(Flag))
10785 return true;
10786 GVarFlags.VCallVisibility = Flag;
10787 break;
10788 default:
10789 return error(Lex.getLoc(), "expected gvar flag type");
10790 }
10791 } while (EatIfPresent(lltok::comma));
10792 return parseToken(lltok::rparen, "expected ')' here");
10793}
10794
10795/// ModuleReference
10796/// ::= 'module' ':' UInt
10797bool LLParser::parseModuleReference(StringRef &ModulePath) {
10798 // parse module id.
10799 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10800 parseToken(lltok::colon, "expected ':' here") ||
10801 parseToken(lltok::SummaryID, "expected module ID"))
10802 return true;
10803
10804 unsigned ModuleID = Lex.getUIntVal();
10805 auto I = ModuleIdMap.find(ModuleID);
10806 // We should have already parsed all module IDs
10807 assert(I != ModuleIdMap.end());
10808 ModulePath = I->second;
10809 return false;
10810}
10811
10812/// GVReference
10813/// ::= SummaryID
10814bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10815 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10816 if (!ReadOnly)
10817 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10818 if (parseToken(lltok::SummaryID, "expected GV ID"))
10819 return true;
10820
10821 GVId = Lex.getUIntVal();
10822 // Check if we already have a VI for this GV
10823 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10824 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10825 VI = NumberedValueInfos[GVId];
10826 } else
10827 // We will create a forward reference to the stored location.
10828 VI = ValueInfo(false, FwdVIRef);
10829
10830 if (ReadOnly)
10831 VI.setReadOnly();
10832 if (WriteOnly)
10833 VI.setWriteOnly();
10834 return false;
10835}
10836
10837/// OptionalAllocs
10838/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10839/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10840/// ',' MemProfs ')'
10841/// Version ::= UInt32
10842bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10843 assert(Lex.getKind() == lltok::kw_allocs);
10844 Lex.Lex();
10845
10846 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10847 parseToken(lltok::lparen, "expected '(' in allocs"))
10848 return true;
10849
10850 // parse each alloc
10851 do {
10852 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10853 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10854 parseToken(lltok::colon, "expected ':'") ||
10855 parseToken(lltok::lparen, "expected '(' in versions"))
10856 return true;
10857
10858 SmallVector<uint8_t> Versions;
10859 do {
10860 uint8_t V = 0;
10861 if (parseAllocType(V))
10862 return true;
10863 Versions.push_back(V);
10864 } while (EatIfPresent(lltok::comma));
10865
10866 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10867 parseToken(lltok::comma, "expected ',' in alloc"))
10868 return true;
10869
10870 std::vector<MIBInfo> MIBs;
10871 if (parseMemProfs(MIBs))
10872 return true;
10873
10874 Allocs.push_back({Versions, MIBs});
10875
10876 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10877 return true;
10878 } while (EatIfPresent(lltok::comma));
10879
10880 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10881 return true;
10882
10883 return false;
10884}
10885
10886/// MemProfs
10887/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10888/// MemProf ::= '(' 'type' ':' AllocType
10889/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10890/// StackId ::= UInt64
10891bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10892 assert(Lex.getKind() == lltok::kw_memProf);
10893 Lex.Lex();
10894
10895 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10896 parseToken(lltok::lparen, "expected '(' in memprof"))
10897 return true;
10898
10899 // parse each MIB
10900 do {
10901 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10902 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10903 parseToken(lltok::colon, "expected ':'"))
10904 return true;
10905
10906 uint8_t AllocType;
10907 if (parseAllocType(AllocType))
10908 return true;
10909
10910 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10911 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10912 parseToken(lltok::colon, "expected ':'") ||
10913 parseToken(lltok::lparen, "expected '(' in stackIds"))
10914 return true;
10915
10916 SmallVector<unsigned> StackIdIndices;
10917 // Combined index alloc records may not have a stack id list.
10918 if (Lex.getKind() != lltok::rparen) {
10919 do {
10920 uint64_t StackId = 0;
10921 if (parseUInt64(StackId))
10922 return true;
10923 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10924 } while (EatIfPresent(lltok::comma));
10925 }
10926
10927 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10928 return true;
10929
10930 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10931
10932 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10933 return true;
10934 } while (EatIfPresent(lltok::comma));
10935
10936 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10937 return true;
10938
10939 return false;
10940}
10941
10942/// AllocType
10943/// := ('none'|'notcold'|'cold'|'hot')
10944bool LLParser::parseAllocType(uint8_t &AllocType) {
10945 switch (Lex.getKind()) {
10946 case lltok::kw_none:
10948 break;
10949 case lltok::kw_notcold:
10951 break;
10952 case lltok::kw_cold:
10954 break;
10955 case lltok::kw_hot:
10956 AllocType = (uint8_t)AllocationType::Hot;
10957 break;
10958 default:
10959 return error(Lex.getLoc(), "invalid alloc type");
10960 }
10961 Lex.Lex();
10962 return false;
10963}
10964
10965/// OptionalCallsites
10966/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10967/// Callsite ::= '(' 'callee' ':' GVReference
10968/// ',' 'clones' ':' '(' Version [',' Version]* ')'
10969/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10970/// Version ::= UInt32
10971/// StackId ::= UInt64
10972bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10973 assert(Lex.getKind() == lltok::kw_callsites);
10974 Lex.Lex();
10975
10976 if (parseToken(lltok::colon, "expected ':' in callsites") ||
10977 parseToken(lltok::lparen, "expected '(' in callsites"))
10978 return true;
10979
10980 IdToIndexMapType IdToIndexMap;
10981 // parse each callsite
10982 do {
10983 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10984 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10985 parseToken(lltok::colon, "expected ':'"))
10986 return true;
10987
10988 ValueInfo VI;
10989 unsigned GVId = 0;
10990 LocTy Loc = Lex.getLoc();
10991 if (!EatIfPresent(lltok::kw_null)) {
10992 if (parseGVReference(VI, GVId))
10993 return true;
10994 }
10995
10996 if (parseToken(lltok::comma, "expected ',' in callsite") ||
10997 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10998 parseToken(lltok::colon, "expected ':'") ||
10999 parseToken(lltok::lparen, "expected '(' in clones"))
11000 return true;
11001
11002 SmallVector<unsigned> Clones;
11003 do {
11004 unsigned V = 0;
11005 if (parseUInt32(V))
11006 return true;
11007 Clones.push_back(V);
11008 } while (EatIfPresent(lltok::comma));
11009
11010 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11011 parseToken(lltok::comma, "expected ',' in callsite") ||
11012 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11013 parseToken(lltok::colon, "expected ':'") ||
11014 parseToken(lltok::lparen, "expected '(' in stackIds"))
11015 return true;
11016
11017 SmallVector<unsigned> StackIdIndices;
11018 // Synthesized callsite records will not have a stack id list.
11019 if (Lex.getKind() != lltok::rparen) {
11020 do {
11021 uint64_t StackId = 0;
11022 if (parseUInt64(StackId))
11023 return true;
11024 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11025 } while (EatIfPresent(lltok::comma));
11026 }
11027
11028 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11029 return true;
11030
11031 // Keep track of the Callsites array index needing a forward reference.
11032 // We will save the location of the ValueInfo needing an update, but
11033 // can only do so once the SmallVector is finalized.
11034 if (VI.getRef() == FwdVIRef)
11035 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11036 Callsites.push_back({VI, Clones, StackIdIndices});
11037
11038 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11039 return true;
11040 } while (EatIfPresent(lltok::comma));
11041
11042 // Now that the Callsites vector is finalized, it is safe to save the
11043 // locations of any forward GV references that need updating later.
11044 for (auto I : IdToIndexMap) {
11045 auto &Infos = ForwardRefValueInfos[I.first];
11046 for (auto P : I.second) {
11047 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11048 "Forward referenced ValueInfo expected to be empty");
11049 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11050 }
11051 }
11052
11053 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11054 return true;
11055
11056 return false;
11057}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:244
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:151
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:67
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1128
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1237
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:120
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
iterator begin() const
Definition ArrayRef.h:135
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:766
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:107
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:88
@ None
No attributes have been set.
Definition Attributes.h:90
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:367
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1274
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:131
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:157
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:194
unsigned size() const
Definition DenseMap.h:110
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:310
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool any() const
Definition FMF.h:56
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition Type.cpp:404
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:399
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:836
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:448
arg_iterator arg_begin()
Definition Function.h:866
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1038
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:274
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:598
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition Globals.cpp:655
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:245
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:93
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:251
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:228
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:524
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:566
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:65
lltok::Kind getKind() const
Definition LLLexer.h:71
LocTy getLoc() const
Definition LLLexer.h:70
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:123
LLLexer::LocTy LocTy
Definition LLParser.h:109
LLVMContext & getContext()
Definition LLParser.h:210
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:107
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:94
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:75
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1078
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1577
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
A single uniqued string.
Definition Metadata.h:721
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1537
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1526
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1546
static MemoryEffectsBase readOnly()
Definition ModRef.h:125
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:193
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:141
static MemoryEffectsBase writeOnly()
Definition ModRef.h:130
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:158
static MemoryEffectsBase none()
Definition ModRef.h:120
static MemoryEffectsBase unknown()
Definition ModRef.h:115
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:183
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:876
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:23
constexpr const char * getPointer() const
Definition SMLoc.h:34
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:221
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:414
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:620
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:704
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition Type.cpp:539
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:441
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:914
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:288
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:62
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:250
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:295
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:198
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:294
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:258
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:503
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
static constexpr uint64_t MaximumAlignment
Definition Value.h:830
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:598
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:631
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:703
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:765
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:220
MacinfoRecordType
Definition Dwarf.h:815
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:821
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:153
@ kw_riscv_vls_cc
Definition LLToken.h:189
@ kw_cxx_fast_tlscc
Definition LLToken.h:172
@ kw_extractvalue
Definition LLToken.h:364
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:499
@ kw_arm_apcscc
Definition LLToken.h:145
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:140
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:151
@ kw_provenance
Definition LLToken.h:220
@ kw_mustBeUnreachable
Definition LLToken.h:410
@ kw_internal
Definition LLToken.h:54
@ kw_no_sanitize_hwaddress
Definition LLToken.h:478
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:449
@ kw_canAutoHide
Definition LLToken.h:394
@ kw_alwaysInline
Definition LLToken.h:406
@ kw_insertelement
Definition LLToken.h:361
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:192
@ kw_inaccessiblememonly
Definition LLToken.h:213
@ kw_amdgpu_gfx
Definition LLToken.h:183
@ kw_getelementptr
Definition LLToken.h:358
@ kw_m68k_rtdcc
Definition LLToken.h:186
@ kw_preserve_nonecc
Definition LLToken.h:167
@ kw_x86_fastcallcc
Definition LLToken.h:141
@ kw_visibility
Definition LLToken.h:390
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:191
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:452
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:139
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:429
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:149
@ kw_amdgpu_kernel
Definition LLToken.h:182
@ kw_uselistorder
Definition LLToken.h:377
@ kw_blockcount
Definition LLToken.h:388
@ kw_notEligibleToImport
Definition LLToken.h:391
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:143
@ kw_ptx_device
Definition LLToken.h:157
@ kw_personality
Definition LLToken.h:333
@ DwarfEnumKind
Definition LLToken.h:512
@ kw_declaration
Definition LLToken.h:397
@ DwarfAttEncoding
Definition LLToken.h:498
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:158
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:409
@ kw_x86_intrcc
Definition LLToken.h:169
@ kw_addrspacecast
Definition LLToken.h:328
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:496
@ kw_x86_thiscallcc
Definition LLToken.h:142
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:190
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:378
@ NameTableKind
Definition LLToken.h:504
@ kw_inlineBits
Definition LLToken.h:447
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:212
@ kw_blockaddress
Definition LLToken.h:366
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:184
@ kw_landingpad
Definition LLToken.h:332
@ kw_aarch64_vector_pcs
Definition LLToken.h:148
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:428
@ FixedPointKind
Definition LLToken.h:505
@ kw_ptx_kernel
Definition LLToken.h:156
@ kw_extractelement
Definition LLToken.h:360
@ kw_branchFunnel
Definition LLToken.h:453
@ kw_typeidCompatibleVTable
Definition LLToken.h:434
@ kw_vTableFuncs
Definition LLToken.h:420
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:427
@ kw_no_sanitize_address
Definition LLToken.h:475
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:214
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:481
@ DwarfSourceLangName
Definition LLToken.h:501
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:181
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:346
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:146
@ kw_read_provenance
Definition LLToken.h:221
@ kw_cleanuppad
Definition LLToken.h:349
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:454
@ kw_swifttailcc
Definition LLToken.h:164
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:426
@ kw_attributes
Definition LLToken.h:195
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:457
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:443
@ kw_nodeduplicate
Definition LLToken.h:250
@ kw_avr_signalcc
Definition LLToken.h:155
@ kw_exactmatch
Definition LLToken.h:248
@ kw_unreachable
Definition LLToken.h:344
@ kw_intel_ocl_bicc
Definition LLToken.h:138
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:404
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:150
@ kw_preserve_allcc
Definition LLToken.h:166
@ kw_importType
Definition LLToken.h:395
@ kw_cleanupret
Definition LLToken.h:345
@ kw_shufflevector
Definition LLToken.h:362
@ kw_riscv_vector_cc
Definition LLToken.h:188
@ kw_avr_intrcc
Definition LLToken.h:154
@ kw_definition
Definition LLToken.h:396
@ kw_virtualConstProp
Definition LLToken.h:459
@ kw_vcall_visibility
Definition LLToken.h:448
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:208
@ kw_preserve_mostcc
Definition LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:147
@ kw_typeTestRes
Definition LLToken.h:436
@ kw_x86_regcallcc
Definition LLToken.h:144
@ kw_typeIdInfo
Definition LLToken.h:424
@ kw_amdgpu_cs_chain
Definition LLToken.h:180
@ kw_dso_local_equivalent
Definition LLToken.h:367
@ kw_x86_64_sysvcc
Definition LLToken.h:160
@ DbgRecordType
Definition LLToken.h:511
@ kw_address_is_null
Definition LLToken.h:219
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:152
@ kw_uniqueRetVal
Definition LLToken.h:458
@ kw_insertvalue
Definition LLToken.h:365
@ kw_indirectbr
Definition LLToken.h:341
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:577
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1655
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:644
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:51
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
auto cast_or_null(const Y &Val)
Definition Casting.h:715
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:293
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:296
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:754
UWTableKind
Definition CodeGen.h:148
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:151
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:150
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:288
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:339
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:198
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:305
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:35
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:1954
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:560
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:315
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
static LLVM_ABI const fltSemantics & IEEEsingle() LLVM_READNONE
Definition APFloat.cpp:266
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:304
static LLVM_ABI const fltSemantics & IEEEdouble() LLVM_READNONE
Definition APFloat.cpp:267
static LLVM_ABI const fltSemantics & IEEEhalf() LLVM_READNONE
Definition APFloat.cpp:264
static LLVM_ABI const fltSemantics & BFloat() LLVM_READNONE
Definition APFloat.cpp:265
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:33
std::map< unsigned, Type * > Types
Definition SlotMapping.h:37
StringMap< Type * > NamedTypes
Definition SlotMapping.h:36
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:35
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:34
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:53
@ t_PackedConstantStruct
Definition LLParser.h:71
@ t_ConstantStruct
Definition LLParser.h:70
@ t_ConstantSplat
Definition LLParser.h:68
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:75
FunctionType * FTy
Definition LLParser.h:76
LLLexer::LocTy Loc
Definition LLParser.h:74
std::string StrVal
Definition LLParser.h:77
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.