LLVM 23.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/AutoUpgrade.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Comdat.h"
30#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalIFunc.h"
36#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
63 "allow-incomplete-ir", cl::init(false), cl::Hidden,
65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
67
68static std::string getTypeString(Type *T) {
69 std::string Result;
70 raw_string_ostream Tmp(Result);
71 Tmp << *T;
72 return Tmp.str();
73}
74
75/// Run: module ::= toplevelentity*
76bool LLParser::Run(bool UpgradeDebugInfo,
77 DataLayoutCallbackTy DataLayoutCallback) {
78 // Prime the lexer.
79 Lex.Lex();
80
81 if (Context.shouldDiscardValueNames())
82 return error(
83 Lex.getLoc(),
84 "Can't read textual IR with a Context that discards named Values");
85
86 if (M) {
87 if (parseTargetDefinitions(DataLayoutCallback))
88 return true;
89 }
90
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
92 validateEndOfIndex();
93}
94
96 const SlotMapping *Slots) {
97 restoreParsingState(Slots);
98 Lex.Lex();
99
100 Type *Ty = nullptr;
101 if (parseType(Ty) || parseConstantValue(Ty, C))
102 return true;
103 if (Lex.getKind() != lltok::Eof)
104 return error(Lex.getLoc(), "expected end of string");
105 return false;
106}
107
109 const SlotMapping *Slots) {
110 restoreParsingState(Slots);
111 Lex.Lex();
112
113 Read = 0;
114 SMLoc Start = Lex.getLoc();
115 Ty = nullptr;
116 if (parseType(Ty))
117 return true;
118 SMLoc End = Lex.getLoc();
119 Read = End.getPointer() - Start.getPointer();
120
121 return false;
122}
123
125 const SlotMapping *Slots) {
126 restoreParsingState(Slots);
127 Lex.Lex();
128
129 Read = 0;
130 SMLoc Start = Lex.getLoc();
131 Result = nullptr;
132 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
133 SMLoc End = Lex.getLoc();
134 Read = End.getPointer() - Start.getPointer();
135
136 return Status;
137}
138
139void LLParser::restoreParsingState(const SlotMapping *Slots) {
140 if (!Slots)
141 return;
142 NumberedVals = Slots->GlobalValues;
143 NumberedMetadata = Slots->MetadataNodes;
144 for (const auto &I : Slots->NamedTypes)
145 NamedTypes.insert(
146 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
147 for (const auto &I : Slots->Types)
148 NumberedTypes.insert(
149 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
150}
151
153 // White-list intrinsics that are safe to drop.
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
156 return;
157
159 for (Value *V : II->args())
160 if (auto *MV = dyn_cast<MetadataAsValue>(V))
161 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
162 if (MD->isTemporary())
163 MVs.push_back(MV);
164
165 if (!MVs.empty()) {
166 assert(II->use_empty() && "Cannot have uses");
167 II->eraseFromParent();
168
169 // Also remove no longer used MetadataAsValue wrappers.
170 for (MetadataAsValue *MV : MVs)
171 if (MV->use_empty())
172 delete MV;
173 }
174}
175
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
178 for (Function &F : *M) {
179 F.eraseMetadataIf(Pred);
180 for (Instruction &I : make_early_inc_range(instructions(F))) {
181 I.eraseMetadataIf(Pred);
182
183 if (auto *II = dyn_cast<IntrinsicInst>(&I))
185 }
186 }
187
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
190
191 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
192 // Check whether there is only a single use left, which would be in our
193 // own NumberedMetadata.
194 if (Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(ID);
196 ForwardRefMDNodes.erase(ID);
197 }
198 }
199}
200
201/// validateEndOfModule - Do final validity and basic correctness checks at the
202/// end of the module.
203bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
204 if (!M)
205 return false;
206
207 // We should have already returned an error if we observed both intrinsics and
208 // records in this IR.
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
211
212 // Handle any function attribute group forward references.
213 for (const auto &RAG : ForwardRefAttrGroups) {
214 Value *V = RAG.first;
215 const std::vector<unsigned> &Attrs = RAG.second;
216 AttrBuilder B(Context);
217
218 for (const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(Attr);
220 if (R != NumberedAttrBuilders.end())
221 B.merge(R->second);
222 }
223
224 if (Function *Fn = dyn_cast<Function>(V)) {
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(Context);
228
229 FnAttrs.merge(B);
230
231 // If the alignment was parsed as an attribute, move to the alignment
232 // field.
233 if (MaybeAlign A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*A);
235 FnAttrs.removeAttribute(Attribute::Alignment);
236 }
237
238 AS = AS.addFnAttributes(Context, FnAttrs);
239 Fn->setAttributes(AS);
240 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(Context);
244 FnAttrs.merge(B);
245 AS = AS.addFnAttributes(Context, FnAttrs);
246 CI->setAttributes(AS);
247 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
248 AttributeList AS = II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(Context);
251 FnAttrs.merge(B);
252 AS = AS.addFnAttributes(Context, FnAttrs);
253 II->setAttributes(AS);
254 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(Context);
258 FnAttrs.merge(B);
259 AS = AS.addFnAttributes(Context, FnAttrs);
260 CBI->setAttributes(AS);
261 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
262 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
263 Attrs.merge(B);
264 GV->setAttributes(AttributeSet::get(Context,Attrs));
265 } else {
266 llvm_unreachable("invalid object with forward attribute group reference");
267 }
268 }
269
270 // If there are entries in ForwardRefBlockAddresses at this point, the
271 // function was never defined.
272 if (!ForwardRefBlockAddresses.empty())
273 return error(ForwardRefBlockAddresses.begin()->first.Loc,
274 "expected function name in blockaddress");
275
276 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV = nullptr;
279 if (GVRef.Kind == ValID::t_GlobalName) {
280 GV = M->getNamedValue(GVRef.StrVal);
281 } else {
282 GV = NumberedVals.get(GVRef.UIntVal);
283 }
284
285 if (!GV)
286 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
287 "' referenced by dso_local_equivalent");
288
289 if (!GV->getValueType()->isFunctionTy())
290 return error(GVRef.Loc,
291 "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
293
294 auto *Equiv = DSOLocalEquivalent::get(GV);
295 FwdRef->replaceAllUsesWith(Equiv);
296 FwdRef->eraseFromParent();
297 return false;
298 };
299
300 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
301 // point, they are references after the function was defined. Resolve those
302 // now.
303 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 return true;
306 }
307 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
309 return true;
310 }
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
313
314 for (const auto &NT : NumberedTypes)
315 if (NT.second.second.isValid())
316 return error(NT.second.second,
317 "use of undefined type '%" + Twine(NT.first) + "'");
318
319 for (const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(TypeInfo.second,
322 "use of undefined type named '" + Name + "'");
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
432 NewDistinctSPs.clear();
433
434 for (auto *Inst : InstsWithTBAATag) {
435 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
436 // With incomplete IR, the tbaa metadata may have been dropped.
438 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
439 if (MD) {
440 auto *UpgradedMD = UpgradeTBAANode(*MD);
441 if (MD != UpgradedMD)
442 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
443 }
444 }
445
446 // Look for intrinsic functions and CallInst that need to be upgraded. We use
447 // make_early_inc_range here because we may remove some functions.
448 for (Function &F : llvm::make_early_inc_range(*M))
450
451 if (UpgradeDebugInfo)
453
458
459 if (!Slots)
460 return false;
461 // Initialize the slot mapping.
462 // Because by this point we've parsed and validated everything, we can "steal"
463 // the mapping from LLParser as it doesn't need it anymore.
464 Slots->GlobalValues = std::move(NumberedVals);
465 Slots->MetadataNodes = std::move(NumberedMetadata);
466 for (const auto &I : NamedTypes)
467 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
468 for (const auto &I : NumberedTypes)
469 Slots->Types.insert(std::make_pair(I.first, I.second.first));
470
471 return false;
472}
473
474/// Do final validity and basic correctness checks at the end of the index.
475bool LLParser::validateEndOfIndex() {
476 if (!Index)
477 return false;
478
479 if (!ForwardRefValueInfos.empty())
480 return error(ForwardRefValueInfos.begin()->second.front().second,
481 "use of undefined summary '^" +
482 Twine(ForwardRefValueInfos.begin()->first) + "'");
483
484 if (!ForwardRefAliasees.empty())
485 return error(ForwardRefAliasees.begin()->second.front().second,
486 "use of undefined summary '^" +
487 Twine(ForwardRefAliasees.begin()->first) + "'");
488
489 if (!ForwardRefTypeIds.empty())
490 return error(ForwardRefTypeIds.begin()->second.front().second,
491 "use of undefined type id summary '^" +
492 Twine(ForwardRefTypeIds.begin()->first) + "'");
493
494 return false;
495}
496
497//===----------------------------------------------------------------------===//
498// Top-Level Entities
499//===----------------------------------------------------------------------===//
500
501bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
502 // Delay parsing of the data layout string until the target triple is known.
503 // Then, pass both the the target triple and the tentative data layout string
504 // to DataLayoutCallback, allowing to override the DL string.
505 // This enables importing modules with invalid DL strings.
506 std::string TentativeDLStr = M->getDataLayoutStr();
507 LocTy DLStrLoc;
508
509 bool Done = false;
510 while (!Done) {
511 switch (Lex.getKind()) {
512 case lltok::kw_target:
513 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
514 return true;
515 break;
517 if (parseSourceFileName())
518 return true;
519 break;
520 default:
521 Done = true;
522 }
523 }
524 // Run the override callback to potentially change the data layout string, and
525 // parse the data layout string.
526 if (auto LayoutOverride =
527 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
528 TentativeDLStr = *LayoutOverride;
529 DLStrLoc = {};
530 }
531 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
532 if (!MaybeDL)
533 return error(DLStrLoc, toString(MaybeDL.takeError()));
534 M->setDataLayout(MaybeDL.get());
535 return false;
536}
537
538bool LLParser::parseTopLevelEntities() {
539 // If there is no Module, then parse just the summary index entries.
540 if (!M) {
541 while (true) {
542 switch (Lex.getKind()) {
543 case lltok::Eof:
544 return false;
545 case lltok::SummaryID:
546 if (parseSummaryEntry())
547 return true;
548 break;
550 if (parseSourceFileName())
551 return true;
552 break;
553 default:
554 // Skip everything else
555 Lex.Lex();
556 }
557 }
558 }
559 while (true) {
560 switch (Lex.getKind()) {
561 default:
562 return tokError("expected top-level entity");
563 case lltok::Eof: return false;
565 if (parseDeclare())
566 return true;
567 break;
568 case lltok::kw_define:
569 if (parseDefine())
570 return true;
571 break;
572 case lltok::kw_module:
573 if (parseModuleAsm())
574 return true;
575 break;
577 if (parseUnnamedType())
578 return true;
579 break;
580 case lltok::LocalVar:
581 if (parseNamedType())
582 return true;
583 break;
584 case lltok::GlobalID:
585 if (parseUnnamedGlobal())
586 return true;
587 break;
588 case lltok::GlobalVar:
589 if (parseNamedGlobal())
590 return true;
591 break;
592 case lltok::ComdatVar: if (parseComdat()) return true; break;
593 case lltok::exclaim:
594 if (parseStandaloneMetadata())
595 return true;
596 break;
597 case lltok::SummaryID:
598 if (parseSummaryEntry())
599 return true;
600 break;
602 if (parseNamedMetadata())
603 return true;
604 break;
606 if (parseUnnamedAttrGrp())
607 return true;
608 break;
610 if (parseUseListOrder())
611 return true;
612 break;
614 if (parseUseListOrderBB())
615 return true;
616 break;
617 }
618 }
619}
620
621/// toplevelentity
622/// ::= 'module' 'asm' STRINGCONSTANT
623bool LLParser::parseModuleAsm() {
624 assert(Lex.getKind() == lltok::kw_module);
625 Lex.Lex();
626
627 std::string AsmStr;
628 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
629 parseStringConstant(AsmStr))
630 return true;
631
632 M->appendModuleInlineAsm(AsmStr);
633 return false;
634}
635
636/// toplevelentity
637/// ::= 'target' 'triple' '=' STRINGCONSTANT
638/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
639bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
640 LocTy &DLStrLoc) {
641 assert(Lex.getKind() == lltok::kw_target);
642 std::string Str;
643 switch (Lex.Lex()) {
644 default:
645 return tokError("unknown target property");
646 case lltok::kw_triple:
647 Lex.Lex();
648 if (parseToken(lltok::equal, "expected '=' after target triple") ||
649 parseStringConstant(Str))
650 return true;
651 M->setTargetTriple(Triple(std::move(Str)));
652 return false;
654 Lex.Lex();
655 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
656 return true;
657 DLStrLoc = Lex.getLoc();
658 if (parseStringConstant(TentativeDLStr))
659 return true;
660 return false;
661 }
662}
663
664/// toplevelentity
665/// ::= 'source_filename' '=' STRINGCONSTANT
666bool LLParser::parseSourceFileName() {
667 assert(Lex.getKind() == lltok::kw_source_filename);
668 Lex.Lex();
669 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
670 parseStringConstant(SourceFileName))
671 return true;
672 if (M)
673 M->setSourceFileName(SourceFileName);
674 return false;
675}
676
677/// parseUnnamedType:
678/// ::= LocalVarID '=' 'type' type
679bool LLParser::parseUnnamedType() {
680 LocTy TypeLoc = Lex.getLoc();
681 unsigned TypeID = Lex.getUIntVal();
682 Lex.Lex(); // eat LocalVarID;
683
684 if (parseToken(lltok::equal, "expected '=' after name") ||
685 parseToken(lltok::kw_type, "expected 'type' after '='"))
686 return true;
687
688 Type *Result = nullptr;
689 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
690 return true;
691
692 if (!isa<StructType>(Result)) {
693 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
694 if (Entry.first)
695 return error(TypeLoc, "non-struct types may not be recursive");
696 Entry.first = Result;
697 Entry.second = SMLoc();
698 }
699
700 return false;
701}
702
703/// toplevelentity
704/// ::= LocalVar '=' 'type' type
705bool LLParser::parseNamedType() {
706 std::string Name = Lex.getStrVal();
707 LocTy NameLoc = Lex.getLoc();
708 Lex.Lex(); // eat LocalVar.
709
710 if (parseToken(lltok::equal, "expected '=' after name") ||
711 parseToken(lltok::kw_type, "expected 'type' after name"))
712 return true;
713
714 Type *Result = nullptr;
715 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
716 return true;
717
718 if (!isa<StructType>(Result)) {
719 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
720 if (Entry.first)
721 return error(NameLoc, "non-struct types may not be recursive");
722 Entry.first = Result;
723 Entry.second = SMLoc();
724 }
725
726 return false;
727}
728
729/// toplevelentity
730/// ::= 'declare' FunctionHeader
731bool LLParser::parseDeclare() {
732 assert(Lex.getKind() == lltok::kw_declare);
733 Lex.Lex();
734
735 std::vector<std::pair<unsigned, MDNode *>> MDs;
736 while (Lex.getKind() == lltok::MetadataVar) {
737 unsigned MDK;
738 MDNode *N;
739 if (parseMetadataAttachment(MDK, N))
740 return true;
741 MDs.push_back({MDK, N});
742 }
743
744 Function *F;
745 unsigned FunctionNumber = -1;
746 SmallVector<unsigned> UnnamedArgNums;
747 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
748 return true;
749 for (auto &MD : MDs)
750 F->addMetadata(MD.first, *MD.second);
751 return false;
752}
753
754/// toplevelentity
755/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
756bool LLParser::parseDefine() {
757 assert(Lex.getKind() == lltok::kw_define);
758
759 FileLoc FunctionStart = getTokLineColumnPos();
760 Lex.Lex();
761
762 Function *F;
763 unsigned FunctionNumber = -1;
764 SmallVector<unsigned> UnnamedArgNums;
765 bool RetValue =
766 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
767 parseOptionalFunctionMetadata(*F) ||
768 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
769 if (ParserContext)
770 ParserContext->addFunctionLocation(
771 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
772
773 return RetValue;
774}
775
776/// parseGlobalType
777/// ::= 'constant'
778/// ::= 'global'
779bool LLParser::parseGlobalType(bool &IsConstant) {
780 if (Lex.getKind() == lltok::kw_constant)
781 IsConstant = true;
782 else if (Lex.getKind() == lltok::kw_global)
783 IsConstant = false;
784 else {
785 IsConstant = false;
786 return tokError("expected 'global' or 'constant'");
787 }
788 Lex.Lex();
789 return false;
790}
791
792bool LLParser::parseOptionalUnnamedAddr(
793 GlobalVariable::UnnamedAddr &UnnamedAddr) {
794 if (EatIfPresent(lltok::kw_unnamed_addr))
796 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
798 else
799 UnnamedAddr = GlobalValue::UnnamedAddr::None;
800 return false;
801}
802
803/// parseUnnamedGlobal:
804/// OptionalVisibility (ALIAS | IFUNC) ...
805/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
806/// OptionalDLLStorageClass
807/// ... -> global variable
808/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
809/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
810/// OptionalVisibility
811/// OptionalDLLStorageClass
812/// ... -> global variable
813bool LLParser::parseUnnamedGlobal() {
814 unsigned VarID;
815 std::string Name;
816 LocTy NameLoc = Lex.getLoc();
817
818 // Handle the GlobalID form.
819 if (Lex.getKind() == lltok::GlobalID) {
820 VarID = Lex.getUIntVal();
821 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
822 return true;
823
824 Lex.Lex(); // eat GlobalID;
825 if (parseToken(lltok::equal, "expected '=' after name"))
826 return true;
827 } else {
828 VarID = NumberedVals.getNext();
829 }
830
831 bool HasLinkage;
832 unsigned Linkage, Visibility, DLLStorageClass;
833 bool DSOLocal;
835 GlobalVariable::UnnamedAddr UnnamedAddr;
836 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
837 DSOLocal) ||
838 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
839 return true;
840
841 switch (Lex.getKind()) {
842 default:
843 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
844 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
845 case lltok::kw_alias:
846 case lltok::kw_ifunc:
847 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
848 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
849 }
850}
851
852/// parseNamedGlobal:
853/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
854/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
855/// OptionalVisibility OptionalDLLStorageClass
856/// ... -> global variable
857bool LLParser::parseNamedGlobal() {
858 assert(Lex.getKind() == lltok::GlobalVar);
859 LocTy NameLoc = Lex.getLoc();
860 std::string Name = Lex.getStrVal();
861 Lex.Lex();
862
863 bool HasLinkage;
864 unsigned Linkage, Visibility, DLLStorageClass;
865 bool DSOLocal;
867 GlobalVariable::UnnamedAddr UnnamedAddr;
868 if (parseToken(lltok::equal, "expected '=' in global variable") ||
869 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
870 DSOLocal) ||
871 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
872 return true;
873
874 switch (Lex.getKind()) {
875 default:
876 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
877 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
878 case lltok::kw_alias:
879 case lltok::kw_ifunc:
880 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
881 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
882 }
883}
884
885bool LLParser::parseComdat() {
886 assert(Lex.getKind() == lltok::ComdatVar);
887 std::string Name = Lex.getStrVal();
888 LocTy NameLoc = Lex.getLoc();
889 Lex.Lex();
890
891 if (parseToken(lltok::equal, "expected '=' here"))
892 return true;
893
894 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
895 return tokError("expected comdat type");
896
898 switch (Lex.getKind()) {
899 default:
900 return tokError("unknown selection kind");
901 case lltok::kw_any:
902 SK = Comdat::Any;
903 break;
906 break;
908 SK = Comdat::Largest;
909 break;
912 break;
914 SK = Comdat::SameSize;
915 break;
916 }
917 Lex.Lex();
918
919 // See if the comdat was forward referenced, if so, use the comdat.
920 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
921 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
922 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
923 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
924
925 Comdat *C;
926 if (I != ComdatSymTab.end())
927 C = &I->second;
928 else
929 C = M->getOrInsertComdat(Name);
930 C->setSelectionKind(SK);
931
932 return false;
933}
934
935// MDString:
936// ::= '!' STRINGCONSTANT
937bool LLParser::parseMDString(MDString *&Result) {
938 std::string Str;
939 if (parseStringConstant(Str))
940 return true;
941 Result = MDString::get(Context, Str);
942 return false;
943}
944
945// MDNode:
946// ::= '!' MDNodeNumber
947bool LLParser::parseMDNodeID(MDNode *&Result) {
948 // !{ ..., !42, ... }
949 LocTy IDLoc = Lex.getLoc();
950 unsigned MID = 0;
951 if (parseUInt32(MID))
952 return true;
953
954 // If not a forward reference, just return it now.
955 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
956 if (!Inserted) {
957 Result = It->second;
958 return false;
959 }
960
961 // Otherwise, create MDNode forward reference.
962 auto &FwdRef = ForwardRefMDNodes[MID];
963 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
964
965 Result = FwdRef.first.get();
966 It->second.reset(Result);
967 return false;
968}
969
970/// parseNamedMetadata:
971/// !foo = !{ !1, !2 }
972bool LLParser::parseNamedMetadata() {
973 assert(Lex.getKind() == lltok::MetadataVar);
974 std::string Name = Lex.getStrVal();
975 Lex.Lex();
976
977 if (parseToken(lltok::equal, "expected '=' here") ||
978 parseToken(lltok::exclaim, "Expected '!' here") ||
979 parseToken(lltok::lbrace, "Expected '{' here"))
980 return true;
981
982 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
983 if (Lex.getKind() != lltok::rbrace)
984 do {
985 MDNode *N = nullptr;
986 // parse DIExpressions inline as a special case. They are still MDNodes,
987 // so they can still appear in named metadata. Remove this logic if they
988 // become plain Metadata.
989 if (Lex.getKind() == lltok::MetadataVar &&
990 Lex.getStrVal() == "DIExpression") {
991 if (parseDIExpression(N, /*IsDistinct=*/false))
992 return true;
993 // DIArgLists should only appear inline in a function, as they may
994 // contain LocalAsMetadata arguments which require a function context.
995 } else if (Lex.getKind() == lltok::MetadataVar &&
996 Lex.getStrVal() == "DIArgList") {
997 return tokError("found DIArgList outside of function");
998 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
999 parseMDNodeID(N)) {
1000 return true;
1001 }
1002 NMD->addOperand(N);
1003 } while (EatIfPresent(lltok::comma));
1004
1005 return parseToken(lltok::rbrace, "expected end of metadata node");
1006}
1007
1008/// parseStandaloneMetadata:
1009/// !42 = !{...}
1010bool LLParser::parseStandaloneMetadata() {
1011 assert(Lex.getKind() == lltok::exclaim);
1012 Lex.Lex();
1013 unsigned MetadataID = 0;
1014
1015 MDNode *Init;
1016 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1017 return true;
1018
1019 // Detect common error, from old metadata syntax.
1020 if (Lex.getKind() == lltok::Type)
1021 return tokError("unexpected type in metadata definition");
1022
1023 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1024 if (Lex.getKind() == lltok::MetadataVar) {
1025 if (parseSpecializedMDNode(Init, IsDistinct))
1026 return true;
1027 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1028 parseMDTuple(Init, IsDistinct))
1029 return true;
1030
1031 // See if this was forward referenced, if so, handle it.
1032 auto FI = ForwardRefMDNodes.find(MetadataID);
1033 if (FI != ForwardRefMDNodes.end()) {
1034 auto *ToReplace = FI->second.first.get();
1035 // DIAssignID has its own special forward-reference "replacement" for
1036 // attachments (the temporary attachments are never actually attached).
1037 if (isa<DIAssignID>(Init)) {
1038 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1039 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1040 "Inst unexpectedly already has DIAssignID attachment");
1041 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1042 }
1043 }
1044
1045 ToReplace->replaceAllUsesWith(Init);
1046 ForwardRefMDNodes.erase(FI);
1047
1048 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1049 } else {
1050 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1051 if (!Inserted)
1052 return tokError("Metadata id is already used");
1053 It->second.reset(Init);
1054 }
1055
1056 return false;
1057}
1058
1059// Skips a single module summary entry.
1060bool LLParser::skipModuleSummaryEntry() {
1061 // Each module summary entry consists of a tag for the entry
1062 // type, followed by a colon, then the fields which may be surrounded by
1063 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1064 // support is in place we will look for the tokens corresponding to the
1065 // expected tags.
1066 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1067 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1068 Lex.getKind() != lltok::kw_blockcount)
1069 return tokError(
1070 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1071 "start of summary entry");
1072 if (Lex.getKind() == lltok::kw_flags)
1073 return parseSummaryIndexFlags();
1074 if (Lex.getKind() == lltok::kw_blockcount)
1075 return parseBlockCount();
1076 Lex.Lex();
1077 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1078 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1079 return true;
1080 // Now walk through the parenthesized entry, until the number of open
1081 // parentheses goes back down to 0 (the first '(' was parsed above).
1082 unsigned NumOpenParen = 1;
1083 do {
1084 switch (Lex.getKind()) {
1085 case lltok::lparen:
1086 NumOpenParen++;
1087 break;
1088 case lltok::rparen:
1089 NumOpenParen--;
1090 break;
1091 case lltok::Eof:
1092 return tokError("found end of file while parsing summary entry");
1093 default:
1094 // Skip everything in between parentheses.
1095 break;
1096 }
1097 Lex.Lex();
1098 } while (NumOpenParen > 0);
1099 return false;
1100}
1101
1102/// SummaryEntry
1103/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1104bool LLParser::parseSummaryEntry() {
1105 assert(Lex.getKind() == lltok::SummaryID);
1106 unsigned SummaryID = Lex.getUIntVal();
1107
1108 // For summary entries, colons should be treated as distinct tokens,
1109 // not an indication of the end of a label token.
1110 Lex.setIgnoreColonInIdentifiers(true);
1111
1112 Lex.Lex();
1113 if (parseToken(lltok::equal, "expected '=' here"))
1114 return true;
1115
1116 // If we don't have an index object, skip the summary entry.
1117 if (!Index)
1118 return skipModuleSummaryEntry();
1119
1120 bool result = false;
1121 switch (Lex.getKind()) {
1122 case lltok::kw_gv:
1123 result = parseGVEntry(SummaryID);
1124 break;
1125 case lltok::kw_module:
1126 result = parseModuleEntry(SummaryID);
1127 break;
1128 case lltok::kw_typeid:
1129 result = parseTypeIdEntry(SummaryID);
1130 break;
1132 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1133 break;
1134 case lltok::kw_flags:
1135 result = parseSummaryIndexFlags();
1136 break;
1138 result = parseBlockCount();
1139 break;
1140 default:
1141 result = error(Lex.getLoc(), "unexpected summary kind");
1142 break;
1143 }
1144 Lex.setIgnoreColonInIdentifiers(false);
1145 return result;
1146}
1147
1156
1157// If there was an explicit dso_local, update GV. In the absence of an explicit
1158// dso_local we keep the default value.
1159static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1160 if (DSOLocal)
1161 GV.setDSOLocal(true);
1162}
1163
1164/// parseAliasOrIFunc:
1165/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1166/// OptionalVisibility OptionalDLLStorageClass
1167/// OptionalThreadLocal OptionalUnnamedAddr
1168/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1169///
1170/// AliaseeOrResolver
1171/// ::= TypeAndValue
1172///
1173/// SymbolAttrs
1174/// ::= ',' 'partition' StringConstant
1175///
1176/// Everything through OptionalUnnamedAddr has already been parsed.
1177///
1178bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1179 LocTy NameLoc, unsigned L, unsigned Visibility,
1180 unsigned DLLStorageClass, bool DSOLocal,
1182 GlobalVariable::UnnamedAddr UnnamedAddr) {
1183 bool IsAlias;
1184 if (Lex.getKind() == lltok::kw_alias)
1185 IsAlias = true;
1186 else if (Lex.getKind() == lltok::kw_ifunc)
1187 IsAlias = false;
1188 else
1189 llvm_unreachable("Not an alias or ifunc!");
1190 Lex.Lex();
1191
1193
1194 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1195 return error(NameLoc, "invalid linkage type for alias");
1196
1197 if (!isValidVisibilityForLinkage(Visibility, L))
1198 return error(NameLoc,
1199 "symbol with local linkage must have default visibility");
1200
1201 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1202 return error(NameLoc,
1203 "symbol with local linkage cannot have a DLL storage class");
1204
1205 Type *Ty;
1206 LocTy ExplicitTypeLoc = Lex.getLoc();
1207 if (parseType(Ty) ||
1208 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1209 return true;
1210
1211 Constant *Aliasee;
1212 LocTy AliaseeLoc = Lex.getLoc();
1213 if (Lex.getKind() != lltok::kw_bitcast &&
1214 Lex.getKind() != lltok::kw_getelementptr &&
1215 Lex.getKind() != lltok::kw_addrspacecast &&
1216 Lex.getKind() != lltok::kw_inttoptr) {
1217 if (parseGlobalTypeAndValue(Aliasee))
1218 return true;
1219 } else {
1220 // The bitcast dest type is not present, it is implied by the dest type.
1221 ValID ID;
1222 if (parseValID(ID, /*PFS=*/nullptr))
1223 return true;
1224 if (ID.Kind != ValID::t_Constant)
1225 return error(AliaseeLoc, "invalid aliasee");
1226 Aliasee = ID.ConstantVal;
1227 }
1228
1229 Type *AliaseeType = Aliasee->getType();
1230 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1231 if (!PTy)
1232 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1233 unsigned AddrSpace = PTy->getAddressSpace();
1234
1235 GlobalValue *GVal = nullptr;
1236
1237 // See if the alias was forward referenced, if so, prepare to replace the
1238 // forward reference.
1239 if (!Name.empty()) {
1240 auto I = ForwardRefVals.find(Name);
1241 if (I != ForwardRefVals.end()) {
1242 GVal = I->second.first;
1243 ForwardRefVals.erase(Name);
1244 } else if (M->getNamedValue(Name)) {
1245 return error(NameLoc, "redefinition of global '@" + Name + "'");
1246 }
1247 } else {
1248 auto I = ForwardRefValIDs.find(NameID);
1249 if (I != ForwardRefValIDs.end()) {
1250 GVal = I->second.first;
1251 ForwardRefValIDs.erase(I);
1252 }
1253 }
1254
1255 // Okay, create the alias/ifunc but do not insert it into the module yet.
1256 std::unique_ptr<GlobalAlias> GA;
1257 std::unique_ptr<GlobalIFunc> GI;
1258 GlobalValue *GV;
1259 if (IsAlias) {
1260 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1261 /*Parent=*/nullptr));
1262 GV = GA.get();
1263 } else {
1264 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1265 /*Parent=*/nullptr));
1266 GV = GI.get();
1267 }
1268 GV->setThreadLocalMode(TLM);
1271 GV->setUnnamedAddr(UnnamedAddr);
1272 maybeSetDSOLocal(DSOLocal, *GV);
1273
1274 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1275 // Now parse them if there are any.
1276 while (Lex.getKind() == lltok::comma) {
1277 Lex.Lex();
1278
1279 if (Lex.getKind() == lltok::kw_partition) {
1280 Lex.Lex();
1281 GV->setPartition(Lex.getStrVal());
1282 if (parseToken(lltok::StringConstant, "expected partition string"))
1283 return true;
1284 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1285 if (parseGlobalObjectMetadataAttachment(*GI))
1286 return true;
1287 } else {
1288 return tokError("unknown alias or ifunc property!");
1289 }
1290 }
1291
1292 if (Name.empty())
1293 NumberedVals.add(NameID, GV);
1294
1295 if (GVal) {
1296 // Verify that types agree.
1297 if (GVal->getType() != GV->getType())
1298 return error(
1299 ExplicitTypeLoc,
1300 "forward reference and definition of alias have different types");
1301
1302 // If they agree, just RAUW the old value with the alias and remove the
1303 // forward ref info.
1304 GVal->replaceAllUsesWith(GV);
1305 GVal->eraseFromParent();
1306 }
1307
1308 // Insert into the module, we know its name won't collide now.
1309 if (IsAlias)
1310 M->insertAlias(GA.release());
1311 else
1312 M->insertIFunc(GI.release());
1313 assert(GV->getName() == Name && "Should not be a name conflict!");
1314
1315 return false;
1316}
1317
1318static bool isSanitizer(lltok::Kind Kind) {
1319 switch (Kind) {
1322 case lltok::kw_sanitize_memtag:
1324 return true;
1325 default:
1326 return false;
1327 }
1328}
1329
1330bool LLParser::parseSanitizer(GlobalVariable *GV) {
1331 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1333 if (GV->hasSanitizerMetadata())
1334 Meta = GV->getSanitizerMetadata();
1335
1336 switch (Lex.getKind()) {
1338 Meta.NoAddress = true;
1339 break;
1341 Meta.NoHWAddress = true;
1342 break;
1343 case lltok::kw_sanitize_memtag:
1344 Meta.Memtag = true;
1345 break;
1347 Meta.IsDynInit = true;
1348 break;
1349 default:
1350 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1351 }
1352 GV->setSanitizerMetadata(Meta);
1353 Lex.Lex();
1354 return false;
1355}
1356
1357/// parseGlobal
1358/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1359/// OptionalVisibility OptionalDLLStorageClass
1360/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1361/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1362/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1363/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1364/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1365/// Const OptionalAttrs
1366///
1367/// Everything up to and including OptionalUnnamedAddr has been parsed
1368/// already.
1369///
1370bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1371 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1372 unsigned Visibility, unsigned DLLStorageClass,
1373 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1374 GlobalVariable::UnnamedAddr UnnamedAddr) {
1375 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1376 return error(NameLoc,
1377 "symbol with local linkage must have default visibility");
1378
1379 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1380 return error(NameLoc,
1381 "symbol with local linkage cannot have a DLL storage class");
1382
1383 unsigned AddrSpace;
1384 bool IsConstant, IsExternallyInitialized;
1385 LocTy IsExternallyInitializedLoc;
1386 LocTy TyLoc;
1387
1388 Type *Ty = nullptr;
1389 if (parseOptionalAddrSpace(AddrSpace) ||
1390 parseOptionalToken(lltok::kw_externally_initialized,
1391 IsExternallyInitialized,
1392 &IsExternallyInitializedLoc) ||
1393 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1394 return true;
1395
1396 // If the linkage is specified and is external, then no initializer is
1397 // present.
1398 Constant *Init = nullptr;
1399 if (!HasLinkage ||
1402 if (parseGlobalValue(Ty, Init))
1403 return true;
1404 }
1405
1407 return error(TyLoc, "invalid type for global variable");
1408
1409 GlobalValue *GVal = nullptr;
1410
1411 // See if the global was forward referenced, if so, use the global.
1412 if (!Name.empty()) {
1413 auto I = ForwardRefVals.find(Name);
1414 if (I != ForwardRefVals.end()) {
1415 GVal = I->second.first;
1416 ForwardRefVals.erase(I);
1417 } else if (M->getNamedValue(Name)) {
1418 return error(NameLoc, "redefinition of global '@" + Name + "'");
1419 }
1420 } else {
1421 // Handle @"", where a name is syntactically specified, but semantically
1422 // missing.
1423 if (NameID == (unsigned)-1)
1424 NameID = NumberedVals.getNext();
1425
1426 auto I = ForwardRefValIDs.find(NameID);
1427 if (I != ForwardRefValIDs.end()) {
1428 GVal = I->second.first;
1429 ForwardRefValIDs.erase(I);
1430 }
1431 }
1432
1433 GlobalVariable *GV = new GlobalVariable(
1434 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1436
1437 if (Name.empty())
1438 NumberedVals.add(NameID, GV);
1439
1440 // Set the parsed properties on the global.
1441 if (Init)
1442 GV->setInitializer(Init);
1443 GV->setConstant(IsConstant);
1445 maybeSetDSOLocal(DSOLocal, *GV);
1448 GV->setExternallyInitialized(IsExternallyInitialized);
1449 GV->setThreadLocalMode(TLM);
1450 GV->setUnnamedAddr(UnnamedAddr);
1451
1452 if (GVal) {
1453 if (GVal->getAddressSpace() != AddrSpace)
1454 return error(
1455 TyLoc,
1456 "forward reference and definition of global have different types");
1457
1458 GVal->replaceAllUsesWith(GV);
1459 GVal->eraseFromParent();
1460 }
1461
1462 // parse attributes on the global.
1463 while (Lex.getKind() == lltok::comma) {
1464 Lex.Lex();
1465
1466 if (Lex.getKind() == lltok::kw_section) {
1467 Lex.Lex();
1468 GV->setSection(Lex.getStrVal());
1469 if (parseToken(lltok::StringConstant, "expected global section string"))
1470 return true;
1471 } else if (Lex.getKind() == lltok::kw_partition) {
1472 Lex.Lex();
1473 GV->setPartition(Lex.getStrVal());
1474 if (parseToken(lltok::StringConstant, "expected partition string"))
1475 return true;
1476 } else if (Lex.getKind() == lltok::kw_align) {
1477 MaybeAlign Alignment;
1478 if (parseOptionalAlignment(Alignment))
1479 return true;
1480 if (Alignment)
1481 GV->setAlignment(*Alignment);
1482 } else if (Lex.getKind() == lltok::kw_code_model) {
1484 if (parseOptionalCodeModel(CodeModel))
1485 return true;
1486 GV->setCodeModel(CodeModel);
1487 } else if (Lex.getKind() == lltok::MetadataVar) {
1488 if (parseGlobalObjectMetadataAttachment(*GV))
1489 return true;
1490 } else if (isSanitizer(Lex.getKind())) {
1491 if (parseSanitizer(GV))
1492 return true;
1493 } else {
1494 Comdat *C;
1495 if (parseOptionalComdat(Name, C))
1496 return true;
1497 if (C)
1498 GV->setComdat(C);
1499 else
1500 return tokError("unknown global variable property!");
1501 }
1502 }
1503
1504 AttrBuilder Attrs(M->getContext());
1505 LocTy BuiltinLoc;
1506 std::vector<unsigned> FwdRefAttrGrps;
1507 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1508 return true;
1509 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1510 GV->setAttributes(AttributeSet::get(Context, Attrs));
1511 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1512 }
1513
1514 return false;
1515}
1516
1517/// parseUnnamedAttrGrp
1518/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1519bool LLParser::parseUnnamedAttrGrp() {
1520 assert(Lex.getKind() == lltok::kw_attributes);
1521 LocTy AttrGrpLoc = Lex.getLoc();
1522 Lex.Lex();
1523
1524 if (Lex.getKind() != lltok::AttrGrpID)
1525 return tokError("expected attribute group id");
1526
1527 unsigned VarID = Lex.getUIntVal();
1528 std::vector<unsigned> unused;
1529 LocTy BuiltinLoc;
1530 Lex.Lex();
1531
1532 if (parseToken(lltok::equal, "expected '=' here") ||
1533 parseToken(lltok::lbrace, "expected '{' here"))
1534 return true;
1535
1536 auto R = NumberedAttrBuilders.find(VarID);
1537 if (R == NumberedAttrBuilders.end())
1538 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1539
1540 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1541 parseToken(lltok::rbrace, "expected end of attribute group"))
1542 return true;
1543
1544 if (!R->second.hasAttributes())
1545 return error(AttrGrpLoc, "attribute group has no attributes");
1546
1547 return false;
1548}
1549
1551 switch (Kind) {
1552#define GET_ATTR_NAMES
1553#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1554 case lltok::kw_##DISPLAY_NAME: \
1555 return Attribute::ENUM_NAME;
1556#include "llvm/IR/Attributes.inc"
1557 default:
1558 return Attribute::None;
1559 }
1560}
1561
1562bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1563 bool InAttrGroup) {
1564 if (Attribute::isTypeAttrKind(Attr))
1565 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1566
1567 switch (Attr) {
1568 case Attribute::Alignment: {
1569 MaybeAlign Alignment;
1570 if (InAttrGroup) {
1571 uint32_t Value = 0;
1572 Lex.Lex();
1573 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1574 return true;
1575 Alignment = Align(Value);
1576 } else {
1577 if (parseOptionalAlignment(Alignment, true))
1578 return true;
1579 }
1580 B.addAlignmentAttr(Alignment);
1581 return false;
1582 }
1583 case Attribute::StackAlignment: {
1584 unsigned Alignment;
1585 if (InAttrGroup) {
1586 Lex.Lex();
1587 if (parseToken(lltok::equal, "expected '=' here") ||
1588 parseUInt32(Alignment))
1589 return true;
1590 } else {
1591 if (parseOptionalStackAlignment(Alignment))
1592 return true;
1593 }
1594 B.addStackAlignmentAttr(Alignment);
1595 return false;
1596 }
1597 case Attribute::AllocSize: {
1598 unsigned ElemSizeArg;
1599 std::optional<unsigned> NumElemsArg;
1600 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1601 return true;
1602 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1603 return false;
1604 }
1605 case Attribute::VScaleRange: {
1606 unsigned MinValue, MaxValue;
1607 if (parseVScaleRangeArguments(MinValue, MaxValue))
1608 return true;
1609 B.addVScaleRangeAttr(MinValue,
1610 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1611 return false;
1612 }
1613 case Attribute::Dereferenceable: {
1614 std::optional<uint64_t> Bytes;
1615 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1616 return true;
1617 assert(Bytes.has_value());
1618 B.addDereferenceableAttr(Bytes.value());
1619 return false;
1620 }
1621 case Attribute::DeadOnReturn: {
1622 std::optional<uint64_t> Bytes;
1623 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1624 /*ErrorNoBytes=*/false))
1625 return true;
1626 if (Bytes.has_value()) {
1627 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1628 } else {
1629 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1630 }
1631 return false;
1632 }
1633 case Attribute::DereferenceableOrNull: {
1634 std::optional<uint64_t> Bytes;
1635 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1636 return true;
1637 assert(Bytes.has_value());
1638 B.addDereferenceableOrNullAttr(Bytes.value());
1639 return false;
1640 }
1641 case Attribute::UWTable: {
1643 if (parseOptionalUWTableKind(Kind))
1644 return true;
1645 B.addUWTableAttr(Kind);
1646 return false;
1647 }
1648 case Attribute::AllocKind: {
1650 if (parseAllocKind(Kind))
1651 return true;
1652 B.addAllocKindAttr(Kind);
1653 return false;
1654 }
1655 case Attribute::Memory: {
1656 std::optional<MemoryEffects> ME = parseMemoryAttr();
1657 if (!ME)
1658 return true;
1659 B.addMemoryAttr(*ME);
1660 return false;
1661 }
1662 case Attribute::DenormalFPEnv: {
1663 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1664 if (!Mode)
1665 return true;
1666
1667 B.addDenormalFPEnvAttr(*Mode);
1668 return false;
1669 }
1670 case Attribute::NoFPClass: {
1671 if (FPClassTest NoFPClass =
1672 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1673 B.addNoFPClassAttr(NoFPClass);
1674 return false;
1675 }
1676
1677 return true;
1678 }
1679 case Attribute::Range:
1680 return parseRangeAttr(B);
1681 case Attribute::Initializes:
1682 return parseInitializesAttr(B);
1683 case Attribute::Captures:
1684 return parseCapturesAttr(B);
1685 default:
1686 B.addAttribute(Attr);
1687 Lex.Lex();
1688 return false;
1689 }
1690}
1691
1693 switch (Kind) {
1694 case lltok::kw_readnone:
1695 ME &= MemoryEffects::none();
1696 return true;
1697 case lltok::kw_readonly:
1699 return true;
1700 case lltok::kw_writeonly:
1702 return true;
1705 return true;
1708 return true;
1711 return true;
1712 default:
1713 return false;
1714 }
1715}
1716
1717/// parseFnAttributeValuePairs
1718/// ::= <attr> | <attr> '=' <value>
1719bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1720 std::vector<unsigned> &FwdRefAttrGrps,
1721 bool InAttrGrp, LocTy &BuiltinLoc) {
1722 bool HaveError = false;
1723
1724 B.clear();
1725
1727 while (true) {
1728 lltok::Kind Token = Lex.getKind();
1729 if (Token == lltok::rbrace)
1730 break; // Finished.
1731
1732 if (Token == lltok::StringConstant) {
1733 if (parseStringAttribute(B))
1734 return true;
1735 continue;
1736 }
1737
1738 if (Token == lltok::AttrGrpID) {
1739 // Allow a function to reference an attribute group:
1740 //
1741 // define void @foo() #1 { ... }
1742 if (InAttrGrp) {
1743 HaveError |= error(
1744 Lex.getLoc(),
1745 "cannot have an attribute group reference in an attribute group");
1746 } else {
1747 // Save the reference to the attribute group. We'll fill it in later.
1748 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1749 }
1750 Lex.Lex();
1751 continue;
1752 }
1753
1754 SMLoc Loc = Lex.getLoc();
1755 if (Token == lltok::kw_builtin)
1756 BuiltinLoc = Loc;
1757
1758 if (upgradeMemoryAttr(ME, Token)) {
1759 Lex.Lex();
1760 continue;
1761 }
1762
1764 if (Attr == Attribute::None) {
1765 if (!InAttrGrp)
1766 break;
1767 return error(Lex.getLoc(), "unterminated attribute group");
1768 }
1769
1770 if (parseEnumAttribute(Attr, B, InAttrGrp))
1771 return true;
1772
1773 // As a hack, we allow function alignment to be initially parsed as an
1774 // attribute on a function declaration/definition or added to an attribute
1775 // group and later moved to the alignment field.
1776 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1777 HaveError |= error(Loc, "this attribute does not apply to functions");
1778 }
1779
1780 if (ME != MemoryEffects::unknown())
1781 B.addMemoryAttr(ME);
1782 return HaveError;
1783}
1784
1785//===----------------------------------------------------------------------===//
1786// GlobalValue Reference/Resolution Routines.
1787//===----------------------------------------------------------------------===//
1788
1790 // The used global type does not matter. We will later RAUW it with a
1791 // global/function of the correct type.
1792 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1795 PTy->getAddressSpace());
1796}
1797
1798Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1799 Value *Val) {
1800 Type *ValTy = Val->getType();
1801 if (ValTy == Ty)
1802 return Val;
1803 if (Ty->isLabelTy())
1804 error(Loc, "'" + Name + "' is not a basic block");
1805 else
1806 error(Loc, "'" + Name + "' defined with type '" +
1807 getTypeString(Val->getType()) + "' but expected '" +
1808 getTypeString(Ty) + "'");
1809 return nullptr;
1810}
1811
1812/// getGlobalVal - Get a value with the specified name or ID, creating a
1813/// forward reference record if needed. This can return null if the value
1814/// exists but does not have the right type.
1815GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1816 LocTy Loc) {
1818 if (!PTy) {
1819 error(Loc, "global variable reference must have pointer type");
1820 return nullptr;
1821 }
1822
1823 // Look this name up in the normal function symbol table.
1824 GlobalValue *Val =
1825 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1826
1827 // If this is a forward reference for the value, see if we already created a
1828 // forward ref record.
1829 if (!Val) {
1830 auto I = ForwardRefVals.find(Name);
1831 if (I != ForwardRefVals.end())
1832 Val = I->second.first;
1833 }
1834
1835 // If we have the value in the symbol table or fwd-ref table, return it.
1836 if (Val)
1838 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1839
1840 // Otherwise, create a new forward reference for this value and remember it.
1841 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1842 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1843 return FwdVal;
1844}
1845
1846GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1848 if (!PTy) {
1849 error(Loc, "global variable reference must have pointer type");
1850 return nullptr;
1851 }
1852
1853 GlobalValue *Val = NumberedVals.get(ID);
1854
1855 // If this is a forward reference for the value, see if we already created a
1856 // forward ref record.
1857 if (!Val) {
1858 auto I = ForwardRefValIDs.find(ID);
1859 if (I != ForwardRefValIDs.end())
1860 Val = I->second.first;
1861 }
1862
1863 // If we have the value in the symbol table or fwd-ref table, return it.
1864 if (Val)
1866 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1867
1868 // Otherwise, create a new forward reference for this value and remember it.
1869 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1870 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1871 return FwdVal;
1872}
1873
1874//===----------------------------------------------------------------------===//
1875// Comdat Reference/Resolution Routines.
1876//===----------------------------------------------------------------------===//
1877
1878Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1879 // Look this name up in the comdat symbol table.
1880 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1881 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1882 if (I != ComdatSymTab.end())
1883 return &I->second;
1884
1885 // Otherwise, create a new forward reference for this value and remember it.
1886 Comdat *C = M->getOrInsertComdat(Name);
1887 ForwardRefComdats[Name] = Loc;
1888 return C;
1889}
1890
1891//===----------------------------------------------------------------------===//
1892// Helper Routines.
1893//===----------------------------------------------------------------------===//
1894
1895/// parseToken - If the current token has the specified kind, eat it and return
1896/// success. Otherwise, emit the specified error and return failure.
1897bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1898 if (Lex.getKind() != T)
1899 return tokError(ErrMsg);
1900 Lex.Lex();
1901 return false;
1902}
1903
1904/// parseStringConstant
1905/// ::= StringConstant
1906bool LLParser::parseStringConstant(std::string &Result) {
1907 if (Lex.getKind() != lltok::StringConstant)
1908 return tokError("expected string constant");
1909 Result = Lex.getStrVal();
1910 Lex.Lex();
1911 return false;
1912}
1913
1914/// parseUInt32
1915/// ::= uint32
1916bool LLParser::parseUInt32(uint32_t &Val) {
1917 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1918 return tokError("expected integer");
1919 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1920 if (Val64 != unsigned(Val64))
1921 return tokError("expected 32-bit integer (too large)");
1922 Val = Val64;
1923 Lex.Lex();
1924 return false;
1925}
1926
1927/// parseUInt64
1928/// ::= uint64
1929bool LLParser::parseUInt64(uint64_t &Val) {
1930 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1931 return tokError("expected integer");
1932 Val = Lex.getAPSIntVal().getLimitedValue();
1933 Lex.Lex();
1934 return false;
1935}
1936
1937/// parseTLSModel
1938/// := 'localdynamic'
1939/// := 'initialexec'
1940/// := 'localexec'
1941bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1942 switch (Lex.getKind()) {
1943 default:
1944 return tokError("expected localdynamic, initialexec or localexec");
1947 break;
1950 break;
1953 break;
1954 }
1955
1956 Lex.Lex();
1957 return false;
1958}
1959
1960/// parseOptionalThreadLocal
1961/// := /*empty*/
1962/// := 'thread_local'
1963/// := 'thread_local' '(' tlsmodel ')'
1964bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1966 if (!EatIfPresent(lltok::kw_thread_local))
1967 return false;
1968
1970 if (Lex.getKind() == lltok::lparen) {
1971 Lex.Lex();
1972 return parseTLSModel(TLM) ||
1973 parseToken(lltok::rparen, "expected ')' after thread local model");
1974 }
1975 return false;
1976}
1977
1978/// parseOptionalAddrSpace
1979/// := /*empty*/
1980/// := 'addrspace' '(' uint32 ')'
1981bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1982 AddrSpace = DefaultAS;
1983 if (!EatIfPresent(lltok::kw_addrspace))
1984 return false;
1985
1986 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1987 if (Lex.getKind() == lltok::StringConstant) {
1988 const std::string &AddrSpaceStr = Lex.getStrVal();
1989 if (AddrSpaceStr == "A") {
1990 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1991 } else if (AddrSpaceStr == "G") {
1992 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1993 } else if (AddrSpaceStr == "P") {
1994 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1995 } else if (std::optional<unsigned> AS =
1996 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
1997 AddrSpace = *AS;
1998 } else {
1999 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2000 }
2001 Lex.Lex();
2002 return false;
2003 }
2004 if (Lex.getKind() != lltok::APSInt)
2005 return tokError("expected integer or string constant");
2006 SMLoc Loc = Lex.getLoc();
2007 if (parseUInt32(AddrSpace))
2008 return true;
2009 if (!isUInt<24>(AddrSpace))
2010 return error(Loc, "invalid address space, must be a 24-bit integer");
2011 return false;
2012 };
2013
2014 return parseToken(lltok::lparen, "expected '(' in address space") ||
2015 ParseAddrspaceValue(AddrSpace) ||
2016 parseToken(lltok::rparen, "expected ')' in address space");
2017}
2018
2019/// parseStringAttribute
2020/// := StringConstant
2021/// := StringConstant '=' StringConstant
2022bool LLParser::parseStringAttribute(AttrBuilder &B) {
2023 std::string Attr = Lex.getStrVal();
2024 Lex.Lex();
2025 std::string Val;
2026 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2027 return true;
2028 B.addAttribute(Attr, Val);
2029 return false;
2030}
2031
2032/// Parse a potentially empty list of parameter or return attributes.
2033bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2034 bool HaveError = false;
2035
2036 B.clear();
2037
2038 while (true) {
2039 lltok::Kind Token = Lex.getKind();
2040 if (Token == lltok::StringConstant) {
2041 if (parseStringAttribute(B))
2042 return true;
2043 continue;
2044 }
2045
2046 if (Token == lltok::kw_nocapture) {
2047 Lex.Lex();
2048 B.addCapturesAttr(CaptureInfo::none());
2049 continue;
2050 }
2051
2052 SMLoc Loc = Lex.getLoc();
2054 if (Attr == Attribute::None)
2055 return HaveError;
2056
2057 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2058 return true;
2059
2060 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2061 HaveError |= error(Loc, "this attribute does not apply to parameters");
2062 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2063 HaveError |= error(Loc, "this attribute does not apply to return values");
2064 }
2065}
2066
2067static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2068 HasLinkage = true;
2069 switch (Kind) {
2070 default:
2071 HasLinkage = false;
2073 case lltok::kw_private:
2075 case lltok::kw_internal:
2077 case lltok::kw_weak:
2079 case lltok::kw_weak_odr:
2081 case lltok::kw_linkonce:
2089 case lltok::kw_common:
2093 case lltok::kw_external:
2095 }
2096}
2097
2098/// parseOptionalLinkage
2099/// ::= /*empty*/
2100/// ::= 'private'
2101/// ::= 'internal'
2102/// ::= 'weak'
2103/// ::= 'weak_odr'
2104/// ::= 'linkonce'
2105/// ::= 'linkonce_odr'
2106/// ::= 'available_externally'
2107/// ::= 'appending'
2108/// ::= 'common'
2109/// ::= 'extern_weak'
2110/// ::= 'external'
2111bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2112 unsigned &Visibility,
2113 unsigned &DLLStorageClass, bool &DSOLocal) {
2114 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2115 if (HasLinkage)
2116 Lex.Lex();
2117 parseOptionalDSOLocal(DSOLocal);
2118 parseOptionalVisibility(Visibility);
2119 parseOptionalDLLStorageClass(DLLStorageClass);
2120
2121 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2122 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2123 }
2124
2125 return false;
2126}
2127
2128void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2129 switch (Lex.getKind()) {
2130 default:
2131 DSOLocal = false;
2132 break;
2134 DSOLocal = true;
2135 Lex.Lex();
2136 break;
2138 DSOLocal = false;
2139 Lex.Lex();
2140 break;
2141 }
2142}
2143
2144/// parseOptionalVisibility
2145/// ::= /*empty*/
2146/// ::= 'default'
2147/// ::= 'hidden'
2148/// ::= 'protected'
2149///
2150void LLParser::parseOptionalVisibility(unsigned &Res) {
2151 switch (Lex.getKind()) {
2152 default:
2154 return;
2155 case lltok::kw_default:
2157 break;
2158 case lltok::kw_hidden:
2160 break;
2163 break;
2164 }
2165 Lex.Lex();
2166}
2167
2168bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2170 switch (Kind) {
2171 default:
2172 return tokError("unknown import kind. Expect definition or declaration.");
2175 return false;
2178 return false;
2179 }
2180}
2181
2182/// parseOptionalDLLStorageClass
2183/// ::= /*empty*/
2184/// ::= 'dllimport'
2185/// ::= 'dllexport'
2186///
2187void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2188 switch (Lex.getKind()) {
2189 default:
2191 return;
2194 break;
2197 break;
2198 }
2199 Lex.Lex();
2200}
2201
2202/// parseOptionalCallingConv
2203/// ::= /*empty*/
2204/// ::= 'ccc'
2205/// ::= 'fastcc'
2206/// ::= 'intel_ocl_bicc'
2207/// ::= 'coldcc'
2208/// ::= 'cfguard_checkcc'
2209/// ::= 'x86_stdcallcc'
2210/// ::= 'x86_fastcallcc'
2211/// ::= 'x86_thiscallcc'
2212/// ::= 'x86_vectorcallcc'
2213/// ::= 'arm_apcscc'
2214/// ::= 'arm_aapcscc'
2215/// ::= 'arm_aapcs_vfpcc'
2216/// ::= 'aarch64_vector_pcs'
2217/// ::= 'aarch64_sve_vector_pcs'
2218/// ::= 'aarch64_sme_preservemost_from_x0'
2219/// ::= 'aarch64_sme_preservemost_from_x1'
2220/// ::= 'aarch64_sme_preservemost_from_x2'
2221/// ::= 'msp430_intrcc'
2222/// ::= 'avr_intrcc'
2223/// ::= 'avr_signalcc'
2224/// ::= 'ptx_kernel'
2225/// ::= 'ptx_device'
2226/// ::= 'spir_func'
2227/// ::= 'spir_kernel'
2228/// ::= 'x86_64_sysvcc'
2229/// ::= 'win64cc'
2230/// ::= 'anyregcc'
2231/// ::= 'preserve_mostcc'
2232/// ::= 'preserve_allcc'
2233/// ::= 'preserve_nonecc'
2234/// ::= 'ghccc'
2235/// ::= 'swiftcc'
2236/// ::= 'swifttailcc'
2237/// ::= 'x86_intrcc'
2238/// ::= 'hhvmcc'
2239/// ::= 'hhvm_ccc'
2240/// ::= 'cxx_fast_tlscc'
2241/// ::= 'amdgpu_vs'
2242/// ::= 'amdgpu_ls'
2243/// ::= 'amdgpu_hs'
2244/// ::= 'amdgpu_es'
2245/// ::= 'amdgpu_gs'
2246/// ::= 'amdgpu_ps'
2247/// ::= 'amdgpu_cs'
2248/// ::= 'amdgpu_cs_chain'
2249/// ::= 'amdgpu_cs_chain_preserve'
2250/// ::= 'amdgpu_kernel'
2251/// ::= 'tailcc'
2252/// ::= 'm68k_rtdcc'
2253/// ::= 'graalcc'
2254/// ::= 'riscv_vector_cc'
2255/// ::= 'riscv_vls_cc'
2256/// ::= 'cc' UINT
2257///
2258bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2259 switch (Lex.getKind()) {
2260 default: CC = CallingConv::C; return false;
2261 case lltok::kw_ccc: CC = CallingConv::C; break;
2262 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2263 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2276 break;
2279 break;
2282 break;
2285 break;
2295 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2296 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2300 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2301 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2304 case lltok::kw_hhvmcc:
2306 break;
2307 case lltok::kw_hhvm_ccc:
2309 break;
2321 break;
2324 break;
2328 break;
2329 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2331 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2334 break;
2336 // Default ABI_VLEN
2338 Lex.Lex();
2339 if (!EatIfPresent(lltok::lparen))
2340 break;
2341 uint32_t ABIVlen;
2342 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2343 return true;
2344 switch (ABIVlen) {
2345 default:
2346 return tokError("unknown RISC-V ABI VLEN");
2347#define CC_VLS_CASE(ABIVlen) \
2348 case ABIVlen: \
2349 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2350 break;
2351 CC_VLS_CASE(32)
2352 CC_VLS_CASE(64)
2353 CC_VLS_CASE(128)
2354 CC_VLS_CASE(256)
2355 CC_VLS_CASE(512)
2356 CC_VLS_CASE(1024)
2357 CC_VLS_CASE(2048)
2358 CC_VLS_CASE(4096)
2359 CC_VLS_CASE(8192)
2360 CC_VLS_CASE(16384)
2361 CC_VLS_CASE(32768)
2362 CC_VLS_CASE(65536)
2363#undef CC_VLS_CASE
2364 }
2365 return false;
2368 break;
2371 break;
2374 break;
2375 case lltok::kw_cc: {
2376 Lex.Lex();
2377 return parseUInt32(CC);
2378 }
2379 }
2380
2381 Lex.Lex();
2382 return false;
2383}
2384
2385/// parseMetadataAttachment
2386/// ::= !dbg !42
2387bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2388 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2389
2390 std::string Name = Lex.getStrVal();
2391 Kind = M->getMDKindID(Name);
2392 Lex.Lex();
2393
2394 return parseMDNode(MD);
2395}
2396
2397/// parseInstructionMetadata
2398/// ::= !dbg !42 (',' !dbg !57)*
2399bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2400 do {
2401 if (Lex.getKind() != lltok::MetadataVar)
2402 return tokError("expected metadata after comma");
2403
2404 unsigned MDK;
2405 MDNode *N;
2406 if (parseMetadataAttachment(MDK, N))
2407 return true;
2408
2409 if (MDK == LLVMContext::MD_DIAssignID)
2410 TempDIAssignIDAttachments[N].push_back(&Inst);
2411 else
2412 Inst.setMetadata(MDK, N);
2413
2414 if (MDK == LLVMContext::MD_tbaa)
2415 InstsWithTBAATag.push_back(&Inst);
2416
2417 // If this is the end of the list, we're done.
2418 } while (EatIfPresent(lltok::comma));
2419 return false;
2420}
2421
2422/// parseGlobalObjectMetadataAttachment
2423/// ::= !dbg !57
2424bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2425 unsigned MDK;
2426 MDNode *N;
2427 if (parseMetadataAttachment(MDK, N))
2428 return true;
2429
2430 GO.addMetadata(MDK, *N);
2431 return false;
2432}
2433
2434/// parseOptionalFunctionMetadata
2435/// ::= (!dbg !57)*
2436bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2437 while (Lex.getKind() == lltok::MetadataVar)
2438 if (parseGlobalObjectMetadataAttachment(F))
2439 return true;
2440 return false;
2441}
2442
2443/// parseOptionalAlignment
2444/// ::= /* empty */
2445/// ::= 'align' 4
2446bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2447 Alignment = std::nullopt;
2448 if (!EatIfPresent(lltok::kw_align))
2449 return false;
2450 LocTy AlignLoc = Lex.getLoc();
2451 uint64_t Value = 0;
2452
2453 LocTy ParenLoc = Lex.getLoc();
2454 bool HaveParens = false;
2455 if (AllowParens) {
2456 if (EatIfPresent(lltok::lparen))
2457 HaveParens = true;
2458 }
2459
2460 if (parseUInt64(Value))
2461 return true;
2462
2463 if (HaveParens && !EatIfPresent(lltok::rparen))
2464 return error(ParenLoc, "expected ')'");
2465
2466 if (!isPowerOf2_64(Value))
2467 return error(AlignLoc, "alignment is not a power of two");
2469 return error(AlignLoc, "huge alignments are not supported yet");
2470 Alignment = Align(Value);
2471 return false;
2472}
2473
2474/// parseOptionalPrefAlignment
2475/// ::= /* empty */
2476/// ::= 'prefalign' '(' 4 ')'
2477bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2478 Alignment = std::nullopt;
2479 if (!EatIfPresent(lltok::kw_prefalign))
2480 return false;
2481 LocTy AlignLoc = Lex.getLoc();
2482 uint64_t Value = 0;
2483
2484 LocTy ParenLoc = Lex.getLoc();
2485 if (!EatIfPresent(lltok::lparen))
2486 return error(ParenLoc, "expected '('");
2487
2488 if (parseUInt64(Value))
2489 return true;
2490
2491 ParenLoc = Lex.getLoc();
2492 if (!EatIfPresent(lltok::rparen))
2493 return error(ParenLoc, "expected ')'");
2494
2495 if (!isPowerOf2_64(Value))
2496 return error(AlignLoc, "alignment is not a power of two");
2498 return error(AlignLoc, "huge alignments are not supported yet");
2499 Alignment = Align(Value);
2500 return false;
2501}
2502
2503/// parseOptionalCodeModel
2504/// ::= /* empty */
2505/// ::= 'code_model' "large"
2506bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2507 Lex.Lex();
2508 auto StrVal = Lex.getStrVal();
2509 auto ErrMsg = "expected global code model string";
2510 if (StrVal == "tiny")
2511 model = CodeModel::Tiny;
2512 else if (StrVal == "small")
2513 model = CodeModel::Small;
2514 else if (StrVal == "kernel")
2515 model = CodeModel::Kernel;
2516 else if (StrVal == "medium")
2517 model = CodeModel::Medium;
2518 else if (StrVal == "large")
2519 model = CodeModel::Large;
2520 else
2521 return tokError(ErrMsg);
2522 if (parseToken(lltok::StringConstant, ErrMsg))
2523 return true;
2524 return false;
2525}
2526
2527/// parseOptionalAttrBytes
2528/// ::= /* empty */
2529/// ::= AttrKind '(' 4 ')'
2530///
2531/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2532/// 'dead_on_return'
2533bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2534 std::optional<uint64_t> &Bytes,
2535 bool ErrorNoBytes) {
2536 assert((AttrKind == lltok::kw_dereferenceable ||
2537 AttrKind == lltok::kw_dereferenceable_or_null ||
2538 AttrKind == lltok::kw_dead_on_return) &&
2539 "contract!");
2540
2541 Bytes = 0;
2542 if (!EatIfPresent(AttrKind))
2543 return false;
2544 LocTy ParenLoc = Lex.getLoc();
2545 if (!EatIfPresent(lltok::lparen)) {
2546 if (ErrorNoBytes)
2547 return error(ParenLoc, "expected '('");
2548 Bytes = std::nullopt;
2549 return false;
2550 }
2551 LocTy DerefLoc = Lex.getLoc();
2552 if (parseUInt64(Bytes.value()))
2553 return true;
2554 ParenLoc = Lex.getLoc();
2555 if (!EatIfPresent(lltok::rparen))
2556 return error(ParenLoc, "expected ')'");
2557 if (!Bytes.value())
2558 return error(DerefLoc, "byte count specified must be non-zero");
2559 return false;
2560}
2561
2562bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2563 Lex.Lex();
2565 if (!EatIfPresent(lltok::lparen))
2566 return false;
2567 LocTy KindLoc = Lex.getLoc();
2568 if (Lex.getKind() == lltok::kw_sync)
2570 else if (Lex.getKind() == lltok::kw_async)
2572 else
2573 return error(KindLoc, "expected unwind table kind");
2574 Lex.Lex();
2575 return parseToken(lltok::rparen, "expected ')'");
2576}
2577
2578bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2579 Lex.Lex();
2580 LocTy ParenLoc = Lex.getLoc();
2581 if (!EatIfPresent(lltok::lparen))
2582 return error(ParenLoc, "expected '('");
2583 LocTy KindLoc = Lex.getLoc();
2584 std::string Arg;
2585 if (parseStringConstant(Arg))
2586 return error(KindLoc, "expected allockind value");
2587 for (StringRef A : llvm::split(Arg, ",")) {
2588 if (A == "alloc") {
2590 } else if (A == "realloc") {
2592 } else if (A == "free") {
2594 } else if (A == "uninitialized") {
2596 } else if (A == "zeroed") {
2598 } else if (A == "aligned") {
2600 } else {
2601 return error(KindLoc, Twine("unknown allockind ") + A);
2602 }
2603 }
2604 ParenLoc = Lex.getLoc();
2605 if (!EatIfPresent(lltok::rparen))
2606 return error(ParenLoc, "expected ')'");
2607 if (Kind == AllocFnKind::Unknown)
2608 return error(KindLoc, "expected allockind value");
2609 return false;
2610}
2611
2613 using Loc = IRMemLocation;
2614
2615 switch (Tok) {
2616 case lltok::kw_argmem:
2617 return {Loc::ArgMem};
2619 return {Loc::InaccessibleMem};
2620 case lltok::kw_errnomem:
2621 return {Loc::ErrnoMem};
2623 return {Loc::TargetMem0};
2625 return {Loc::TargetMem1};
2626 case lltok::kw_target_mem: {
2629 Targets.push_back(Loc);
2630 return Targets;
2631 }
2632 default:
2633 return {};
2634 }
2635}
2636
2637static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2638 switch (Tok) {
2639 case lltok::kw_none:
2640 return ModRefInfo::NoModRef;
2641 case lltok::kw_read:
2642 return ModRefInfo::Ref;
2643 case lltok::kw_write:
2644 return ModRefInfo::Mod;
2646 return ModRefInfo::ModRef;
2647 default:
2648 return std::nullopt;
2649 }
2650}
2651
2652static std::optional<DenormalMode::DenormalModeKind>
2654 switch (Tok) {
2655 case lltok::kw_ieee:
2656 return DenormalMode::IEEE;
2661 case lltok::kw_dynamic:
2662 return DenormalMode::Dynamic;
2663 default:
2664 return std::nullopt;
2665 }
2666}
2667
2668std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2670
2671 // We use syntax like memory(argmem: read), so the colon should not be
2672 // interpreted as a label terminator.
2673 Lex.setIgnoreColonInIdentifiers(true);
2674 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2675
2676 Lex.Lex();
2677 if (!EatIfPresent(lltok::lparen)) {
2678 tokError("expected '('");
2679 return std::nullopt;
2680 }
2681
2682 bool SeenLoc = false;
2683 bool SeenTargetLoc = false;
2684 do {
2685 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2686 if (!Locs.empty()) {
2687 Lex.Lex();
2688 if (!EatIfPresent(lltok::colon)) {
2689 tokError("expected ':' after location");
2690 return std::nullopt;
2691 }
2692 }
2693
2694 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2695 if (!MR) {
2696 if (Locs.empty())
2697 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2698 "or access kind (none, read, write, readwrite)");
2699 else
2700 tokError("expected access kind (none, read, write, readwrite)");
2701 return std::nullopt;
2702 }
2703
2704 Lex.Lex();
2705 if (!Locs.empty()) {
2706 SeenLoc = true;
2707 for (IRMemLocation Loc : Locs) {
2708 ME = ME.getWithModRef(Loc, *MR);
2709 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2710 SeenTargetLoc = true;
2711 }
2712 if (Locs.size() > 1 && SeenTargetLoc) {
2713 tokError("target memory default access kind must be specified first");
2714 return std::nullopt;
2715 }
2716
2717 } else {
2718 if (SeenLoc) {
2719 tokError("default access kind must be specified first");
2720 return std::nullopt;
2721 }
2722 ME = MemoryEffects(*MR);
2723 }
2724
2725 if (EatIfPresent(lltok::rparen))
2726 return ME;
2727 } while (EatIfPresent(lltok::comma));
2728
2729 tokError("unterminated memory attribute");
2730 return std::nullopt;
2731}
2732
2733std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2734 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2735 keywordToDenormalModeKind(Lex.getKind());
2736 if (!OutputMode) {
2737 tokError("expected denormal behavior kind (ieee, preservesign, "
2738 "positivezero, dynamic)");
2739 return {};
2740 }
2741
2742 Lex.Lex();
2743
2744 std::optional<DenormalMode::DenormalModeKind> InputMode;
2745 if (EatIfPresent(lltok::bar)) {
2746 InputMode = keywordToDenormalModeKind(Lex.getKind());
2747 if (!InputMode) {
2748 tokError("expected denormal behavior kind (ieee, preservesign, "
2749 "positivezero, dynamic)");
2750 return {};
2751 }
2752
2753 Lex.Lex();
2754 } else {
2755 // Single item, input == output mode
2756 InputMode = OutputMode;
2757 }
2758
2759 return DenormalMode(*OutputMode, *InputMode);
2760}
2761
2762std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2763 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2764 // not be interpreted as a label terminator.
2765 Lex.setIgnoreColonInIdentifiers(true);
2766 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2767
2768 Lex.Lex();
2769
2770 if (parseToken(lltok::lparen, "expected '('"))
2771 return {};
2772
2773 DenormalMode DefaultMode = DenormalMode::getIEEE();
2774 DenormalMode F32Mode = DenormalMode::getInvalid();
2775
2776 bool HasDefaultSection = false;
2777 if (Lex.getKind() != lltok::Type) {
2778 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2779 if (!ParsedDefaultMode)
2780 return {};
2781 DefaultMode = *ParsedDefaultMode;
2782 HasDefaultSection = true;
2783 }
2784
2785 bool HasComma = EatIfPresent(lltok::comma);
2786 if (Lex.getKind() == lltok::Type) {
2787 if (HasDefaultSection && !HasComma) {
2788 tokError("expected ',' before float:");
2789 return {};
2790 }
2791
2792 Type *Ty = nullptr;
2793 if (parseType(Ty) || !Ty->isFloatTy()) {
2794 tokError("expected float:");
2795 return {};
2796 }
2797
2798 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2799 return {};
2800
2801 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2802 if (!ParsedF32Mode)
2803 return {};
2804
2805 F32Mode = *ParsedF32Mode;
2806 }
2807
2808 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2809 return {};
2810
2811 return DenormalFPEnv(DefaultMode, F32Mode);
2812}
2813
2814static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2815 switch (Tok) {
2816 case lltok::kw_all:
2817 return fcAllFlags;
2818 case lltok::kw_nan:
2819 return fcNan;
2820 case lltok::kw_snan:
2821 return fcSNan;
2822 case lltok::kw_qnan:
2823 return fcQNan;
2824 case lltok::kw_inf:
2825 return fcInf;
2826 case lltok::kw_ninf:
2827 return fcNegInf;
2828 case lltok::kw_pinf:
2829 return fcPosInf;
2830 case lltok::kw_norm:
2831 return fcNormal;
2832 case lltok::kw_nnorm:
2833 return fcNegNormal;
2834 case lltok::kw_pnorm:
2835 return fcPosNormal;
2836 case lltok::kw_sub:
2837 return fcSubnormal;
2838 case lltok::kw_nsub:
2839 return fcNegSubnormal;
2840 case lltok::kw_psub:
2841 return fcPosSubnormal;
2842 case lltok::kw_zero:
2843 return fcZero;
2844 case lltok::kw_nzero:
2845 return fcNegZero;
2846 case lltok::kw_pzero:
2847 return fcPosZero;
2848 default:
2849 return 0;
2850 }
2851}
2852
2853unsigned LLParser::parseNoFPClassAttr() {
2854 unsigned Mask = fcNone;
2855
2856 Lex.Lex();
2857 if (!EatIfPresent(lltok::lparen)) {
2858 tokError("expected '('");
2859 return 0;
2860 }
2861
2862 do {
2863 uint64_t Value = 0;
2864 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2865 if (TestMask != 0) {
2866 Mask |= TestMask;
2867 // TODO: Disallow overlapping masks to avoid copy paste errors
2868 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2869 !parseUInt64(Value)) {
2870 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2871 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2872 return 0;
2873 }
2874
2875 if (!EatIfPresent(lltok::rparen)) {
2876 error(Lex.getLoc(), "expected ')'");
2877 return 0;
2878 }
2879
2880 return Value;
2881 } else {
2882 error(Lex.getLoc(), "expected nofpclass test mask");
2883 return 0;
2884 }
2885
2886 Lex.Lex();
2887 if (EatIfPresent(lltok::rparen))
2888 return Mask;
2889 } while (1);
2890
2891 llvm_unreachable("unterminated nofpclass attribute");
2892}
2893
2894/// parseOptionalCommaAlign
2895/// ::=
2896/// ::= ',' align 4
2897///
2898/// This returns with AteExtraComma set to true if it ate an excess comma at the
2899/// end.
2900bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2901 bool &AteExtraComma) {
2902 AteExtraComma = false;
2903 while (EatIfPresent(lltok::comma)) {
2904 // Metadata at the end is an early exit.
2905 if (Lex.getKind() == lltok::MetadataVar) {
2906 AteExtraComma = true;
2907 return false;
2908 }
2909
2910 if (Lex.getKind() != lltok::kw_align)
2911 return error(Lex.getLoc(), "expected metadata or 'align'");
2912
2913 if (parseOptionalAlignment(Alignment))
2914 return true;
2915 }
2916
2917 return false;
2918}
2919
2920/// parseOptionalCommaAddrSpace
2921/// ::=
2922/// ::= ',' addrspace(1)
2923///
2924/// This returns with AteExtraComma set to true if it ate an excess comma at the
2925/// end.
2926bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2927 bool &AteExtraComma) {
2928 AteExtraComma = false;
2929 while (EatIfPresent(lltok::comma)) {
2930 // Metadata at the end is an early exit.
2931 if (Lex.getKind() == lltok::MetadataVar) {
2932 AteExtraComma = true;
2933 return false;
2934 }
2935
2936 Loc = Lex.getLoc();
2937 if (Lex.getKind() != lltok::kw_addrspace)
2938 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2939
2940 if (parseOptionalAddrSpace(AddrSpace))
2941 return true;
2942 }
2943
2944 return false;
2945}
2946
2947bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2948 std::optional<unsigned> &HowManyArg) {
2949 Lex.Lex();
2950
2951 auto StartParen = Lex.getLoc();
2952 if (!EatIfPresent(lltok::lparen))
2953 return error(StartParen, "expected '('");
2954
2955 if (parseUInt32(BaseSizeArg))
2956 return true;
2957
2958 if (EatIfPresent(lltok::comma)) {
2959 auto HowManyAt = Lex.getLoc();
2960 unsigned HowMany;
2961 if (parseUInt32(HowMany))
2962 return true;
2963 if (HowMany == BaseSizeArg)
2964 return error(HowManyAt,
2965 "'allocsize' indices can't refer to the same parameter");
2966 HowManyArg = HowMany;
2967 } else
2968 HowManyArg = std::nullopt;
2969
2970 auto EndParen = Lex.getLoc();
2971 if (!EatIfPresent(lltok::rparen))
2972 return error(EndParen, "expected ')'");
2973 return false;
2974}
2975
2976bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2977 unsigned &MaxValue) {
2978 Lex.Lex();
2979
2980 auto StartParen = Lex.getLoc();
2981 if (!EatIfPresent(lltok::lparen))
2982 return error(StartParen, "expected '('");
2983
2984 if (parseUInt32(MinValue))
2985 return true;
2986
2987 if (EatIfPresent(lltok::comma)) {
2988 if (parseUInt32(MaxValue))
2989 return true;
2990 } else
2991 MaxValue = MinValue;
2992
2993 auto EndParen = Lex.getLoc();
2994 if (!EatIfPresent(lltok::rparen))
2995 return error(EndParen, "expected ')'");
2996 return false;
2997}
2998
2999/// parseScopeAndOrdering
3000/// if isAtomic: ::= SyncScope? AtomicOrdering
3001/// else: ::=
3002///
3003/// This sets Scope and Ordering to the parsed values.
3004bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3005 AtomicOrdering &Ordering) {
3006 if (!IsAtomic)
3007 return false;
3008
3009 return parseScope(SSID) || parseOrdering(Ordering);
3010}
3011
3012/// parseScope
3013/// ::= syncscope("singlethread" | "<target scope>")?
3014///
3015/// This sets synchronization scope ID to the ID of the parsed value.
3016bool LLParser::parseScope(SyncScope::ID &SSID) {
3017 SSID = SyncScope::System;
3018 if (EatIfPresent(lltok::kw_syncscope)) {
3019 auto StartParenAt = Lex.getLoc();
3020 if (!EatIfPresent(lltok::lparen))
3021 return error(StartParenAt, "Expected '(' in syncscope");
3022
3023 std::string SSN;
3024 auto SSNAt = Lex.getLoc();
3025 if (parseStringConstant(SSN))
3026 return error(SSNAt, "Expected synchronization scope name");
3027
3028 auto EndParenAt = Lex.getLoc();
3029 if (!EatIfPresent(lltok::rparen))
3030 return error(EndParenAt, "Expected ')' in syncscope");
3031
3032 SSID = Context.getOrInsertSyncScopeID(SSN);
3033 }
3034
3035 return false;
3036}
3037
3038/// parseOrdering
3039/// ::= AtomicOrdering
3040///
3041/// This sets Ordering to the parsed value.
3042bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3043 switch (Lex.getKind()) {
3044 default:
3045 return tokError("Expected ordering on atomic instruction");
3048 // Not specified yet:
3049 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3053 case lltok::kw_seq_cst:
3055 break;
3056 }
3057 Lex.Lex();
3058 return false;
3059}
3060
3061/// parseOptionalStackAlignment
3062/// ::= /* empty */
3063/// ::= 'alignstack' '(' 4 ')'
3064bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3065 Alignment = 0;
3066 if (!EatIfPresent(lltok::kw_alignstack))
3067 return false;
3068 LocTy ParenLoc = Lex.getLoc();
3069 if (!EatIfPresent(lltok::lparen))
3070 return error(ParenLoc, "expected '('");
3071 LocTy AlignLoc = Lex.getLoc();
3072 if (parseUInt32(Alignment))
3073 return true;
3074 ParenLoc = Lex.getLoc();
3075 if (!EatIfPresent(lltok::rparen))
3076 return error(ParenLoc, "expected ')'");
3077 if (!isPowerOf2_32(Alignment))
3078 return error(AlignLoc, "stack alignment is not a power of two");
3079 return false;
3080}
3081
3082/// parseIndexList - This parses the index list for an insert/extractvalue
3083/// instruction. This sets AteExtraComma in the case where we eat an extra
3084/// comma at the end of the line and find that it is followed by metadata.
3085/// Clients that don't allow metadata can call the version of this function that
3086/// only takes one argument.
3087///
3088/// parseIndexList
3089/// ::= (',' uint32)+
3090///
3091bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3092 bool &AteExtraComma) {
3093 AteExtraComma = false;
3094
3095 if (Lex.getKind() != lltok::comma)
3096 return tokError("expected ',' as start of index list");
3097
3098 while (EatIfPresent(lltok::comma)) {
3099 if (Lex.getKind() == lltok::MetadataVar) {
3100 if (Indices.empty())
3101 return tokError("expected index");
3102 AteExtraComma = true;
3103 return false;
3104 }
3105 unsigned Idx = 0;
3106 if (parseUInt32(Idx))
3107 return true;
3108 Indices.push_back(Idx);
3109 }
3110
3111 return false;
3112}
3113
3114//===----------------------------------------------------------------------===//
3115// Type Parsing.
3116//===----------------------------------------------------------------------===//
3117
3118/// parseType - parse a type.
3119bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3120 SMLoc TypeLoc = Lex.getLoc();
3121 switch (Lex.getKind()) {
3122 default:
3123 return tokError(Msg);
3124 case lltok::Type:
3125 // Type ::= 'float' | 'void' (etc)
3126 Result = Lex.getTyVal();
3127 Lex.Lex();
3128
3129 // Handle "ptr" opaque pointer type.
3130 //
3131 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3132 if (Result->isPointerTy()) {
3133 unsigned AddrSpace;
3134 if (parseOptionalAddrSpace(AddrSpace))
3135 return true;
3136 Result = PointerType::get(getContext(), AddrSpace);
3137
3138 // Give a nice error for 'ptr*'.
3139 if (Lex.getKind() == lltok::star)
3140 return tokError("ptr* is invalid - use ptr instead");
3141
3142 // Fall through to parsing the type suffixes only if this 'ptr' is a
3143 // function return. Otherwise, return success, implicitly rejecting other
3144 // suffixes.
3145 if (Lex.getKind() != lltok::lparen)
3146 return false;
3147 }
3148 break;
3149 case lltok::kw_target: {
3150 // Type ::= TargetExtType
3151 if (parseTargetExtType(Result))
3152 return true;
3153 break;
3154 }
3155 case lltok::lbrace:
3156 // Type ::= StructType
3157 if (parseAnonStructType(Result, false))
3158 return true;
3159 break;
3160 case lltok::lsquare:
3161 // Type ::= '[' ... ']'
3162 Lex.Lex(); // eat the lsquare.
3163 if (parseArrayVectorType(Result, false))
3164 return true;
3165 break;
3166 case lltok::less: // Either vector or packed struct.
3167 // Type ::= '<' ... '>'
3168 Lex.Lex();
3169 if (Lex.getKind() == lltok::lbrace) {
3170 if (parseAnonStructType(Result, true) ||
3171 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3172 return true;
3173 } else if (parseArrayVectorType(Result, true))
3174 return true;
3175 break;
3176 case lltok::LocalVar: {
3177 // Type ::= %foo
3178 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3179
3180 // If the type hasn't been defined yet, create a forward definition and
3181 // remember where that forward def'n was seen (in case it never is defined).
3182 if (!Entry.first) {
3183 Entry.first = StructType::create(Context, Lex.getStrVal());
3184 Entry.second = Lex.getLoc();
3185 }
3186 Result = Entry.first;
3187 Lex.Lex();
3188 break;
3189 }
3190
3191 case lltok::LocalVarID: {
3192 // Type ::= %4
3193 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3194
3195 // If the type hasn't been defined yet, create a forward definition and
3196 // remember where that forward def'n was seen (in case it never is defined).
3197 if (!Entry.first) {
3198 Entry.first = StructType::create(Context);
3199 Entry.second = Lex.getLoc();
3200 }
3201 Result = Entry.first;
3202 Lex.Lex();
3203 break;
3204 }
3205 }
3206
3207 // parse the type suffixes.
3208 while (true) {
3209 switch (Lex.getKind()) {
3210 // End of type.
3211 default:
3212 if (!AllowVoid && Result->isVoidTy())
3213 return error(TypeLoc, "void type only allowed for function results");
3214 return false;
3215
3216 // Type ::= Type '*'
3217 case lltok::star:
3218 if (Result->isLabelTy())
3219 return tokError("basic block pointers are invalid");
3220 if (Result->isVoidTy())
3221 return tokError("pointers to void are invalid - use i8* instead");
3223 return tokError("pointer to this type is invalid");
3224 Result = PointerType::getUnqual(Context);
3225 Lex.Lex();
3226 break;
3227
3228 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3229 case lltok::kw_addrspace: {
3230 if (Result->isLabelTy())
3231 return tokError("basic block pointers are invalid");
3232 if (Result->isVoidTy())
3233 return tokError("pointers to void are invalid; use i8* instead");
3235 return tokError("pointer to this type is invalid");
3236 unsigned AddrSpace;
3237 if (parseOptionalAddrSpace(AddrSpace) ||
3238 parseToken(lltok::star, "expected '*' in address space"))
3239 return true;
3240
3241 Result = PointerType::get(Context, AddrSpace);
3242 break;
3243 }
3244
3245 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3246 case lltok::lparen:
3247 if (parseFunctionType(Result))
3248 return true;
3249 break;
3250 }
3251 }
3252}
3253
3254/// parseParameterList
3255/// ::= '(' ')'
3256/// ::= '(' Arg (',' Arg)* ')'
3257/// Arg
3258/// ::= Type OptionalAttributes Value OptionalAttributes
3259bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3260 PerFunctionState &PFS, bool IsMustTailCall,
3261 bool InVarArgsFunc) {
3262 if (parseToken(lltok::lparen, "expected '(' in call"))
3263 return true;
3264
3265 while (Lex.getKind() != lltok::rparen) {
3266 // If this isn't the first argument, we need a comma.
3267 if (!ArgList.empty() &&
3268 parseToken(lltok::comma, "expected ',' in argument list"))
3269 return true;
3270
3271 // parse an ellipsis if this is a musttail call in a variadic function.
3272 if (Lex.getKind() == lltok::dotdotdot) {
3273 const char *Msg = "unexpected ellipsis in argument list for ";
3274 if (!IsMustTailCall)
3275 return tokError(Twine(Msg) + "non-musttail call");
3276 if (!InVarArgsFunc)
3277 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3278 Lex.Lex(); // Lex the '...', it is purely for readability.
3279 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3280 }
3281
3282 // parse the argument.
3283 LocTy ArgLoc;
3284 Type *ArgTy = nullptr;
3285 Value *V;
3286 if (parseType(ArgTy, ArgLoc))
3287 return true;
3289 return error(ArgLoc, "invalid type for function argument");
3290
3291 AttrBuilder ArgAttrs(M->getContext());
3292
3293 if (ArgTy->isMetadataTy()) {
3294 if (parseMetadataAsValue(V, PFS))
3295 return true;
3296 } else {
3297 // Otherwise, handle normal operands.
3298 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3299 return true;
3300 }
3301 ArgList.push_back(ParamInfo(
3302 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3303 }
3304
3305 if (IsMustTailCall && InVarArgsFunc)
3306 return tokError("expected '...' at end of argument list for musttail call "
3307 "in varargs function");
3308
3309 Lex.Lex(); // Lex the ')'.
3310 return false;
3311}
3312
3313/// parseRequiredTypeAttr
3314/// ::= attrname(<ty>)
3315bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3316 Attribute::AttrKind AttrKind) {
3317 Type *Ty = nullptr;
3318 if (!EatIfPresent(AttrToken))
3319 return true;
3320 if (!EatIfPresent(lltok::lparen))
3321 return error(Lex.getLoc(), "expected '('");
3322 if (parseType(Ty))
3323 return true;
3324 if (!EatIfPresent(lltok::rparen))
3325 return error(Lex.getLoc(), "expected ')'");
3326
3327 B.addTypeAttr(AttrKind, Ty);
3328 return false;
3329}
3330
3331/// parseRangeAttr
3332/// ::= range(<ty> <n>,<n>)
3333bool LLParser::parseRangeAttr(AttrBuilder &B) {
3334 Lex.Lex();
3335
3336 APInt Lower;
3337 APInt Upper;
3338 Type *Ty = nullptr;
3339 LocTy TyLoc;
3340
3341 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3342 if (Lex.getKind() != lltok::APSInt)
3343 return tokError("expected integer");
3344 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3345 return tokError(
3346 "integer is too large for the bit width of specified type");
3347 Val = Lex.getAPSIntVal().extend(BitWidth);
3348 Lex.Lex();
3349 return false;
3350 };
3351
3352 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3353 return true;
3354 if (!Ty->isIntegerTy())
3355 return error(TyLoc, "the range must have integer type!");
3356
3357 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3358
3359 if (ParseAPSInt(BitWidth, Lower) ||
3360 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3361 return true;
3362 if (Lower == Upper && !Lower.isZero())
3363 return tokError("the range represent the empty set but limits aren't 0!");
3364
3365 if (parseToken(lltok::rparen, "expected ')'"))
3366 return true;
3367
3368 B.addRangeAttr(ConstantRange(Lower, Upper));
3369 return false;
3370}
3371
3372/// parseInitializesAttr
3373/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3374bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3375 Lex.Lex();
3376
3377 auto ParseAPSInt = [&](APInt &Val) {
3378 if (Lex.getKind() != lltok::APSInt)
3379 return tokError("expected integer");
3380 Val = Lex.getAPSIntVal().extend(64);
3381 Lex.Lex();
3382 return false;
3383 };
3384
3385 if (parseToken(lltok::lparen, "expected '('"))
3386 return true;
3387
3389 // Parse each constant range.
3390 do {
3391 APInt Lower, Upper;
3392 if (parseToken(lltok::lparen, "expected '('"))
3393 return true;
3394
3395 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3396 ParseAPSInt(Upper))
3397 return true;
3398
3399 if (Lower == Upper)
3400 return tokError("the range should not represent the full or empty set!");
3401
3402 if (parseToken(lltok::rparen, "expected ')'"))
3403 return true;
3404
3405 RangeList.push_back(ConstantRange(Lower, Upper));
3406 } while (EatIfPresent(lltok::comma));
3407
3408 if (parseToken(lltok::rparen, "expected ')'"))
3409 return true;
3410
3411 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3412 if (!CRLOrNull.has_value())
3413 return tokError("Invalid (unordered or overlapping) range list");
3414 B.addInitializesAttr(*CRLOrNull);
3415 return false;
3416}
3417
3418bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3420 std::optional<CaptureComponents> Ret;
3421
3422 // We use syntax like captures(ret: address, provenance), so the colon
3423 // should not be interpreted as a label terminator.
3424 Lex.setIgnoreColonInIdentifiers(true);
3425 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3426
3427 Lex.Lex();
3428 if (parseToken(lltok::lparen, "expected '('"))
3429 return true;
3430
3431 CaptureComponents *Current = &Other;
3432 bool SeenComponent = false;
3433 while (true) {
3434 if (EatIfPresent(lltok::kw_ret)) {
3435 if (parseToken(lltok::colon, "expected ':'"))
3436 return true;
3437 if (Ret)
3438 return tokError("duplicate 'ret' location");
3440 Current = &*Ret;
3441 SeenComponent = false;
3442 }
3443
3444 if (EatIfPresent(lltok::kw_none)) {
3445 if (SeenComponent)
3446 return tokError("cannot use 'none' with other component");
3447 *Current = CaptureComponents::None;
3448 } else {
3449 if (SeenComponent && capturesNothing(*Current))
3450 return tokError("cannot use 'none' with other component");
3451
3452 if (EatIfPresent(lltok::kw_address_is_null))
3454 else if (EatIfPresent(lltok::kw_address))
3455 *Current |= CaptureComponents::Address;
3456 else if (EatIfPresent(lltok::kw_provenance))
3458 else if (EatIfPresent(lltok::kw_read_provenance))
3460 else
3461 return tokError("expected one of 'none', 'address', 'address_is_null', "
3462 "'provenance' or 'read_provenance'");
3463 }
3464
3465 SeenComponent = true;
3466 if (EatIfPresent(lltok::rparen))
3467 break;
3468
3469 if (parseToken(lltok::comma, "expected ',' or ')'"))
3470 return true;
3471 }
3472
3473 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3474 return false;
3475}
3476
3477/// parseOptionalOperandBundles
3478/// ::= /*empty*/
3479/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3480///
3481/// OperandBundle
3482/// ::= bundle-tag '(' ')'
3483/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3484///
3485/// bundle-tag ::= String Constant
3486bool LLParser::parseOptionalOperandBundles(
3487 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3488 LocTy BeginLoc = Lex.getLoc();
3489 if (!EatIfPresent(lltok::lsquare))
3490 return false;
3491
3492 while (Lex.getKind() != lltok::rsquare) {
3493 // If this isn't the first operand bundle, we need a comma.
3494 if (!BundleList.empty() &&
3495 parseToken(lltok::comma, "expected ',' in input list"))
3496 return true;
3497
3498 std::string Tag;
3499 if (parseStringConstant(Tag))
3500 return true;
3501
3502 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3503 return true;
3504
3505 std::vector<Value *> Inputs;
3506 while (Lex.getKind() != lltok::rparen) {
3507 // If this isn't the first input, we need a comma.
3508 if (!Inputs.empty() &&
3509 parseToken(lltok::comma, "expected ',' in input list"))
3510 return true;
3511
3512 Type *Ty = nullptr;
3513 Value *Input = nullptr;
3514 if (parseType(Ty))
3515 return true;
3516 if (Ty->isMetadataTy()) {
3517 if (parseMetadataAsValue(Input, PFS))
3518 return true;
3519 } else if (parseValue(Ty, Input, PFS)) {
3520 return true;
3521 }
3522 Inputs.push_back(Input);
3523 }
3524
3525 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3526
3527 Lex.Lex(); // Lex the ')'.
3528 }
3529
3530 if (BundleList.empty())
3531 return error(BeginLoc, "operand bundle set must not be empty");
3532
3533 Lex.Lex(); // Lex the ']'.
3534 return false;
3535}
3536
3537bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3538 unsigned NextID, unsigned ID) {
3539 if (ID < NextID)
3540 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3541 Twine(NextID) + "' or greater");
3542
3543 return false;
3544}
3545
3546/// parseArgumentList - parse the argument list for a function type or function
3547/// prototype.
3548/// ::= '(' ArgTypeListI ')'
3549/// ArgTypeListI
3550/// ::= /*empty*/
3551/// ::= '...'
3552/// ::= ArgTypeList ',' '...'
3553/// ::= ArgType (',' ArgType)*
3554///
3555bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3556 SmallVectorImpl<unsigned> &UnnamedArgNums,
3557 bool &IsVarArg) {
3558 unsigned CurValID = 0;
3559 IsVarArg = false;
3560 assert(Lex.getKind() == lltok::lparen);
3561 Lex.Lex(); // eat the (.
3562
3563 if (Lex.getKind() != lltok::rparen) {
3564 do {
3565 // Handle ... at end of arg list.
3566 if (EatIfPresent(lltok::dotdotdot)) {
3567 IsVarArg = true;
3568 break;
3569 }
3570
3571 // Otherwise must be an argument type.
3572 LocTy TypeLoc = Lex.getLoc();
3573 Type *ArgTy = nullptr;
3574 AttrBuilder Attrs(M->getContext());
3575 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3576 return true;
3577
3578 if (ArgTy->isVoidTy())
3579 return error(TypeLoc, "argument can not have void type");
3580
3581 std::string Name;
3582 FileLoc IdentStart;
3583 FileLoc IdentEnd;
3584 bool Unnamed = false;
3585 if (Lex.getKind() == lltok::LocalVar) {
3586 Name = Lex.getStrVal();
3587 IdentStart = getTokLineColumnPos();
3588 Lex.Lex();
3589 IdentEnd = getPrevTokEndLineColumnPos();
3590 } else {
3591 unsigned ArgID;
3592 if (Lex.getKind() == lltok::LocalVarID) {
3593 ArgID = Lex.getUIntVal();
3594 IdentStart = getTokLineColumnPos();
3595 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3596 return true;
3597 Lex.Lex();
3598 IdentEnd = getPrevTokEndLineColumnPos();
3599 } else {
3600 ArgID = CurValID;
3601 Unnamed = true;
3602 }
3603 UnnamedArgNums.push_back(ArgID);
3604 CurValID = ArgID + 1;
3605 }
3606
3608 return error(TypeLoc, "invalid type for function argument");
3609
3610 ArgList.emplace_back(
3611 TypeLoc, ArgTy,
3612 Unnamed ? std::nullopt
3613 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3614 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3615 } while (EatIfPresent(lltok::comma));
3616 }
3617
3618 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3619}
3620
3621/// parseFunctionType
3622/// ::= Type ArgumentList OptionalAttrs
3623bool LLParser::parseFunctionType(Type *&Result) {
3624 assert(Lex.getKind() == lltok::lparen);
3625
3627 return tokError("invalid function return type");
3628
3630 bool IsVarArg;
3631 SmallVector<unsigned> UnnamedArgNums;
3632 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3633 return true;
3634
3635 // Reject names on the arguments lists.
3636 for (const ArgInfo &Arg : ArgList) {
3637 if (!Arg.Name.empty())
3638 return error(Arg.Loc, "argument name invalid in function type");
3639 if (Arg.Attrs.hasAttributes())
3640 return error(Arg.Loc, "argument attributes invalid in function type");
3641 }
3642
3643 SmallVector<Type*, 16> ArgListTy;
3644 for (const ArgInfo &Arg : ArgList)
3645 ArgListTy.push_back(Arg.Ty);
3646
3647 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3648 return false;
3649}
3650
3651/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3652/// other structs.
3653bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3655 if (parseStructBody(Elts))
3656 return true;
3657
3658 Result = StructType::get(Context, Elts, Packed);
3659 return false;
3660}
3661
3662/// parseStructDefinition - parse a struct in a 'type' definition.
3663bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3664 std::pair<Type *, LocTy> &Entry,
3665 Type *&ResultTy) {
3666 // If the type was already defined, diagnose the redefinition.
3667 if (Entry.first && !Entry.second.isValid())
3668 return error(TypeLoc, "redefinition of type");
3669
3670 // If we have opaque, just return without filling in the definition for the
3671 // struct. This counts as a definition as far as the .ll file goes.
3672 if (EatIfPresent(lltok::kw_opaque)) {
3673 // This type is being defined, so clear the location to indicate this.
3674 Entry.second = SMLoc();
3675
3676 // If this type number has never been uttered, create it.
3677 if (!Entry.first)
3678 Entry.first = StructType::create(Context, Name);
3679 ResultTy = Entry.first;
3680 return false;
3681 }
3682
3683 // If the type starts with '<', then it is either a packed struct or a vector.
3684 bool isPacked = EatIfPresent(lltok::less);
3685
3686 // If we don't have a struct, then we have a random type alias, which we
3687 // accept for compatibility with old files. These types are not allowed to be
3688 // forward referenced and not allowed to be recursive.
3689 if (Lex.getKind() != lltok::lbrace) {
3690 if (Entry.first)
3691 return error(TypeLoc, "forward references to non-struct type");
3692
3693 ResultTy = nullptr;
3694 if (isPacked)
3695 return parseArrayVectorType(ResultTy, true);
3696 return parseType(ResultTy);
3697 }
3698
3699 // This type is being defined, so clear the location to indicate this.
3700 Entry.second = SMLoc();
3701
3702 // If this type number has never been uttered, create it.
3703 if (!Entry.first)
3704 Entry.first = StructType::create(Context, Name);
3705
3706 StructType *STy = cast<StructType>(Entry.first);
3707
3709 if (parseStructBody(Body) ||
3710 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3711 return true;
3712
3713 if (auto E = STy->setBodyOrError(Body, isPacked))
3714 return tokError(toString(std::move(E)));
3715
3716 ResultTy = STy;
3717 return false;
3718}
3719
3720/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3721/// StructType
3722/// ::= '{' '}'
3723/// ::= '{' Type (',' Type)* '}'
3724/// ::= '<' '{' '}' '>'
3725/// ::= '<' '{' Type (',' Type)* '}' '>'
3726bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3727 assert(Lex.getKind() == lltok::lbrace);
3728 Lex.Lex(); // Consume the '{'
3729
3730 // Handle the empty struct.
3731 if (EatIfPresent(lltok::rbrace))
3732 return false;
3733
3734 LocTy EltTyLoc = Lex.getLoc();
3735 Type *Ty = nullptr;
3736 if (parseType(Ty))
3737 return true;
3738 Body.push_back(Ty);
3739
3741 return error(EltTyLoc, "invalid element type for struct");
3742
3743 while (EatIfPresent(lltok::comma)) {
3744 EltTyLoc = Lex.getLoc();
3745 if (parseType(Ty))
3746 return true;
3747
3749 return error(EltTyLoc, "invalid element type for struct");
3750
3751 Body.push_back(Ty);
3752 }
3753
3754 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3755}
3756
3757/// parseArrayVectorType - parse an array or vector type, assuming the first
3758/// token has already been consumed.
3759/// Type
3760/// ::= '[' APSINTVAL 'x' Types ']'
3761/// ::= '<' APSINTVAL 'x' Types '>'
3762/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3763bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3764 bool Scalable = false;
3765
3766 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3767 Lex.Lex(); // consume the 'vscale'
3768 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3769 return true;
3770
3771 Scalable = true;
3772 }
3773
3774 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3775 Lex.getAPSIntVal().getBitWidth() > 64)
3776 return tokError("expected number in address space");
3777
3778 LocTy SizeLoc = Lex.getLoc();
3779 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3780 Lex.Lex();
3781
3782 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3783 return true;
3784
3785 LocTy TypeLoc = Lex.getLoc();
3786 Type *EltTy = nullptr;
3787 if (parseType(EltTy))
3788 return true;
3789
3790 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3791 "expected end of sequential type"))
3792 return true;
3793
3794 if (IsVector) {
3795 if (Size == 0)
3796 return error(SizeLoc, "zero element vector is illegal");
3797 if ((unsigned)Size != Size)
3798 return error(SizeLoc, "size too large for vector");
3800 return error(TypeLoc, "invalid vector element type");
3801 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3802 } else {
3804 return error(TypeLoc, "invalid array element type");
3805 Result = ArrayType::get(EltTy, Size);
3806 }
3807 return false;
3808}
3809
3810/// parseTargetExtType - handle target extension type syntax
3811/// TargetExtType
3812/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3813///
3814/// TargetExtTypeParams
3815/// ::= /*empty*/
3816/// ::= ',' Type TargetExtTypeParams
3817///
3818/// TargetExtIntParams
3819/// ::= /*empty*/
3820/// ::= ',' uint32 TargetExtIntParams
3821bool LLParser::parseTargetExtType(Type *&Result) {
3822 Lex.Lex(); // Eat the 'target' keyword.
3823
3824 // Get the mandatory type name.
3825 std::string TypeName;
3826 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3827 parseStringConstant(TypeName))
3828 return true;
3829
3830 // Parse all of the integer and type parameters at the same time; the use of
3831 // SeenInt will allow us to catch cases where type parameters follow integer
3832 // parameters.
3833 SmallVector<Type *> TypeParams;
3834 SmallVector<unsigned> IntParams;
3835 bool SeenInt = false;
3836 while (Lex.getKind() == lltok::comma) {
3837 Lex.Lex(); // Eat the comma.
3838
3839 if (Lex.getKind() == lltok::APSInt) {
3840 SeenInt = true;
3841 unsigned IntVal;
3842 if (parseUInt32(IntVal))
3843 return true;
3844 IntParams.push_back(IntVal);
3845 } else if (SeenInt) {
3846 // The only other kind of parameter we support is type parameters, which
3847 // must precede the integer parameters. This is therefore an error.
3848 return tokError("expected uint32 param");
3849 } else {
3850 Type *TypeParam;
3851 if (parseType(TypeParam, /*AllowVoid=*/true))
3852 return true;
3853 TypeParams.push_back(TypeParam);
3854 }
3855 }
3856
3857 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3858 return true;
3859
3860 auto TTy =
3861 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3862 if (auto E = TTy.takeError())
3863 return tokError(toString(std::move(E)));
3864
3865 Result = *TTy;
3866 return false;
3867}
3868
3869//===----------------------------------------------------------------------===//
3870// Function Semantic Analysis.
3871//===----------------------------------------------------------------------===//
3872
3873LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3874 int functionNumber,
3875 ArrayRef<unsigned> UnnamedArgNums)
3876 : P(p), F(f), FunctionNumber(functionNumber) {
3877
3878 // Insert unnamed arguments into the NumberedVals list.
3879 auto It = UnnamedArgNums.begin();
3880 for (Argument &A : F.args()) {
3881 if (!A.hasName()) {
3882 unsigned ArgNum = *It++;
3883 NumberedVals.add(ArgNum, &A);
3884 }
3885 }
3886}
3887
3888LLParser::PerFunctionState::~PerFunctionState() {
3889 // If there were any forward referenced non-basicblock values, delete them.
3890
3891 for (const auto &P : ForwardRefVals) {
3892 if (isa<BasicBlock>(P.second.first))
3893 continue;
3894 P.second.first->replaceAllUsesWith(
3895 PoisonValue::get(P.second.first->getType()));
3896 P.second.first->deleteValue();
3897 }
3898
3899 for (const auto &P : ForwardRefValIDs) {
3900 if (isa<BasicBlock>(P.second.first))
3901 continue;
3902 P.second.first->replaceAllUsesWith(
3903 PoisonValue::get(P.second.first->getType()));
3904 P.second.first->deleteValue();
3905 }
3906}
3907
3908bool LLParser::PerFunctionState::finishFunction() {
3909 if (!ForwardRefVals.empty())
3910 return P.error(ForwardRefVals.begin()->second.second,
3911 "use of undefined value '%" + ForwardRefVals.begin()->first +
3912 "'");
3913 if (!ForwardRefValIDs.empty())
3914 return P.error(ForwardRefValIDs.begin()->second.second,
3915 "use of undefined value '%" +
3916 Twine(ForwardRefValIDs.begin()->first) + "'");
3917 return false;
3918}
3919
3920/// getVal - Get a value with the specified name or ID, creating a
3921/// forward reference record if needed. This can return null if the value
3922/// exists but does not have the right type.
3923Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3924 LocTy Loc) {
3925 // Look this name up in the normal function symbol table.
3926 Value *Val = F.getValueSymbolTable()->lookup(Name);
3927
3928 // If this is a forward reference for the value, see if we already created a
3929 // forward ref record.
3930 if (!Val) {
3931 auto I = ForwardRefVals.find(Name);
3932 if (I != ForwardRefVals.end())
3933 Val = I->second.first;
3934 }
3935
3936 // If we have the value in the symbol table or fwd-ref table, return it.
3937 if (Val)
3938 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3939
3940 // Don't make placeholders with invalid type.
3941 if (!Ty->isFirstClassType()) {
3942 P.error(Loc, "invalid use of a non-first-class type");
3943 return nullptr;
3944 }
3945
3946 // Otherwise, create a new forward reference for this value and remember it.
3947 Value *FwdVal;
3948 if (Ty->isLabelTy()) {
3949 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3950 } else {
3951 FwdVal = new Argument(Ty, Name);
3952 }
3953 if (FwdVal->getName() != Name) {
3954 P.error(Loc, "name is too long which can result in name collisions, "
3955 "consider making the name shorter or "
3956 "increasing -non-global-value-max-name-size");
3957 return nullptr;
3958 }
3959
3960 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3961 return FwdVal;
3962}
3963
3964Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3965 // Look this name up in the normal function symbol table.
3966 Value *Val = NumberedVals.get(ID);
3967
3968 // If this is a forward reference for the value, see if we already created a
3969 // forward ref record.
3970 if (!Val) {
3971 auto I = ForwardRefValIDs.find(ID);
3972 if (I != ForwardRefValIDs.end())
3973 Val = I->second.first;
3974 }
3975
3976 // If we have the value in the symbol table or fwd-ref table, return it.
3977 if (Val)
3978 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3979
3980 if (!Ty->isFirstClassType()) {
3981 P.error(Loc, "invalid use of a non-first-class type");
3982 return nullptr;
3983 }
3984
3985 // Otherwise, create a new forward reference for this value and remember it.
3986 Value *FwdVal;
3987 if (Ty->isLabelTy()) {
3988 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3989 } else {
3990 FwdVal = new Argument(Ty);
3991 }
3992
3993 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3994 return FwdVal;
3995}
3996
3997/// setInstName - After an instruction is parsed and inserted into its
3998/// basic block, this installs its name.
3999bool LLParser::PerFunctionState::setInstName(int NameID,
4000 const std::string &NameStr,
4001 LocTy NameLoc, Instruction *Inst) {
4002 // If this instruction has void type, it cannot have a name or ID specified.
4003 if (Inst->getType()->isVoidTy()) {
4004 if (NameID != -1 || !NameStr.empty())
4005 return P.error(NameLoc, "instructions returning void cannot have a name");
4006 return false;
4007 }
4008
4009 // If this was a numbered instruction, verify that the instruction is the
4010 // expected value and resolve any forward references.
4011 if (NameStr.empty()) {
4012 // If neither a name nor an ID was specified, just use the next ID.
4013 if (NameID == -1)
4014 NameID = NumberedVals.getNext();
4015
4016 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4017 NameID))
4018 return true;
4019
4020 auto FI = ForwardRefValIDs.find(NameID);
4021 if (FI != ForwardRefValIDs.end()) {
4022 Value *Sentinel = FI->second.first;
4023 if (Sentinel->getType() != Inst->getType())
4024 return P.error(NameLoc, "instruction forward referenced with type '" +
4025 getTypeString(FI->second.first->getType()) +
4026 "'");
4027
4028 Sentinel->replaceAllUsesWith(Inst);
4029 Sentinel->deleteValue();
4030 ForwardRefValIDs.erase(FI);
4031 }
4032
4033 NumberedVals.add(NameID, Inst);
4034 return false;
4035 }
4036
4037 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4038 auto FI = ForwardRefVals.find(NameStr);
4039 if (FI != ForwardRefVals.end()) {
4040 Value *Sentinel = FI->second.first;
4041 if (Sentinel->getType() != Inst->getType())
4042 return P.error(NameLoc, "instruction forward referenced with type '" +
4043 getTypeString(FI->second.first->getType()) +
4044 "'");
4045
4046 Sentinel->replaceAllUsesWith(Inst);
4047 Sentinel->deleteValue();
4048 ForwardRefVals.erase(FI);
4049 }
4050
4051 // Set the name on the instruction.
4052 Inst->setName(NameStr);
4053
4054 if (Inst->getName() != NameStr)
4055 return P.error(NameLoc, "multiple definition of local value named '" +
4056 NameStr + "'");
4057 return false;
4058}
4059
4060/// getBB - Get a basic block with the specified name or ID, creating a
4061/// forward reference record if needed.
4062BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4063 LocTy Loc) {
4065 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4066}
4067
4068BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4070 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4071}
4072
4073/// defineBB - Define the specified basic block, which is either named or
4074/// unnamed. If there is an error, this returns null otherwise it returns
4075/// the block being defined.
4076BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4077 int NameID, LocTy Loc) {
4078 BasicBlock *BB;
4079 if (Name.empty()) {
4080 if (NameID != -1) {
4081 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4082 return nullptr;
4083 } else {
4084 NameID = NumberedVals.getNext();
4085 }
4086 BB = getBB(NameID, Loc);
4087 if (!BB) {
4088 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4089 return nullptr;
4090 }
4091 } else {
4092 BB = getBB(Name, Loc);
4093 if (!BB) {
4094 P.error(Loc, "unable to create block named '" + Name + "'");
4095 return nullptr;
4096 }
4097 }
4098
4099 // Move the block to the end of the function. Forward ref'd blocks are
4100 // inserted wherever they happen to be referenced.
4101 F.splice(F.end(), &F, BB->getIterator());
4102
4103 // Remove the block from forward ref sets.
4104 if (Name.empty()) {
4105 ForwardRefValIDs.erase(NameID);
4106 NumberedVals.add(NameID, BB);
4107 } else {
4108 // BB forward references are already in the function symbol table.
4109 ForwardRefVals.erase(Name);
4110 }
4111
4112 return BB;
4113}
4114
4115//===----------------------------------------------------------------------===//
4116// Constants.
4117//===----------------------------------------------------------------------===//
4118
4119/// parseValID - parse an abstract value that doesn't necessarily have a
4120/// type implied. For example, if we parse "4" we don't know what integer type
4121/// it has. The value will later be combined with its type and checked for
4122/// basic correctness. PFS is used to convert function-local operands of
4123/// metadata (since metadata operands are not just parsed here but also
4124/// converted to values). PFS can be null when we are not parsing metadata
4125/// values inside a function.
4126bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4127 ID.Loc = Lex.getLoc();
4128 switch (Lex.getKind()) {
4129 default:
4130 return tokError("expected value token");
4131 case lltok::GlobalID: // @42
4132 ID.UIntVal = Lex.getUIntVal();
4133 ID.Kind = ValID::t_GlobalID;
4134 break;
4135 case lltok::GlobalVar: // @foo
4136 ID.StrVal = Lex.getStrVal();
4137 ID.Kind = ValID::t_GlobalName;
4138 break;
4139 case lltok::LocalVarID: // %42
4140 ID.UIntVal = Lex.getUIntVal();
4141 ID.Kind = ValID::t_LocalID;
4142 break;
4143 case lltok::LocalVar: // %foo
4144 ID.StrVal = Lex.getStrVal();
4145 ID.Kind = ValID::t_LocalName;
4146 break;
4147 case lltok::APSInt:
4148 ID.APSIntVal = Lex.getAPSIntVal();
4149 ID.Kind = ValID::t_APSInt;
4150 break;
4151 case lltok::APFloat:
4152 ID.APFloatVal = Lex.getAPFloatVal();
4153 ID.Kind = ValID::t_APFloat;
4154 break;
4155 case lltok::kw_true:
4156 ID.ConstantVal = ConstantInt::getTrue(Context);
4157 ID.Kind = ValID::t_Constant;
4158 break;
4159 case lltok::kw_false:
4160 ID.ConstantVal = ConstantInt::getFalse(Context);
4161 ID.Kind = ValID::t_Constant;
4162 break;
4163 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4164 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4165 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4166 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4167 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4168
4169 case lltok::lbrace: {
4170 // ValID ::= '{' ConstVector '}'
4171 Lex.Lex();
4173 if (parseGlobalValueVector(Elts) ||
4174 parseToken(lltok::rbrace, "expected end of struct constant"))
4175 return true;
4176
4177 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4178 ID.UIntVal = Elts.size();
4179 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4180 Elts.size() * sizeof(Elts[0]));
4182 return false;
4183 }
4184 case lltok::less: {
4185 // ValID ::= '<' ConstVector '>' --> Vector.
4186 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4187 Lex.Lex();
4188 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4189
4191 LocTy FirstEltLoc = Lex.getLoc();
4192 if (parseGlobalValueVector(Elts) ||
4193 (isPackedStruct &&
4194 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4195 parseToken(lltok::greater, "expected end of constant"))
4196 return true;
4197
4198 if (isPackedStruct) {
4199 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4200 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4201 Elts.size() * sizeof(Elts[0]));
4202 ID.UIntVal = Elts.size();
4204 return false;
4205 }
4206
4207 if (Elts.empty())
4208 return error(ID.Loc, "constant vector must not be empty");
4209
4210 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4211 !Elts[0]->getType()->isFloatingPointTy() &&
4212 !Elts[0]->getType()->isPointerTy())
4213 return error(
4214 FirstEltLoc,
4215 "vector elements must have integer, byte, pointer or floating point "
4216 "type");
4217
4218 // Verify that all the vector elements have the same type.
4219 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4220 if (Elts[i]->getType() != Elts[0]->getType())
4221 return error(FirstEltLoc, "vector element #" + Twine(i) +
4222 " is not of type '" +
4223 getTypeString(Elts[0]->getType()));
4224
4225 ID.ConstantVal = ConstantVector::get(Elts);
4226 ID.Kind = ValID::t_Constant;
4227 return false;
4228 }
4229 case lltok::lsquare: { // Array Constant
4230 Lex.Lex();
4232 LocTy FirstEltLoc = Lex.getLoc();
4233 if (parseGlobalValueVector(Elts) ||
4234 parseToken(lltok::rsquare, "expected end of array constant"))
4235 return true;
4236
4237 // Handle empty element.
4238 if (Elts.empty()) {
4239 // Use undef instead of an array because it's inconvenient to determine
4240 // the element type at this point, there being no elements to examine.
4241 ID.Kind = ValID::t_EmptyArray;
4242 return false;
4243 }
4244
4245 if (!Elts[0]->getType()->isFirstClassType())
4246 return error(FirstEltLoc, "invalid array element type: " +
4247 getTypeString(Elts[0]->getType()));
4248
4249 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4250
4251 // Verify all elements are correct type!
4252 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4253 if (Elts[i]->getType() != Elts[0]->getType())
4254 return error(FirstEltLoc, "array element #" + Twine(i) +
4255 " is not of type '" +
4256 getTypeString(Elts[0]->getType()));
4257 }
4258
4259 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4260 ID.Kind = ValID::t_Constant;
4261 return false;
4262 }
4263 case lltok::kw_c: { // c "foo"
4264 Lex.Lex();
4265 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4266 ID.ConstantVal = ConstantDataArray::getString(
4267 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4268 if (parseToken(lltok::StringConstant, "expected string"))
4269 return true;
4270 ID.Kind = ValID::t_Constant;
4271 return false;
4272 }
4273 case lltok::kw_asm: {
4274 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4275 // STRINGCONSTANT
4276 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4277 Lex.Lex();
4278 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4279 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4280 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4281 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4282 parseStringConstant(ID.StrVal) ||
4283 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4284 parseToken(lltok::StringConstant, "expected constraint string"))
4285 return true;
4286 ID.StrVal2 = Lex.getStrVal();
4287 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4288 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4289 ID.Kind = ValID::t_InlineAsm;
4290 return false;
4291 }
4292
4294 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4295 Lex.Lex();
4296
4297 ValID Fn, Label;
4298
4299 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4300 parseValID(Fn, PFS) ||
4301 parseToken(lltok::comma,
4302 "expected comma in block address expression") ||
4303 parseValID(Label, PFS) ||
4304 parseToken(lltok::rparen, "expected ')' in block address expression"))
4305 return true;
4306
4308 return error(Fn.Loc, "expected function name in blockaddress");
4309 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4310 return error(Label.Loc, "expected basic block name in blockaddress");
4311
4312 // Try to find the function (but skip it if it's forward-referenced).
4313 GlobalValue *GV = nullptr;
4314 if (Fn.Kind == ValID::t_GlobalID) {
4315 GV = NumberedVals.get(Fn.UIntVal);
4316 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4317 GV = M->getNamedValue(Fn.StrVal);
4318 }
4319 Function *F = nullptr;
4320 if (GV) {
4321 // Confirm that it's actually a function with a definition.
4322 if (!isa<Function>(GV))
4323 return error(Fn.Loc, "expected function name in blockaddress");
4324 F = cast<Function>(GV);
4325 if (F->isDeclaration())
4326 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4327 }
4328
4329 if (!F) {
4330 // Make a global variable as a placeholder for this reference.
4331 GlobalValue *&FwdRef =
4332 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4333 if (!FwdRef) {
4334 unsigned FwdDeclAS;
4335 if (ExpectedTy) {
4336 // If we know the type that the blockaddress is being assigned to,
4337 // we can use the address space of that type.
4338 if (!ExpectedTy->isPointerTy())
4339 return error(ID.Loc,
4340 "type of blockaddress must be a pointer and not '" +
4341 getTypeString(ExpectedTy) + "'");
4342 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4343 } else if (PFS) {
4344 // Otherwise, we default the address space of the current function.
4345 FwdDeclAS = PFS->getFunction().getAddressSpace();
4346 } else {
4347 llvm_unreachable("Unknown address space for blockaddress");
4348 }
4349 FwdRef = new GlobalVariable(
4350 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4351 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4352 }
4353
4354 ID.ConstantVal = FwdRef;
4355 ID.Kind = ValID::t_Constant;
4356 return false;
4357 }
4358
4359 // We found the function; now find the basic block. Don't use PFS, since we
4360 // might be inside a constant expression.
4361 BasicBlock *BB;
4362 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4363 if (Label.Kind == ValID::t_LocalID)
4364 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4365 else
4366 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4367 if (!BB)
4368 return error(Label.Loc, "referenced value is not a basic block");
4369 } else {
4370 if (Label.Kind == ValID::t_LocalID)
4371 return error(Label.Loc, "cannot take address of numeric label after "
4372 "the function is defined");
4374 F->getValueSymbolTable()->lookup(Label.StrVal));
4375 if (!BB)
4376 return error(Label.Loc, "referenced value is not a basic block");
4377 }
4378
4379 ID.ConstantVal = BlockAddress::get(F, BB);
4380 ID.Kind = ValID::t_Constant;
4381 return false;
4382 }
4383
4385 // ValID ::= 'dso_local_equivalent' @foo
4386 Lex.Lex();
4387
4388 ValID Fn;
4389
4390 if (parseValID(Fn, PFS))
4391 return true;
4392
4394 return error(Fn.Loc,
4395 "expected global value name in dso_local_equivalent");
4396
4397 // Try to find the function (but skip it if it's forward-referenced).
4398 GlobalValue *GV = nullptr;
4399 if (Fn.Kind == ValID::t_GlobalID) {
4400 GV = NumberedVals.get(Fn.UIntVal);
4401 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4402 GV = M->getNamedValue(Fn.StrVal);
4403 }
4404
4405 if (!GV) {
4406 // Make a placeholder global variable as a placeholder for this reference.
4407 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4408 ? ForwardRefDSOLocalEquivalentIDs
4409 : ForwardRefDSOLocalEquivalentNames;
4410 GlobalValue *&FwdRef = FwdRefMap[Fn];
4411 if (!FwdRef) {
4412 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4413 GlobalValue::InternalLinkage, nullptr, "",
4415 }
4416
4417 ID.ConstantVal = FwdRef;
4418 ID.Kind = ValID::t_Constant;
4419 return false;
4420 }
4421
4422 if (!GV->getValueType()->isFunctionTy())
4423 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4424 "in dso_local_equivalent");
4425
4426 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4427 ID.Kind = ValID::t_Constant;
4428 return false;
4429 }
4430
4431 case lltok::kw_no_cfi: {
4432 // ValID ::= 'no_cfi' @foo
4433 Lex.Lex();
4434
4435 if (parseValID(ID, PFS))
4436 return true;
4437
4438 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4439 return error(ID.Loc, "expected global value name in no_cfi");
4440
4441 ID.NoCFI = true;
4442 return false;
4443 }
4444 case lltok::kw_ptrauth: {
4445 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4446 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4447 // )? )? ')'
4448 Lex.Lex();
4449
4450 Constant *Ptr, *Key;
4451 Constant *Disc = nullptr, *AddrDisc = nullptr,
4452 *DeactivationSymbol = nullptr;
4453
4454 if (parseToken(lltok::lparen,
4455 "expected '(' in constant ptrauth expression") ||
4456 parseGlobalTypeAndValue(Ptr) ||
4457 parseToken(lltok::comma,
4458 "expected comma in constant ptrauth expression") ||
4459 parseGlobalTypeAndValue(Key))
4460 return true;
4461 // If present, parse the optional disc/addrdisc/ds.
4462 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4463 return true;
4464 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4465 return true;
4466 if (EatIfPresent(lltok::comma) &&
4467 parseGlobalTypeAndValue(DeactivationSymbol))
4468 return true;
4469 if (parseToken(lltok::rparen,
4470 "expected ')' in constant ptrauth expression"))
4471 return true;
4472
4473 if (!Ptr->getType()->isPointerTy())
4474 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4475
4476 auto *KeyC = dyn_cast<ConstantInt>(Key);
4477 if (!KeyC || KeyC->getBitWidth() != 32)
4478 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4479
4480 ConstantInt *DiscC = nullptr;
4481 if (Disc) {
4482 DiscC = dyn_cast<ConstantInt>(Disc);
4483 if (!DiscC || DiscC->getBitWidth() != 64)
4484 return error(
4485 ID.Loc,
4486 "constant ptrauth integer discriminator must be i64 constant");
4487 } else {
4488 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4489 }
4490
4491 if (AddrDisc) {
4492 if (!AddrDisc->getType()->isPointerTy())
4493 return error(
4494 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4495 } else {
4496 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4497 }
4498
4499 if (!DeactivationSymbol)
4500 DeactivationSymbol =
4502 if (!DeactivationSymbol->getType()->isPointerTy())
4503 return error(ID.Loc,
4504 "constant ptrauth deactivation symbol must be a pointer");
4505
4506 ID.ConstantVal =
4507 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4508 ID.Kind = ValID::t_Constant;
4509 return false;
4510 }
4511
4512 case lltok::kw_trunc:
4513 case lltok::kw_bitcast:
4515 case lltok::kw_inttoptr:
4517 case lltok::kw_ptrtoint: {
4518 unsigned Opc = Lex.getUIntVal();
4519 Type *DestTy = nullptr;
4520 Constant *SrcVal;
4521 Lex.Lex();
4522 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4523 parseGlobalTypeAndValue(SrcVal) ||
4524 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4525 parseType(DestTy) ||
4526 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4527 return true;
4528 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4529 return error(ID.Loc, "invalid cast opcode for cast from '" +
4530 getTypeString(SrcVal->getType()) + "' to '" +
4531 getTypeString(DestTy) + "'");
4533 SrcVal, DestTy);
4534 ID.Kind = ValID::t_Constant;
4535 return false;
4536 }
4538 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4540 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4541 case lltok::kw_udiv:
4542 return error(ID.Loc, "udiv constexprs are no longer supported");
4543 case lltok::kw_sdiv:
4544 return error(ID.Loc, "sdiv constexprs are no longer supported");
4545 case lltok::kw_urem:
4546 return error(ID.Loc, "urem constexprs are no longer supported");
4547 case lltok::kw_srem:
4548 return error(ID.Loc, "srem constexprs are no longer supported");
4549 case lltok::kw_fadd:
4550 return error(ID.Loc, "fadd constexprs are no longer supported");
4551 case lltok::kw_fsub:
4552 return error(ID.Loc, "fsub constexprs are no longer supported");
4553 case lltok::kw_fmul:
4554 return error(ID.Loc, "fmul constexprs are no longer supported");
4555 case lltok::kw_fdiv:
4556 return error(ID.Loc, "fdiv constexprs are no longer supported");
4557 case lltok::kw_frem:
4558 return error(ID.Loc, "frem constexprs are no longer supported");
4559 case lltok::kw_and:
4560 return error(ID.Loc, "and constexprs are no longer supported");
4561 case lltok::kw_or:
4562 return error(ID.Loc, "or constexprs are no longer supported");
4563 case lltok::kw_lshr:
4564 return error(ID.Loc, "lshr constexprs are no longer supported");
4565 case lltok::kw_ashr:
4566 return error(ID.Loc, "ashr constexprs are no longer supported");
4567 case lltok::kw_shl:
4568 return error(ID.Loc, "shl constexprs are no longer supported");
4569 case lltok::kw_mul:
4570 return error(ID.Loc, "mul constexprs are no longer supported");
4571 case lltok::kw_fneg:
4572 return error(ID.Loc, "fneg constexprs are no longer supported");
4573 case lltok::kw_select:
4574 return error(ID.Loc, "select constexprs are no longer supported");
4575 case lltok::kw_zext:
4576 return error(ID.Loc, "zext constexprs are no longer supported");
4577 case lltok::kw_sext:
4578 return error(ID.Loc, "sext constexprs are no longer supported");
4579 case lltok::kw_fptrunc:
4580 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4581 case lltok::kw_fpext:
4582 return error(ID.Loc, "fpext constexprs are no longer supported");
4583 case lltok::kw_uitofp:
4584 return error(ID.Loc, "uitofp constexprs are no longer supported");
4585 case lltok::kw_sitofp:
4586 return error(ID.Loc, "sitofp constexprs are no longer supported");
4587 case lltok::kw_fptoui:
4588 return error(ID.Loc, "fptoui constexprs are no longer supported");
4589 case lltok::kw_fptosi:
4590 return error(ID.Loc, "fptosi constexprs are no longer supported");
4591 case lltok::kw_icmp:
4592 return error(ID.Loc, "icmp constexprs are no longer supported");
4593 case lltok::kw_fcmp:
4594 return error(ID.Loc, "fcmp constexprs are no longer supported");
4595
4596 // Binary Operators.
4597 case lltok::kw_add:
4598 case lltok::kw_sub:
4599 case lltok::kw_xor: {
4600 bool NUW = false;
4601 bool NSW = false;
4602 unsigned Opc = Lex.getUIntVal();
4603 Constant *Val0, *Val1;
4604 Lex.Lex();
4605 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4606 Opc == Instruction::Mul) {
4607 if (EatIfPresent(lltok::kw_nuw))
4608 NUW = true;
4609 if (EatIfPresent(lltok::kw_nsw)) {
4610 NSW = true;
4611 if (EatIfPresent(lltok::kw_nuw))
4612 NUW = true;
4613 }
4614 }
4615 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4616 parseGlobalTypeAndValue(Val0) ||
4617 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4618 parseGlobalTypeAndValue(Val1) ||
4619 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4620 return true;
4621 if (Val0->getType() != Val1->getType())
4622 return error(ID.Loc, "operands of constexpr must have same type");
4623 // Check that the type is valid for the operator.
4624 if (!Val0->getType()->isIntOrIntVectorTy())
4625 return error(ID.Loc,
4626 "constexpr requires integer or integer vector operands");
4627 unsigned Flags = 0;
4630 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4631 ID.Kind = ValID::t_Constant;
4632 return false;
4633 }
4634
4635 case lltok::kw_splat: {
4636 Lex.Lex();
4637 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4638 return true;
4639 Constant *C;
4640 if (parseGlobalTypeAndValue(C))
4641 return true;
4642 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4643 return true;
4644
4645 ID.ConstantVal = C;
4647 return false;
4648 }
4649
4654 unsigned Opc = Lex.getUIntVal();
4656 GEPNoWrapFlags NW;
4657 bool HasInRange = false;
4658 APSInt InRangeStart;
4659 APSInt InRangeEnd;
4660 Type *Ty;
4661 Lex.Lex();
4662
4663 if (Opc == Instruction::GetElementPtr) {
4664 while (true) {
4665 if (EatIfPresent(lltok::kw_inbounds))
4667 else if (EatIfPresent(lltok::kw_nusw))
4669 else if (EatIfPresent(lltok::kw_nuw))
4671 else
4672 break;
4673 }
4674
4675 if (EatIfPresent(lltok::kw_inrange)) {
4676 if (parseToken(lltok::lparen, "expected '('"))
4677 return true;
4678 if (Lex.getKind() != lltok::APSInt)
4679 return tokError("expected integer");
4680 InRangeStart = Lex.getAPSIntVal();
4681 Lex.Lex();
4682 if (parseToken(lltok::comma, "expected ','"))
4683 return true;
4684 if (Lex.getKind() != lltok::APSInt)
4685 return tokError("expected integer");
4686 InRangeEnd = Lex.getAPSIntVal();
4687 Lex.Lex();
4688 if (parseToken(lltok::rparen, "expected ')'"))
4689 return true;
4690 HasInRange = true;
4691 }
4692 }
4693
4694 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4695 return true;
4696
4697 if (Opc == Instruction::GetElementPtr) {
4698 if (parseType(Ty) ||
4699 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4700 return true;
4701 }
4702
4703 if (parseGlobalValueVector(Elts) ||
4704 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4705 return true;
4706
4707 if (Opc == Instruction::GetElementPtr) {
4708 if (Elts.size() == 0 ||
4709 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4710 return error(ID.Loc, "base of getelementptr must be a pointer");
4711
4712 Type *BaseType = Elts[0]->getType();
4713 std::optional<ConstantRange> InRange;
4714 if (HasInRange) {
4715 unsigned IndexWidth =
4716 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4717 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4718 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4719 if (InRangeStart.sge(InRangeEnd))
4720 return error(ID.Loc, "expected end to be larger than start");
4721 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4722 }
4723
4724 unsigned GEPWidth =
4725 BaseType->isVectorTy()
4726 ? cast<FixedVectorType>(BaseType)->getNumElements()
4727 : 0;
4728
4729 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4730 for (Constant *Val : Indices) {
4731 Type *ValTy = Val->getType();
4732 if (!ValTy->isIntOrIntVectorTy())
4733 return error(ID.Loc, "getelementptr index must be an integer");
4734 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4735 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4736 if (GEPWidth && (ValNumEl != GEPWidth))
4737 return error(
4738 ID.Loc,
4739 "getelementptr vector index has a wrong number of elements");
4740 // GEPWidth may have been unknown because the base is a scalar,
4741 // but it is known now.
4742 GEPWidth = ValNumEl;
4743 }
4744 }
4745
4746 SmallPtrSet<Type*, 4> Visited;
4747 if (!Indices.empty() && !Ty->isSized(&Visited))
4748 return error(ID.Loc, "base element of getelementptr must be sized");
4749
4751 return error(ID.Loc, "invalid base element for constant getelementptr");
4752
4753 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4754 return error(ID.Loc, "invalid getelementptr indices");
4755
4756 ID.ConstantVal =
4757 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4758 } else if (Opc == Instruction::ShuffleVector) {
4759 if (Elts.size() != 3)
4760 return error(ID.Loc, "expected three operands to shufflevector");
4761 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4762 return error(ID.Loc, "invalid operands to shufflevector");
4763 SmallVector<int, 16> Mask;
4765 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4766 } else if (Opc == Instruction::ExtractElement) {
4767 if (Elts.size() != 2)
4768 return error(ID.Loc, "expected two operands to extractelement");
4769 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4770 return error(ID.Loc, "invalid extractelement operands");
4771 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4772 } else {
4773 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4774 if (Elts.size() != 3)
4775 return error(ID.Loc, "expected three operands to insertelement");
4776 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4777 return error(ID.Loc, "invalid insertelement operands");
4778 ID.ConstantVal =
4779 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4780 }
4781
4782 ID.Kind = ValID::t_Constant;
4783 return false;
4784 }
4785 }
4786
4787 Lex.Lex();
4788 return false;
4789}
4790
4791/// parseGlobalValue - parse a global value with the specified type.
4792bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4793 C = nullptr;
4794 ValID ID;
4795 Value *V = nullptr;
4796 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4797 convertValIDToValue(Ty, ID, V, nullptr);
4798 if (V && !(C = dyn_cast<Constant>(V)))
4799 return error(ID.Loc, "global values must be constants");
4800 return Parsed;
4801}
4802
4803bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4804 Type *Ty = nullptr;
4805 return parseType(Ty) || parseGlobalValue(Ty, V);
4806}
4807
4808bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4809 C = nullptr;
4810
4811 LocTy KwLoc = Lex.getLoc();
4812 if (!EatIfPresent(lltok::kw_comdat))
4813 return false;
4814
4815 if (EatIfPresent(lltok::lparen)) {
4816 if (Lex.getKind() != lltok::ComdatVar)
4817 return tokError("expected comdat variable");
4818 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4819 Lex.Lex();
4820 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4821 return true;
4822 } else {
4823 if (GlobalName.empty())
4824 return tokError("comdat cannot be unnamed");
4825 C = getComdat(std::string(GlobalName), KwLoc);
4826 }
4827
4828 return false;
4829}
4830
4831/// parseGlobalValueVector
4832/// ::= /*empty*/
4833/// ::= TypeAndValue (',' TypeAndValue)*
4834bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4835 // Empty list.
4836 if (Lex.getKind() == lltok::rbrace ||
4837 Lex.getKind() == lltok::rsquare ||
4838 Lex.getKind() == lltok::greater ||
4839 Lex.getKind() == lltok::rparen)
4840 return false;
4841
4842 do {
4843 // Let the caller deal with inrange.
4844 if (Lex.getKind() == lltok::kw_inrange)
4845 return false;
4846
4847 Constant *C;
4848 if (parseGlobalTypeAndValue(C))
4849 return true;
4850 Elts.push_back(C);
4851 } while (EatIfPresent(lltok::comma));
4852
4853 return false;
4854}
4855
4856bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4858 if (parseMDNodeVector(Elts))
4859 return true;
4860
4861 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4862 return false;
4863}
4864
4865/// MDNode:
4866/// ::= !{ ... }
4867/// ::= !7
4868/// ::= !DILocation(...)
4869bool LLParser::parseMDNode(MDNode *&N) {
4870 if (Lex.getKind() == lltok::MetadataVar)
4871 return parseSpecializedMDNode(N);
4872
4873 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4874}
4875
4876bool LLParser::parseMDNodeTail(MDNode *&N) {
4877 // !{ ... }
4878 if (Lex.getKind() == lltok::lbrace)
4879 return parseMDTuple(N);
4880
4881 // !42
4882 return parseMDNodeID(N);
4883}
4884
4885namespace {
4886
4887/// Structure to represent an optional metadata field.
4888template <class FieldTy> struct MDFieldImpl {
4889 typedef MDFieldImpl ImplTy;
4890 FieldTy Val;
4891 bool Seen;
4892
4893 void assign(FieldTy Val) {
4894 Seen = true;
4895 this->Val = std::move(Val);
4896 }
4897
4898 explicit MDFieldImpl(FieldTy Default)
4899 : Val(std::move(Default)), Seen(false) {}
4900};
4901
4902/// Structure to represent an optional metadata field that
4903/// can be of either type (A or B) and encapsulates the
4904/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4905/// to reimplement the specifics for representing each Field.
4906template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4907 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4908 FieldTypeA A;
4909 FieldTypeB B;
4910 bool Seen;
4911
4912 enum {
4913 IsInvalid = 0,
4914 IsTypeA = 1,
4915 IsTypeB = 2
4916 } WhatIs;
4917
4918 void assign(FieldTypeA A) {
4919 Seen = true;
4920 this->A = std::move(A);
4921 WhatIs = IsTypeA;
4922 }
4923
4924 void assign(FieldTypeB B) {
4925 Seen = true;
4926 this->B = std::move(B);
4927 WhatIs = IsTypeB;
4928 }
4929
4930 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4931 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4932 WhatIs(IsInvalid) {}
4933};
4934
4935struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4936 uint64_t Max;
4937
4938 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4939 : ImplTy(Default), Max(Max) {}
4940};
4941
4942struct LineField : public MDUnsignedField {
4943 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4944};
4945
4946struct ColumnField : public MDUnsignedField {
4947 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4948};
4949
4950struct DwarfTagField : public MDUnsignedField {
4951 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4952 DwarfTagField(dwarf::Tag DefaultTag)
4953 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4954};
4955
4956struct DwarfMacinfoTypeField : public MDUnsignedField {
4957 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4958 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4959 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4960};
4961
4962struct DwarfAttEncodingField : public MDUnsignedField {
4963 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4964};
4965
4966struct DwarfVirtualityField : public MDUnsignedField {
4967 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4968};
4969
4970struct DwarfLangField : public MDUnsignedField {
4971 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4972};
4973
4974struct DwarfSourceLangNameField : public MDUnsignedField {
4975 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4976};
4977
4978struct DwarfCCField : public MDUnsignedField {
4979 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4980};
4981
4982struct DwarfEnumKindField : public MDUnsignedField {
4983 DwarfEnumKindField()
4984 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4985 dwarf::DW_APPLE_ENUM_KIND_max) {}
4986};
4987
4988struct EmissionKindField : public MDUnsignedField {
4989 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4990};
4991
4992struct FixedPointKindField : public MDUnsignedField {
4993 FixedPointKindField()
4994 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4995};
4996
4997struct NameTableKindField : public MDUnsignedField {
4998 NameTableKindField()
4999 : MDUnsignedField(
5000 0, (unsigned)
5001 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5002};
5003
5004struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5005 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5006};
5007
5008struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5009 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5010};
5011
5012struct MDAPSIntField : public MDFieldImpl<APSInt> {
5013 MDAPSIntField() : ImplTy(APSInt()) {}
5014};
5015
5016struct MDSignedField : public MDFieldImpl<int64_t> {
5017 int64_t Min = INT64_MIN;
5018 int64_t Max = INT64_MAX;
5019
5020 MDSignedField(int64_t Default = 0)
5021 : ImplTy(Default) {}
5022 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5023 : ImplTy(Default), Min(Min), Max(Max) {}
5024};
5025
5026struct MDBoolField : public MDFieldImpl<bool> {
5027 MDBoolField(bool Default = false) : ImplTy(Default) {}
5028};
5029
5030struct MDField : public MDFieldImpl<Metadata *> {
5031 bool AllowNull;
5032
5033 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5034};
5035
5036struct MDStringField : public MDFieldImpl<MDString *> {
5037 enum class EmptyIs {
5038 Null, //< Allow empty input string, map to nullptr
5039 Empty, //< Allow empty input string, map to an empty MDString
5040 Error, //< Disallow empty string, map to an error
5041 } EmptyIs;
5042 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5043 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5044};
5045
5046struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5047 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5048};
5049
5050struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5051 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5052};
5053
5054struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5055 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5056 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5057
5058 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5059 bool AllowNull = true)
5060 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5061
5062 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5063 bool isMDField() const { return WhatIs == IsTypeB; }
5064 int64_t getMDSignedValue() const {
5065 assert(isMDSignedField() && "Wrong field type");
5066 return A.Val;
5067 }
5068 Metadata *getMDFieldValue() const {
5069 assert(isMDField() && "Wrong field type");
5070 return B.Val;
5071 }
5072};
5073
5074struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5075 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5076 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5077
5078 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5079 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5080
5081 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5082 bool isMDField() const { return WhatIs == IsTypeB; }
5083 uint64_t getMDUnsignedValue() const {
5084 assert(isMDUnsignedField() && "Wrong field type");
5085 return A.Val;
5086 }
5087 Metadata *getMDFieldValue() const {
5088 assert(isMDField() && "Wrong field type");
5089 return B.Val;
5090 }
5091
5092 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5093 if (isMDUnsignedField())
5095 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5096 if (isMDField())
5097 return getMDFieldValue();
5098 return nullptr;
5099 }
5100};
5101
5102} // end anonymous namespace
5103
5104namespace llvm {
5105
5106template <>
5107bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5108 if (Lex.getKind() != lltok::APSInt)
5109 return tokError("expected integer");
5110
5111 Result.assign(Lex.getAPSIntVal());
5112 Lex.Lex();
5113 return false;
5114}
5115
5116template <>
5117bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5118 MDUnsignedField &Result) {
5119 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5120 return tokError("expected unsigned integer");
5121
5122 auto &U = Lex.getAPSIntVal();
5123 if (U.ugt(Result.Max))
5124 return tokError("value for '" + Name + "' too large, limit is " +
5125 Twine(Result.Max));
5126 Result.assign(U.getZExtValue());
5127 assert(Result.Val <= Result.Max && "Expected value in range");
5128 Lex.Lex();
5129 return false;
5130}
5131
5132template <>
5133bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5134 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5135}
5136template <>
5137bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5138 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5139}
5140
5141template <>
5142bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5143 if (Lex.getKind() == lltok::APSInt)
5144 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5145
5146 if (Lex.getKind() != lltok::DwarfTag)
5147 return tokError("expected DWARF tag");
5148
5149 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5151 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5152 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5153
5154 Result.assign(Tag);
5155 Lex.Lex();
5156 return false;
5157}
5158
5159template <>
5160bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5161 DwarfMacinfoTypeField &Result) {
5162 if (Lex.getKind() == lltok::APSInt)
5163 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5164
5165 if (Lex.getKind() != lltok::DwarfMacinfo)
5166 return tokError("expected DWARF macinfo type");
5167
5168 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5169 if (Macinfo == dwarf::DW_MACINFO_invalid)
5170 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5171 Lex.getStrVal() + "'");
5172 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5173
5174 Result.assign(Macinfo);
5175 Lex.Lex();
5176 return false;
5177}
5178
5179template <>
5180bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5181 DwarfVirtualityField &Result) {
5182 if (Lex.getKind() == lltok::APSInt)
5183 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5184
5185 if (Lex.getKind() != lltok::DwarfVirtuality)
5186 return tokError("expected DWARF virtuality code");
5187
5188 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5189 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5190 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5191 Lex.getStrVal() + "'");
5192 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5193 Result.assign(Virtuality);
5194 Lex.Lex();
5195 return false;
5196}
5197
5198template <>
5199bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5200 DwarfEnumKindField &Result) {
5201 if (Lex.getKind() == lltok::APSInt)
5202 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5203
5204 if (Lex.getKind() != lltok::DwarfEnumKind)
5205 return tokError("expected DWARF enum kind code");
5206
5207 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5208 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5209 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5210 Lex.getStrVal() + "'");
5211 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5212 Result.assign(EnumKind);
5213 Lex.Lex();
5214 return false;
5215}
5216
5217template <>
5218bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5219 if (Lex.getKind() == lltok::APSInt)
5220 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5221
5222 if (Lex.getKind() != lltok::DwarfLang)
5223 return tokError("expected DWARF language");
5224
5225 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5226 if (!Lang)
5227 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5228 "'");
5229 assert(Lang <= Result.Max && "Expected valid DWARF language");
5230 Result.assign(Lang);
5231 Lex.Lex();
5232 return false;
5233}
5234
5235template <>
5236bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5237 DwarfSourceLangNameField &Result) {
5238 if (Lex.getKind() == lltok::APSInt)
5239 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5240
5241 if (Lex.getKind() != lltok::DwarfSourceLangName)
5242 return tokError("expected DWARF source language name");
5243
5244 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5245 if (!Lang)
5246 return tokError("invalid DWARF source language name" + Twine(" '") +
5247 Lex.getStrVal() + "'");
5248 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5249 Result.assign(Lang);
5250 Lex.Lex();
5251 return false;
5252}
5253
5254template <>
5255bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5256 if (Lex.getKind() == lltok::APSInt)
5257 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5258
5259 if (Lex.getKind() != lltok::DwarfCC)
5260 return tokError("expected DWARF calling convention");
5261
5262 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5263 if (!CC)
5264 return tokError("invalid DWARF calling convention" + Twine(" '") +
5265 Lex.getStrVal() + "'");
5266 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5267 Result.assign(CC);
5268 Lex.Lex();
5269 return false;
5270}
5271
5272template <>
5273bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5274 EmissionKindField &Result) {
5275 if (Lex.getKind() == lltok::APSInt)
5276 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5277
5278 if (Lex.getKind() != lltok::EmissionKind)
5279 return tokError("expected emission kind");
5280
5281 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5282 if (!Kind)
5283 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5284 "'");
5285 assert(*Kind <= Result.Max && "Expected valid emission kind");
5286 Result.assign(*Kind);
5287 Lex.Lex();
5288 return false;
5289}
5290
5291template <>
5292bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5293 FixedPointKindField &Result) {
5294 if (Lex.getKind() == lltok::APSInt)
5295 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5296
5297 if (Lex.getKind() != lltok::FixedPointKind)
5298 return tokError("expected fixed-point kind");
5299
5300 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5301 if (!Kind)
5302 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5303 "'");
5304 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5305 Result.assign(*Kind);
5306 Lex.Lex();
5307 return false;
5308}
5309
5310template <>
5311bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5312 NameTableKindField &Result) {
5313 if (Lex.getKind() == lltok::APSInt)
5314 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5315
5316 if (Lex.getKind() != lltok::NameTableKind)
5317 return tokError("expected nameTable kind");
5318
5319 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5320 if (!Kind)
5321 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5322 "'");
5323 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5324 Result.assign((unsigned)*Kind);
5325 Lex.Lex();
5326 return false;
5327}
5328
5329template <>
5330bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5331 DwarfAttEncodingField &Result) {
5332 if (Lex.getKind() == lltok::APSInt)
5333 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5334
5335 if (Lex.getKind() != lltok::DwarfAttEncoding)
5336 return tokError("expected DWARF type attribute encoding");
5337
5338 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5339 if (!Encoding)
5340 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5341 Lex.getStrVal() + "'");
5342 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5343 Result.assign(Encoding);
5344 Lex.Lex();
5345 return false;
5346}
5347
5348/// DIFlagField
5349/// ::= uint32
5350/// ::= DIFlagVector
5351/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5352template <>
5353bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5354
5355 // parser for a single flag.
5356 auto parseFlag = [&](DINode::DIFlags &Val) {
5357 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5358 uint32_t TempVal = static_cast<uint32_t>(Val);
5359 bool Res = parseUInt32(TempVal);
5360 Val = static_cast<DINode::DIFlags>(TempVal);
5361 return Res;
5362 }
5363
5364 if (Lex.getKind() != lltok::DIFlag)
5365 return tokError("expected debug info flag");
5366
5367 Val = DINode::getFlag(Lex.getStrVal());
5368 if (!Val)
5369 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5370 "'");
5371 Lex.Lex();
5372 return false;
5373 };
5374
5375 // parse the flags and combine them together.
5376 DINode::DIFlags Combined = DINode::FlagZero;
5377 do {
5378 DINode::DIFlags Val;
5379 if (parseFlag(Val))
5380 return true;
5381 Combined |= Val;
5382 } while (EatIfPresent(lltok::bar));
5383
5384 Result.assign(Combined);
5385 return false;
5386}
5387
5388/// DISPFlagField
5389/// ::= uint32
5390/// ::= DISPFlagVector
5391/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5392template <>
5393bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5394
5395 // parser for a single flag.
5396 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5397 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5398 uint32_t TempVal = static_cast<uint32_t>(Val);
5399 bool Res = parseUInt32(TempVal);
5400 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5401 return Res;
5402 }
5403
5404 if (Lex.getKind() != lltok::DISPFlag)
5405 return tokError("expected debug info flag");
5406
5407 Val = DISubprogram::getFlag(Lex.getStrVal());
5408 if (!Val)
5409 return tokError(Twine("invalid subprogram debug info flag '") +
5410 Lex.getStrVal() + "'");
5411 Lex.Lex();
5412 return false;
5413 };
5414
5415 // parse the flags and combine them together.
5416 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5417 do {
5419 if (parseFlag(Val))
5420 return true;
5421 Combined |= Val;
5422 } while (EatIfPresent(lltok::bar));
5423
5424 Result.assign(Combined);
5425 return false;
5426}
5427
5428template <>
5429bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5430 if (Lex.getKind() != lltok::APSInt)
5431 return tokError("expected signed integer");
5432
5433 auto &S = Lex.getAPSIntVal();
5434 if (S < Result.Min)
5435 return tokError("value for '" + Name + "' too small, limit is " +
5436 Twine(Result.Min));
5437 if (S > Result.Max)
5438 return tokError("value for '" + Name + "' too large, limit is " +
5439 Twine(Result.Max));
5440 Result.assign(S.getExtValue());
5441 assert(Result.Val >= Result.Min && "Expected value in range");
5442 assert(Result.Val <= Result.Max && "Expected value in range");
5443 Lex.Lex();
5444 return false;
5445}
5446
5447template <>
5448bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5449 switch (Lex.getKind()) {
5450 default:
5451 return tokError("expected 'true' or 'false'");
5452 case lltok::kw_true:
5453 Result.assign(true);
5454 break;
5455 case lltok::kw_false:
5456 Result.assign(false);
5457 break;
5458 }
5459 Lex.Lex();
5460 return false;
5461}
5462
5463template <>
5464bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5465 if (Lex.getKind() == lltok::kw_null) {
5466 if (!Result.AllowNull)
5467 return tokError("'" + Name + "' cannot be null");
5468 Lex.Lex();
5469 Result.assign(nullptr);
5470 return false;
5471 }
5472
5473 Metadata *MD;
5474 if (parseMetadata(MD, nullptr))
5475 return true;
5476
5477 Result.assign(MD);
5478 return false;
5479}
5480
5481template <>
5482bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5483 MDSignedOrMDField &Result) {
5484 // Try to parse a signed int.
5485 if (Lex.getKind() == lltok::APSInt) {
5486 MDSignedField Res = Result.A;
5487 if (!parseMDField(Loc, Name, Res)) {
5488 Result.assign(Res);
5489 return false;
5490 }
5491 return true;
5492 }
5493
5494 // Otherwise, try to parse as an MDField.
5495 MDField Res = Result.B;
5496 if (!parseMDField(Loc, Name, Res)) {
5497 Result.assign(Res);
5498 return false;
5499 }
5500
5501 return true;
5502}
5503
5504template <>
5505bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5506 MDUnsignedOrMDField &Result) {
5507 // Try to parse an unsigned int.
5508 if (Lex.getKind() == lltok::APSInt) {
5509 MDUnsignedField Res = Result.A;
5510 if (!parseMDField(Loc, Name, Res)) {
5511 Result.assign(Res);
5512 return false;
5513 }
5514 return true;
5515 }
5516
5517 // Otherwise, try to parse as an MDField.
5518 MDField Res = Result.B;
5519 if (!parseMDField(Loc, Name, Res)) {
5520 Result.assign(Res);
5521 return false;
5522 }
5523
5524 return true;
5525}
5526
5527template <>
5528bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5529 LocTy ValueLoc = Lex.getLoc();
5530 std::string S;
5531 if (parseStringConstant(S))
5532 return true;
5533
5534 if (S.empty()) {
5535 switch (Result.EmptyIs) {
5536 case MDStringField::EmptyIs::Null:
5537 Result.assign(nullptr);
5538 return false;
5539 case MDStringField::EmptyIs::Empty:
5540 break;
5541 case MDStringField::EmptyIs::Error:
5542 return error(ValueLoc, "'" + Name + "' cannot be empty");
5543 }
5544 }
5545
5546 Result.assign(MDString::get(Context, S));
5547 return false;
5548}
5549
5550template <>
5551bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5553 if (parseMDNodeVector(MDs))
5554 return true;
5555
5556 Result.assign(std::move(MDs));
5557 return false;
5558}
5559
5560template <>
5561bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5562 ChecksumKindField &Result) {
5563 std::optional<DIFile::ChecksumKind> CSKind =
5564 DIFile::getChecksumKind(Lex.getStrVal());
5565
5566 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5567 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5568 "'");
5569
5570 Result.assign(*CSKind);
5571 Lex.Lex();
5572 return false;
5573}
5574
5575} // end namespace llvm
5576
5577template <class ParserTy>
5578bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5579 do {
5580 if (Lex.getKind() != lltok::LabelStr)
5581 return tokError("expected field label here");
5582
5583 if (ParseField())
5584 return true;
5585 } while (EatIfPresent(lltok::comma));
5586
5587 return false;
5588}
5589
5590template <class ParserTy>
5591bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5592 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5593 Lex.Lex();
5594
5595 if (parseToken(lltok::lparen, "expected '(' here"))
5596 return true;
5597 if (Lex.getKind() != lltok::rparen)
5598 if (parseMDFieldsImplBody(ParseField))
5599 return true;
5600
5601 ClosingLoc = Lex.getLoc();
5602 return parseToken(lltok::rparen, "expected ')' here");
5603}
5604
5605template <class FieldTy>
5606bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5607 if (Result.Seen)
5608 return tokError("field '" + Name + "' cannot be specified more than once");
5609
5610 LocTy Loc = Lex.getLoc();
5611 Lex.Lex();
5612 return parseMDField(Loc, Name, Result);
5613}
5614
5615bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5616 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5617
5618#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5619 if (Lex.getStrVal() == #CLASS) \
5620 return parse##CLASS(N, IsDistinct);
5621#include "llvm/IR/Metadata.def"
5622
5623 return tokError("expected metadata type");
5624}
5625
5626#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5627#define NOP_FIELD(NAME, TYPE, INIT)
5628#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5629 if (!NAME.Seen) \
5630 return error(ClosingLoc, "missing required field '" #NAME "'");
5631#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5632 if (Lex.getStrVal() == #NAME) \
5633 return parseMDField(#NAME, NAME);
5634#define PARSE_MD_FIELDS() \
5635 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5636 do { \
5637 LocTy ClosingLoc; \
5638 if (parseMDFieldsImpl( \
5639 [&]() -> bool { \
5640 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5641 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5642 "'"); \
5643 }, \
5644 ClosingLoc)) \
5645 return true; \
5646 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5647 } while (false)
5648#define GET_OR_DISTINCT(CLASS, ARGS) \
5649 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5650
5651/// parseDILocationFields:
5652/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5653/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5654bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5655#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5656 OPTIONAL(line, LineField, ); \
5657 OPTIONAL(column, ColumnField, ); \
5658 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5659 OPTIONAL(inlinedAt, MDField, ); \
5660 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5661 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5662 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5664#undef VISIT_MD_FIELDS
5665
5666 Result = GET_OR_DISTINCT(
5667 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5668 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5669 return false;
5670}
5671
5672/// parseDIAssignID:
5673/// ::= distinct !DIAssignID()
5674bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5675 if (!IsDistinct)
5676 return tokError("missing 'distinct', required for !DIAssignID()");
5677
5678 Lex.Lex();
5679
5680 // Now eat the parens.
5681 if (parseToken(lltok::lparen, "expected '(' here"))
5682 return true;
5683 if (parseToken(lltok::rparen, "expected ')' here"))
5684 return true;
5685
5687 return false;
5688}
5689
5690/// parseGenericDINode:
5691/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5692bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5693#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5694 REQUIRED(tag, DwarfTagField, ); \
5695 OPTIONAL(header, MDStringField, ); \
5696 OPTIONAL(operands, MDFieldList, );
5698#undef VISIT_MD_FIELDS
5699
5700 Result = GET_OR_DISTINCT(GenericDINode,
5701 (Context, tag.Val, header.Val, operands.Val));
5702 return false;
5703}
5704
5705/// parseDISubrangeType:
5706/// ::= !DISubrangeType(name: "whatever", file: !0,
5707/// line: 7, scope: !1, baseType: !2, size: 32,
5708/// align: 32, flags: 0, lowerBound: !3
5709/// upperBound: !4, stride: !5, bias: !6)
5710bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5711#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5712 OPTIONAL(name, MDStringField, ); \
5713 OPTIONAL(file, MDField, ); \
5714 OPTIONAL(line, LineField, ); \
5715 OPTIONAL(scope, MDField, ); \
5716 OPTIONAL(baseType, MDField, ); \
5717 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5718 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5719 OPTIONAL(flags, DIFlagField, ); \
5720 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5721 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5722 OPTIONAL(stride, MDSignedOrMDField, ); \
5723 OPTIONAL(bias, MDSignedOrMDField, );
5725#undef VISIT_MD_FIELDS
5726
5727 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5728 if (Bound.isMDSignedField())
5730 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5731 if (Bound.isMDField())
5732 return Bound.getMDFieldValue();
5733 return nullptr;
5734 };
5735
5736 Metadata *LowerBound = convToMetadata(lowerBound);
5737 Metadata *UpperBound = convToMetadata(upperBound);
5738 Metadata *Stride = convToMetadata(stride);
5739 Metadata *Bias = convToMetadata(bias);
5740
5742 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5743 size.getValueAsMetadata(Context), align.Val, flags.Val,
5744 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5745
5746 return false;
5747}
5748
5749/// parseDISubrange:
5750/// ::= !DISubrange(count: 30, lowerBound: 2)
5751/// ::= !DISubrange(count: !node, lowerBound: 2)
5752/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5753bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5754#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5755 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5756 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5757 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5758 OPTIONAL(stride, MDSignedOrMDField, );
5760#undef VISIT_MD_FIELDS
5761
5762 Metadata *Count = nullptr;
5763 Metadata *LowerBound = nullptr;
5764 Metadata *UpperBound = nullptr;
5765 Metadata *Stride = nullptr;
5766
5767 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5768 if (Bound.isMDSignedField())
5770 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5771 if (Bound.isMDField())
5772 return Bound.getMDFieldValue();
5773 return nullptr;
5774 };
5775
5776 Count = convToMetadata(count);
5777 LowerBound = convToMetadata(lowerBound);
5778 UpperBound = convToMetadata(upperBound);
5779 Stride = convToMetadata(stride);
5780
5781 Result = GET_OR_DISTINCT(DISubrange,
5782 (Context, Count, LowerBound, UpperBound, Stride));
5783
5784 return false;
5785}
5786
5787/// parseDIGenericSubrange:
5788/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5789/// !node3)
5790bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5791#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5792 OPTIONAL(count, MDSignedOrMDField, ); \
5793 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5794 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5795 OPTIONAL(stride, MDSignedOrMDField, );
5797#undef VISIT_MD_FIELDS
5798
5799 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5800 if (Bound.isMDSignedField())
5801 return DIExpression::get(
5802 Context, {dwarf::DW_OP_consts,
5803 static_cast<uint64_t>(Bound.getMDSignedValue())});
5804 if (Bound.isMDField())
5805 return Bound.getMDFieldValue();
5806 return nullptr;
5807 };
5808
5809 Metadata *Count = ConvToMetadata(count);
5810 Metadata *LowerBound = ConvToMetadata(lowerBound);
5811 Metadata *UpperBound = ConvToMetadata(upperBound);
5812 Metadata *Stride = ConvToMetadata(stride);
5813
5814 Result = GET_OR_DISTINCT(DIGenericSubrange,
5815 (Context, Count, LowerBound, UpperBound, Stride));
5816
5817 return false;
5818}
5819
5820/// parseDIEnumerator:
5821/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5822bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5823#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5824 REQUIRED(name, MDStringField, ); \
5825 REQUIRED(value, MDAPSIntField, ); \
5826 OPTIONAL(isUnsigned, MDBoolField, (false));
5828#undef VISIT_MD_FIELDS
5829
5830 if (isUnsigned.Val && value.Val.isNegative())
5831 return tokError("unsigned enumerator with negative value");
5832
5833 APSInt Value(value.Val);
5834 // Add a leading zero so that unsigned values with the msb set are not
5835 // mistaken for negative values when used for signed enumerators.
5836 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5837 Value = Value.zext(Value.getBitWidth() + 1);
5838
5839 Result =
5840 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5841
5842 return false;
5843}
5844
5845/// parseDIBasicType:
5846/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5847/// encoding: DW_ATE_encoding, flags: 0)
5848bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5849#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5850 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5851 OPTIONAL(name, MDStringField, ); \
5852 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5853 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5854 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5855 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5856 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5857 OPTIONAL(flags, DIFlagField, );
5859#undef VISIT_MD_FIELDS
5860
5862 DIBasicType,
5863 (Context, tag.Val, name.Val, size.getValueAsMetadata(Context), align.Val,
5864 encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5865 return false;
5866}
5867
5868/// parseDIFixedPointType:
5869/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5870/// align: 32, encoding: DW_ATE_signed_fixed,
5871/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5872/// denominator: 8)
5873bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5874#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5875 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5876 OPTIONAL(name, MDStringField, ); \
5877 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5878 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5879 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5880 OPTIONAL(flags, DIFlagField, ); \
5881 OPTIONAL(kind, FixedPointKindField, ); \
5882 OPTIONAL(factor, MDSignedField, ); \
5883 OPTIONAL(numerator, MDAPSIntField, ); \
5884 OPTIONAL(denominator, MDAPSIntField, );
5886#undef VISIT_MD_FIELDS
5887
5888 Result = GET_OR_DISTINCT(DIFixedPointType,
5889 (Context, tag.Val, name.Val,
5890 size.getValueAsMetadata(Context), align.Val,
5891 encoding.Val, flags.Val, kind.Val, factor.Val,
5892 numerator.Val, denominator.Val));
5893 return false;
5894}
5895
5896/// parseDIStringType:
5897/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5898bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5899#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5900 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5901 OPTIONAL(name, MDStringField, ); \
5902 OPTIONAL(stringLength, MDField, ); \
5903 OPTIONAL(stringLengthExpression, MDField, ); \
5904 OPTIONAL(stringLocationExpression, MDField, ); \
5905 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5906 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5907 OPTIONAL(encoding, DwarfAttEncodingField, );
5909#undef VISIT_MD_FIELDS
5910
5912 DIStringType,
5913 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5914 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5915 align.Val, encoding.Val));
5916 return false;
5917}
5918
5919/// parseDIDerivedType:
5920/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5921/// line: 7, scope: !1, baseType: !2, size: 32,
5922/// align: 32, offset: 0, flags: 0, extraData: !3,
5923/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5924/// ptrAuthIsAddressDiscriminated: true,
5925/// ptrAuthExtraDiscriminator: 0x1234,
5926/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5927/// )
5928bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5929#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5930 REQUIRED(tag, DwarfTagField, ); \
5931 OPTIONAL(name, MDStringField, ); \
5932 OPTIONAL(file, MDField, ); \
5933 OPTIONAL(line, LineField, ); \
5934 OPTIONAL(scope, MDField, ); \
5935 REQUIRED(baseType, MDField, ); \
5936 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5937 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5938 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5939 OPTIONAL(flags, DIFlagField, ); \
5940 OPTIONAL(extraData, MDField, ); \
5941 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5942 OPTIONAL(annotations, MDField, ); \
5943 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5944 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5945 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5946 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5947 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5949#undef VISIT_MD_FIELDS
5950
5951 std::optional<unsigned> DWARFAddressSpace;
5952 if (dwarfAddressSpace.Val != UINT32_MAX)
5953 DWARFAddressSpace = dwarfAddressSpace.Val;
5954 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5955 if (ptrAuthKey.Val)
5956 PtrAuthData.emplace(
5957 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5958 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5959 ptrAuthAuthenticatesNullValues.Val);
5960
5962 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5963 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5964 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5965 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5966 return false;
5967}
5968
5969bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5970#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5971 REQUIRED(tag, DwarfTagField, ); \
5972 OPTIONAL(name, MDStringField, ); \
5973 OPTIONAL(file, MDField, ); \
5974 OPTIONAL(line, LineField, ); \
5975 OPTIONAL(scope, MDField, ); \
5976 OPTIONAL(baseType, MDField, ); \
5977 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5978 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5979 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5980 OPTIONAL(flags, DIFlagField, ); \
5981 OPTIONAL(elements, MDField, ); \
5982 OPTIONAL(runtimeLang, DwarfLangField, ); \
5983 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5984 OPTIONAL(vtableHolder, MDField, ); \
5985 OPTIONAL(templateParams, MDField, ); \
5986 OPTIONAL(identifier, MDStringField, ); \
5987 OPTIONAL(discriminator, MDField, ); \
5988 OPTIONAL(dataLocation, MDField, ); \
5989 OPTIONAL(associated, MDField, ); \
5990 OPTIONAL(allocated, MDField, ); \
5991 OPTIONAL(rank, MDSignedOrMDField, ); \
5992 OPTIONAL(annotations, MDField, ); \
5993 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5994 OPTIONAL(specification, MDField, ); \
5995 OPTIONAL(bitStride, MDField, );
5997#undef VISIT_MD_FIELDS
5998
5999 Metadata *Rank = nullptr;
6000 if (rank.isMDSignedField())
6002 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6003 else if (rank.isMDField())
6004 Rank = rank.getMDFieldValue();
6005
6006 std::optional<unsigned> EnumKind;
6007 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6008 EnumKind = enumKind.Val;
6009
6010 // If this has an identifier try to build an ODR type.
6011 if (identifier.Val)
6012 if (auto *CT = DICompositeType::buildODRType(
6013 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6014 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6015 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6016 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6017 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6018 dataLocation.Val, associated.Val, allocated.Val, Rank,
6019 annotations.Val, bitStride.Val)) {
6020 Result = CT;
6021 return false;
6022 }
6023
6024 // Create a new node, and save it in the context if it belongs in the type
6025 // map.
6027 DICompositeType,
6028 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6029 size.getValueAsMetadata(Context), align.Val,
6030 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6031 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6032 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6033 allocated.Val, Rank, annotations.Val, specification.Val,
6034 num_extra_inhabitants.Val, bitStride.Val));
6035 return false;
6036}
6037
6038bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6039#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6040 OPTIONAL(flags, DIFlagField, ); \
6041 OPTIONAL(cc, DwarfCCField, ); \
6042 REQUIRED(types, MDField, );
6044#undef VISIT_MD_FIELDS
6045
6046 Result = GET_OR_DISTINCT(DISubroutineType,
6047 (Context, flags.Val, cc.Val, types.Val));
6048 return false;
6049}
6050
6051/// parseDIFileType:
6052/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6053/// checksumkind: CSK_MD5,
6054/// checksum: "000102030405060708090a0b0c0d0e0f",
6055/// source: "source file contents")
6056bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6057 // The default constructed value for checksumkind is required, but will never
6058 // be used, as the parser checks if the field was actually Seen before using
6059 // the Val.
6060#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6061 REQUIRED(filename, MDStringField, ); \
6062 REQUIRED(directory, MDStringField, ); \
6063 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6064 OPTIONAL(checksum, MDStringField, ); \
6065 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6067#undef VISIT_MD_FIELDS
6068
6069 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6070 if (checksumkind.Seen && checksum.Seen)
6071 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6072 else if (checksumkind.Seen || checksum.Seen)
6073 return tokError("'checksumkind' and 'checksum' must be provided together");
6074
6075 MDString *Source = nullptr;
6076 if (source.Seen)
6077 Source = source.Val;
6079 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6080 return false;
6081}
6082
6083/// parseDICompileUnit:
6084/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6085/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6086/// splitDebugFilename: "abc.debug",
6087/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6088/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6089/// sysroot: "/", sdk: "MacOSX.sdk")
6090bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6091 if (!IsDistinct)
6092 return tokError("missing 'distinct', required for !DICompileUnit");
6093
6094 LocTy Loc = Lex.getLoc();
6095
6096#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6097 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6098 OPTIONAL(language, DwarfLangField, ); \
6099 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6100 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6101 OPTIONAL(producer, MDStringField, ); \
6102 OPTIONAL(isOptimized, MDBoolField, ); \
6103 OPTIONAL(flags, MDStringField, ); \
6104 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6105 OPTIONAL(splitDebugFilename, MDStringField, ); \
6106 OPTIONAL(emissionKind, EmissionKindField, ); \
6107 OPTIONAL(enums, MDField, ); \
6108 OPTIONAL(retainedTypes, MDField, ); \
6109 OPTIONAL(globals, MDField, ); \
6110 OPTIONAL(imports, MDField, ); \
6111 OPTIONAL(macros, MDField, ); \
6112 OPTIONAL(dwoId, MDUnsignedField, ); \
6113 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6114 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6115 OPTIONAL(nameTableKind, NameTableKindField, ); \
6116 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6117 OPTIONAL(sysroot, MDStringField, ); \
6118 OPTIONAL(sdk, MDStringField, );
6120#undef VISIT_MD_FIELDS
6121
6122 if (!language.Seen && !sourceLanguageName.Seen)
6123 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6124 "required for !DICompileUnit");
6125
6126 if (language.Seen && sourceLanguageName.Seen)
6127 return error(Loc, "can only specify one of 'language' and "
6128 "'sourceLanguageName' on !DICompileUnit");
6129
6130 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6131 return error(Loc, "'sourceLanguageVersion' requires an associated "
6132 "'sourceLanguageName' on !DICompileUnit");
6133
6135 Context,
6136 language.Seen ? DISourceLanguageName(language.Val)
6137 : DISourceLanguageName(sourceLanguageName.Val,
6138 sourceLanguageVersion.Val),
6139 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
6140 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
6141 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
6142 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
6143 sysroot.Val, sdk.Val);
6144 return false;
6145}
6146
6147/// parseDISubprogram:
6148/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6149/// file: !1, line: 7, type: !2, isLocal: false,
6150/// isDefinition: true, scopeLine: 8, containingType: !3,
6151/// virtuality: DW_VIRTUALTIY_pure_virtual,
6152/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6153/// spFlags: 10, isOptimized: false, templateParams: !4,
6154/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6155/// annotations: !8)
6156bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6157 auto Loc = Lex.getLoc();
6158#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6159 OPTIONAL(scope, MDField, ); \
6160 OPTIONAL(name, MDStringField, ); \
6161 OPTIONAL(linkageName, MDStringField, ); \
6162 OPTIONAL(file, MDField, ); \
6163 OPTIONAL(line, LineField, ); \
6164 OPTIONAL(type, MDField, ); \
6165 OPTIONAL(isLocal, MDBoolField, ); \
6166 OPTIONAL(isDefinition, MDBoolField, (true)); \
6167 OPTIONAL(scopeLine, LineField, ); \
6168 OPTIONAL(containingType, MDField, ); \
6169 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6170 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6171 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6172 OPTIONAL(flags, DIFlagField, ); \
6173 OPTIONAL(spFlags, DISPFlagField, ); \
6174 OPTIONAL(isOptimized, MDBoolField, ); \
6175 OPTIONAL(unit, MDField, ); \
6176 OPTIONAL(templateParams, MDField, ); \
6177 OPTIONAL(declaration, MDField, ); \
6178 OPTIONAL(retainedNodes, MDField, ); \
6179 OPTIONAL(thrownTypes, MDField, ); \
6180 OPTIONAL(annotations, MDField, ); \
6181 OPTIONAL(targetFuncName, MDStringField, ); \
6182 OPTIONAL(keyInstructions, MDBoolField, );
6184#undef VISIT_MD_FIELDS
6185
6186 // An explicit spFlags field takes precedence over individual fields in
6187 // older IR versions.
6188 DISubprogram::DISPFlags SPFlags =
6189 spFlags.Seen ? spFlags.Val
6190 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6191 isOptimized.Val, virtuality.Val);
6192 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6193 return error(
6194 Loc,
6195 "missing 'distinct', required for !DISubprogram that is a Definition");
6197 DISubprogram,
6198 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6199 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6200 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6201 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6202 targetFuncName.Val, keyInstructions.Val));
6203
6204 if (IsDistinct)
6205 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6206
6207 return false;
6208}
6209
6210/// parseDILexicalBlock:
6211/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6212bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6213#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6214 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6215 OPTIONAL(file, MDField, ); \
6216 OPTIONAL(line, LineField, ); \
6217 OPTIONAL(column, ColumnField, );
6219#undef VISIT_MD_FIELDS
6220
6222 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6223 return false;
6224}
6225
6226/// parseDILexicalBlockFile:
6227/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6228bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6229#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6230 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6231 OPTIONAL(file, MDField, ); \
6232 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6234#undef VISIT_MD_FIELDS
6235
6236 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6237 (Context, scope.Val, file.Val, discriminator.Val));
6238 return false;
6239}
6240
6241/// parseDICommonBlock:
6242/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6243bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6244#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6245 REQUIRED(scope, MDField, ); \
6246 OPTIONAL(declaration, MDField, ); \
6247 OPTIONAL(name, MDStringField, ); \
6248 OPTIONAL(file, MDField, ); \
6249 OPTIONAL(line, LineField, );
6251#undef VISIT_MD_FIELDS
6252
6253 Result = GET_OR_DISTINCT(DICommonBlock,
6254 (Context, scope.Val, declaration.Val, name.Val,
6255 file.Val, line.Val));
6256 return false;
6257}
6258
6259/// parseDINamespace:
6260/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6261bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6262#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6263 REQUIRED(scope, MDField, ); \
6264 OPTIONAL(name, MDStringField, ); \
6265 OPTIONAL(exportSymbols, MDBoolField, );
6267#undef VISIT_MD_FIELDS
6268
6269 Result = GET_OR_DISTINCT(DINamespace,
6270 (Context, scope.Val, name.Val, exportSymbols.Val));
6271 return false;
6272}
6273
6274/// parseDIMacro:
6275/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6276/// "SomeValue")
6277bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6278#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6279 REQUIRED(type, DwarfMacinfoTypeField, ); \
6280 OPTIONAL(line, LineField, ); \
6281 REQUIRED(name, MDStringField, ); \
6282 OPTIONAL(value, MDStringField, );
6284#undef VISIT_MD_FIELDS
6285
6286 Result = GET_OR_DISTINCT(DIMacro,
6287 (Context, type.Val, line.Val, name.Val, value.Val));
6288 return false;
6289}
6290
6291/// parseDIMacroFile:
6292/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6293bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6294#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6295 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6296 OPTIONAL(line, LineField, ); \
6297 REQUIRED(file, MDField, ); \
6298 OPTIONAL(nodes, MDField, );
6300#undef VISIT_MD_FIELDS
6301
6302 Result = GET_OR_DISTINCT(DIMacroFile,
6303 (Context, type.Val, line.Val, file.Val, nodes.Val));
6304 return false;
6305}
6306
6307/// parseDIModule:
6308/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6309/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6310/// file: !1, line: 4, isDecl: false)
6311bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6312#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6313 REQUIRED(scope, MDField, ); \
6314 REQUIRED(name, MDStringField, ); \
6315 OPTIONAL(configMacros, MDStringField, ); \
6316 OPTIONAL(includePath, MDStringField, ); \
6317 OPTIONAL(apinotes, MDStringField, ); \
6318 OPTIONAL(file, MDField, ); \
6319 OPTIONAL(line, LineField, ); \
6320 OPTIONAL(isDecl, MDBoolField, );
6322#undef VISIT_MD_FIELDS
6323
6324 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6325 configMacros.Val, includePath.Val,
6326 apinotes.Val, line.Val, isDecl.Val));
6327 return false;
6328}
6329
6330/// parseDITemplateTypeParameter:
6331/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6332bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6333#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6334 OPTIONAL(name, MDStringField, ); \
6335 REQUIRED(type, MDField, ); \
6336 OPTIONAL(defaulted, MDBoolField, );
6338#undef VISIT_MD_FIELDS
6339
6340 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6341 (Context, name.Val, type.Val, defaulted.Val));
6342 return false;
6343}
6344
6345/// parseDITemplateValueParameter:
6346/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6347/// name: "V", type: !1, defaulted: false,
6348/// value: i32 7)
6349bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6350#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6351 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6352 OPTIONAL(name, MDStringField, ); \
6353 OPTIONAL(type, MDField, ); \
6354 OPTIONAL(defaulted, MDBoolField, ); \
6355 REQUIRED(value, MDField, );
6356
6358#undef VISIT_MD_FIELDS
6359
6361 DITemplateValueParameter,
6362 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6363 return false;
6364}
6365
6366/// parseDIGlobalVariable:
6367/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6368/// file: !1, line: 7, type: !2, isLocal: false,
6369/// isDefinition: true, templateParams: !3,
6370/// declaration: !4, align: 8)
6371bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6372#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6373 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6374 OPTIONAL(scope, MDField, ); \
6375 OPTIONAL(linkageName, MDStringField, ); \
6376 OPTIONAL(file, MDField, ); \
6377 OPTIONAL(line, LineField, ); \
6378 OPTIONAL(type, MDField, ); \
6379 OPTIONAL(isLocal, MDBoolField, ); \
6380 OPTIONAL(isDefinition, MDBoolField, (true)); \
6381 OPTIONAL(templateParams, MDField, ); \
6382 OPTIONAL(declaration, MDField, ); \
6383 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6384 OPTIONAL(annotations, MDField, );
6386#undef VISIT_MD_FIELDS
6387
6388 Result =
6389 GET_OR_DISTINCT(DIGlobalVariable,
6390 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6391 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6392 declaration.Val, templateParams.Val, align.Val,
6393 annotations.Val));
6394 return false;
6395}
6396
6397/// parseDILocalVariable:
6398/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6399/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6400/// align: 8)
6401/// ::= !DILocalVariable(scope: !0, name: "foo",
6402/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6403/// align: 8)
6404bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6405#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6406 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6407 OPTIONAL(name, MDStringField, ); \
6408 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6409 OPTIONAL(file, MDField, ); \
6410 OPTIONAL(line, LineField, ); \
6411 OPTIONAL(type, MDField, ); \
6412 OPTIONAL(flags, DIFlagField, ); \
6413 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6414 OPTIONAL(annotations, MDField, );
6416#undef VISIT_MD_FIELDS
6417
6418 Result = GET_OR_DISTINCT(DILocalVariable,
6419 (Context, scope.Val, name.Val, file.Val, line.Val,
6420 type.Val, arg.Val, flags.Val, align.Val,
6421 annotations.Val));
6422 return false;
6423}
6424
6425/// parseDILabel:
6426/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6427bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6428#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6429 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6430 REQUIRED(name, MDStringField, ); \
6431 REQUIRED(file, MDField, ); \
6432 REQUIRED(line, LineField, ); \
6433 OPTIONAL(column, ColumnField, ); \
6434 OPTIONAL(isArtificial, MDBoolField, ); \
6435 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6437#undef VISIT_MD_FIELDS
6438
6439 std::optional<unsigned> CoroSuspendIdx =
6440 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6441 : std::nullopt;
6442
6443 Result = GET_OR_DISTINCT(DILabel,
6444 (Context, scope.Val, name.Val, file.Val, line.Val,
6445 column.Val, isArtificial.Val, CoroSuspendIdx));
6446 return false;
6447}
6448
6449/// parseDIExpressionBody:
6450/// ::= (0, 7, -1)
6451bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6452 if (parseToken(lltok::lparen, "expected '(' here"))
6453 return true;
6454
6455 SmallVector<uint64_t, 8> Elements;
6456 if (Lex.getKind() != lltok::rparen)
6457 do {
6458 if (Lex.getKind() == lltok::DwarfOp) {
6459 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6460 Lex.Lex();
6461 Elements.push_back(Op);
6462 continue;
6463 }
6464 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6465 }
6466
6467 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6468 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6469 Lex.Lex();
6470 Elements.push_back(Op);
6471 continue;
6472 }
6473 return tokError(Twine("invalid DWARF attribute encoding '") +
6474 Lex.getStrVal() + "'");
6475 }
6476
6477 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6478 return tokError("expected unsigned integer");
6479
6480 auto &U = Lex.getAPSIntVal();
6481 if (U.ugt(UINT64_MAX))
6482 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6483 Elements.push_back(U.getZExtValue());
6484 Lex.Lex();
6485 } while (EatIfPresent(lltok::comma));
6486
6487 if (parseToken(lltok::rparen, "expected ')' here"))
6488 return true;
6489
6490 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6491 return false;
6492}
6493
6494/// parseDIExpression:
6495/// ::= !DIExpression(0, 7, -1)
6496bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6497 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6498 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6499 Lex.Lex();
6500
6501 return parseDIExpressionBody(Result, IsDistinct);
6502}
6503
6504/// ParseDIArgList:
6505/// ::= !DIArgList(i32 7, i64 %0)
6506bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6507 assert(PFS && "Expected valid function state");
6508 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6509 Lex.Lex();
6510
6511 if (parseToken(lltok::lparen, "expected '(' here"))
6512 return true;
6513
6515 if (Lex.getKind() != lltok::rparen)
6516 do {
6517 Metadata *MD;
6518 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6519 return true;
6520 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6521 } while (EatIfPresent(lltok::comma));
6522
6523 if (parseToken(lltok::rparen, "expected ')' here"))
6524 return true;
6525
6526 MD = DIArgList::get(Context, Args);
6527 return false;
6528}
6529
6530/// parseDIGlobalVariableExpression:
6531/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6532bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6533 bool IsDistinct) {
6534#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6535 REQUIRED(var, MDField, ); \
6536 REQUIRED(expr, MDField, );
6538#undef VISIT_MD_FIELDS
6539
6540 Result =
6541 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6542 return false;
6543}
6544
6545/// parseDIObjCProperty:
6546/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6547/// getter: "getFoo", attributes: 7, type: !2)
6548bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6549#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6550 OPTIONAL(name, MDStringField, ); \
6551 OPTIONAL(file, MDField, ); \
6552 OPTIONAL(line, LineField, ); \
6553 OPTIONAL(setter, MDStringField, ); \
6554 OPTIONAL(getter, MDStringField, ); \
6555 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6556 OPTIONAL(type, MDField, );
6558#undef VISIT_MD_FIELDS
6559
6560 Result = GET_OR_DISTINCT(DIObjCProperty,
6561 (Context, name.Val, file.Val, line.Val, getter.Val,
6562 setter.Val, attributes.Val, type.Val));
6563 return false;
6564}
6565
6566/// parseDIImportedEntity:
6567/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6568/// line: 7, name: "foo", elements: !2)
6569bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6570#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6571 REQUIRED(tag, DwarfTagField, ); \
6572 REQUIRED(scope, MDField, ); \
6573 OPTIONAL(entity, MDField, ); \
6574 OPTIONAL(file, MDField, ); \
6575 OPTIONAL(line, LineField, ); \
6576 OPTIONAL(name, MDStringField, ); \
6577 OPTIONAL(elements, MDField, );
6579#undef VISIT_MD_FIELDS
6580
6581 Result = GET_OR_DISTINCT(DIImportedEntity,
6582 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6583 line.Val, name.Val, elements.Val));
6584 return false;
6585}
6586
6587#undef PARSE_MD_FIELD
6588#undef NOP_FIELD
6589#undef REQUIRE_FIELD
6590#undef DECLARE_FIELD
6591
6592/// parseMetadataAsValue
6593/// ::= metadata i32 %local
6594/// ::= metadata i32 @global
6595/// ::= metadata i32 7
6596/// ::= metadata !0
6597/// ::= metadata !{...}
6598/// ::= metadata !"string"
6599bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6600 // Note: the type 'metadata' has already been parsed.
6601 Metadata *MD;
6602 if (parseMetadata(MD, &PFS))
6603 return true;
6604
6605 V = MetadataAsValue::get(Context, MD);
6606 return false;
6607}
6608
6609/// parseValueAsMetadata
6610/// ::= i32 %local
6611/// ::= i32 @global
6612/// ::= i32 7
6613bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6614 PerFunctionState *PFS) {
6615 Type *Ty;
6616 LocTy Loc;
6617 if (parseType(Ty, TypeMsg, Loc))
6618 return true;
6619 if (Ty->isMetadataTy())
6620 return error(Loc, "invalid metadata-value-metadata roundtrip");
6621
6622 Value *V;
6623 if (parseValue(Ty, V, PFS))
6624 return true;
6625
6626 MD = ValueAsMetadata::get(V);
6627 return false;
6628}
6629
6630/// parseMetadata
6631/// ::= i32 %local
6632/// ::= i32 @global
6633/// ::= i32 7
6634/// ::= !42
6635/// ::= !{...}
6636/// ::= !"string"
6637/// ::= !DILocation(...)
6638bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6639 if (Lex.getKind() == lltok::MetadataVar) {
6640 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6641 // so parsing this requires a Function State.
6642 if (Lex.getStrVal() == "DIArgList") {
6643 Metadata *AL;
6644 if (parseDIArgList(AL, PFS))
6645 return true;
6646 MD = AL;
6647 return false;
6648 }
6649 MDNode *N;
6650 if (parseSpecializedMDNode(N)) {
6651 return true;
6652 }
6653 MD = N;
6654 return false;
6655 }
6656
6657 // ValueAsMetadata:
6658 // <type> <value>
6659 if (Lex.getKind() != lltok::exclaim)
6660 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6661
6662 // '!'.
6663 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6664 Lex.Lex();
6665
6666 // MDString:
6667 // ::= '!' STRINGCONSTANT
6668 if (Lex.getKind() == lltok::StringConstant) {
6669 MDString *S;
6670 if (parseMDString(S))
6671 return true;
6672 MD = S;
6673 return false;
6674 }
6675
6676 // MDNode:
6677 // !{ ... }
6678 // !7
6679 MDNode *N;
6680 if (parseMDNodeTail(N))
6681 return true;
6682 MD = N;
6683 return false;
6684}
6685
6686//===----------------------------------------------------------------------===//
6687// Function Parsing.
6688//===----------------------------------------------------------------------===//
6689
6690bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6691 PerFunctionState *PFS) {
6692 if (Ty->isFunctionTy())
6693 return error(ID.Loc, "functions are not values, refer to them as pointers");
6694
6695 switch (ID.Kind) {
6696 case ValID::t_LocalID:
6697 if (!PFS)
6698 return error(ID.Loc, "invalid use of function-local name");
6699 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6700 return V == nullptr;
6701 case ValID::t_LocalName:
6702 if (!PFS)
6703 return error(ID.Loc, "invalid use of function-local name");
6704 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6705 return V == nullptr;
6706 case ValID::t_InlineAsm: {
6707 if (!ID.FTy)
6708 return error(ID.Loc, "invalid type for inline asm constraint string");
6709 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6710 return error(ID.Loc, toString(std::move(Err)));
6711 V = InlineAsm::get(
6712 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6713 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6714 return false;
6715 }
6717 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6718 if (V && ID.NoCFI)
6720 return V == nullptr;
6721 case ValID::t_GlobalID:
6722 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6723 if (V && ID.NoCFI)
6725 return V == nullptr;
6726 case ValID::t_APSInt:
6727 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6728 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6729 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6730 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6731 : V = ConstantByte::get(Context, ID.APSIntVal);
6732 return false;
6733 case ValID::t_APFloat:
6734 if (!Ty->isFloatingPointTy() ||
6735 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6736 return error(ID.Loc, "floating point constant invalid for type");
6737
6738 // The lexer has no type info, so builds all half, bfloat, float, and double
6739 // FP constants as double. Fix this here. Long double does not need this.
6740 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6741 // Check for signaling before potentially converting and losing that info.
6742 bool IsSNAN = ID.APFloatVal.isSignaling();
6743 bool Ignored;
6744 if (Ty->isHalfTy())
6745 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6746 &Ignored);
6747 else if (Ty->isBFloatTy())
6748 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6749 &Ignored);
6750 else if (Ty->isFloatTy())
6751 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6752 &Ignored);
6753 if (IsSNAN) {
6754 // The convert call above may quiet an SNaN, so manufacture another
6755 // SNaN. The bitcast works because the payload (significand) parameter
6756 // is truncated to fit.
6757 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6758 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6759 ID.APFloatVal.isNegative(), &Payload);
6760 }
6761 }
6762 V = ConstantFP::get(Context, ID.APFloatVal);
6763
6764 if (V->getType() != Ty)
6765 return error(ID.Loc, "floating point constant does not have type '" +
6766 getTypeString(Ty) + "'");
6767
6768 return false;
6769 case ValID::t_Null:
6770 if (!Ty->isPointerTy())
6771 return error(ID.Loc, "null must be a pointer type");
6773 return false;
6774 case ValID::t_Undef:
6775 // FIXME: LabelTy should not be a first-class type.
6776 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6777 return error(ID.Loc, "invalid type for undef constant");
6778 V = UndefValue::get(Ty);
6779 return false;
6781 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6782 return error(ID.Loc, "invalid empty array initializer");
6783 V = PoisonValue::get(Ty);
6784 return false;
6785 case ValID::t_Zero:
6786 // FIXME: LabelTy should not be a first-class type.
6787 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6788 return error(ID.Loc, "invalid type for null constant");
6789 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6790 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6791 return error(ID.Loc, "invalid type for null constant");
6793 return false;
6794 case ValID::t_None:
6795 if (!Ty->isTokenTy())
6796 return error(ID.Loc, "invalid type for none constant");
6798 return false;
6799 case ValID::t_Poison:
6800 // FIXME: LabelTy should not be a first-class type.
6801 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6802 return error(ID.Loc, "invalid type for poison constant");
6803 V = PoisonValue::get(Ty);
6804 return false;
6805 case ValID::t_Constant:
6806 if (ID.ConstantVal->getType() != Ty)
6807 return error(ID.Loc, "constant expression type mismatch: got type '" +
6808 getTypeString(ID.ConstantVal->getType()) +
6809 "' but expected '" + getTypeString(Ty) + "'");
6810 V = ID.ConstantVal;
6811 return false;
6813 if (!Ty->isVectorTy())
6814 return error(ID.Loc, "vector constant must have vector type");
6815 if (ID.ConstantVal->getType() != Ty->getScalarType())
6816 return error(ID.Loc, "constant expression type mismatch: got type '" +
6817 getTypeString(ID.ConstantVal->getType()) +
6818 "' but expected '" +
6819 getTypeString(Ty->getScalarType()) + "'");
6820 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6821 ID.ConstantVal);
6822 return false;
6825 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6826 if (ST->getNumElements() != ID.UIntVal)
6827 return error(ID.Loc,
6828 "initializer with struct type has wrong # elements");
6829 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6830 return error(ID.Loc, "packed'ness of initializer and type don't match");
6831
6832 // Verify that the elements are compatible with the structtype.
6833 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6834 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6835 return error(
6836 ID.Loc,
6837 "element " + Twine(i) +
6838 " of struct initializer doesn't match struct element type");
6839
6841 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6842 } else
6843 return error(ID.Loc, "constant expression type mismatch");
6844 return false;
6845 }
6846 llvm_unreachable("Invalid ValID");
6847}
6848
6849bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6850 C = nullptr;
6851 ValID ID;
6852 auto Loc = Lex.getLoc();
6853 if (parseValID(ID, /*PFS=*/nullptr))
6854 return true;
6855 switch (ID.Kind) {
6856 case ValID::t_APSInt:
6857 case ValID::t_APFloat:
6858 case ValID::t_Undef:
6859 case ValID::t_Poison:
6860 case ValID::t_Zero:
6861 case ValID::t_Constant:
6865 Value *V;
6866 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6867 return true;
6868 assert(isa<Constant>(V) && "Expected a constant value");
6869 C = cast<Constant>(V);
6870 return false;
6871 }
6872 case ValID::t_Null:
6874 return false;
6875 default:
6876 return error(Loc, "expected a constant value");
6877 }
6878}
6879
6880bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6881 V = nullptr;
6882 ValID ID;
6883
6884 FileLoc Start = getTokLineColumnPos();
6885 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
6886 if (!Ret && ParserContext) {
6887 FileLoc End = getPrevTokEndLineColumnPos();
6888 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6889 }
6890 return Ret;
6891}
6892
6893bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6894 Type *Ty = nullptr;
6895 return parseType(Ty) || parseValue(Ty, V, PFS);
6896}
6897
6898bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6899 PerFunctionState &PFS) {
6900 Value *V;
6901 Loc = Lex.getLoc();
6902 if (parseTypeAndValue(V, PFS))
6903 return true;
6904 if (!isa<BasicBlock>(V))
6905 return error(Loc, "expected a basic block");
6906 BB = cast<BasicBlock>(V);
6907 return false;
6908}
6909
6911 // Exit early for the common (non-debug-intrinsic) case.
6912 // We can make this the only check when we begin supporting all "llvm.dbg"
6913 // intrinsics in the new debug info format.
6914 if (!Name.starts_with("llvm.dbg."))
6915 return false;
6917 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6918 FnID == Intrinsic::dbg_assign;
6919}
6920
6921/// FunctionHeader
6922/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6923/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6924/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6925/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6926bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6927 unsigned &FunctionNumber,
6928 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6929 // parse the linkage.
6930 LocTy LinkageLoc = Lex.getLoc();
6931 unsigned Linkage;
6932 unsigned Visibility;
6933 unsigned DLLStorageClass;
6934 bool DSOLocal;
6935 AttrBuilder RetAttrs(M->getContext());
6936 unsigned CC;
6937 bool HasLinkage;
6938 Type *RetType = nullptr;
6939 LocTy RetTypeLoc = Lex.getLoc();
6940 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6941 DSOLocal) ||
6942 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6943 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6944 return true;
6945
6946 // Verify that the linkage is ok.
6949 break; // always ok.
6951 if (IsDefine)
6952 return error(LinkageLoc, "invalid linkage for function definition");
6953 break;
6961 if (!IsDefine)
6962 return error(LinkageLoc, "invalid linkage for function declaration");
6963 break;
6966 return error(LinkageLoc, "invalid function linkage type");
6967 }
6968
6969 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6970 return error(LinkageLoc,
6971 "symbol with local linkage must have default visibility");
6972
6973 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6974 return error(LinkageLoc,
6975 "symbol with local linkage cannot have a DLL storage class");
6976
6977 if (!FunctionType::isValidReturnType(RetType))
6978 return error(RetTypeLoc, "invalid function return type");
6979
6980 LocTy NameLoc = Lex.getLoc();
6981
6982 std::string FunctionName;
6983 if (Lex.getKind() == lltok::GlobalVar) {
6984 FunctionName = Lex.getStrVal();
6985 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6986 FunctionNumber = Lex.getUIntVal();
6987 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6988 FunctionNumber))
6989 return true;
6990 } else {
6991 return tokError("expected function name");
6992 }
6993
6994 Lex.Lex();
6995
6996 if (Lex.getKind() != lltok::lparen)
6997 return tokError("expected '(' in function argument list");
6998
7000 bool IsVarArg;
7001 AttrBuilder FuncAttrs(M->getContext());
7002 std::vector<unsigned> FwdRefAttrGrps;
7003 LocTy BuiltinLoc;
7004 std::string Section;
7005 std::string Partition;
7006 MaybeAlign Alignment, PrefAlignment;
7007 std::string GC;
7009 unsigned AddrSpace = 0;
7010 Constant *Prefix = nullptr;
7011 Constant *Prologue = nullptr;
7012 Constant *PersonalityFn = nullptr;
7013 Comdat *C;
7014
7015 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7016 parseOptionalUnnamedAddr(UnnamedAddr) ||
7017 parseOptionalProgramAddrSpace(AddrSpace) ||
7018 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7019 BuiltinLoc) ||
7020 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7021 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7022 parseOptionalComdat(FunctionName, C) ||
7023 parseOptionalAlignment(Alignment) ||
7024 parseOptionalPrefAlignment(PrefAlignment) ||
7025 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7026 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7027 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7028 (EatIfPresent(lltok::kw_personality) &&
7029 parseGlobalTypeAndValue(PersonalityFn)))
7030 return true;
7031
7032 if (FuncAttrs.contains(Attribute::Builtin))
7033 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7034
7035 // If the alignment was parsed as an attribute, move to the alignment field.
7036 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7037 Alignment = A;
7038 FuncAttrs.removeAttribute(Attribute::Alignment);
7039 }
7040
7041 // Okay, if we got here, the function is syntactically valid. Convert types
7042 // and do semantic checks.
7043 std::vector<Type*> ParamTypeList;
7045
7046 for (const ArgInfo &Arg : ArgList) {
7047 ParamTypeList.push_back(Arg.Ty);
7048 Attrs.push_back(Arg.Attrs);
7049 }
7050
7051 AttributeList PAL =
7052 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7053 AttributeSet::get(Context, RetAttrs), Attrs);
7054
7055 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7056 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7057
7058 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7059 PointerType *PFT = PointerType::get(Context, AddrSpace);
7060
7061 Fn = nullptr;
7062 GlobalValue *FwdFn = nullptr;
7063 if (!FunctionName.empty()) {
7064 // If this was a definition of a forward reference, remove the definition
7065 // from the forward reference table and fill in the forward ref.
7066 auto FRVI = ForwardRefVals.find(FunctionName);
7067 if (FRVI != ForwardRefVals.end()) {
7068 FwdFn = FRVI->second.first;
7069 if (FwdFn->getType() != PFT)
7070 return error(FRVI->second.second,
7071 "invalid forward reference to "
7072 "function '" +
7073 FunctionName +
7074 "' with wrong type: "
7075 "expected '" +
7076 getTypeString(PFT) + "' but was '" +
7077 getTypeString(FwdFn->getType()) + "'");
7078 ForwardRefVals.erase(FRVI);
7079 } else if ((Fn = M->getFunction(FunctionName))) {
7080 // Reject redefinitions.
7081 return error(NameLoc,
7082 "invalid redefinition of function '" + FunctionName + "'");
7083 } else if (M->getNamedValue(FunctionName)) {
7084 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7085 }
7086
7087 } else {
7088 // Handle @"", where a name is syntactically specified, but semantically
7089 // missing.
7090 if (FunctionNumber == (unsigned)-1)
7091 FunctionNumber = NumberedVals.getNext();
7092
7093 // If this is a definition of a forward referenced function, make sure the
7094 // types agree.
7095 auto I = ForwardRefValIDs.find(FunctionNumber);
7096 if (I != ForwardRefValIDs.end()) {
7097 FwdFn = I->second.first;
7098 if (FwdFn->getType() != PFT)
7099 return error(NameLoc, "type of definition and forward reference of '@" +
7100 Twine(FunctionNumber) +
7101 "' disagree: "
7102 "expected '" +
7103 getTypeString(PFT) + "' but was '" +
7104 getTypeString(FwdFn->getType()) + "'");
7105 ForwardRefValIDs.erase(I);
7106 }
7107 }
7108
7110 FunctionName, M);
7111
7112 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7113
7114 if (FunctionName.empty())
7115 NumberedVals.add(FunctionNumber, Fn);
7116
7118 maybeSetDSOLocal(DSOLocal, *Fn);
7121 Fn->setCallingConv(CC);
7122 Fn->setAttributes(PAL);
7123 Fn->setUnnamedAddr(UnnamedAddr);
7124 if (Alignment)
7125 Fn->setAlignment(*Alignment);
7126 Fn->setPreferredAlignment(PrefAlignment);
7127 Fn->setSection(Section);
7128 Fn->setPartition(Partition);
7129 Fn->setComdat(C);
7130 Fn->setPersonalityFn(PersonalityFn);
7131 if (!GC.empty()) Fn->setGC(GC);
7132 Fn->setPrefixData(Prefix);
7133 Fn->setPrologueData(Prologue);
7134 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7135
7136 // Add all of the arguments we parsed to the function.
7137 Function::arg_iterator ArgIt = Fn->arg_begin();
7138 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7139 if (ParserContext && ArgList[i].IdentLoc)
7140 ParserContext->addInstructionOrArgumentLocation(
7141 &*ArgIt, ArgList[i].IdentLoc.value());
7142 // If the argument has a name, insert it into the argument symbol table.
7143 if (ArgList[i].Name.empty()) continue;
7144
7145 // Set the name, if it conflicted, it will be auto-renamed.
7146 ArgIt->setName(ArgList[i].Name);
7147
7148 if (ArgIt->getName() != ArgList[i].Name)
7149 return error(ArgList[i].Loc,
7150 "redefinition of argument '%" + ArgList[i].Name + "'");
7151 }
7152
7153 if (FwdFn) {
7154 FwdFn->replaceAllUsesWith(Fn);
7155 FwdFn->eraseFromParent();
7156 }
7157
7158 if (IsDefine)
7159 return false;
7160
7161 // Check the declaration has no block address forward references.
7162 ValID ID;
7163 if (FunctionName.empty()) {
7164 ID.Kind = ValID::t_GlobalID;
7165 ID.UIntVal = FunctionNumber;
7166 } else {
7167 ID.Kind = ValID::t_GlobalName;
7168 ID.StrVal = FunctionName;
7169 }
7170 auto Blocks = ForwardRefBlockAddresses.find(ID);
7171 if (Blocks != ForwardRefBlockAddresses.end())
7172 return error(Blocks->first.Loc,
7173 "cannot take blockaddress inside a declaration");
7174 return false;
7175}
7176
7177bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7178 ValID ID;
7179 if (FunctionNumber == -1) {
7180 ID.Kind = ValID::t_GlobalName;
7181 ID.StrVal = std::string(F.getName());
7182 } else {
7183 ID.Kind = ValID::t_GlobalID;
7184 ID.UIntVal = FunctionNumber;
7185 }
7186
7187 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7188 if (Blocks == P.ForwardRefBlockAddresses.end())
7189 return false;
7190
7191 for (const auto &I : Blocks->second) {
7192 const ValID &BBID = I.first;
7193 GlobalValue *GV = I.second;
7194
7195 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7196 "Expected local id or name");
7197 BasicBlock *BB;
7198 if (BBID.Kind == ValID::t_LocalName)
7199 BB = getBB(BBID.StrVal, BBID.Loc);
7200 else
7201 BB = getBB(BBID.UIntVal, BBID.Loc);
7202 if (!BB)
7203 return P.error(BBID.Loc, "referenced value is not a basic block");
7204
7205 Value *ResolvedVal = BlockAddress::get(&F, BB);
7206 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7207 ResolvedVal);
7208 if (!ResolvedVal)
7209 return true;
7210 GV->replaceAllUsesWith(ResolvedVal);
7211 GV->eraseFromParent();
7212 }
7213
7214 P.ForwardRefBlockAddresses.erase(Blocks);
7215 return false;
7216}
7217
7218/// parseFunctionBody
7219/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7220bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7221 ArrayRef<unsigned> UnnamedArgNums) {
7222 if (Lex.getKind() != lltok::lbrace)
7223 return tokError("expected '{' in function body");
7224 Lex.Lex(); // eat the {.
7225
7226 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7227
7228 // Resolve block addresses and allow basic blocks to be forward-declared
7229 // within this function.
7230 if (PFS.resolveForwardRefBlockAddresses())
7231 return true;
7232 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7233
7234 // We need at least one basic block.
7235 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7236 return tokError("function body requires at least one basic block");
7237
7238 while (Lex.getKind() != lltok::rbrace &&
7239 Lex.getKind() != lltok::kw_uselistorder)
7240 if (parseBasicBlock(PFS))
7241 return true;
7242
7243 while (Lex.getKind() != lltok::rbrace)
7244 if (parseUseListOrder(&PFS))
7245 return true;
7246
7247 // Eat the }.
7248 Lex.Lex();
7249
7250 // Verify function is ok.
7251 return PFS.finishFunction();
7252}
7253
7254/// parseBasicBlock
7255/// ::= (LabelStr|LabelID)? Instruction*
7256bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7257 FileLoc BBStart = getTokLineColumnPos();
7258
7259 // If this basic block starts out with a name, remember it.
7260 std::string Name;
7261 int NameID = -1;
7262 LocTy NameLoc = Lex.getLoc();
7263 if (Lex.getKind() == lltok::LabelStr) {
7264 Name = Lex.getStrVal();
7265 Lex.Lex();
7266 } else if (Lex.getKind() == lltok::LabelID) {
7267 NameID = Lex.getUIntVal();
7268 Lex.Lex();
7269 }
7270
7271 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7272 if (!BB)
7273 return true;
7274
7275 std::string NameStr;
7276
7277 // Parse the instructions and debug values in this block until we get a
7278 // terminator.
7279 Instruction *Inst;
7280 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7281 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7282 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7283 do {
7284 // Handle debug records first - there should always be an instruction
7285 // following the debug records, i.e. they cannot appear after the block
7286 // terminator.
7287 while (Lex.getKind() == lltok::hash) {
7288 if (SeenOldDbgInfoFormat)
7289 return error(Lex.getLoc(), "debug record should not appear in a module "
7290 "containing debug info intrinsics");
7291 SeenNewDbgInfoFormat = true;
7292 Lex.Lex();
7293
7294 DbgRecord *DR;
7295 if (parseDebugRecord(DR, PFS))
7296 return true;
7297 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7298 }
7299
7300 FileLoc InstStart = getTokLineColumnPos();
7301 // This instruction may have three possibilities for a name: a) none
7302 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7303 LocTy NameLoc = Lex.getLoc();
7304 int NameID = -1;
7305 NameStr = "";
7306
7307 if (Lex.getKind() == lltok::LocalVarID) {
7308 NameID = Lex.getUIntVal();
7309 Lex.Lex();
7310 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7311 return true;
7312 } else if (Lex.getKind() == lltok::LocalVar) {
7313 NameStr = Lex.getStrVal();
7314 Lex.Lex();
7315 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7316 return true;
7317 }
7318
7319 switch (parseInstruction(Inst, BB, PFS)) {
7320 default:
7321 llvm_unreachable("Unknown parseInstruction result!");
7322 case InstError: return true;
7323 case InstNormal:
7324 Inst->insertInto(BB, BB->end());
7325
7326 // With a normal result, we check to see if the instruction is followed by
7327 // a comma and metadata.
7328 if (EatIfPresent(lltok::comma))
7329 if (parseInstructionMetadata(*Inst))
7330 return true;
7331 break;
7332 case InstExtraComma:
7333 Inst->insertInto(BB, BB->end());
7334
7335 // If the instruction parser ate an extra comma at the end of it, it
7336 // *must* be followed by metadata.
7337 if (parseInstructionMetadata(*Inst))
7338 return true;
7339 break;
7340 }
7341
7342 // Set the name on the instruction.
7343 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7344 return true;
7345
7346 // Attach any preceding debug values to this instruction.
7347 for (DbgRecordPtr &DR : TrailingDbgRecord)
7348 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7349 TrailingDbgRecord.clear();
7350 if (ParserContext) {
7351 ParserContext->addInstructionOrArgumentLocation(
7352 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7353 }
7354 } while (!Inst->isTerminator());
7355
7356 if (ParserContext)
7357 ParserContext->addBlockLocation(
7358 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7359
7360 assert(TrailingDbgRecord.empty() &&
7361 "All debug values should have been attached to an instruction.");
7362
7363 return false;
7364}
7365
7366/// parseDebugRecord
7367/// ::= #dbg_label '(' MDNode ')'
7368/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7369/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7370bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7371 using RecordKind = DbgRecord::Kind;
7372 using LocType = DbgVariableRecord::LocationType;
7373 LocTy DVRLoc = Lex.getLoc();
7374 if (Lex.getKind() != lltok::DbgRecordType)
7375 return error(DVRLoc, "expected debug record type here");
7376 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7377 .Case("declare", RecordKind::ValueKind)
7378 .Case("value", RecordKind::ValueKind)
7379 .Case("assign", RecordKind::ValueKind)
7380 .Case("label", RecordKind::LabelKind)
7381 .Case("declare_value", RecordKind::ValueKind);
7382
7383 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7384 // full DbgVariableRecord processing stage.
7385 if (RecordType == RecordKind::LabelKind) {
7386 Lex.Lex();
7387 if (parseToken(lltok::lparen, "Expected '(' here"))
7388 return true;
7389 MDNode *Label;
7390 if (parseMDNode(Label))
7391 return true;
7392 if (parseToken(lltok::comma, "Expected ',' here"))
7393 return true;
7394 MDNode *DbgLoc;
7395 if (parseMDNode(DbgLoc))
7396 return true;
7397 if (parseToken(lltok::rparen, "Expected ')' here"))
7398 return true;
7400 return false;
7401 }
7402
7403 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7404 .Case("declare", LocType::Declare)
7405 .Case("value", LocType::Value)
7406 .Case("assign", LocType::Assign)
7407 .Case("declare_value", LocType::DeclareValue);
7408
7409 Lex.Lex();
7410 if (parseToken(lltok::lparen, "Expected '(' here"))
7411 return true;
7412
7413 // Parse Value field.
7414 Metadata *ValLocMD;
7415 if (parseMetadata(ValLocMD, &PFS))
7416 return true;
7417 if (parseToken(lltok::comma, "Expected ',' here"))
7418 return true;
7419
7420 // Parse Variable field.
7421 MDNode *Variable;
7422 if (parseMDNode(Variable))
7423 return true;
7424 if (parseToken(lltok::comma, "Expected ',' here"))
7425 return true;
7426
7427 // Parse Expression field.
7428 MDNode *Expression;
7429 if (parseMDNode(Expression))
7430 return true;
7431 if (parseToken(lltok::comma, "Expected ',' here"))
7432 return true;
7433
7434 // Parse additional fields for #dbg_assign.
7435 MDNode *AssignID = nullptr;
7436 Metadata *AddressLocation = nullptr;
7437 MDNode *AddressExpression = nullptr;
7438 if (ValueType == LocType::Assign) {
7439 // Parse DIAssignID.
7440 if (parseMDNode(AssignID))
7441 return true;
7442 if (parseToken(lltok::comma, "Expected ',' here"))
7443 return true;
7444
7445 // Parse address ValueAsMetadata.
7446 if (parseMetadata(AddressLocation, &PFS))
7447 return true;
7448 if (parseToken(lltok::comma, "Expected ',' here"))
7449 return true;
7450
7451 // Parse address DIExpression.
7452 if (parseMDNode(AddressExpression))
7453 return true;
7454 if (parseToken(lltok::comma, "Expected ',' here"))
7455 return true;
7456 }
7457
7458 /// Parse DILocation.
7459 MDNode *DebugLoc;
7460 if (parseMDNode(DebugLoc))
7461 return true;
7462
7463 if (parseToken(lltok::rparen, "Expected ')' here"))
7464 return true;
7466 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7467 AddressExpression, DebugLoc);
7468 return false;
7469}
7470//===----------------------------------------------------------------------===//
7471// Instruction Parsing.
7472//===----------------------------------------------------------------------===//
7473
7474/// parseInstruction - parse one of the many different instructions.
7475///
7476int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7477 PerFunctionState &PFS) {
7478 lltok::Kind Token = Lex.getKind();
7479 if (Token == lltok::Eof)
7480 return tokError("found end of file when expecting more instructions");
7481 LocTy Loc = Lex.getLoc();
7482 unsigned KeywordVal = Lex.getUIntVal();
7483 Lex.Lex(); // Eat the keyword.
7484
7485 switch (Token) {
7486 default:
7487 return error(Loc, "expected instruction opcode");
7488 // Terminator Instructions.
7489 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7490 case lltok::kw_ret:
7491 return parseRet(Inst, BB, PFS);
7492 case lltok::kw_br:
7493 return parseBr(Inst, PFS);
7494 case lltok::kw_switch:
7495 return parseSwitch(Inst, PFS);
7497 return parseIndirectBr(Inst, PFS);
7498 case lltok::kw_invoke:
7499 return parseInvoke(Inst, PFS);
7500 case lltok::kw_resume:
7501 return parseResume(Inst, PFS);
7503 return parseCleanupRet(Inst, PFS);
7504 case lltok::kw_catchret:
7505 return parseCatchRet(Inst, PFS);
7507 return parseCatchSwitch(Inst, PFS);
7508 case lltok::kw_catchpad:
7509 return parseCatchPad(Inst, PFS);
7511 return parseCleanupPad(Inst, PFS);
7512 case lltok::kw_callbr:
7513 return parseCallBr(Inst, PFS);
7514 // Unary Operators.
7515 case lltok::kw_fneg: {
7516 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7517 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7518 if (Res != 0)
7519 return Res;
7520 if (FMF.any())
7521 Inst->setFastMathFlags(FMF);
7522 return false;
7523 }
7524 // Binary Operators.
7525 case lltok::kw_add:
7526 case lltok::kw_sub:
7527 case lltok::kw_mul:
7528 case lltok::kw_shl: {
7529 bool NUW = EatIfPresent(lltok::kw_nuw);
7530 bool NSW = EatIfPresent(lltok::kw_nsw);
7531 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7532
7533 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7534 return true;
7535
7536 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7537 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7538 return false;
7539 }
7540 case lltok::kw_fadd:
7541 case lltok::kw_fsub:
7542 case lltok::kw_fmul:
7543 case lltok::kw_fdiv:
7544 case lltok::kw_frem: {
7545 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7546 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7547 if (Res != 0)
7548 return Res;
7549 if (FMF.any())
7550 Inst->setFastMathFlags(FMF);
7551 return 0;
7552 }
7553
7554 case lltok::kw_sdiv:
7555 case lltok::kw_udiv:
7556 case lltok::kw_lshr:
7557 case lltok::kw_ashr: {
7558 bool Exact = EatIfPresent(lltok::kw_exact);
7559
7560 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7561 return true;
7562 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7563 return false;
7564 }
7565
7566 case lltok::kw_urem:
7567 case lltok::kw_srem:
7568 return parseArithmetic(Inst, PFS, KeywordVal,
7569 /*IsFP*/ false);
7570 case lltok::kw_or: {
7571 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7572 if (parseLogical(Inst, PFS, KeywordVal))
7573 return true;
7574 if (Disjoint)
7575 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7576 return false;
7577 }
7578 case lltok::kw_and:
7579 case lltok::kw_xor:
7580 return parseLogical(Inst, PFS, KeywordVal);
7581 case lltok::kw_icmp: {
7582 bool SameSign = EatIfPresent(lltok::kw_samesign);
7583 if (parseCompare(Inst, PFS, KeywordVal))
7584 return true;
7585 if (SameSign)
7586 cast<ICmpInst>(Inst)->setSameSign();
7587 return false;
7588 }
7589 case lltok::kw_fcmp: {
7590 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7591 int Res = parseCompare(Inst, PFS, KeywordVal);
7592 if (Res != 0)
7593 return Res;
7594 if (FMF.any())
7595 Inst->setFastMathFlags(FMF);
7596 return 0;
7597 }
7598
7599 // Casts.
7600 case lltok::kw_uitofp:
7601 case lltok::kw_zext: {
7602 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7603 bool Res = parseCast(Inst, PFS, KeywordVal);
7604 if (Res != 0)
7605 return Res;
7606 if (NonNeg)
7607 Inst->setNonNeg();
7608 return 0;
7609 }
7610 case lltok::kw_trunc: {
7611 bool NUW = EatIfPresent(lltok::kw_nuw);
7612 bool NSW = EatIfPresent(lltok::kw_nsw);
7613 if (!NUW)
7614 NUW = EatIfPresent(lltok::kw_nuw);
7615 if (parseCast(Inst, PFS, KeywordVal))
7616 return true;
7617 if (NUW)
7618 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7619 if (NSW)
7620 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7621 return false;
7622 }
7623 case lltok::kw_sext:
7624 case lltok::kw_bitcast:
7626 case lltok::kw_sitofp:
7627 case lltok::kw_fptoui:
7628 case lltok::kw_fptosi:
7629 case lltok::kw_inttoptr:
7631 case lltok::kw_ptrtoint:
7632 return parseCast(Inst, PFS, KeywordVal);
7633 case lltok::kw_fptrunc:
7634 case lltok::kw_fpext: {
7635 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7636 if (parseCast(Inst, PFS, KeywordVal))
7637 return true;
7638 if (FMF.any())
7639 Inst->setFastMathFlags(FMF);
7640 return false;
7641 }
7642
7643 // Other.
7644 case lltok::kw_select: {
7645 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7646 int Res = parseSelect(Inst, PFS);
7647 if (Res != 0)
7648 return Res;
7649 if (FMF.any()) {
7650 if (!isa<FPMathOperator>(Inst))
7651 return error(Loc, "fast-math-flags specified for select without "
7652 "floating-point scalar or vector return type");
7653 Inst->setFastMathFlags(FMF);
7654 }
7655 return 0;
7656 }
7657 case lltok::kw_va_arg:
7658 return parseVAArg(Inst, PFS);
7660 return parseExtractElement(Inst, PFS);
7662 return parseInsertElement(Inst, PFS);
7664 return parseShuffleVector(Inst, PFS);
7665 case lltok::kw_phi: {
7666 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7667 int Res = parsePHI(Inst, PFS);
7668 if (Res != 0)
7669 return Res;
7670 if (FMF.any()) {
7671 if (!isa<FPMathOperator>(Inst))
7672 return error(Loc, "fast-math-flags specified for phi without "
7673 "floating-point scalar or vector return type");
7674 Inst->setFastMathFlags(FMF);
7675 }
7676 return 0;
7677 }
7679 return parseLandingPad(Inst, PFS);
7680 case lltok::kw_freeze:
7681 return parseFreeze(Inst, PFS);
7682 // Call.
7683 case lltok::kw_call:
7684 return parseCall(Inst, PFS, CallInst::TCK_None);
7685 case lltok::kw_tail:
7686 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7687 case lltok::kw_musttail:
7688 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7689 case lltok::kw_notail:
7690 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7691 // Memory.
7692 case lltok::kw_alloca:
7693 return parseAlloc(Inst, PFS);
7694 case lltok::kw_load:
7695 return parseLoad(Inst, PFS);
7696 case lltok::kw_store:
7697 return parseStore(Inst, PFS);
7698 case lltok::kw_cmpxchg:
7699 return parseCmpXchg(Inst, PFS);
7701 return parseAtomicRMW(Inst, PFS);
7702 case lltok::kw_fence:
7703 return parseFence(Inst, PFS);
7705 return parseGetElementPtr(Inst, PFS);
7707 return parseExtractValue(Inst, PFS);
7709 return parseInsertValue(Inst, PFS);
7710 }
7711}
7712
7713/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7714bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7715 if (Opc == Instruction::FCmp) {
7716 switch (Lex.getKind()) {
7717 default:
7718 return tokError("expected fcmp predicate (e.g. 'oeq')");
7719 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7720 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7721 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7722 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7723 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7724 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7725 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7726 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7727 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7728 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7729 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7730 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7731 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7732 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7733 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7734 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7735 }
7736 } else {
7737 switch (Lex.getKind()) {
7738 default:
7739 return tokError("expected icmp predicate (e.g. 'eq')");
7740 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7741 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7742 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7743 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7744 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7745 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7746 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7747 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7748 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7749 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7750 }
7751 }
7752 Lex.Lex();
7753 return false;
7754}
7755
7756//===----------------------------------------------------------------------===//
7757// Terminator Instructions.
7758//===----------------------------------------------------------------------===//
7759
7760/// parseRet - parse a return instruction.
7761/// ::= 'ret' void (',' !dbg, !1)*
7762/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7763bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7764 PerFunctionState &PFS) {
7765 SMLoc TypeLoc = Lex.getLoc();
7766 Type *Ty = nullptr;
7767 if (parseType(Ty, true /*void allowed*/))
7768 return true;
7769
7770 Type *ResType = PFS.getFunction().getReturnType();
7771
7772 if (Ty->isVoidTy()) {
7773 if (!ResType->isVoidTy())
7774 return error(TypeLoc, "value doesn't match function result type '" +
7775 getTypeString(ResType) + "'");
7776
7777 Inst = ReturnInst::Create(Context);
7778 return false;
7779 }
7780
7781 Value *RV;
7782 if (parseValue(Ty, RV, PFS))
7783 return true;
7784
7785 if (ResType != RV->getType())
7786 return error(TypeLoc, "value doesn't match function result type '" +
7787 getTypeString(ResType) + "'");
7788
7789 Inst = ReturnInst::Create(Context, RV);
7790 return false;
7791}
7792
7793/// parseBr
7794/// ::= 'br' TypeAndValue
7795/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7796bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7797 LocTy Loc, Loc2;
7798 Value *Op0;
7799 BasicBlock *Op1, *Op2;
7800 if (parseTypeAndValue(Op0, Loc, PFS))
7801 return true;
7802
7803 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7804 Inst = UncondBrInst::Create(BB);
7805 return false;
7806 }
7807
7808 if (Op0->getType() != Type::getInt1Ty(Context))
7809 return error(Loc, "branch condition must have 'i1' type");
7810
7811 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7812 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7813 parseToken(lltok::comma, "expected ',' after true destination") ||
7814 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7815 return true;
7816
7817 Inst = CondBrInst::Create(Op0, Op1, Op2);
7818 return false;
7819}
7820
7821/// parseSwitch
7822/// Instruction
7823/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7824/// JumpTable
7825/// ::= (TypeAndValue ',' TypeAndValue)*
7826bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7827 LocTy CondLoc, BBLoc;
7828 Value *Cond;
7829 BasicBlock *DefaultBB;
7830 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7831 parseToken(lltok::comma, "expected ',' after switch condition") ||
7832 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7833 parseToken(lltok::lsquare, "expected '[' with switch table"))
7834 return true;
7835
7836 if (!Cond->getType()->isIntegerTy())
7837 return error(CondLoc, "switch condition must have integer type");
7838
7839 // parse the jump table pairs.
7840 SmallPtrSet<Value*, 32> SeenCases;
7842 while (Lex.getKind() != lltok::rsquare) {
7843 Value *Constant;
7844 BasicBlock *DestBB;
7845
7846 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7847 parseToken(lltok::comma, "expected ',' after case value") ||
7848 parseTypeAndBasicBlock(DestBB, PFS))
7849 return true;
7850
7851 if (!SeenCases.insert(Constant).second)
7852 return error(CondLoc, "duplicate case value in switch");
7853 if (!isa<ConstantInt>(Constant))
7854 return error(CondLoc, "case value is not a constant integer");
7855
7856 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7857 }
7858
7859 Lex.Lex(); // Eat the ']'.
7860
7861 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7862 for (const auto &[OnVal, Dest] : Table)
7863 SI->addCase(OnVal, Dest);
7864 Inst = SI;
7865 return false;
7866}
7867
7868/// parseIndirectBr
7869/// Instruction
7870/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7871bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7872 LocTy AddrLoc;
7873 Value *Address;
7874 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7875 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7876 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7877 return true;
7878
7879 if (!Address->getType()->isPointerTy())
7880 return error(AddrLoc, "indirectbr address must have pointer type");
7881
7882 // parse the destination list.
7883 SmallVector<BasicBlock*, 16> DestList;
7884
7885 if (Lex.getKind() != lltok::rsquare) {
7886 BasicBlock *DestBB;
7887 if (parseTypeAndBasicBlock(DestBB, PFS))
7888 return true;
7889 DestList.push_back(DestBB);
7890
7891 while (EatIfPresent(lltok::comma)) {
7892 if (parseTypeAndBasicBlock(DestBB, PFS))
7893 return true;
7894 DestList.push_back(DestBB);
7895 }
7896 }
7897
7898 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7899 return true;
7900
7901 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7902 for (BasicBlock *Dest : DestList)
7903 IBI->addDestination(Dest);
7904 Inst = IBI;
7905 return false;
7906}
7907
7908// If RetType is a non-function pointer type, then this is the short syntax
7909// for the call, which means that RetType is just the return type. Infer the
7910// rest of the function argument types from the arguments that are present.
7911bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7912 FunctionType *&FuncTy) {
7913 FuncTy = dyn_cast<FunctionType>(RetType);
7914 if (!FuncTy) {
7915 // Pull out the types of all of the arguments...
7916 SmallVector<Type *, 8> ParamTypes;
7917 ParamTypes.reserve(ArgList.size());
7918 for (const ParamInfo &Arg : ArgList)
7919 ParamTypes.push_back(Arg.V->getType());
7920
7921 if (!FunctionType::isValidReturnType(RetType))
7922 return true;
7923
7924 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7925 }
7926 return false;
7927}
7928
7929/// parseInvoke
7930/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7931/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7932bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7933 LocTy CallLoc = Lex.getLoc();
7934 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7935 std::vector<unsigned> FwdRefAttrGrps;
7936 LocTy NoBuiltinLoc;
7937 unsigned CC;
7938 unsigned InvokeAddrSpace;
7939 Type *RetType = nullptr;
7940 LocTy RetTypeLoc;
7941 ValID CalleeID;
7944
7945 BasicBlock *NormalBB, *UnwindBB;
7946 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7947 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7948 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7949 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7950 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7951 NoBuiltinLoc) ||
7952 parseOptionalOperandBundles(BundleList, PFS) ||
7953 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7954 parseTypeAndBasicBlock(NormalBB, PFS) ||
7955 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7956 parseTypeAndBasicBlock(UnwindBB, PFS))
7957 return true;
7958
7959 // If RetType is a non-function pointer type, then this is the short syntax
7960 // for the call, which means that RetType is just the return type. Infer the
7961 // rest of the function argument types from the arguments that are present.
7962 FunctionType *Ty;
7963 if (resolveFunctionType(RetType, ArgList, Ty))
7964 return error(RetTypeLoc, "Invalid result type for LLVM function");
7965
7966 CalleeID.FTy = Ty;
7967
7968 // Look up the callee.
7969 Value *Callee;
7970 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7971 Callee, &PFS))
7972 return true;
7973
7974 // Set up the Attribute for the function.
7975 SmallVector<Value *, 8> Args;
7977
7978 // Loop through FunctionType's arguments and ensure they are specified
7979 // correctly. Also, gather any parameter attributes.
7980 FunctionType::param_iterator I = Ty->param_begin();
7981 FunctionType::param_iterator E = Ty->param_end();
7982 for (const ParamInfo &Arg : ArgList) {
7983 Type *ExpectedTy = nullptr;
7984 if (I != E) {
7985 ExpectedTy = *I++;
7986 } else if (!Ty->isVarArg()) {
7987 return error(Arg.Loc, "too many arguments specified");
7988 }
7989
7990 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7991 return error(Arg.Loc, "argument is not of expected type '" +
7992 getTypeString(ExpectedTy) + "'");
7993 Args.push_back(Arg.V);
7994 ArgAttrs.push_back(Arg.Attrs);
7995 }
7996
7997 if (I != E)
7998 return error(CallLoc, "not enough parameters specified for call");
7999
8000 // Finish off the Attribute and check them
8001 AttributeList PAL =
8002 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8003 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8004
8005 InvokeInst *II =
8006 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8007 II->setCallingConv(CC);
8008 II->setAttributes(PAL);
8009 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8010 Inst = II;
8011 return false;
8012}
8013
8014/// parseResume
8015/// ::= 'resume' TypeAndValue
8016bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8017 Value *Exn; LocTy ExnLoc;
8018 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8019 return true;
8020
8021 ResumeInst *RI = ResumeInst::Create(Exn);
8022 Inst = RI;
8023 return false;
8024}
8025
8026bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8027 PerFunctionState &PFS) {
8028 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8029 return true;
8030
8031 while (Lex.getKind() != lltok::rsquare) {
8032 // If this isn't the first argument, we need a comma.
8033 if (!Args.empty() &&
8034 parseToken(lltok::comma, "expected ',' in argument list"))
8035 return true;
8036
8037 // parse the argument.
8038 LocTy ArgLoc;
8039 Type *ArgTy = nullptr;
8040 if (parseType(ArgTy, ArgLoc))
8041 return true;
8042
8043 Value *V;
8044 if (ArgTy->isMetadataTy()) {
8045 if (parseMetadataAsValue(V, PFS))
8046 return true;
8047 } else {
8048 if (parseValue(ArgTy, V, PFS))
8049 return true;
8050 }
8051 Args.push_back(V);
8052 }
8053
8054 Lex.Lex(); // Lex the ']'.
8055 return false;
8056}
8057
8058/// parseCleanupRet
8059/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8060bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8061 Value *CleanupPad = nullptr;
8062
8063 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8064 return true;
8065
8066 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8067 return true;
8068
8069 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8070 return true;
8071
8072 BasicBlock *UnwindBB = nullptr;
8073 if (Lex.getKind() == lltok::kw_to) {
8074 Lex.Lex();
8075 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8076 return true;
8077 } else {
8078 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8079 return true;
8080 }
8081 }
8082
8083 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8084 return false;
8085}
8086
8087/// parseCatchRet
8088/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8089bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8090 Value *CatchPad = nullptr;
8091
8092 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8093 return true;
8094
8095 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8096 return true;
8097
8098 BasicBlock *BB;
8099 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8100 parseTypeAndBasicBlock(BB, PFS))
8101 return true;
8102
8103 Inst = CatchReturnInst::Create(CatchPad, BB);
8104 return false;
8105}
8106
8107/// parseCatchSwitch
8108/// ::= 'catchswitch' within Parent
8109bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8110 Value *ParentPad;
8111
8112 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8113 return true;
8114
8115 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8116 Lex.getKind() != lltok::LocalVarID)
8117 return tokError("expected scope value for catchswitch");
8118
8119 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8120 return true;
8121
8122 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8123 return true;
8124
8126 do {
8127 BasicBlock *DestBB;
8128 if (parseTypeAndBasicBlock(DestBB, PFS))
8129 return true;
8130 Table.push_back(DestBB);
8131 } while (EatIfPresent(lltok::comma));
8132
8133 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8134 return true;
8135
8136 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8137 return true;
8138
8139 BasicBlock *UnwindBB = nullptr;
8140 if (EatIfPresent(lltok::kw_to)) {
8141 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8142 return true;
8143 } else {
8144 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8145 return true;
8146 }
8147
8148 auto *CatchSwitch =
8149 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8150 for (BasicBlock *DestBB : Table)
8151 CatchSwitch->addHandler(DestBB);
8152 Inst = CatchSwitch;
8153 return false;
8154}
8155
8156/// parseCatchPad
8157/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8158bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8159 Value *CatchSwitch = nullptr;
8160
8161 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8162 return true;
8163
8164 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8165 return tokError("expected scope value for catchpad");
8166
8167 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8168 return true;
8169
8170 SmallVector<Value *, 8> Args;
8171 if (parseExceptionArgs(Args, PFS))
8172 return true;
8173
8174 Inst = CatchPadInst::Create(CatchSwitch, Args);
8175 return false;
8176}
8177
8178/// parseCleanupPad
8179/// ::= 'cleanuppad' within Parent ParamList
8180bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8181 Value *ParentPad = nullptr;
8182
8183 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8184 return true;
8185
8186 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8187 Lex.getKind() != lltok::LocalVarID)
8188 return tokError("expected scope value for cleanuppad");
8189
8190 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8191 return true;
8192
8193 SmallVector<Value *, 8> Args;
8194 if (parseExceptionArgs(Args, PFS))
8195 return true;
8196
8197 Inst = CleanupPadInst::Create(ParentPad, Args);
8198 return false;
8199}
8200
8201//===----------------------------------------------------------------------===//
8202// Unary Operators.
8203//===----------------------------------------------------------------------===//
8204
8205/// parseUnaryOp
8206/// ::= UnaryOp TypeAndValue ',' Value
8207///
8208/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8209/// operand is allowed.
8210bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8211 unsigned Opc, bool IsFP) {
8212 LocTy Loc; Value *LHS;
8213 if (parseTypeAndValue(LHS, Loc, PFS))
8214 return true;
8215
8216 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8218
8219 if (!Valid)
8220 return error(Loc, "invalid operand type for instruction");
8221
8223 return false;
8224}
8225
8226/// parseCallBr
8227/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8228/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8229/// '[' LabelList ']'
8230bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8231 LocTy CallLoc = Lex.getLoc();
8232 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8233 std::vector<unsigned> FwdRefAttrGrps;
8234 LocTy NoBuiltinLoc;
8235 unsigned CC;
8236 Type *RetType = nullptr;
8237 LocTy RetTypeLoc;
8238 ValID CalleeID;
8241
8242 BasicBlock *DefaultDest;
8243 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8244 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8245 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8246 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8247 NoBuiltinLoc) ||
8248 parseOptionalOperandBundles(BundleList, PFS) ||
8249 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8250 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8251 parseToken(lltok::lsquare, "expected '[' in callbr"))
8252 return true;
8253
8254 // parse the destination list.
8255 SmallVector<BasicBlock *, 16> IndirectDests;
8256
8257 if (Lex.getKind() != lltok::rsquare) {
8258 BasicBlock *DestBB;
8259 if (parseTypeAndBasicBlock(DestBB, PFS))
8260 return true;
8261 IndirectDests.push_back(DestBB);
8262
8263 while (EatIfPresent(lltok::comma)) {
8264 if (parseTypeAndBasicBlock(DestBB, PFS))
8265 return true;
8266 IndirectDests.push_back(DestBB);
8267 }
8268 }
8269
8270 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8271 return true;
8272
8273 // If RetType is a non-function pointer type, then this is the short syntax
8274 // for the call, which means that RetType is just the return type. Infer the
8275 // rest of the function argument types from the arguments that are present.
8276 FunctionType *Ty;
8277 if (resolveFunctionType(RetType, ArgList, Ty))
8278 return error(RetTypeLoc, "Invalid result type for LLVM function");
8279
8280 CalleeID.FTy = Ty;
8281
8282 // Look up the callee.
8283 Value *Callee;
8284 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8285 &PFS))
8286 return true;
8287
8288 // Set up the Attribute for the function.
8289 SmallVector<Value *, 8> Args;
8291
8292 // Loop through FunctionType's arguments and ensure they are specified
8293 // correctly. Also, gather any parameter attributes.
8294 FunctionType::param_iterator I = Ty->param_begin();
8295 FunctionType::param_iterator E = Ty->param_end();
8296 for (const ParamInfo &Arg : ArgList) {
8297 Type *ExpectedTy = nullptr;
8298 if (I != E) {
8299 ExpectedTy = *I++;
8300 } else if (!Ty->isVarArg()) {
8301 return error(Arg.Loc, "too many arguments specified");
8302 }
8303
8304 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8305 return error(Arg.Loc, "argument is not of expected type '" +
8306 getTypeString(ExpectedTy) + "'");
8307 Args.push_back(Arg.V);
8308 ArgAttrs.push_back(Arg.Attrs);
8309 }
8310
8311 if (I != E)
8312 return error(CallLoc, "not enough parameters specified for call");
8313
8314 // Finish off the Attribute and check them
8315 AttributeList PAL =
8316 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8317 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8318
8319 CallBrInst *CBI =
8320 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8321 BundleList);
8322 CBI->setCallingConv(CC);
8323 CBI->setAttributes(PAL);
8324 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8325 Inst = CBI;
8326 return false;
8327}
8328
8329//===----------------------------------------------------------------------===//
8330// Binary Operators.
8331//===----------------------------------------------------------------------===//
8332
8333/// parseArithmetic
8334/// ::= ArithmeticOps TypeAndValue ',' Value
8335///
8336/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8337/// operand is allowed.
8338bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8339 unsigned Opc, bool IsFP) {
8340 LocTy Loc; Value *LHS, *RHS;
8341 if (parseTypeAndValue(LHS, Loc, PFS) ||
8342 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8343 parseValue(LHS->getType(), RHS, PFS))
8344 return true;
8345
8346 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8348
8349 if (!Valid)
8350 return error(Loc, "invalid operand type for instruction");
8351
8353 return false;
8354}
8355
8356/// parseLogical
8357/// ::= ArithmeticOps TypeAndValue ',' Value {
8358bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8359 unsigned Opc) {
8360 LocTy Loc; Value *LHS, *RHS;
8361 if (parseTypeAndValue(LHS, Loc, PFS) ||
8362 parseToken(lltok::comma, "expected ',' in logical operation") ||
8363 parseValue(LHS->getType(), RHS, PFS))
8364 return true;
8365
8366 if (!LHS->getType()->isIntOrIntVectorTy())
8367 return error(Loc,
8368 "instruction requires integer or integer vector operands");
8369
8371 return false;
8372}
8373
8374/// parseCompare
8375/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8376/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8377bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8378 unsigned Opc) {
8379 // parse the integer/fp comparison predicate.
8380 LocTy Loc;
8381 unsigned Pred;
8382 Value *LHS, *RHS;
8383 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8384 parseToken(lltok::comma, "expected ',' after compare value") ||
8385 parseValue(LHS->getType(), RHS, PFS))
8386 return true;
8387
8388 if (Opc == Instruction::FCmp) {
8389 if (!LHS->getType()->isFPOrFPVectorTy())
8390 return error(Loc, "fcmp requires floating point operands");
8391 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8392 } else {
8393 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8394 if (!LHS->getType()->isIntOrIntVectorTy() &&
8396 return error(Loc, "icmp requires integer operands");
8397 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8398 }
8399 return false;
8400}
8401
8402//===----------------------------------------------------------------------===//
8403// Other Instructions.
8404//===----------------------------------------------------------------------===//
8405
8406/// parseCast
8407/// ::= CastOpc TypeAndValue 'to' Type
8408bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8409 unsigned Opc) {
8410 LocTy Loc;
8411 Value *Op;
8412 Type *DestTy = nullptr;
8413 if (parseTypeAndValue(Op, Loc, PFS) ||
8414 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8415 parseType(DestTy))
8416 return true;
8417
8419 return error(Loc, "invalid cast opcode for cast from '" +
8420 getTypeString(Op->getType()) + "' to '" +
8421 getTypeString(DestTy) + "'");
8422 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8423 return false;
8424}
8425
8426/// parseSelect
8427/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8428bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8429 LocTy Loc;
8430 Value *Op0, *Op1, *Op2;
8431 if (parseTypeAndValue(Op0, Loc, PFS) ||
8432 parseToken(lltok::comma, "expected ',' after select condition") ||
8433 parseTypeAndValue(Op1, PFS) ||
8434 parseToken(lltok::comma, "expected ',' after select value") ||
8435 parseTypeAndValue(Op2, PFS))
8436 return true;
8437
8438 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8439 return error(Loc, Reason);
8440
8441 Inst = SelectInst::Create(Op0, Op1, Op2);
8442 return false;
8443}
8444
8445/// parseVAArg
8446/// ::= 'va_arg' TypeAndValue ',' Type
8447bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8448 Value *Op;
8449 Type *EltTy = nullptr;
8450 LocTy TypeLoc;
8451 if (parseTypeAndValue(Op, PFS) ||
8452 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8453 parseType(EltTy, TypeLoc))
8454 return true;
8455
8456 if (!EltTy->isFirstClassType())
8457 return error(TypeLoc, "va_arg requires operand with first class type");
8458
8459 Inst = new VAArgInst(Op, EltTy);
8460 return false;
8461}
8462
8463/// parseExtractElement
8464/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8465bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8466 LocTy Loc;
8467 Value *Op0, *Op1;
8468 if (parseTypeAndValue(Op0, Loc, PFS) ||
8469 parseToken(lltok::comma, "expected ',' after extract value") ||
8470 parseTypeAndValue(Op1, PFS))
8471 return true;
8472
8474 return error(Loc, "invalid extractelement operands");
8475
8476 Inst = ExtractElementInst::Create(Op0, Op1);
8477 return false;
8478}
8479
8480/// parseInsertElement
8481/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8482bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8483 LocTy Loc;
8484 Value *Op0, *Op1, *Op2;
8485 if (parseTypeAndValue(Op0, Loc, PFS) ||
8486 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8487 parseTypeAndValue(Op1, PFS) ||
8488 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8489 parseTypeAndValue(Op2, PFS))
8490 return true;
8491
8492 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8493 return error(Loc, "invalid insertelement operands");
8494
8495 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8496 return false;
8497}
8498
8499/// parseShuffleVector
8500/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8501bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8502 LocTy Loc;
8503 Value *Op0, *Op1, *Op2;
8504 if (parseTypeAndValue(Op0, Loc, PFS) ||
8505 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8506 parseTypeAndValue(Op1, PFS) ||
8507 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8508 parseTypeAndValue(Op2, PFS))
8509 return true;
8510
8511 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8512 return error(Loc, "invalid shufflevector operands");
8513
8514 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8515 return false;
8516}
8517
8518/// parsePHI
8519/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8520int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8521 Type *Ty = nullptr; LocTy TypeLoc;
8522 Value *Op0, *Op1;
8523
8524 if (parseType(Ty, TypeLoc))
8525 return true;
8526
8527 if (!Ty->isFirstClassType())
8528 return error(TypeLoc, "phi node must have first class type");
8529
8530 bool First = true;
8531 bool AteExtraComma = false;
8533
8534 while (true) {
8535 if (First) {
8536 if (Lex.getKind() != lltok::lsquare)
8537 break;
8538 First = false;
8539 } else if (!EatIfPresent(lltok::comma))
8540 break;
8541
8542 if (Lex.getKind() == lltok::MetadataVar) {
8543 AteExtraComma = true;
8544 break;
8545 }
8546
8547 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8548 parseValue(Ty, Op0, PFS) ||
8549 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8550 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8551 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8552 return true;
8553
8554 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8555 }
8556
8557 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8558 for (const auto &[Val, BB] : PHIVals)
8559 PN->addIncoming(Val, BB);
8560 Inst = PN;
8561 return AteExtraComma ? InstExtraComma : InstNormal;
8562}
8563
8564/// parseLandingPad
8565/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8566/// Clause
8567/// ::= 'catch' TypeAndValue
8568/// ::= 'filter'
8569/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8570bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8571 Type *Ty = nullptr; LocTy TyLoc;
8572
8573 if (parseType(Ty, TyLoc))
8574 return true;
8575
8576 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8577 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8578
8579 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8581 if (EatIfPresent(lltok::kw_catch))
8583 else if (EatIfPresent(lltok::kw_filter))
8585 else
8586 return tokError("expected 'catch' or 'filter' clause type");
8587
8588 Value *V;
8589 LocTy VLoc;
8590 if (parseTypeAndValue(V, VLoc, PFS))
8591 return true;
8592
8593 // A 'catch' type expects a non-array constant. A filter clause expects an
8594 // array constant.
8595 if (CT == LandingPadInst::Catch) {
8596 if (isa<ArrayType>(V->getType()))
8597 return error(VLoc, "'catch' clause has an invalid type");
8598 } else {
8599 if (!isa<ArrayType>(V->getType()))
8600 return error(VLoc, "'filter' clause has an invalid type");
8601 }
8602
8604 if (!CV)
8605 return error(VLoc, "clause argument must be a constant");
8606 LP->addClause(CV);
8607 }
8608
8609 Inst = LP.release();
8610 return false;
8611}
8612
8613/// parseFreeze
8614/// ::= 'freeze' Type Value
8615bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8616 LocTy Loc;
8617 Value *Op;
8618 if (parseTypeAndValue(Op, Loc, PFS))
8619 return true;
8620
8621 Inst = new FreezeInst(Op);
8622 return false;
8623}
8624
8625/// parseCall
8626/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8627/// OptionalAttrs Type Value ParameterList OptionalAttrs
8628/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8629/// OptionalAttrs Type Value ParameterList OptionalAttrs
8630/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8631/// OptionalAttrs Type Value ParameterList OptionalAttrs
8632/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8633/// OptionalAttrs Type Value ParameterList OptionalAttrs
8634bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8636 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8637 std::vector<unsigned> FwdRefAttrGrps;
8638 LocTy BuiltinLoc;
8639 unsigned CallAddrSpace;
8640 unsigned CC;
8641 Type *RetType = nullptr;
8642 LocTy RetTypeLoc;
8643 ValID CalleeID;
8646 LocTy CallLoc = Lex.getLoc();
8647
8648 if (TCK != CallInst::TCK_None &&
8649 parseToken(lltok::kw_call,
8650 "expected 'tail call', 'musttail call', or 'notail call'"))
8651 return true;
8652
8653 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8654
8655 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8656 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8657 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8658 parseValID(CalleeID, &PFS) ||
8659 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8660 PFS.getFunction().isVarArg()) ||
8661 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8662 parseOptionalOperandBundles(BundleList, PFS))
8663 return true;
8664
8665 // If RetType is a non-function pointer type, then this is the short syntax
8666 // for the call, which means that RetType is just the return type. Infer the
8667 // rest of the function argument types from the arguments that are present.
8668 FunctionType *Ty;
8669 if (resolveFunctionType(RetType, ArgList, Ty))
8670 return error(RetTypeLoc, "Invalid result type for LLVM function");
8671
8672 CalleeID.FTy = Ty;
8673
8674 // Look up the callee.
8675 Value *Callee;
8676 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8677 Callee, &PFS))
8678 return true;
8679
8680 // Set up the Attribute for the function.
8682
8683 SmallVector<Value*, 8> Args;
8684
8685 // Loop through FunctionType's arguments and ensure they are specified
8686 // correctly. Also, gather any parameter attributes.
8687 FunctionType::param_iterator I = Ty->param_begin();
8688 FunctionType::param_iterator E = Ty->param_end();
8689 for (const ParamInfo &Arg : ArgList) {
8690 Type *ExpectedTy = nullptr;
8691 if (I != E) {
8692 ExpectedTy = *I++;
8693 } else if (!Ty->isVarArg()) {
8694 return error(Arg.Loc, "too many arguments specified");
8695 }
8696
8697 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8698 return error(Arg.Loc, "argument is not of expected type '" +
8699 getTypeString(ExpectedTy) + "'");
8700 Args.push_back(Arg.V);
8701 Attrs.push_back(Arg.Attrs);
8702 }
8703
8704 if (I != E)
8705 return error(CallLoc, "not enough parameters specified for call");
8706
8707 // Finish off the Attribute and check them
8708 AttributeList PAL =
8709 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8710 AttributeSet::get(Context, RetAttrs), Attrs);
8711
8712 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8713 CI->setTailCallKind(TCK);
8714 CI->setCallingConv(CC);
8715 if (FMF.any()) {
8716 if (!isa<FPMathOperator>(CI)) {
8717 CI->deleteValue();
8718 return error(CallLoc, "fast-math-flags specified for call without "
8719 "floating-point scalar or vector return type");
8720 }
8721 CI->setFastMathFlags(FMF);
8722 }
8723
8724 if (CalleeID.Kind == ValID::t_GlobalName &&
8725 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8726 if (SeenNewDbgInfoFormat) {
8727 CI->deleteValue();
8728 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8729 "using non-intrinsic debug info");
8730 }
8731 SeenOldDbgInfoFormat = true;
8732 }
8733 CI->setAttributes(PAL);
8734 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8735 Inst = CI;
8736 return false;
8737}
8738
8739//===----------------------------------------------------------------------===//
8740// Memory Instructions.
8741//===----------------------------------------------------------------------===//
8742
8743/// parseAlloc
8744/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8745/// (',' 'align' i32)? (',', 'addrspace(n))?
8746int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8747 Value *Size = nullptr;
8748 LocTy SizeLoc, TyLoc, ASLoc;
8749 MaybeAlign Alignment;
8750 unsigned AddrSpace = 0;
8751 Type *Ty = nullptr;
8752
8753 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8754 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8755
8756 if (parseType(Ty, TyLoc))
8757 return true;
8758
8760 return error(TyLoc, "invalid type for alloca");
8761
8762 bool AteExtraComma = false;
8763 if (EatIfPresent(lltok::comma)) {
8764 if (Lex.getKind() == lltok::kw_align) {
8765 if (parseOptionalAlignment(Alignment))
8766 return true;
8767 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8768 return true;
8769 } else if (Lex.getKind() == lltok::kw_addrspace) {
8770 ASLoc = Lex.getLoc();
8771 if (parseOptionalAddrSpace(AddrSpace))
8772 return true;
8773 } else if (Lex.getKind() == lltok::MetadataVar) {
8774 AteExtraComma = true;
8775 } else {
8776 if (parseTypeAndValue(Size, SizeLoc, PFS))
8777 return true;
8778 if (EatIfPresent(lltok::comma)) {
8779 if (Lex.getKind() == lltok::kw_align) {
8780 if (parseOptionalAlignment(Alignment))
8781 return true;
8782 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8783 return true;
8784 } else if (Lex.getKind() == lltok::kw_addrspace) {
8785 ASLoc = Lex.getLoc();
8786 if (parseOptionalAddrSpace(AddrSpace))
8787 return true;
8788 } else if (Lex.getKind() == lltok::MetadataVar) {
8789 AteExtraComma = true;
8790 }
8791 }
8792 }
8793 }
8794
8795 if (Size && !Size->getType()->isIntegerTy())
8796 return error(SizeLoc, "element count must have integer type");
8797
8798 SmallPtrSet<Type *, 4> Visited;
8799 if (!Alignment && !Ty->isSized(&Visited))
8800 return error(TyLoc, "Cannot allocate unsized type");
8801 if (!Alignment)
8802 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8803 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8804 AI->setUsedWithInAlloca(IsInAlloca);
8805 AI->setSwiftError(IsSwiftError);
8806 Inst = AI;
8807 return AteExtraComma ? InstExtraComma : InstNormal;
8808}
8809
8810/// parseLoad
8811/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8812/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8813/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8814int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8815 Value *Val; LocTy Loc;
8816 MaybeAlign Alignment;
8817 bool AteExtraComma = false;
8818 bool isAtomic = false;
8821
8822 if (Lex.getKind() == lltok::kw_atomic) {
8823 isAtomic = true;
8824 Lex.Lex();
8825 }
8826
8827 bool isVolatile = false;
8828 if (Lex.getKind() == lltok::kw_volatile) {
8829 isVolatile = true;
8830 Lex.Lex();
8831 }
8832
8833 Type *Ty;
8834 LocTy ExplicitTypeLoc = Lex.getLoc();
8835 if (parseType(Ty) ||
8836 parseToken(lltok::comma, "expected comma after load's type") ||
8837 parseTypeAndValue(Val, Loc, PFS) ||
8838 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8839 parseOptionalCommaAlign(Alignment, AteExtraComma))
8840 return true;
8841
8842 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8843 return error(Loc, "load operand must be a pointer to a first class type");
8844 if (isAtomic && !Alignment)
8845 return error(Loc, "atomic load must have explicit non-zero alignment");
8846 if (Ordering == AtomicOrdering::Release ||
8848 return error(Loc, "atomic load cannot use Release ordering");
8849
8850 SmallPtrSet<Type *, 4> Visited;
8851 if (!Alignment && !Ty->isSized(&Visited))
8852 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8853 if (!Alignment)
8854 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8855 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8856 return AteExtraComma ? InstExtraComma : InstNormal;
8857}
8858
8859/// parseStore
8860
8861/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8862/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8863/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8864int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8865 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8866 MaybeAlign Alignment;
8867 bool AteExtraComma = false;
8868 bool isAtomic = false;
8871
8872 if (Lex.getKind() == lltok::kw_atomic) {
8873 isAtomic = true;
8874 Lex.Lex();
8875 }
8876
8877 bool isVolatile = false;
8878 if (Lex.getKind() == lltok::kw_volatile) {
8879 isVolatile = true;
8880 Lex.Lex();
8881 }
8882
8883 if (parseTypeAndValue(Val, Loc, PFS) ||
8884 parseToken(lltok::comma, "expected ',' after store operand") ||
8885 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8886 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8887 parseOptionalCommaAlign(Alignment, AteExtraComma))
8888 return true;
8889
8890 if (!Ptr->getType()->isPointerTy())
8891 return error(PtrLoc, "store operand must be a pointer");
8892 if (!Val->getType()->isFirstClassType())
8893 return error(Loc, "store operand must be a first class value");
8894 if (isAtomic && !Alignment)
8895 return error(Loc, "atomic store must have explicit non-zero alignment");
8896 if (Ordering == AtomicOrdering::Acquire ||
8898 return error(Loc, "atomic store cannot use Acquire ordering");
8899 SmallPtrSet<Type *, 4> Visited;
8900 if (!Alignment && !Val->getType()->isSized(&Visited))
8901 return error(Loc, "storing unsized types is not allowed");
8902 if (!Alignment)
8903 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8904
8905 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8906 return AteExtraComma ? InstExtraComma : InstNormal;
8907}
8908
8909/// parseCmpXchg
8910/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8911/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8912/// 'Align'?
8913int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8914 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8915 bool AteExtraComma = false;
8916 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8917 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8919 bool isVolatile = false;
8920 bool isWeak = false;
8921 MaybeAlign Alignment;
8922
8923 if (EatIfPresent(lltok::kw_weak))
8924 isWeak = true;
8925
8926 if (EatIfPresent(lltok::kw_volatile))
8927 isVolatile = true;
8928
8929 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8930 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8931 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8932 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8933 parseTypeAndValue(New, NewLoc, PFS) ||
8934 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8935 parseOrdering(FailureOrdering) ||
8936 parseOptionalCommaAlign(Alignment, AteExtraComma))
8937 return true;
8938
8939 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8940 return tokError("invalid cmpxchg success ordering");
8941 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8942 return tokError("invalid cmpxchg failure ordering");
8943 if (!Ptr->getType()->isPointerTy())
8944 return error(PtrLoc, "cmpxchg operand must be a pointer");
8945 if (Cmp->getType() != New->getType())
8946 return error(NewLoc, "compare value and new value type do not match");
8947 if (!New->getType()->isFirstClassType())
8948 return error(NewLoc, "cmpxchg operand must be a first class value");
8949
8950 const Align DefaultAlignment(
8951 PFS.getFunction().getDataLayout().getTypeStoreSize(
8952 Cmp->getType()));
8953
8954 AtomicCmpXchgInst *CXI =
8955 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8956 SuccessOrdering, FailureOrdering, SSID);
8957 CXI->setVolatile(isVolatile);
8958 CXI->setWeak(isWeak);
8959
8960 Inst = CXI;
8961 return AteExtraComma ? InstExtraComma : InstNormal;
8962}
8963
8964/// parseAtomicRMW
8965/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8966/// 'singlethread'? AtomicOrdering
8967int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8968 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8969 bool AteExtraComma = false;
8972 bool isVolatile = false;
8973 bool IsFP = false;
8975 MaybeAlign Alignment;
8976
8977 if (EatIfPresent(lltok::kw_volatile))
8978 isVolatile = true;
8979
8980 switch (Lex.getKind()) {
8981 default:
8982 return tokError("expected binary operation in atomicrmw");
8996 break;
8999 break;
9002 break;
9003 case lltok::kw_usub_sat:
9005 break;
9006 case lltok::kw_fadd:
9008 IsFP = true;
9009 break;
9010 case lltok::kw_fsub:
9012 IsFP = true;
9013 break;
9014 case lltok::kw_fmax:
9016 IsFP = true;
9017 break;
9018 case lltok::kw_fmin:
9020 IsFP = true;
9021 break;
9022 case lltok::kw_fmaximum:
9024 IsFP = true;
9025 break;
9026 case lltok::kw_fminimum:
9028 IsFP = true;
9029 break;
9032 IsFP = true;
9033 break;
9036 IsFP = true;
9037 break;
9038 }
9039 Lex.Lex(); // Eat the operation.
9040
9041 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9042 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9043 parseTypeAndValue(Val, ValLoc, PFS) ||
9044 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9045 parseOptionalCommaAlign(Alignment, AteExtraComma))
9046 return true;
9047
9048 if (Ordering == AtomicOrdering::Unordered)
9049 return tokError("atomicrmw cannot be unordered");
9050 if (!Ptr->getType()->isPointerTy())
9051 return error(PtrLoc, "atomicrmw operand must be a pointer");
9052 if (Val->getType()->isScalableTy())
9053 return error(ValLoc, "atomicrmw operand may not be scalable");
9054
9056 if (!Val->getType()->isIntegerTy() &&
9057 !Val->getType()->isFloatingPointTy() &&
9058 !Val->getType()->isPointerTy()) {
9059 return error(
9060 ValLoc,
9062 " operand must be an integer, floating point, or pointer type");
9063 }
9064 } else if (IsFP) {
9065 if (!Val->getType()->isFPOrFPVectorTy()) {
9066 return error(ValLoc, "atomicrmw " +
9068 " operand must be a floating point type");
9069 }
9070 } else {
9071 if (!Val->getType()->isIntegerTy()) {
9072 return error(ValLoc, "atomicrmw " +
9074 " operand must be an integer");
9075 }
9076 }
9077
9078 unsigned Size =
9079 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
9080 Val->getType());
9081 if (Size < 8 || (Size & (Size - 1)))
9082 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
9083 " integer");
9084 const Align DefaultAlignment(
9085 PFS.getFunction().getDataLayout().getTypeStoreSize(
9086 Val->getType()));
9087 AtomicRMWInst *RMWI =
9088 new AtomicRMWInst(Operation, Ptr, Val,
9089 Alignment.value_or(DefaultAlignment), Ordering, SSID);
9090 RMWI->setVolatile(isVolatile);
9091 Inst = RMWI;
9092 return AteExtraComma ? InstExtraComma : InstNormal;
9093}
9094
9095/// parseFence
9096/// ::= 'fence' 'singlethread'? AtomicOrdering
9097int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9100 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9101 return true;
9102
9103 if (Ordering == AtomicOrdering::Unordered)
9104 return tokError("fence cannot be unordered");
9105 if (Ordering == AtomicOrdering::Monotonic)
9106 return tokError("fence cannot be monotonic");
9107
9108 Inst = new FenceInst(Context, Ordering, SSID);
9109 return InstNormal;
9110}
9111
9112/// parseGetElementPtr
9113/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9114int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9115 Value *Ptr = nullptr;
9116 Value *Val = nullptr;
9117 LocTy Loc, EltLoc;
9118 GEPNoWrapFlags NW;
9119
9120 while (true) {
9121 if (EatIfPresent(lltok::kw_inbounds))
9123 else if (EatIfPresent(lltok::kw_nusw))
9125 else if (EatIfPresent(lltok::kw_nuw))
9127 else
9128 break;
9129 }
9130
9131 Type *Ty = nullptr;
9132 if (parseType(Ty) ||
9133 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9134 parseTypeAndValue(Ptr, Loc, PFS))
9135 return true;
9136
9137 Type *BaseType = Ptr->getType();
9138 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9139 if (!BasePointerType)
9140 return error(Loc, "base of getelementptr must be a pointer");
9141
9142 SmallVector<Value*, 16> Indices;
9143 bool AteExtraComma = false;
9144 // GEP returns a vector of pointers if at least one of parameters is a vector.
9145 // All vector parameters should have the same vector width.
9146 ElementCount GEPWidth = BaseType->isVectorTy()
9147 ? cast<VectorType>(BaseType)->getElementCount()
9149
9150 while (EatIfPresent(lltok::comma)) {
9151 if (Lex.getKind() == lltok::MetadataVar) {
9152 AteExtraComma = true;
9153 break;
9154 }
9155 if (parseTypeAndValue(Val, EltLoc, PFS))
9156 return true;
9157 if (!Val->getType()->isIntOrIntVectorTy())
9158 return error(EltLoc, "getelementptr index must be an integer");
9159
9160 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9161 ElementCount ValNumEl = ValVTy->getElementCount();
9162 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9163 return error(
9164 EltLoc,
9165 "getelementptr vector index has a wrong number of elements");
9166 GEPWidth = ValNumEl;
9167 }
9168 Indices.push_back(Val);
9169 }
9170
9171 SmallPtrSet<Type*, 4> Visited;
9172 if (!Indices.empty() && !Ty->isSized(&Visited))
9173 return error(Loc, "base element of getelementptr must be sized");
9174
9175 auto *STy = dyn_cast<StructType>(Ty);
9176 if (STy && STy->isScalableTy())
9177 return error(Loc, "getelementptr cannot target structure that contains "
9178 "scalable vector type");
9179
9180 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9181 return error(Loc, "invalid getelementptr indices");
9182 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9183 Inst = GEP;
9184 GEP->setNoWrapFlags(NW);
9185 return AteExtraComma ? InstExtraComma : InstNormal;
9186}
9187
9188/// parseExtractValue
9189/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9190int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9191 Value *Val; LocTy Loc;
9192 SmallVector<unsigned, 4> Indices;
9193 bool AteExtraComma;
9194 if (parseTypeAndValue(Val, Loc, PFS) ||
9195 parseIndexList(Indices, AteExtraComma))
9196 return true;
9197
9198 if (!Val->getType()->isAggregateType())
9199 return error(Loc, "extractvalue operand must be aggregate type");
9200
9201 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9202 return error(Loc, "invalid indices for extractvalue");
9203 Inst = ExtractValueInst::Create(Val, Indices);
9204 return AteExtraComma ? InstExtraComma : InstNormal;
9205}
9206
9207/// parseInsertValue
9208/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9209int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9210 Value *Val0, *Val1; LocTy Loc0, Loc1;
9211 SmallVector<unsigned, 4> Indices;
9212 bool AteExtraComma;
9213 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9214 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9215 parseTypeAndValue(Val1, Loc1, PFS) ||
9216 parseIndexList(Indices, AteExtraComma))
9217 return true;
9218
9219 if (!Val0->getType()->isAggregateType())
9220 return error(Loc0, "insertvalue operand must be aggregate type");
9221
9222 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9223 if (!IndexedType)
9224 return error(Loc0, "invalid indices for insertvalue");
9225 if (IndexedType != Val1->getType())
9226 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9227 getTypeString(Val1->getType()) + "' instead of '" +
9228 getTypeString(IndexedType) + "'");
9229 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9230 return AteExtraComma ? InstExtraComma : InstNormal;
9231}
9232
9233//===----------------------------------------------------------------------===//
9234// Embedded metadata.
9235//===----------------------------------------------------------------------===//
9236
9237/// parseMDNodeVector
9238/// ::= { Element (',' Element)* }
9239/// Element
9240/// ::= 'null' | Metadata
9241bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9242 if (parseToken(lltok::lbrace, "expected '{' here"))
9243 return true;
9244
9245 // Check for an empty list.
9246 if (EatIfPresent(lltok::rbrace))
9247 return false;
9248
9249 do {
9250 if (EatIfPresent(lltok::kw_null)) {
9251 Elts.push_back(nullptr);
9252 continue;
9253 }
9254
9255 Metadata *MD;
9256 if (parseMetadata(MD, nullptr))
9257 return true;
9258 Elts.push_back(MD);
9259 } while (EatIfPresent(lltok::comma));
9260
9261 return parseToken(lltok::rbrace, "expected end of metadata node");
9262}
9263
9264//===----------------------------------------------------------------------===//
9265// Use-list order directives.
9266//===----------------------------------------------------------------------===//
9267bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9268 SMLoc Loc) {
9269 if (!V->hasUseList())
9270 return false;
9271 if (V->use_empty())
9272 return error(Loc, "value has no uses");
9273
9274 unsigned NumUses = 0;
9275 SmallDenseMap<const Use *, unsigned, 16> Order;
9276 for (const Use &U : V->uses()) {
9277 if (++NumUses > Indexes.size())
9278 break;
9279 Order[&U] = Indexes[NumUses - 1];
9280 }
9281 if (NumUses < 2)
9282 return error(Loc, "value only has one use");
9283 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9284 return error(Loc,
9285 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9286
9287 V->sortUseList([&](const Use &L, const Use &R) {
9288 return Order.lookup(&L) < Order.lookup(&R);
9289 });
9290 return false;
9291}
9292
9293/// parseUseListOrderIndexes
9294/// ::= '{' uint32 (',' uint32)+ '}'
9295bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9296 SMLoc Loc = Lex.getLoc();
9297 if (parseToken(lltok::lbrace, "expected '{' here"))
9298 return true;
9299 if (Lex.getKind() == lltok::rbrace)
9300 return tokError("expected non-empty list of uselistorder indexes");
9301
9302 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9303 // indexes should be distinct numbers in the range [0, size-1], and should
9304 // not be in order.
9305 unsigned Offset = 0;
9306 unsigned Max = 0;
9307 bool IsOrdered = true;
9308 assert(Indexes.empty() && "Expected empty order vector");
9309 do {
9310 unsigned Index;
9311 if (parseUInt32(Index))
9312 return true;
9313
9314 // Update consistency checks.
9315 Offset += Index - Indexes.size();
9316 Max = std::max(Max, Index);
9317 IsOrdered &= Index == Indexes.size();
9318
9319 Indexes.push_back(Index);
9320 } while (EatIfPresent(lltok::comma));
9321
9322 if (parseToken(lltok::rbrace, "expected '}' here"))
9323 return true;
9324
9325 if (Indexes.size() < 2)
9326 return error(Loc, "expected >= 2 uselistorder indexes");
9327 if (Offset != 0 || Max >= Indexes.size())
9328 return error(Loc,
9329 "expected distinct uselistorder indexes in range [0, size)");
9330 if (IsOrdered)
9331 return error(Loc, "expected uselistorder indexes to change the order");
9332
9333 return false;
9334}
9335
9336/// parseUseListOrder
9337/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9338bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9339 SMLoc Loc = Lex.getLoc();
9340 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9341 return true;
9342
9343 Value *V;
9344 SmallVector<unsigned, 16> Indexes;
9345 if (parseTypeAndValue(V, PFS) ||
9346 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9347 parseUseListOrderIndexes(Indexes))
9348 return true;
9349
9350 return sortUseListOrder(V, Indexes, Loc);
9351}
9352
9353/// parseUseListOrderBB
9354/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9355bool LLParser::parseUseListOrderBB() {
9356 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9357 SMLoc Loc = Lex.getLoc();
9358 Lex.Lex();
9359
9360 ValID Fn, Label;
9361 SmallVector<unsigned, 16> Indexes;
9362 if (parseValID(Fn, /*PFS=*/nullptr) ||
9363 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9364 parseValID(Label, /*PFS=*/nullptr) ||
9365 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9366 parseUseListOrderIndexes(Indexes))
9367 return true;
9368
9369 // Check the function.
9370 GlobalValue *GV;
9371 if (Fn.Kind == ValID::t_GlobalName)
9372 GV = M->getNamedValue(Fn.StrVal);
9373 else if (Fn.Kind == ValID::t_GlobalID)
9374 GV = NumberedVals.get(Fn.UIntVal);
9375 else
9376 return error(Fn.Loc, "expected function name in uselistorder_bb");
9377 if (!GV)
9378 return error(Fn.Loc,
9379 "invalid function forward reference in uselistorder_bb");
9380 auto *F = dyn_cast<Function>(GV);
9381 if (!F)
9382 return error(Fn.Loc, "expected function name in uselistorder_bb");
9383 if (F->isDeclaration())
9384 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9385
9386 // Check the basic block.
9387 if (Label.Kind == ValID::t_LocalID)
9388 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9389 if (Label.Kind != ValID::t_LocalName)
9390 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9391 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9392 if (!V)
9393 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9394 if (!isa<BasicBlock>(V))
9395 return error(Label.Loc, "expected basic block in uselistorder_bb");
9396
9397 return sortUseListOrder(V, Indexes, Loc);
9398}
9399
9400/// ModuleEntry
9401/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9402/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9403bool LLParser::parseModuleEntry(unsigned ID) {
9404 assert(Lex.getKind() == lltok::kw_module);
9405 Lex.Lex();
9406
9407 std::string Path;
9408 if (parseToken(lltok::colon, "expected ':' here") ||
9409 parseToken(lltok::lparen, "expected '(' here") ||
9410 parseToken(lltok::kw_path, "expected 'path' here") ||
9411 parseToken(lltok::colon, "expected ':' here") ||
9412 parseStringConstant(Path) ||
9413 parseToken(lltok::comma, "expected ',' here") ||
9414 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9415 parseToken(lltok::colon, "expected ':' here") ||
9416 parseToken(lltok::lparen, "expected '(' here"))
9417 return true;
9418
9419 ModuleHash Hash;
9420 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9421 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9422 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9423 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9424 parseUInt32(Hash[4]))
9425 return true;
9426
9427 if (parseToken(lltok::rparen, "expected ')' here") ||
9428 parseToken(lltok::rparen, "expected ')' here"))
9429 return true;
9430
9431 auto ModuleEntry = Index->addModule(Path, Hash);
9432 ModuleIdMap[ID] = ModuleEntry->first();
9433
9434 return false;
9435}
9436
9437/// TypeIdEntry
9438/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9439bool LLParser::parseTypeIdEntry(unsigned ID) {
9440 assert(Lex.getKind() == lltok::kw_typeid);
9441 Lex.Lex();
9442
9443 std::string Name;
9444 if (parseToken(lltok::colon, "expected ':' here") ||
9445 parseToken(lltok::lparen, "expected '(' here") ||
9446 parseToken(lltok::kw_name, "expected 'name' here") ||
9447 parseToken(lltok::colon, "expected ':' here") ||
9448 parseStringConstant(Name))
9449 return true;
9450
9451 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9452 if (parseToken(lltok::comma, "expected ',' here") ||
9453 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9454 return true;
9455
9456 // Check if this ID was forward referenced, and if so, update the
9457 // corresponding GUIDs.
9458 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9459 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9460 for (auto TIDRef : FwdRefTIDs->second) {
9461 assert(!*TIDRef.first &&
9462 "Forward referenced type id GUID expected to be 0");
9463 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9464 }
9465 ForwardRefTypeIds.erase(FwdRefTIDs);
9466 }
9467
9468 return false;
9469}
9470
9471/// TypeIdSummary
9472/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9473bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9474 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9475 parseToken(lltok::colon, "expected ':' here") ||
9476 parseToken(lltok::lparen, "expected '(' here") ||
9477 parseTypeTestResolution(TIS.TTRes))
9478 return true;
9479
9480 if (EatIfPresent(lltok::comma)) {
9481 // Expect optional wpdResolutions field
9482 if (parseOptionalWpdResolutions(TIS.WPDRes))
9483 return true;
9484 }
9485
9486 if (parseToken(lltok::rparen, "expected ')' here"))
9487 return true;
9488
9489 return false;
9490}
9491
9493 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9494
9495/// TypeIdCompatibleVtableEntry
9496/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9497/// TypeIdCompatibleVtableInfo
9498/// ')'
9499bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9501 Lex.Lex();
9502
9503 std::string Name;
9504 if (parseToken(lltok::colon, "expected ':' here") ||
9505 parseToken(lltok::lparen, "expected '(' here") ||
9506 parseToken(lltok::kw_name, "expected 'name' here") ||
9507 parseToken(lltok::colon, "expected ':' here") ||
9508 parseStringConstant(Name))
9509 return true;
9510
9512 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9513 if (parseToken(lltok::comma, "expected ',' here") ||
9514 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9515 parseToken(lltok::colon, "expected ':' here") ||
9516 parseToken(lltok::lparen, "expected '(' here"))
9517 return true;
9518
9519 IdToIndexMapType IdToIndexMap;
9520 // parse each call edge
9521 do {
9523 if (parseToken(lltok::lparen, "expected '(' here") ||
9524 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9525 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9526 parseToken(lltok::comma, "expected ',' here"))
9527 return true;
9528
9529 LocTy Loc = Lex.getLoc();
9530 unsigned GVId;
9531 ValueInfo VI;
9532 if (parseGVReference(VI, GVId))
9533 return true;
9534
9535 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9536 // forward reference. We will save the location of the ValueInfo needing an
9537 // update, but can only do so once the std::vector is finalized.
9538 if (VI == EmptyVI)
9539 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9540 TI.push_back({Offset, VI});
9541
9542 if (parseToken(lltok::rparen, "expected ')' in call"))
9543 return true;
9544 } while (EatIfPresent(lltok::comma));
9545
9546 // Now that the TI vector is finalized, it is safe to save the locations
9547 // of any forward GV references that need updating later.
9548 for (auto I : IdToIndexMap) {
9549 auto &Infos = ForwardRefValueInfos[I.first];
9550 for (auto P : I.second) {
9551 assert(TI[P.first].VTableVI == EmptyVI &&
9552 "Forward referenced ValueInfo expected to be empty");
9553 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9554 }
9555 }
9556
9557 if (parseToken(lltok::rparen, "expected ')' here") ||
9558 parseToken(lltok::rparen, "expected ')' here"))
9559 return true;
9560
9561 // Check if this ID was forward referenced, and if so, update the
9562 // corresponding GUIDs.
9563 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9564 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9565 for (auto TIDRef : FwdRefTIDs->second) {
9566 assert(!*TIDRef.first &&
9567 "Forward referenced type id GUID expected to be 0");
9568 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9569 }
9570 ForwardRefTypeIds.erase(FwdRefTIDs);
9571 }
9572
9573 return false;
9574}
9575
9576/// TypeTestResolution
9577/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9578/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9579/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9580/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9581/// [',' 'inlinesBits' ':' UInt64]? ')'
9582bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9583 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9584 parseToken(lltok::colon, "expected ':' here") ||
9585 parseToken(lltok::lparen, "expected '(' here") ||
9586 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9587 parseToken(lltok::colon, "expected ':' here"))
9588 return true;
9589
9590 switch (Lex.getKind()) {
9591 case lltok::kw_unknown:
9593 break;
9594 case lltok::kw_unsat:
9596 break;
9599 break;
9600 case lltok::kw_inline:
9602 break;
9603 case lltok::kw_single:
9605 break;
9606 case lltok::kw_allOnes:
9608 break;
9609 default:
9610 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9611 }
9612 Lex.Lex();
9613
9614 if (parseToken(lltok::comma, "expected ',' here") ||
9615 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9616 parseToken(lltok::colon, "expected ':' here") ||
9617 parseUInt32(TTRes.SizeM1BitWidth))
9618 return true;
9619
9620 // parse optional fields
9621 while (EatIfPresent(lltok::comma)) {
9622 switch (Lex.getKind()) {
9624 Lex.Lex();
9625 if (parseToken(lltok::colon, "expected ':'") ||
9626 parseUInt64(TTRes.AlignLog2))
9627 return true;
9628 break;
9629 case lltok::kw_sizeM1:
9630 Lex.Lex();
9631 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9632 return true;
9633 break;
9634 case lltok::kw_bitMask: {
9635 unsigned Val;
9636 Lex.Lex();
9637 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9638 return true;
9639 assert(Val <= 0xff);
9640 TTRes.BitMask = (uint8_t)Val;
9641 break;
9642 }
9644 Lex.Lex();
9645 if (parseToken(lltok::colon, "expected ':'") ||
9646 parseUInt64(TTRes.InlineBits))
9647 return true;
9648 break;
9649 default:
9650 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9651 }
9652 }
9653
9654 if (parseToken(lltok::rparen, "expected ')' here"))
9655 return true;
9656
9657 return false;
9658}
9659
9660/// OptionalWpdResolutions
9661/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9662/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9663bool LLParser::parseOptionalWpdResolutions(
9664 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9665 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9666 parseToken(lltok::colon, "expected ':' here") ||
9667 parseToken(lltok::lparen, "expected '(' here"))
9668 return true;
9669
9670 do {
9671 uint64_t Offset;
9672 WholeProgramDevirtResolution WPDRes;
9673 if (parseToken(lltok::lparen, "expected '(' here") ||
9674 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9675 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9676 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9677 parseToken(lltok::rparen, "expected ')' here"))
9678 return true;
9679 WPDResMap[Offset] = WPDRes;
9680 } while (EatIfPresent(lltok::comma));
9681
9682 if (parseToken(lltok::rparen, "expected ')' here"))
9683 return true;
9684
9685 return false;
9686}
9687
9688/// WpdRes
9689/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9690/// [',' OptionalResByArg]? ')'
9691/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9692/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9693/// [',' OptionalResByArg]? ')'
9694/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9695/// [',' OptionalResByArg]? ')'
9696bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9697 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9698 parseToken(lltok::colon, "expected ':' here") ||
9699 parseToken(lltok::lparen, "expected '(' here") ||
9700 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9701 parseToken(lltok::colon, "expected ':' here"))
9702 return true;
9703
9704 switch (Lex.getKind()) {
9705 case lltok::kw_indir:
9707 break;
9710 break;
9713 break;
9714 default:
9715 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9716 }
9717 Lex.Lex();
9718
9719 // parse optional fields
9720 while (EatIfPresent(lltok::comma)) {
9721 switch (Lex.getKind()) {
9723 Lex.Lex();
9724 if (parseToken(lltok::colon, "expected ':' here") ||
9725 parseStringConstant(WPDRes.SingleImplName))
9726 return true;
9727 break;
9728 case lltok::kw_resByArg:
9729 if (parseOptionalResByArg(WPDRes.ResByArg))
9730 return true;
9731 break;
9732 default:
9733 return error(Lex.getLoc(),
9734 "expected optional WholeProgramDevirtResolution field");
9735 }
9736 }
9737
9738 if (parseToken(lltok::rparen, "expected ')' here"))
9739 return true;
9740
9741 return false;
9742}
9743
9744/// OptionalResByArg
9745/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9746/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9747/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9748/// 'virtualConstProp' )
9749/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9750/// [',' 'bit' ':' UInt32]? ')'
9751bool LLParser::parseOptionalResByArg(
9752 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9753 &ResByArg) {
9754 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9755 parseToken(lltok::colon, "expected ':' here") ||
9756 parseToken(lltok::lparen, "expected '(' here"))
9757 return true;
9758
9759 do {
9760 std::vector<uint64_t> Args;
9761 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9762 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9763 parseToken(lltok::colon, "expected ':' here") ||
9764 parseToken(lltok::lparen, "expected '(' here") ||
9765 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9766 parseToken(lltok::colon, "expected ':' here"))
9767 return true;
9768
9769 WholeProgramDevirtResolution::ByArg ByArg;
9770 switch (Lex.getKind()) {
9771 case lltok::kw_indir:
9773 break;
9776 break;
9779 break;
9782 break;
9783 default:
9784 return error(Lex.getLoc(),
9785 "unexpected WholeProgramDevirtResolution::ByArg kind");
9786 }
9787 Lex.Lex();
9788
9789 // parse optional fields
9790 while (EatIfPresent(lltok::comma)) {
9791 switch (Lex.getKind()) {
9792 case lltok::kw_info:
9793 Lex.Lex();
9794 if (parseToken(lltok::colon, "expected ':' here") ||
9795 parseUInt64(ByArg.Info))
9796 return true;
9797 break;
9798 case lltok::kw_byte:
9799 Lex.Lex();
9800 if (parseToken(lltok::colon, "expected ':' here") ||
9801 parseUInt32(ByArg.Byte))
9802 return true;
9803 break;
9804 case lltok::kw_bit:
9805 Lex.Lex();
9806 if (parseToken(lltok::colon, "expected ':' here") ||
9807 parseUInt32(ByArg.Bit))
9808 return true;
9809 break;
9810 default:
9811 return error(Lex.getLoc(),
9812 "expected optional whole program devirt field");
9813 }
9814 }
9815
9816 if (parseToken(lltok::rparen, "expected ')' here"))
9817 return true;
9818
9819 ResByArg[Args] = ByArg;
9820 } while (EatIfPresent(lltok::comma));
9821
9822 if (parseToken(lltok::rparen, "expected ')' here"))
9823 return true;
9824
9825 return false;
9826}
9827
9828/// OptionalResByArg
9829/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9830bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9831 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9832 parseToken(lltok::colon, "expected ':' here") ||
9833 parseToken(lltok::lparen, "expected '(' here"))
9834 return true;
9835
9836 do {
9837 uint64_t Val;
9838 if (parseUInt64(Val))
9839 return true;
9840 Args.push_back(Val);
9841 } while (EatIfPresent(lltok::comma));
9842
9843 if (parseToken(lltok::rparen, "expected ')' here"))
9844 return true;
9845
9846 return false;
9847}
9848
9849static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9850
9851static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9852 bool ReadOnly = Fwd->isReadOnly();
9853 bool WriteOnly = Fwd->isWriteOnly();
9854 assert(!(ReadOnly && WriteOnly));
9855 *Fwd = Resolved;
9856 if (ReadOnly)
9857 Fwd->setReadOnly();
9858 if (WriteOnly)
9859 Fwd->setWriteOnly();
9860}
9861
9862/// Stores the given Name/GUID and associated summary into the Index.
9863/// Also updates any forward references to the associated entry ID.
9864bool LLParser::addGlobalValueToIndex(
9865 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9866 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9867 // First create the ValueInfo utilizing the Name or GUID.
9868 ValueInfo VI;
9869 if (GUID != 0) {
9870 assert(Name.empty());
9871 VI = Index->getOrInsertValueInfo(GUID);
9872 } else {
9873 assert(!Name.empty());
9874 if (M) {
9875 auto *GV = M->getNamedValue(Name);
9876 if (!GV)
9877 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9878
9879 VI = Index->getOrInsertValueInfo(GV);
9880 } else {
9881 assert(
9882 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9883 "Need a source_filename to compute GUID for local");
9885 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9886 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9887 }
9888 }
9889
9890 // Resolve forward references from calls/refs
9891 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9892 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9893 for (auto VIRef : FwdRefVIs->second) {
9894 assert(VIRef.first->getRef() == FwdVIRef &&
9895 "Forward referenced ValueInfo expected to be empty");
9896 resolveFwdRef(VIRef.first, VI);
9897 }
9898 ForwardRefValueInfos.erase(FwdRefVIs);
9899 }
9900
9901 // Resolve forward references from aliases
9902 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9903 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9904 for (auto AliaseeRef : FwdRefAliasees->second) {
9905 assert(!AliaseeRef.first->hasAliasee() &&
9906 "Forward referencing alias already has aliasee");
9907 assert(Summary && "Aliasee must be a definition");
9908 AliaseeRef.first->setAliasee(VI, Summary.get());
9909 }
9910 ForwardRefAliasees.erase(FwdRefAliasees);
9911 }
9912
9913 // Add the summary if one was provided.
9914 if (Summary)
9915 Index->addGlobalValueSummary(VI, std::move(Summary));
9916
9917 // Save the associated ValueInfo for use in later references by ID.
9918 if (ID == NumberedValueInfos.size())
9919 NumberedValueInfos.push_back(VI);
9920 else {
9921 // Handle non-continuous numbers (to make test simplification easier).
9922 if (ID > NumberedValueInfos.size())
9923 NumberedValueInfos.resize(ID + 1);
9924 NumberedValueInfos[ID] = VI;
9925 }
9926
9927 return false;
9928}
9929
9930/// parseSummaryIndexFlags
9931/// ::= 'flags' ':' UInt64
9932bool LLParser::parseSummaryIndexFlags() {
9933 assert(Lex.getKind() == lltok::kw_flags);
9934 Lex.Lex();
9935
9936 if (parseToken(lltok::colon, "expected ':' here"))
9937 return true;
9938 uint64_t Flags;
9939 if (parseUInt64(Flags))
9940 return true;
9941 if (Index)
9942 Index->setFlags(Flags);
9943 return false;
9944}
9945
9946/// parseBlockCount
9947/// ::= 'blockcount' ':' UInt64
9948bool LLParser::parseBlockCount() {
9949 assert(Lex.getKind() == lltok::kw_blockcount);
9950 Lex.Lex();
9951
9952 if (parseToken(lltok::colon, "expected ':' here"))
9953 return true;
9954 uint64_t BlockCount;
9955 if (parseUInt64(BlockCount))
9956 return true;
9957 if (Index)
9958 Index->setBlockCount(BlockCount);
9959 return false;
9960}
9961
9962/// parseGVEntry
9963/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9964/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9965/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9966bool LLParser::parseGVEntry(unsigned ID) {
9967 assert(Lex.getKind() == lltok::kw_gv);
9968 Lex.Lex();
9969
9970 if (parseToken(lltok::colon, "expected ':' here") ||
9971 parseToken(lltok::lparen, "expected '(' here"))
9972 return true;
9973
9974 LocTy Loc = Lex.getLoc();
9975 std::string Name;
9977 switch (Lex.getKind()) {
9978 case lltok::kw_name:
9979 Lex.Lex();
9980 if (parseToken(lltok::colon, "expected ':' here") ||
9981 parseStringConstant(Name))
9982 return true;
9983 // Can't create GUID/ValueInfo until we have the linkage.
9984 break;
9985 case lltok::kw_guid:
9986 Lex.Lex();
9987 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9988 return true;
9989 break;
9990 default:
9991 return error(Lex.getLoc(), "expected name or guid tag");
9992 }
9993
9994 if (!EatIfPresent(lltok::comma)) {
9995 // No summaries. Wrap up.
9996 if (parseToken(lltok::rparen, "expected ')' here"))
9997 return true;
9998 // This was created for a call to an external or indirect target.
9999 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10000 // created for indirect calls with VP. A Name with no GUID came from
10001 // an external definition. We pass ExternalLinkage since that is only
10002 // used when the GUID must be computed from Name, and in that case
10003 // the symbol must have external linkage.
10004 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10005 nullptr, Loc);
10006 }
10007
10008 // Have a list of summaries
10009 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10010 parseToken(lltok::colon, "expected ':' here") ||
10011 parseToken(lltok::lparen, "expected '(' here"))
10012 return true;
10013 do {
10014 switch (Lex.getKind()) {
10015 case lltok::kw_function:
10016 if (parseFunctionSummary(Name, GUID, ID))
10017 return true;
10018 break;
10019 case lltok::kw_variable:
10020 if (parseVariableSummary(Name, GUID, ID))
10021 return true;
10022 break;
10023 case lltok::kw_alias:
10024 if (parseAliasSummary(Name, GUID, ID))
10025 return true;
10026 break;
10027 default:
10028 return error(Lex.getLoc(), "expected summary type");
10029 }
10030 } while (EatIfPresent(lltok::comma));
10031
10032 if (parseToken(lltok::rparen, "expected ')' here") ||
10033 parseToken(lltok::rparen, "expected ')' here"))
10034 return true;
10035
10036 return false;
10037}
10038
10039/// FunctionSummary
10040/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10041/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10042/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10043/// [',' OptionalRefs]? ')'
10044bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10045 unsigned ID) {
10046 LocTy Loc = Lex.getLoc();
10047 assert(Lex.getKind() == lltok::kw_function);
10048 Lex.Lex();
10049
10050 StringRef ModulePath;
10051 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10053 /*NotEligibleToImport=*/false,
10054 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10055 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10056 unsigned InstCount;
10058 FunctionSummary::TypeIdInfo TypeIdInfo;
10059 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10061 std::vector<CallsiteInfo> Callsites;
10062 std::vector<AllocInfo> Allocs;
10063 // Default is all-zeros (conservative values).
10064 FunctionSummary::FFlags FFlags = {};
10065 if (parseToken(lltok::colon, "expected ':' here") ||
10066 parseToken(lltok::lparen, "expected '(' here") ||
10067 parseModuleReference(ModulePath) ||
10068 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10069 parseToken(lltok::comma, "expected ',' here") ||
10070 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10071 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10072 return true;
10073
10074 // parse optional fields
10075 while (EatIfPresent(lltok::comma)) {
10076 switch (Lex.getKind()) {
10078 if (parseOptionalFFlags(FFlags))
10079 return true;
10080 break;
10081 case lltok::kw_calls:
10082 if (parseOptionalCalls(Calls))
10083 return true;
10084 break;
10086 if (parseOptionalTypeIdInfo(TypeIdInfo))
10087 return true;
10088 break;
10089 case lltok::kw_refs:
10090 if (parseOptionalRefs(Refs))
10091 return true;
10092 break;
10093 case lltok::kw_params:
10094 if (parseOptionalParamAccesses(ParamAccesses))
10095 return true;
10096 break;
10097 case lltok::kw_allocs:
10098 if (parseOptionalAllocs(Allocs))
10099 return true;
10100 break;
10102 if (parseOptionalCallsites(Callsites))
10103 return true;
10104 break;
10105 default:
10106 return error(Lex.getLoc(), "expected optional function summary field");
10107 }
10108 }
10109
10110 if (parseToken(lltok::rparen, "expected ')' here"))
10111 return true;
10112
10113 auto FS = std::make_unique<FunctionSummary>(
10114 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10115 std::move(TypeIdInfo.TypeTests),
10116 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10117 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10118 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10119 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10120 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10121
10122 FS->setModulePath(ModulePath);
10123
10124 return addGlobalValueToIndex(Name, GUID,
10126 std::move(FS), Loc);
10127}
10128
10129/// VariableSummary
10130/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10131/// [',' OptionalRefs]? ')'
10132bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10133 unsigned ID) {
10134 LocTy Loc = Lex.getLoc();
10135 assert(Lex.getKind() == lltok::kw_variable);
10136 Lex.Lex();
10137
10138 StringRef ModulePath;
10139 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10141 /*NotEligibleToImport=*/false,
10142 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10143 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10144 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10145 /* WriteOnly */ false,
10146 /* Constant */ false,
10149 VTableFuncList VTableFuncs;
10150 if (parseToken(lltok::colon, "expected ':' here") ||
10151 parseToken(lltok::lparen, "expected '(' here") ||
10152 parseModuleReference(ModulePath) ||
10153 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10154 parseToken(lltok::comma, "expected ',' here") ||
10155 parseGVarFlags(GVarFlags))
10156 return true;
10157
10158 // parse optional fields
10159 while (EatIfPresent(lltok::comma)) {
10160 switch (Lex.getKind()) {
10162 if (parseOptionalVTableFuncs(VTableFuncs))
10163 return true;
10164 break;
10165 case lltok::kw_refs:
10166 if (parseOptionalRefs(Refs))
10167 return true;
10168 break;
10169 default:
10170 return error(Lex.getLoc(), "expected optional variable summary field");
10171 }
10172 }
10173
10174 if (parseToken(lltok::rparen, "expected ')' here"))
10175 return true;
10176
10177 auto GS =
10178 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10179
10180 GS->setModulePath(ModulePath);
10181 GS->setVTableFuncs(std::move(VTableFuncs));
10182
10183 return addGlobalValueToIndex(Name, GUID,
10185 std::move(GS), Loc);
10186}
10187
10188/// AliasSummary
10189/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10190/// 'aliasee' ':' GVReference ')'
10191bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10192 unsigned ID) {
10193 assert(Lex.getKind() == lltok::kw_alias);
10194 LocTy Loc = Lex.getLoc();
10195 Lex.Lex();
10196
10197 StringRef ModulePath;
10198 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10200 /*NotEligibleToImport=*/false,
10201 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10202 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10203 if (parseToken(lltok::colon, "expected ':' here") ||
10204 parseToken(lltok::lparen, "expected '(' here") ||
10205 parseModuleReference(ModulePath) ||
10206 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10207 parseToken(lltok::comma, "expected ',' here") ||
10208 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10209 parseToken(lltok::colon, "expected ':' here"))
10210 return true;
10211
10212 ValueInfo AliaseeVI;
10213 unsigned GVId;
10214 auto AS = std::make_unique<AliasSummary>(GVFlags);
10215 AS->setModulePath(ModulePath);
10216
10217 if (!EatIfPresent(lltok::kw_null)) {
10218 if (parseGVReference(AliaseeVI, GVId))
10219 return true;
10220
10221 // Record forward reference if the aliasee is not parsed yet.
10222 if (AliaseeVI.getRef() == FwdVIRef) {
10223 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10224 } else {
10225 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10226 assert(Summary && "Aliasee must be a definition");
10227 AS->setAliasee(AliaseeVI, Summary);
10228 }
10229 }
10230
10231 if (parseToken(lltok::rparen, "expected ')' here"))
10232 return true;
10233
10234 return addGlobalValueToIndex(Name, GUID,
10236 std::move(AS), Loc);
10237}
10238
10239/// Flag
10240/// ::= [0|1]
10241bool LLParser::parseFlag(unsigned &Val) {
10242 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10243 return tokError("expected integer");
10244 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10245 Lex.Lex();
10246 return false;
10247}
10248
10249/// OptionalFFlags
10250/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10251/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10252/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10253/// [',' 'noInline' ':' Flag]? ')'
10254/// [',' 'alwaysInline' ':' Flag]? ')'
10255/// [',' 'noUnwind' ':' Flag]? ')'
10256/// [',' 'mayThrow' ':' Flag]? ')'
10257/// [',' 'hasUnknownCall' ':' Flag]? ')'
10258/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10259
10260bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10261 assert(Lex.getKind() == lltok::kw_funcFlags);
10262 Lex.Lex();
10263
10264 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10265 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10266 return true;
10267
10268 do {
10269 unsigned Val = 0;
10270 switch (Lex.getKind()) {
10271 case lltok::kw_readNone:
10272 Lex.Lex();
10273 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10274 return true;
10275 FFlags.ReadNone = Val;
10276 break;
10277 case lltok::kw_readOnly:
10278 Lex.Lex();
10279 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10280 return true;
10281 FFlags.ReadOnly = Val;
10282 break;
10284 Lex.Lex();
10285 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10286 return true;
10287 FFlags.NoRecurse = Val;
10288 break;
10290 Lex.Lex();
10291 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10292 return true;
10293 FFlags.ReturnDoesNotAlias = Val;
10294 break;
10295 case lltok::kw_noInline:
10296 Lex.Lex();
10297 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10298 return true;
10299 FFlags.NoInline = Val;
10300 break;
10302 Lex.Lex();
10303 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10304 return true;
10305 FFlags.AlwaysInline = Val;
10306 break;
10307 case lltok::kw_noUnwind:
10308 Lex.Lex();
10309 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10310 return true;
10311 FFlags.NoUnwind = Val;
10312 break;
10313 case lltok::kw_mayThrow:
10314 Lex.Lex();
10315 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10316 return true;
10317 FFlags.MayThrow = Val;
10318 break;
10320 Lex.Lex();
10321 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10322 return true;
10323 FFlags.HasUnknownCall = Val;
10324 break;
10326 Lex.Lex();
10327 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10328 return true;
10329 FFlags.MustBeUnreachable = Val;
10330 break;
10331 default:
10332 return error(Lex.getLoc(), "expected function flag type");
10333 }
10334 } while (EatIfPresent(lltok::comma));
10335
10336 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10337 return true;
10338
10339 return false;
10340}
10341
10342/// OptionalCalls
10343/// := 'calls' ':' '(' Call [',' Call]* ')'
10344/// Call ::= '(' 'callee' ':' GVReference
10345/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10346/// [ ',' 'tail' ]? ')'
10347bool LLParser::parseOptionalCalls(
10348 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10349 assert(Lex.getKind() == lltok::kw_calls);
10350 Lex.Lex();
10351
10352 if (parseToken(lltok::colon, "expected ':' in calls") ||
10353 parseToken(lltok::lparen, "expected '(' in calls"))
10354 return true;
10355
10356 IdToIndexMapType IdToIndexMap;
10357 // parse each call edge
10358 do {
10359 ValueInfo VI;
10360 if (parseToken(lltok::lparen, "expected '(' in call") ||
10361 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10362 parseToken(lltok::colon, "expected ':'"))
10363 return true;
10364
10365 LocTy Loc = Lex.getLoc();
10366 unsigned GVId;
10367 if (parseGVReference(VI, GVId))
10368 return true;
10369
10371 unsigned RelBF = 0;
10372 unsigned HasTailCall = false;
10373
10374 // parse optional fields
10375 while (EatIfPresent(lltok::comma)) {
10376 switch (Lex.getKind()) {
10377 case lltok::kw_hotness:
10378 Lex.Lex();
10379 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10380 return true;
10381 break;
10382 // Deprecated, keep in order to support old files.
10383 case lltok::kw_relbf:
10384 Lex.Lex();
10385 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10386 return true;
10387 break;
10388 case lltok::kw_tail:
10389 Lex.Lex();
10390 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10391 return true;
10392 break;
10393 default:
10394 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10395 }
10396 }
10397 // Keep track of the Call array index needing a forward reference.
10398 // We will save the location of the ValueInfo needing an update, but
10399 // can only do so once the std::vector is finalized.
10400 if (VI.getRef() == FwdVIRef)
10401 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10402 Calls.push_back(
10403 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10404
10405 if (parseToken(lltok::rparen, "expected ')' in call"))
10406 return true;
10407 } while (EatIfPresent(lltok::comma));
10408
10409 // Now that the Calls vector is finalized, it is safe to save the locations
10410 // of any forward GV references that need updating later.
10411 for (auto I : IdToIndexMap) {
10412 auto &Infos = ForwardRefValueInfos[I.first];
10413 for (auto P : I.second) {
10414 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10415 "Forward referenced ValueInfo expected to be empty");
10416 Infos.emplace_back(&Calls[P.first].first, P.second);
10417 }
10418 }
10419
10420 if (parseToken(lltok::rparen, "expected ')' in calls"))
10421 return true;
10422
10423 return false;
10424}
10425
10426/// Hotness
10427/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10428bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10429 switch (Lex.getKind()) {
10430 case lltok::kw_unknown:
10432 break;
10433 case lltok::kw_cold:
10435 break;
10436 case lltok::kw_none:
10438 break;
10439 case lltok::kw_hot:
10441 break;
10442 case lltok::kw_critical:
10444 break;
10445 default:
10446 return error(Lex.getLoc(), "invalid call edge hotness");
10447 }
10448 Lex.Lex();
10449 return false;
10450}
10451
10452/// OptionalVTableFuncs
10453/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10454/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10455bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10456 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10457 Lex.Lex();
10458
10459 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10460 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10461 return true;
10462
10463 IdToIndexMapType IdToIndexMap;
10464 // parse each virtual function pair
10465 do {
10466 ValueInfo VI;
10467 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10468 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10469 parseToken(lltok::colon, "expected ':'"))
10470 return true;
10471
10472 LocTy Loc = Lex.getLoc();
10473 unsigned GVId;
10474 if (parseGVReference(VI, GVId))
10475 return true;
10476
10477 uint64_t Offset;
10478 if (parseToken(lltok::comma, "expected comma") ||
10479 parseToken(lltok::kw_offset, "expected offset") ||
10480 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10481 return true;
10482
10483 // Keep track of the VTableFuncs array index needing a forward reference.
10484 // We will save the location of the ValueInfo needing an update, but
10485 // can only do so once the std::vector is finalized.
10486 if (VI == EmptyVI)
10487 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10488 VTableFuncs.push_back({VI, Offset});
10489
10490 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10491 return true;
10492 } while (EatIfPresent(lltok::comma));
10493
10494 // Now that the VTableFuncs vector is finalized, it is safe to save the
10495 // locations of any forward GV references that need updating later.
10496 for (auto I : IdToIndexMap) {
10497 auto &Infos = ForwardRefValueInfos[I.first];
10498 for (auto P : I.second) {
10499 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10500 "Forward referenced ValueInfo expected to be empty");
10501 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10502 }
10503 }
10504
10505 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10506 return true;
10507
10508 return false;
10509}
10510
10511/// ParamNo := 'param' ':' UInt64
10512bool LLParser::parseParamNo(uint64_t &ParamNo) {
10513 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10514 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10515 return true;
10516 return false;
10517}
10518
10519/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10520bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10521 APSInt Lower;
10522 APSInt Upper;
10523 auto ParseAPSInt = [&](APSInt &Val) {
10524 if (Lex.getKind() != lltok::APSInt)
10525 return tokError("expected integer");
10526 Val = Lex.getAPSIntVal();
10527 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10528 Val.setIsSigned(true);
10529 Lex.Lex();
10530 return false;
10531 };
10532 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10533 parseToken(lltok::colon, "expected ':' here") ||
10534 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10535 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10536 parseToken(lltok::rsquare, "expected ']' here"))
10537 return true;
10538
10539 ++Upper;
10540 Range =
10541 (Lower == Upper && !Lower.isMaxValue())
10542 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10543 : ConstantRange(Lower, Upper);
10544
10545 return false;
10546}
10547
10548/// ParamAccessCall
10549/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10550bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10551 IdLocListType &IdLocList) {
10552 if (parseToken(lltok::lparen, "expected '(' here") ||
10553 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10554 parseToken(lltok::colon, "expected ':' here"))
10555 return true;
10556
10557 unsigned GVId;
10558 ValueInfo VI;
10559 LocTy Loc = Lex.getLoc();
10560 if (parseGVReference(VI, GVId))
10561 return true;
10562
10563 Call.Callee = VI;
10564 IdLocList.emplace_back(GVId, Loc);
10565
10566 if (parseToken(lltok::comma, "expected ',' here") ||
10567 parseParamNo(Call.ParamNo) ||
10568 parseToken(lltok::comma, "expected ',' here") ||
10569 parseParamAccessOffset(Call.Offsets))
10570 return true;
10571
10572 if (parseToken(lltok::rparen, "expected ')' here"))
10573 return true;
10574
10575 return false;
10576}
10577
10578/// ParamAccess
10579/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10580/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10581bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10582 IdLocListType &IdLocList) {
10583 if (parseToken(lltok::lparen, "expected '(' here") ||
10584 parseParamNo(Param.ParamNo) ||
10585 parseToken(lltok::comma, "expected ',' here") ||
10586 parseParamAccessOffset(Param.Use))
10587 return true;
10588
10589 if (EatIfPresent(lltok::comma)) {
10590 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10591 parseToken(lltok::colon, "expected ':' here") ||
10592 parseToken(lltok::lparen, "expected '(' here"))
10593 return true;
10594 do {
10595 FunctionSummary::ParamAccess::Call Call;
10596 if (parseParamAccessCall(Call, IdLocList))
10597 return true;
10598 Param.Calls.push_back(Call);
10599 } while (EatIfPresent(lltok::comma));
10600
10601 if (parseToken(lltok::rparen, "expected ')' here"))
10602 return true;
10603 }
10604
10605 if (parseToken(lltok::rparen, "expected ')' here"))
10606 return true;
10607
10608 return false;
10609}
10610
10611/// OptionalParamAccesses
10612/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10613bool LLParser::parseOptionalParamAccesses(
10614 std::vector<FunctionSummary::ParamAccess> &Params) {
10615 assert(Lex.getKind() == lltok::kw_params);
10616 Lex.Lex();
10617
10618 if (parseToken(lltok::colon, "expected ':' here") ||
10619 parseToken(lltok::lparen, "expected '(' here"))
10620 return true;
10621
10622 IdLocListType VContexts;
10623 size_t CallsNum = 0;
10624 do {
10625 FunctionSummary::ParamAccess ParamAccess;
10626 if (parseParamAccess(ParamAccess, VContexts))
10627 return true;
10628 CallsNum += ParamAccess.Calls.size();
10629 assert(VContexts.size() == CallsNum);
10630 (void)CallsNum;
10631 Params.emplace_back(std::move(ParamAccess));
10632 } while (EatIfPresent(lltok::comma));
10633
10634 if (parseToken(lltok::rparen, "expected ')' here"))
10635 return true;
10636
10637 // Now that the Params is finalized, it is safe to save the locations
10638 // of any forward GV references that need updating later.
10639 IdLocListType::const_iterator ItContext = VContexts.begin();
10640 for (auto &PA : Params) {
10641 for (auto &C : PA.Calls) {
10642 if (C.Callee.getRef() == FwdVIRef)
10643 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10644 ItContext->second);
10645 ++ItContext;
10646 }
10647 }
10648 assert(ItContext == VContexts.end());
10649
10650 return false;
10651}
10652
10653/// OptionalRefs
10654/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10655bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10656 assert(Lex.getKind() == lltok::kw_refs);
10657 Lex.Lex();
10658
10659 if (parseToken(lltok::colon, "expected ':' in refs") ||
10660 parseToken(lltok::lparen, "expected '(' in refs"))
10661 return true;
10662
10663 struct ValueContext {
10664 ValueInfo VI;
10665 unsigned GVId;
10666 LocTy Loc;
10667 };
10668 std::vector<ValueContext> VContexts;
10669 // parse each ref edge
10670 do {
10671 ValueContext VC;
10672 VC.Loc = Lex.getLoc();
10673 if (parseGVReference(VC.VI, VC.GVId))
10674 return true;
10675 VContexts.push_back(VC);
10676 } while (EatIfPresent(lltok::comma));
10677
10678 // Sort value contexts so that ones with writeonly
10679 // and readonly ValueInfo are at the end of VContexts vector.
10680 // See FunctionSummary::specialRefCounts()
10681 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10682 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10683 });
10684
10685 IdToIndexMapType IdToIndexMap;
10686 for (auto &VC : VContexts) {
10687 // Keep track of the Refs array index needing a forward reference.
10688 // We will save the location of the ValueInfo needing an update, but
10689 // can only do so once the std::vector is finalized.
10690 if (VC.VI.getRef() == FwdVIRef)
10691 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10692 Refs.push_back(VC.VI);
10693 }
10694
10695 // Now that the Refs vector is finalized, it is safe to save the locations
10696 // of any forward GV references that need updating later.
10697 for (auto I : IdToIndexMap) {
10698 auto &Infos = ForwardRefValueInfos[I.first];
10699 for (auto P : I.second) {
10700 assert(Refs[P.first].getRef() == FwdVIRef &&
10701 "Forward referenced ValueInfo expected to be empty");
10702 Infos.emplace_back(&Refs[P.first], P.second);
10703 }
10704 }
10705
10706 if (parseToken(lltok::rparen, "expected ')' in refs"))
10707 return true;
10708
10709 return false;
10710}
10711
10712/// OptionalTypeIdInfo
10713/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10714/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10715/// [',' TypeCheckedLoadConstVCalls]? ')'
10716bool LLParser::parseOptionalTypeIdInfo(
10717 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10718 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10719 Lex.Lex();
10720
10721 if (parseToken(lltok::colon, "expected ':' here") ||
10722 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10723 return true;
10724
10725 do {
10726 switch (Lex.getKind()) {
10728 if (parseTypeTests(TypeIdInfo.TypeTests))
10729 return true;
10730 break;
10732 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10733 TypeIdInfo.TypeTestAssumeVCalls))
10734 return true;
10735 break;
10737 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10738 TypeIdInfo.TypeCheckedLoadVCalls))
10739 return true;
10740 break;
10742 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10743 TypeIdInfo.TypeTestAssumeConstVCalls))
10744 return true;
10745 break;
10747 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10748 TypeIdInfo.TypeCheckedLoadConstVCalls))
10749 return true;
10750 break;
10751 default:
10752 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10753 }
10754 } while (EatIfPresent(lltok::comma));
10755
10756 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10757 return true;
10758
10759 return false;
10760}
10761
10762/// TypeTests
10763/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10764/// [',' (SummaryID | UInt64)]* ')'
10765bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10766 assert(Lex.getKind() == lltok::kw_typeTests);
10767 Lex.Lex();
10768
10769 if (parseToken(lltok::colon, "expected ':' here") ||
10770 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10771 return true;
10772
10773 IdToIndexMapType IdToIndexMap;
10774 do {
10776 if (Lex.getKind() == lltok::SummaryID) {
10777 unsigned ID = Lex.getUIntVal();
10778 LocTy Loc = Lex.getLoc();
10779 // Keep track of the TypeTests array index needing a forward reference.
10780 // We will save the location of the GUID needing an update, but
10781 // can only do so once the std::vector is finalized.
10782 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10783 Lex.Lex();
10784 } else if (parseUInt64(GUID))
10785 return true;
10786 TypeTests.push_back(GUID);
10787 } while (EatIfPresent(lltok::comma));
10788
10789 // Now that the TypeTests vector is finalized, it is safe to save the
10790 // locations of any forward GV references that need updating later.
10791 for (auto I : IdToIndexMap) {
10792 auto &Ids = ForwardRefTypeIds[I.first];
10793 for (auto P : I.second) {
10794 assert(TypeTests[P.first] == 0 &&
10795 "Forward referenced type id GUID expected to be 0");
10796 Ids.emplace_back(&TypeTests[P.first], P.second);
10797 }
10798 }
10799
10800 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10801 return true;
10802
10803 return false;
10804}
10805
10806/// VFuncIdList
10807/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10808bool LLParser::parseVFuncIdList(
10809 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10810 assert(Lex.getKind() == Kind);
10811 Lex.Lex();
10812
10813 if (parseToken(lltok::colon, "expected ':' here") ||
10814 parseToken(lltok::lparen, "expected '(' here"))
10815 return true;
10816
10817 IdToIndexMapType IdToIndexMap;
10818 do {
10819 FunctionSummary::VFuncId VFuncId;
10820 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10821 return true;
10822 VFuncIdList.push_back(VFuncId);
10823 } while (EatIfPresent(lltok::comma));
10824
10825 if (parseToken(lltok::rparen, "expected ')' here"))
10826 return true;
10827
10828 // Now that the VFuncIdList vector is finalized, it is safe to save the
10829 // locations of any forward GV references that need updating later.
10830 for (auto I : IdToIndexMap) {
10831 auto &Ids = ForwardRefTypeIds[I.first];
10832 for (auto P : I.second) {
10833 assert(VFuncIdList[P.first].GUID == 0 &&
10834 "Forward referenced type id GUID expected to be 0");
10835 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10836 }
10837 }
10838
10839 return false;
10840}
10841
10842/// ConstVCallList
10843/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10844bool LLParser::parseConstVCallList(
10845 lltok::Kind Kind,
10846 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10847 assert(Lex.getKind() == Kind);
10848 Lex.Lex();
10849
10850 if (parseToken(lltok::colon, "expected ':' here") ||
10851 parseToken(lltok::lparen, "expected '(' here"))
10852 return true;
10853
10854 IdToIndexMapType IdToIndexMap;
10855 do {
10856 FunctionSummary::ConstVCall ConstVCall;
10857 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10858 return true;
10859 ConstVCallList.push_back(ConstVCall);
10860 } while (EatIfPresent(lltok::comma));
10861
10862 if (parseToken(lltok::rparen, "expected ')' here"))
10863 return true;
10864
10865 // Now that the ConstVCallList vector is finalized, it is safe to save the
10866 // locations of any forward GV references that need updating later.
10867 for (auto I : IdToIndexMap) {
10868 auto &Ids = ForwardRefTypeIds[I.first];
10869 for (auto P : I.second) {
10870 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10871 "Forward referenced type id GUID expected to be 0");
10872 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10873 }
10874 }
10875
10876 return false;
10877}
10878
10879/// ConstVCall
10880/// ::= '(' VFuncId ',' Args ')'
10881bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10882 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10883 if (parseToken(lltok::lparen, "expected '(' here") ||
10884 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10885 return true;
10886
10887 if (EatIfPresent(lltok::comma))
10888 if (parseArgs(ConstVCall.Args))
10889 return true;
10890
10891 if (parseToken(lltok::rparen, "expected ')' here"))
10892 return true;
10893
10894 return false;
10895}
10896
10897/// VFuncId
10898/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10899/// 'offset' ':' UInt64 ')'
10900bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10901 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10902 assert(Lex.getKind() == lltok::kw_vFuncId);
10903 Lex.Lex();
10904
10905 if (parseToken(lltok::colon, "expected ':' here") ||
10906 parseToken(lltok::lparen, "expected '(' here"))
10907 return true;
10908
10909 if (Lex.getKind() == lltok::SummaryID) {
10910 VFuncId.GUID = 0;
10911 unsigned ID = Lex.getUIntVal();
10912 LocTy Loc = Lex.getLoc();
10913 // Keep track of the array index needing a forward reference.
10914 // We will save the location of the GUID needing an update, but
10915 // can only do so once the caller's std::vector is finalized.
10916 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10917 Lex.Lex();
10918 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10919 parseToken(lltok::colon, "expected ':' here") ||
10920 parseUInt64(VFuncId.GUID))
10921 return true;
10922
10923 if (parseToken(lltok::comma, "expected ',' here") ||
10924 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10925 parseToken(lltok::colon, "expected ':' here") ||
10926 parseUInt64(VFuncId.Offset) ||
10927 parseToken(lltok::rparen, "expected ')' here"))
10928 return true;
10929
10930 return false;
10931}
10932
10933/// GVFlags
10934/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10935/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10936/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10937/// 'canAutoHide' ':' Flag ',' ')'
10938bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10939 assert(Lex.getKind() == lltok::kw_flags);
10940 Lex.Lex();
10941
10942 if (parseToken(lltok::colon, "expected ':' here") ||
10943 parseToken(lltok::lparen, "expected '(' here"))
10944 return true;
10945
10946 do {
10947 unsigned Flag = 0;
10948 switch (Lex.getKind()) {
10949 case lltok::kw_linkage:
10950 Lex.Lex();
10951 if (parseToken(lltok::colon, "expected ':'"))
10952 return true;
10953 bool HasLinkage;
10954 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10955 assert(HasLinkage && "Linkage not optional in summary entry");
10956 Lex.Lex();
10957 break;
10959 Lex.Lex();
10960 if (parseToken(lltok::colon, "expected ':'"))
10961 return true;
10962 parseOptionalVisibility(Flag);
10963 GVFlags.Visibility = Flag;
10964 break;
10966 Lex.Lex();
10967 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10968 return true;
10969 GVFlags.NotEligibleToImport = Flag;
10970 break;
10971 case lltok::kw_live:
10972 Lex.Lex();
10973 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10974 return true;
10975 GVFlags.Live = Flag;
10976 break;
10977 case lltok::kw_dsoLocal:
10978 Lex.Lex();
10979 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10980 return true;
10981 GVFlags.DSOLocal = Flag;
10982 break;
10984 Lex.Lex();
10985 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10986 return true;
10987 GVFlags.CanAutoHide = Flag;
10988 break;
10990 Lex.Lex();
10991 if (parseToken(lltok::colon, "expected ':'"))
10992 return true;
10994 if (parseOptionalImportType(Lex.getKind(), IK))
10995 return true;
10996 GVFlags.ImportType = static_cast<unsigned>(IK);
10997 Lex.Lex();
10998 break;
11000 Lex.Lex();
11001 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11002 return true;
11003 GVFlags.NoRenameOnPromotion = Flag;
11004 break;
11005 default:
11006 return error(Lex.getLoc(), "expected gv flag type");
11007 }
11008 } while (EatIfPresent(lltok::comma));
11009
11010 if (parseToken(lltok::rparen, "expected ')' here"))
11011 return true;
11012
11013 return false;
11014}
11015
11016/// GVarFlags
11017/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11018/// ',' 'writeonly' ':' Flag
11019/// ',' 'constant' ':' Flag ')'
11020bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11021 assert(Lex.getKind() == lltok::kw_varFlags);
11022 Lex.Lex();
11023
11024 if (parseToken(lltok::colon, "expected ':' here") ||
11025 parseToken(lltok::lparen, "expected '(' here"))
11026 return true;
11027
11028 auto ParseRest = [this](unsigned int &Val) {
11029 Lex.Lex();
11030 if (parseToken(lltok::colon, "expected ':'"))
11031 return true;
11032 return parseFlag(Val);
11033 };
11034
11035 do {
11036 unsigned Flag = 0;
11037 switch (Lex.getKind()) {
11038 case lltok::kw_readonly:
11039 if (ParseRest(Flag))
11040 return true;
11041 GVarFlags.MaybeReadOnly = Flag;
11042 break;
11043 case lltok::kw_writeonly:
11044 if (ParseRest(Flag))
11045 return true;
11046 GVarFlags.MaybeWriteOnly = Flag;
11047 break;
11048 case lltok::kw_constant:
11049 if (ParseRest(Flag))
11050 return true;
11051 GVarFlags.Constant = Flag;
11052 break;
11054 if (ParseRest(Flag))
11055 return true;
11056 GVarFlags.VCallVisibility = Flag;
11057 break;
11058 default:
11059 return error(Lex.getLoc(), "expected gvar flag type");
11060 }
11061 } while (EatIfPresent(lltok::comma));
11062 return parseToken(lltok::rparen, "expected ')' here");
11063}
11064
11065/// ModuleReference
11066/// ::= 'module' ':' UInt
11067bool LLParser::parseModuleReference(StringRef &ModulePath) {
11068 // parse module id.
11069 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11070 parseToken(lltok::colon, "expected ':' here") ||
11071 parseToken(lltok::SummaryID, "expected module ID"))
11072 return true;
11073
11074 unsigned ModuleID = Lex.getUIntVal();
11075 auto I = ModuleIdMap.find(ModuleID);
11076 // We should have already parsed all module IDs
11077 assert(I != ModuleIdMap.end());
11078 ModulePath = I->second;
11079 return false;
11080}
11081
11082/// GVReference
11083/// ::= SummaryID
11084bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11085 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11086 if (!ReadOnly)
11087 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11088 if (parseToken(lltok::SummaryID, "expected GV ID"))
11089 return true;
11090
11091 GVId = Lex.getUIntVal();
11092 // Check if we already have a VI for this GV
11093 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11094 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11095 VI = NumberedValueInfos[GVId];
11096 } else
11097 // We will create a forward reference to the stored location.
11098 VI = ValueInfo(false, FwdVIRef);
11099
11100 if (ReadOnly)
11101 VI.setReadOnly();
11102 if (WriteOnly)
11103 VI.setWriteOnly();
11104 return false;
11105}
11106
11107/// OptionalAllocs
11108/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11109/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11110/// ',' MemProfs ')'
11111/// Version ::= UInt32
11112bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11113 assert(Lex.getKind() == lltok::kw_allocs);
11114 Lex.Lex();
11115
11116 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11117 parseToken(lltok::lparen, "expected '(' in allocs"))
11118 return true;
11119
11120 // parse each alloc
11121 do {
11122 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11123 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11124 parseToken(lltok::colon, "expected ':'") ||
11125 parseToken(lltok::lparen, "expected '(' in versions"))
11126 return true;
11127
11128 SmallVector<uint8_t> Versions;
11129 do {
11130 uint8_t V = 0;
11131 if (parseAllocType(V))
11132 return true;
11133 Versions.push_back(V);
11134 } while (EatIfPresent(lltok::comma));
11135
11136 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11137 parseToken(lltok::comma, "expected ',' in alloc"))
11138 return true;
11139
11140 std::vector<MIBInfo> MIBs;
11141 if (parseMemProfs(MIBs))
11142 return true;
11143
11144 Allocs.push_back({Versions, MIBs});
11145
11146 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11147 return true;
11148 } while (EatIfPresent(lltok::comma));
11149
11150 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11151 return true;
11152
11153 return false;
11154}
11155
11156/// MemProfs
11157/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11158/// MemProf ::= '(' 'type' ':' AllocType
11159/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11160/// StackId ::= UInt64
11161bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11162 assert(Lex.getKind() == lltok::kw_memProf);
11163 Lex.Lex();
11164
11165 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11166 parseToken(lltok::lparen, "expected '(' in memprof"))
11167 return true;
11168
11169 // parse each MIB
11170 do {
11171 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11172 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11173 parseToken(lltok::colon, "expected ':'"))
11174 return true;
11175
11176 uint8_t AllocType;
11177 if (parseAllocType(AllocType))
11178 return true;
11179
11180 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11181 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11182 parseToken(lltok::colon, "expected ':'") ||
11183 parseToken(lltok::lparen, "expected '(' in stackIds"))
11184 return true;
11185
11186 SmallVector<unsigned> StackIdIndices;
11187 // Combined index alloc records may not have a stack id list.
11188 if (Lex.getKind() != lltok::rparen) {
11189 do {
11190 uint64_t StackId = 0;
11191 if (parseUInt64(StackId))
11192 return true;
11193 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11194 } while (EatIfPresent(lltok::comma));
11195 }
11196
11197 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11198 return true;
11199
11200 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11201
11202 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11203 return true;
11204 } while (EatIfPresent(lltok::comma));
11205
11206 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11207 return true;
11208
11209 return false;
11210}
11211
11212/// AllocType
11213/// := ('none'|'notcold'|'cold'|'hot')
11214bool LLParser::parseAllocType(uint8_t &AllocType) {
11215 switch (Lex.getKind()) {
11216 case lltok::kw_none:
11218 break;
11219 case lltok::kw_notcold:
11221 break;
11222 case lltok::kw_cold:
11224 break;
11225 case lltok::kw_hot:
11226 AllocType = (uint8_t)AllocationType::Hot;
11227 break;
11228 default:
11229 return error(Lex.getLoc(), "invalid alloc type");
11230 }
11231 Lex.Lex();
11232 return false;
11233}
11234
11235/// OptionalCallsites
11236/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11237/// Callsite ::= '(' 'callee' ':' GVReference
11238/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11239/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11240/// Version ::= UInt32
11241/// StackId ::= UInt64
11242bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11243 assert(Lex.getKind() == lltok::kw_callsites);
11244 Lex.Lex();
11245
11246 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11247 parseToken(lltok::lparen, "expected '(' in callsites"))
11248 return true;
11249
11250 IdToIndexMapType IdToIndexMap;
11251 // parse each callsite
11252 do {
11253 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11254 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11255 parseToken(lltok::colon, "expected ':'"))
11256 return true;
11257
11258 ValueInfo VI;
11259 unsigned GVId = 0;
11260 LocTy Loc = Lex.getLoc();
11261 if (!EatIfPresent(lltok::kw_null)) {
11262 if (parseGVReference(VI, GVId))
11263 return true;
11264 }
11265
11266 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11267 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11268 parseToken(lltok::colon, "expected ':'") ||
11269 parseToken(lltok::lparen, "expected '(' in clones"))
11270 return true;
11271
11272 SmallVector<unsigned> Clones;
11273 do {
11274 unsigned V = 0;
11275 if (parseUInt32(V))
11276 return true;
11277 Clones.push_back(V);
11278 } while (EatIfPresent(lltok::comma));
11279
11280 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11281 parseToken(lltok::comma, "expected ',' in callsite") ||
11282 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11283 parseToken(lltok::colon, "expected ':'") ||
11284 parseToken(lltok::lparen, "expected '(' in stackIds"))
11285 return true;
11286
11287 SmallVector<unsigned> StackIdIndices;
11288 // Synthesized callsite records will not have a stack id list.
11289 if (Lex.getKind() != lltok::rparen) {
11290 do {
11291 uint64_t StackId = 0;
11292 if (parseUInt64(StackId))
11293 return true;
11294 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11295 } while (EatIfPresent(lltok::comma));
11296 }
11297
11298 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11299 return true;
11300
11301 // Keep track of the Callsites array index needing a forward reference.
11302 // We will save the location of the ValueInfo needing an update, but
11303 // can only do so once the SmallVector is finalized.
11304 if (VI.getRef() == FwdVIRef)
11305 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11306 Callsites.push_back({VI, Clones, StackIdIndices});
11307
11308 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11309 return true;
11310 } while (EatIfPresent(lltok::comma));
11311
11312 // Now that the Callsites vector is finalized, it is safe to save the
11313 // locations of any forward GV references that need updating later.
11314 for (auto I : IdToIndexMap) {
11315 auto &Infos = ForwardRefValueInfos[I.first];
11316 for (auto P : I.second) {
11317 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11318 "Forward referenced ValueInfo expected to be empty");
11319 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11320 }
11321 }
11322
11323 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11324 return true;
11325
11326 return false;
11327}
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
This file contains the simple types necessary to represent the attributes associated with functions a...
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")
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:245
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 void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static SmallVector< MemoryEffects::Location, 2 > keywordToLoc(lltok::Kind Tok)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
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:152
#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:68
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
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
if(PassOpts->AAPipeline)
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
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 const fltSemantics & IEEEdouble()
Definition APFloat.h:297
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1244
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:119
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:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
iterator begin() const
Definition ArrayRef.h:130
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:835
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
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ 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:143
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ None
No attributes have been set.
Definition Attributes.h:126
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:462
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.
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:427
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 CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
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 bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1573
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:1445
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, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
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, Constant *DeactivationSymbol)
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.
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
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:205
unsigned size() const
Definition DenseMap.h:110
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
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:59
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:473
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:468
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:168
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:823
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:449
arg_iterator arg_begin()
Definition Function.h:868
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1040
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1052
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
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:613
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:670
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:215
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:276
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:78
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:246
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:94
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:162
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:252
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:229
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:534
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:581
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:68
lltok::Kind getKind() const
Definition LLLexer.h:72
LocTy getLoc() const
Definition LLLexer.h:71
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:124
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:231
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:108
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:95
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:76
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:1080
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1580
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1540
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:224
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
Definition ModRef.h:279
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
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:946
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:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
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:140
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:483
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:689
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:773
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:608
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:510
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:984
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:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:314
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:290
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:281
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:293
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:65
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:284
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:287
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:255
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:201
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:328
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:321
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:310
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:287
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:275
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:233
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 UncondBrInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
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:509
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:832
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
bool use_empty() const
Definition Value.h:347
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:599
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:632
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:704
#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
@ Valid
The data is already valid.
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:154
@ kw_riscv_vls_cc
Definition LLToken.h:190
@ kw_cxx_fast_tlscc
Definition LLToken.h:173
@ kw_extractvalue
Definition LLToken.h:376
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:512
@ kw_arm_apcscc
Definition LLToken.h:146
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:141
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:152
@ kw_provenance
Definition LLToken.h:224
@ kw_mustBeUnreachable
Definition LLToken.h:423
@ kw_internal
Definition LLToken.h:54
@ kw_target_mem
Definition LLToken.h:210
@ kw_no_sanitize_hwaddress
Definition LLToken.h:491
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:462
@ kw_canAutoHide
Definition LLToken.h:406
@ kw_alwaysInline
Definition LLToken.h:419
@ kw_insertelement
Definition LLToken.h:373
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:193
@ kw_fmaximumnum
Definition LLToken.h:295
@ kw_inaccessiblememonly
Definition LLToken.h:217
@ kw_amdgpu_gfx
Definition LLToken.h:184
@ kw_getelementptr
Definition LLToken.h:370
@ kw_m68k_rtdcc
Definition LLToken.h:187
@ kw_preserve_nonecc
Definition LLToken.h:168
@ kw_x86_fastcallcc
Definition LLToken.h:142
@ kw_visibility
Definition LLToken.h:402
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:192
@ kw_positivezero
Definition LLToken.h:230
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:465
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:140
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:442
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:150
@ kw_amdgpu_kernel
Definition LLToken.h:183
@ kw_uselistorder
Definition LLToken.h:389
@ kw_blockcount
Definition LLToken.h:400
@ kw_notEligibleToImport
Definition LLToken.h:403
@ 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:144
@ kw_ptx_device
Definition LLToken.h:158
@ kw_personality
Definition LLToken.h:345
@ DwarfEnumKind
Definition LLToken.h:525
@ kw_declaration
Definition LLToken.h:409
@ DwarfAttEncoding
Definition LLToken.h:511
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:159
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:422
@ kw_x86_intrcc
Definition LLToken.h:170
@ kw_addrspacecast
Definition LLToken.h:340
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:509
@ kw_x86_thiscallcc
Definition LLToken.h:143
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:191
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:390
@ NameTableKind
Definition LLToken.h:517
@ kw_inlineBits
Definition LLToken.h:460
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:216
@ kw_blockaddress
Definition LLToken.h:378
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:185
@ kw_landingpad
Definition LLToken.h:344
@ kw_aarch64_vector_pcs
Definition LLToken.h:149
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:441
@ FixedPointKind
Definition LLToken.h:518
@ kw_target_mem1
Definition LLToken.h:212
@ kw_ptx_kernel
Definition LLToken.h:157
@ kw_extractelement
Definition LLToken.h:372
@ kw_branchFunnel
Definition LLToken.h:466
@ kw_typeidCompatibleVTable
Definition LLToken.h:447
@ kw_vTableFuncs
Definition LLToken.h:433
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:440
@ kw_no_sanitize_address
Definition LLToken.h:488
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:218
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:494
@ DwarfSourceLangName
Definition LLToken.h:514
@ kw_noRenameOnPromotion
Definition LLToken.h:410
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:182
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:358
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:147
@ kw_read_provenance
Definition LLToken.h:225
@ kw_cleanuppad
Definition LLToken.h:361
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:467
@ kw_target_mem0
Definition LLToken.h:211
@ kw_swifttailcc
Definition LLToken.h:165
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:439
@ kw_preservesign
Definition LLToken.h:229
@ kw_attributes
Definition LLToken.h:196
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:470
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:456
@ kw_nodeduplicate
Definition LLToken.h:260
@ kw_avr_signalcc
Definition LLToken.h:156
@ kw_exactmatch
Definition LLToken.h:258
@ kw_fminimumnum
Definition LLToken.h:296
@ kw_unreachable
Definition LLToken.h:356
@ kw_intel_ocl_bicc
Definition LLToken.h:139
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:417
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:151
@ kw_preserve_allcc
Definition LLToken.h:167
@ kw_importType
Definition LLToken.h:407
@ kw_cleanupret
Definition LLToken.h:357
@ kw_shufflevector
Definition LLToken.h:374
@ kw_riscv_vector_cc
Definition LLToken.h:189
@ kw_avr_intrcc
Definition LLToken.h:155
@ kw_definition
Definition LLToken.h:408
@ kw_virtualConstProp
Definition LLToken.h:472
@ kw_vcall_visibility
Definition LLToken.h:461
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:209
@ kw_preserve_mostcc
Definition LLToken.h:166
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:148
@ kw_typeTestRes
Definition LLToken.h:449
@ kw_x86_regcallcc
Definition LLToken.h:145
@ kw_typeIdInfo
Definition LLToken.h:437
@ kw_amdgpu_cs_chain
Definition LLToken.h:181
@ kw_dso_local_equivalent
Definition LLToken.h:379
@ kw_x86_64_sysvcc
Definition LLToken.h:161
@ DbgRecordType
Definition LLToken.h:524
@ kw_address_is_null
Definition LLToken.h:223
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:153
@ kw_uniqueRetVal
Definition LLToken.h:471
@ kw_insertvalue
Definition LLToken.h:377
@ kw_indirectbr
Definition LLToken.h:353
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:578
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
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:1669
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:53
scope_exit(Callable) -> scope_exit< Callable >
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:634
auto cast_or_null(const Y &Val)
Definition Casting.h:714
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:284
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:154
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:156
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:368
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:189
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
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:547
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
IRMemLocation
The locations at which a function might access memory.
Definition ModRef.h:60
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:36
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:2012
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:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:375
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
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
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 NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
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:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
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:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
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.