LLVM 22.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
50#include "llvm/Support/ModRef.h"
53#include <algorithm>
54#include <cassert>
55#include <cstring>
56#include <optional>
57#include <vector>
58
59using namespace llvm;
60
62 "allow-incomplete-ir", cl::init(false), cl::Hidden,
64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
66
67static std::string getTypeString(Type *T) {
68 std::string Result;
69 raw_string_ostream Tmp(Result);
70 Tmp << *T;
71 return Tmp.str();
72}
73
74/// Run: module ::= toplevelentity*
75bool LLParser::Run(bool UpgradeDebugInfo,
76 DataLayoutCallbackTy DataLayoutCallback) {
77 // Prime the lexer.
78 Lex.Lex();
79
80 if (Context.shouldDiscardValueNames())
81 return error(
82 Lex.getLoc(),
83 "Can't read textual IR with a Context that discards named Values");
84
85 if (M) {
86 if (parseTargetDefinitions(DataLayoutCallback))
87 return true;
88 }
89
90 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
91 validateEndOfIndex();
92}
93
95 const SlotMapping *Slots) {
96 restoreParsingState(Slots);
97 Lex.Lex();
98
99 Type *Ty = nullptr;
100 if (parseType(Ty) || parseConstantValue(Ty, C))
101 return true;
102 if (Lex.getKind() != lltok::Eof)
103 return error(Lex.getLoc(), "expected end of string");
104 return false;
105}
106
108 const SlotMapping *Slots) {
109 restoreParsingState(Slots);
110 Lex.Lex();
111
112 Read = 0;
113 SMLoc Start = Lex.getLoc();
114 Ty = nullptr;
115 if (parseType(Ty))
116 return true;
117 SMLoc End = Lex.getLoc();
118 Read = End.getPointer() - Start.getPointer();
119
120 return false;
121}
122
124 const SlotMapping *Slots) {
125 restoreParsingState(Slots);
126 Lex.Lex();
127
128 Read = 0;
129 SMLoc Start = Lex.getLoc();
130 Result = nullptr;
131 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
132 SMLoc End = Lex.getLoc();
133 Read = End.getPointer() - Start.getPointer();
134
135 return Status;
136}
137
138void LLParser::restoreParsingState(const SlotMapping *Slots) {
139 if (!Slots)
140 return;
141 NumberedVals = Slots->GlobalValues;
142 NumberedMetadata = Slots->MetadataNodes;
143 for (const auto &I : Slots->NamedTypes)
144 NamedTypes.insert(
145 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
146 for (const auto &I : Slots->Types)
147 NumberedTypes.insert(
148 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
149}
150
152 // White-list intrinsics that are safe to drop.
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
155 return;
156
158 for (Value *V : II->args())
159 if (auto *MV = dyn_cast<MetadataAsValue>(V))
160 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
161 if (MD->isTemporary())
162 MVs.push_back(MV);
163
164 if (!MVs.empty()) {
165 assert(II->use_empty() && "Cannot have uses");
166 II->eraseFromParent();
167
168 // Also remove no longer used MetadataAsValue wrappers.
169 for (MetadataAsValue *MV : MVs)
170 if (MV->use_empty())
171 delete MV;
172 }
173}
174
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
177 for (Function &F : *M) {
178 F.eraseMetadataIf(Pred);
179 for (Instruction &I : make_early_inc_range(instructions(F))) {
180 I.eraseMetadataIf(Pred);
181
182 if (auto *II = dyn_cast<IntrinsicInst>(&I))
184 }
185 }
186
187 for (GlobalVariable &GV : M->globals())
188 GV.eraseMetadataIf(Pred);
189
190 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
191 // Check whether there is only a single use left, which would be in our
192 // own NumberedMetadata.
193 if (Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(ID);
195 ForwardRefMDNodes.erase(ID);
196 }
197 }
198}
199
200/// validateEndOfModule - Do final validity and basic correctness checks at the
201/// end of the module.
202bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
203 if (!M)
204 return false;
205
206 // We should have already returned an error if we observed both intrinsics and
207 // records in this IR.
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
210
211 // Handle any function attribute group forward references.
212 for (const auto &RAG : ForwardRefAttrGroups) {
213 Value *V = RAG.first;
214 const std::vector<unsigned> &Attrs = RAG.second;
215 AttrBuilder B(Context);
216
217 for (const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
220 B.merge(R->second);
221 }
222
223 if (Function *Fn = dyn_cast<Function>(V)) {
224 AttributeList AS = Fn->getAttributes();
225 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
226 AS = AS.removeFnAttributes(Context);
227
228 FnAttrs.merge(B);
229
230 // If the alignment was parsed as an attribute, move to the alignment
231 // field.
232 if (MaybeAlign A = FnAttrs.getAlignment()) {
233 Fn->setAlignment(*A);
234 FnAttrs.removeAttribute(Attribute::Alignment);
235 }
236
237 AS = AS.addFnAttributes(Context, FnAttrs);
238 Fn->setAttributes(AS);
239 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
240 AttributeList AS = CI->getAttributes();
241 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
242 AS = AS.removeFnAttributes(Context);
243 FnAttrs.merge(B);
244 AS = AS.addFnAttributes(Context, FnAttrs);
245 CI->setAttributes(AS);
246 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
247 AttributeList AS = II->getAttributes();
248 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
249 AS = AS.removeFnAttributes(Context);
250 FnAttrs.merge(B);
251 AS = AS.addFnAttributes(Context, FnAttrs);
252 II->setAttributes(AS);
253 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
254 AttributeList AS = CBI->getAttributes();
255 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
256 AS = AS.removeFnAttributes(Context);
257 FnAttrs.merge(B);
258 AS = AS.addFnAttributes(Context, FnAttrs);
259 CBI->setAttributes(AS);
260 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
261 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
262 Attrs.merge(B);
263 GV->setAttributes(AttributeSet::get(Context,Attrs));
264 } else {
265 llvm_unreachable("invalid object with forward attribute group reference");
266 }
267 }
268
269 // If there are entries in ForwardRefBlockAddresses at this point, the
270 // function was never defined.
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
274
275 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
276 GlobalValue *FwdRef) {
277 GlobalValue *GV = nullptr;
278 if (GVRef.Kind == ValID::t_GlobalName) {
279 GV = M->getNamedValue(GVRef.StrVal);
280 } else {
281 GV = NumberedVals.get(GVRef.UIntVal);
282 }
283
284 if (!GV)
285 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
286 "' referenced by dso_local_equivalent");
287
288 if (!GV->getValueType()->isFunctionTy())
289 return error(GVRef.Loc,
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
292
293 auto *Equiv = DSOLocalEquivalent::get(GV);
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
296 return false;
297 };
298
299 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
300 // point, they are references after the function was defined. Resolve those
301 // now.
302 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
304 return true;
305 }
306 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
308 return true;
309 }
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
312
313 for (const auto &NT : NumberedTypes)
314 if (NT.second.second.isValid())
315 return error(NT.second.second,
316 "use of undefined type '%" + Twine(NT.first) + "'");
317
318 for (const auto &[Name, TypeInfo] : NamedTypes)
319 if (TypeInfo.second.isValid())
320 return error(TypeInfo.second,
321 "use of undefined type named '" + Name + "'");
322
323 if (!ForwardRefComdats.empty())
324 return error(ForwardRefComdats.begin()->second,
325 "use of undefined comdat '$" +
326 ForwardRefComdats.begin()->first + "'");
327
328 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
329 if (StringRef(Name).starts_with("llvm.")) {
331 // Automatically create declarations for intrinsics. Intrinsics can only
332 // be called directly, so the call function type directly determines the
333 // declaration function type.
334 //
335 // Additionally, automatically add the required mangling suffix to the
336 // intrinsic name. This means that we may replace a single forward
337 // declaration with multiple functions here.
338 for (Use &U : make_early_inc_range(Info.first->uses())) {
339 auto *CB = dyn_cast<CallBase>(U.getUser());
340 if (!CB || !CB->isCallee(&U))
341 return error(Info.second, "intrinsic can only be used as callee");
342
343 SmallVector<Type *> OverloadTys;
344 if (IID != Intrinsic::not_intrinsic &&
345 Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
346 OverloadTys)) {
347 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
348 } else {
349 // Try to upgrade the intrinsic.
350 Function *TmpF = Function::Create(CB->getFunctionType(),
352 Function *NewF = nullptr;
353 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
354 if (IID == Intrinsic::not_intrinsic)
355 return error(Info.second, "unknown intrinsic '" + Name + "'");
356 return error(Info.second, "invalid intrinsic signature");
357 }
358
359 U.set(TmpF);
360 UpgradeIntrinsicCall(CB, NewF);
361 if (TmpF->use_empty())
362 TmpF->eraseFromParent();
363 }
364 }
365
366 Info.first->eraseFromParent();
367 ForwardRefVals.erase(Name);
368 continue;
369 }
370
371 // If incomplete IR is allowed, also add declarations for
372 // non-intrinsics.
374 continue;
375
376 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
377 FunctionType *FTy = nullptr;
378 for (Use &U : V->uses()) {
379 auto *CB = dyn_cast<CallBase>(U.getUser());
380 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
381 return nullptr;
382 FTy = CB->getFunctionType();
383 }
384 return FTy;
385 };
386
387 // First check whether this global is only used in calls with the same
388 // type, in which case we'll insert a function. Otherwise, fall back to
389 // using a dummy i8 type.
390 Type *Ty = GetCommonFunctionType(Info.first);
391 if (!Ty)
392 Ty = Type::getInt8Ty(Context);
393
394 GlobalValue *GV;
395 if (auto *FTy = dyn_cast<FunctionType>(Ty))
397 else
398 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
400 /*Initializer*/ nullptr, Name);
401 Info.first->replaceAllUsesWith(GV);
402 Info.first->eraseFromParent();
403 ForwardRefVals.erase(Name);
404 }
405
406 if (!ForwardRefVals.empty())
407 return error(ForwardRefVals.begin()->second.second,
408 "use of undefined value '@" + ForwardRefVals.begin()->first +
409 "'");
410
411 if (!ForwardRefValIDs.empty())
412 return error(ForwardRefValIDs.begin()->second.second,
413 "use of undefined value '@" +
414 Twine(ForwardRefValIDs.begin()->first) + "'");
415
416 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
417 dropUnknownMetadataReferences();
418
419 if (!ForwardRefMDNodes.empty())
420 return error(ForwardRefMDNodes.begin()->second.second,
421 "use of undefined metadata '!" +
422 Twine(ForwardRefMDNodes.begin()->first) + "'");
423
424 // Resolve metadata cycles.
425 for (auto &N : NumberedMetadata) {
426 if (N.second && !N.second->isResolved())
427 N.second->resolveCycles();
428 }
429
430 for (auto *Inst : InstsWithTBAATag) {
431 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
432 // With incomplete IR, the tbaa metadata may have been dropped.
434 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
435 if (MD) {
436 auto *UpgradedMD = UpgradeTBAANode(*MD);
437 if (MD != UpgradedMD)
438 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
439 }
440 }
441
442 // Look for intrinsic functions and CallInst that need to be upgraded. We use
443 // make_early_inc_range here because we may remove some functions.
444 for (Function &F : llvm::make_early_inc_range(*M))
446
447 if (UpgradeDebugInfo)
449
454
455 if (!Slots)
456 return false;
457 // Initialize the slot mapping.
458 // Because by this point we've parsed and validated everything, we can "steal"
459 // the mapping from LLParser as it doesn't need it anymore.
460 Slots->GlobalValues = std::move(NumberedVals);
461 Slots->MetadataNodes = std::move(NumberedMetadata);
462 for (const auto &I : NamedTypes)
463 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
464 for (const auto &I : NumberedTypes)
465 Slots->Types.insert(std::make_pair(I.first, I.second.first));
466
467 return false;
468}
469
470/// Do final validity and basic correctness checks at the end of the index.
471bool LLParser::validateEndOfIndex() {
472 if (!Index)
473 return false;
474
475 if (!ForwardRefValueInfos.empty())
476 return error(ForwardRefValueInfos.begin()->second.front().second,
477 "use of undefined summary '^" +
478 Twine(ForwardRefValueInfos.begin()->first) + "'");
479
480 if (!ForwardRefAliasees.empty())
481 return error(ForwardRefAliasees.begin()->second.front().second,
482 "use of undefined summary '^" +
483 Twine(ForwardRefAliasees.begin()->first) + "'");
484
485 if (!ForwardRefTypeIds.empty())
486 return error(ForwardRefTypeIds.begin()->second.front().second,
487 "use of undefined type id summary '^" +
488 Twine(ForwardRefTypeIds.begin()->first) + "'");
489
490 return false;
491}
492
493//===----------------------------------------------------------------------===//
494// Top-Level Entities
495//===----------------------------------------------------------------------===//
496
497bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
498 // Delay parsing of the data layout string until the target triple is known.
499 // Then, pass both the the target triple and the tentative data layout string
500 // to DataLayoutCallback, allowing to override the DL string.
501 // This enables importing modules with invalid DL strings.
502 std::string TentativeDLStr = M->getDataLayoutStr();
503 LocTy DLStrLoc;
504
505 bool Done = false;
506 while (!Done) {
507 switch (Lex.getKind()) {
508 case lltok::kw_target:
509 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
510 return true;
511 break;
513 if (parseSourceFileName())
514 return true;
515 break;
516 default:
517 Done = true;
518 }
519 }
520 // Run the override callback to potentially change the data layout string, and
521 // parse the data layout string.
522 if (auto LayoutOverride =
523 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
524 TentativeDLStr = *LayoutOverride;
525 DLStrLoc = {};
526 }
527 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
528 if (!MaybeDL)
529 return error(DLStrLoc, toString(MaybeDL.takeError()));
530 M->setDataLayout(MaybeDL.get());
531 return false;
532}
533
534bool LLParser::parseTopLevelEntities() {
535 // If there is no Module, then parse just the summary index entries.
536 if (!M) {
537 while (true) {
538 switch (Lex.getKind()) {
539 case lltok::Eof:
540 return false;
541 case lltok::SummaryID:
542 if (parseSummaryEntry())
543 return true;
544 break;
546 if (parseSourceFileName())
547 return true;
548 break;
549 default:
550 // Skip everything else
551 Lex.Lex();
552 }
553 }
554 }
555 while (true) {
556 switch (Lex.getKind()) {
557 default:
558 return tokError("expected top-level entity");
559 case lltok::Eof: return false;
561 if (parseDeclare())
562 return true;
563 break;
564 case lltok::kw_define:
565 if (parseDefine())
566 return true;
567 break;
568 case lltok::kw_module:
569 if (parseModuleAsm())
570 return true;
571 break;
573 if (parseUnnamedType())
574 return true;
575 break;
576 case lltok::LocalVar:
577 if (parseNamedType())
578 return true;
579 break;
580 case lltok::GlobalID:
581 if (parseUnnamedGlobal())
582 return true;
583 break;
584 case lltok::GlobalVar:
585 if (parseNamedGlobal())
586 return true;
587 break;
588 case lltok::ComdatVar: if (parseComdat()) return true; break;
589 case lltok::exclaim:
590 if (parseStandaloneMetadata())
591 return true;
592 break;
593 case lltok::SummaryID:
594 if (parseSummaryEntry())
595 return true;
596 break;
598 if (parseNamedMetadata())
599 return true;
600 break;
602 if (parseUnnamedAttrGrp())
603 return true;
604 break;
606 if (parseUseListOrder())
607 return true;
608 break;
610 if (parseUseListOrderBB())
611 return true;
612 break;
613 }
614 }
615}
616
617/// toplevelentity
618/// ::= 'module' 'asm' STRINGCONSTANT
619bool LLParser::parseModuleAsm() {
620 assert(Lex.getKind() == lltok::kw_module);
621 Lex.Lex();
622
623 std::string AsmStr;
624 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
625 parseStringConstant(AsmStr))
626 return true;
627
628 M->appendModuleInlineAsm(AsmStr);
629 return false;
630}
631
632/// toplevelentity
633/// ::= 'target' 'triple' '=' STRINGCONSTANT
634/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
635bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
636 LocTy &DLStrLoc) {
637 assert(Lex.getKind() == lltok::kw_target);
638 std::string Str;
639 switch (Lex.Lex()) {
640 default:
641 return tokError("unknown target property");
642 case lltok::kw_triple:
643 Lex.Lex();
644 if (parseToken(lltok::equal, "expected '=' after target triple") ||
645 parseStringConstant(Str))
646 return true;
647 M->setTargetTriple(Triple(std::move(Str)));
648 return false;
650 Lex.Lex();
651 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
652 return true;
653 DLStrLoc = Lex.getLoc();
654 if (parseStringConstant(TentativeDLStr))
655 return true;
656 return false;
657 }
658}
659
660/// toplevelentity
661/// ::= 'source_filename' '=' STRINGCONSTANT
662bool LLParser::parseSourceFileName() {
663 assert(Lex.getKind() == lltok::kw_source_filename);
664 Lex.Lex();
665 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
666 parseStringConstant(SourceFileName))
667 return true;
668 if (M)
669 M->setSourceFileName(SourceFileName);
670 return false;
671}
672
673/// parseUnnamedType:
674/// ::= LocalVarID '=' 'type' type
675bool LLParser::parseUnnamedType() {
676 LocTy TypeLoc = Lex.getLoc();
677 unsigned TypeID = Lex.getUIntVal();
678 Lex.Lex(); // eat LocalVarID;
679
680 if (parseToken(lltok::equal, "expected '=' after name") ||
681 parseToken(lltok::kw_type, "expected 'type' after '='"))
682 return true;
683
684 Type *Result = nullptr;
685 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
686 return true;
687
688 if (!isa<StructType>(Result)) {
689 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
690 if (Entry.first)
691 return error(TypeLoc, "non-struct types may not be recursive");
692 Entry.first = Result;
693 Entry.second = SMLoc();
694 }
695
696 return false;
697}
698
699/// toplevelentity
700/// ::= LocalVar '=' 'type' type
701bool LLParser::parseNamedType() {
702 std::string Name = Lex.getStrVal();
703 LocTy NameLoc = Lex.getLoc();
704 Lex.Lex(); // eat LocalVar.
705
706 if (parseToken(lltok::equal, "expected '=' after name") ||
707 parseToken(lltok::kw_type, "expected 'type' after name"))
708 return true;
709
710 Type *Result = nullptr;
711 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
712 return true;
713
714 if (!isa<StructType>(Result)) {
715 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
716 if (Entry.first)
717 return error(NameLoc, "non-struct types may not be recursive");
718 Entry.first = Result;
719 Entry.second = SMLoc();
720 }
721
722 return false;
723}
724
725/// toplevelentity
726/// ::= 'declare' FunctionHeader
727bool LLParser::parseDeclare() {
728 assert(Lex.getKind() == lltok::kw_declare);
729 Lex.Lex();
730
731 std::vector<std::pair<unsigned, MDNode *>> MDs;
732 while (Lex.getKind() == lltok::MetadataVar) {
733 unsigned MDK;
734 MDNode *N;
735 if (parseMetadataAttachment(MDK, N))
736 return true;
737 MDs.push_back({MDK, N});
738 }
739
740 Function *F;
741 unsigned FunctionNumber = -1;
742 SmallVector<unsigned> UnnamedArgNums;
743 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
744 return true;
745 for (auto &MD : MDs)
746 F->addMetadata(MD.first, *MD.second);
747 return false;
748}
749
750/// toplevelentity
751/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
752bool LLParser::parseDefine() {
753 assert(Lex.getKind() == lltok::kw_define);
754 FileLoc FunctionStart(Lex.getTokLineColumnPos());
755 Lex.Lex();
756
757 Function *F;
758 unsigned FunctionNumber = -1;
759 SmallVector<unsigned> UnnamedArgNums;
760 bool RetValue =
761 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
762 parseOptionalFunctionMetadata(*F) ||
763 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
764 if (ParserContext)
765 ParserContext->addFunctionLocation(
766 F, FileLocRange(FunctionStart, Lex.getPrevTokEndLineColumnPos()));
767
768 return RetValue;
769}
770
771/// parseGlobalType
772/// ::= 'constant'
773/// ::= 'global'
774bool LLParser::parseGlobalType(bool &IsConstant) {
775 if (Lex.getKind() == lltok::kw_constant)
776 IsConstant = true;
777 else if (Lex.getKind() == lltok::kw_global)
778 IsConstant = false;
779 else {
780 IsConstant = false;
781 return tokError("expected 'global' or 'constant'");
782 }
783 Lex.Lex();
784 return false;
785}
786
787bool LLParser::parseOptionalUnnamedAddr(
788 GlobalVariable::UnnamedAddr &UnnamedAddr) {
789 if (EatIfPresent(lltok::kw_unnamed_addr))
791 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
793 else
794 UnnamedAddr = GlobalValue::UnnamedAddr::None;
795 return false;
796}
797
798/// parseUnnamedGlobal:
799/// OptionalVisibility (ALIAS | IFUNC) ...
800/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
801/// OptionalDLLStorageClass
802/// ... -> global variable
803/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
804/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
805/// OptionalVisibility
806/// OptionalDLLStorageClass
807/// ... -> global variable
808bool LLParser::parseUnnamedGlobal() {
809 unsigned VarID;
810 std::string Name;
811 LocTy NameLoc = Lex.getLoc();
812
813 // Handle the GlobalID form.
814 if (Lex.getKind() == lltok::GlobalID) {
815 VarID = Lex.getUIntVal();
816 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
817 return true;
818
819 Lex.Lex(); // eat GlobalID;
820 if (parseToken(lltok::equal, "expected '=' after name"))
821 return true;
822 } else {
823 VarID = NumberedVals.getNext();
824 }
825
826 bool HasLinkage;
827 unsigned Linkage, Visibility, DLLStorageClass;
828 bool DSOLocal;
830 GlobalVariable::UnnamedAddr UnnamedAddr;
831 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
832 DSOLocal) ||
833 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
834 return true;
835
836 switch (Lex.getKind()) {
837 default:
838 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
839 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
840 case lltok::kw_alias:
841 case lltok::kw_ifunc:
842 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
843 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
844 }
845}
846
847/// parseNamedGlobal:
848/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
849/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
850/// OptionalVisibility OptionalDLLStorageClass
851/// ... -> global variable
852bool LLParser::parseNamedGlobal() {
853 assert(Lex.getKind() == lltok::GlobalVar);
854 LocTy NameLoc = Lex.getLoc();
855 std::string Name = Lex.getStrVal();
856 Lex.Lex();
857
858 bool HasLinkage;
859 unsigned Linkage, Visibility, DLLStorageClass;
860 bool DSOLocal;
862 GlobalVariable::UnnamedAddr UnnamedAddr;
863 if (parseToken(lltok::equal, "expected '=' in global variable") ||
864 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
865 DSOLocal) ||
866 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
867 return true;
868
869 switch (Lex.getKind()) {
870 default:
871 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
872 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
873 case lltok::kw_alias:
874 case lltok::kw_ifunc:
875 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
876 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
877 }
878}
879
880bool LLParser::parseComdat() {
881 assert(Lex.getKind() == lltok::ComdatVar);
882 std::string Name = Lex.getStrVal();
883 LocTy NameLoc = Lex.getLoc();
884 Lex.Lex();
885
886 if (parseToken(lltok::equal, "expected '=' here"))
887 return true;
888
889 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
890 return tokError("expected comdat type");
891
893 switch (Lex.getKind()) {
894 default:
895 return tokError("unknown selection kind");
896 case lltok::kw_any:
897 SK = Comdat::Any;
898 break;
901 break;
903 SK = Comdat::Largest;
904 break;
907 break;
909 SK = Comdat::SameSize;
910 break;
911 }
912 Lex.Lex();
913
914 // See if the comdat was forward referenced, if so, use the comdat.
915 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
916 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
917 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
918 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
919
920 Comdat *C;
921 if (I != ComdatSymTab.end())
922 C = &I->second;
923 else
924 C = M->getOrInsertComdat(Name);
925 C->setSelectionKind(SK);
926
927 return false;
928}
929
930// MDString:
931// ::= '!' STRINGCONSTANT
932bool LLParser::parseMDString(MDString *&Result) {
933 std::string Str;
934 if (parseStringConstant(Str))
935 return true;
936 Result = MDString::get(Context, Str);
937 return false;
938}
939
940// MDNode:
941// ::= '!' MDNodeNumber
942bool LLParser::parseMDNodeID(MDNode *&Result) {
943 // !{ ..., !42, ... }
944 LocTy IDLoc = Lex.getLoc();
945 unsigned MID = 0;
946 if (parseUInt32(MID))
947 return true;
948
949 // If not a forward reference, just return it now.
950 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
951 if (!Inserted) {
952 Result = It->second;
953 return false;
954 }
955
956 // Otherwise, create MDNode forward reference.
957 auto &FwdRef = ForwardRefMDNodes[MID];
958 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
959
960 Result = FwdRef.first.get();
961 It->second.reset(Result);
962 return false;
963}
964
965/// parseNamedMetadata:
966/// !foo = !{ !1, !2 }
967bool LLParser::parseNamedMetadata() {
968 assert(Lex.getKind() == lltok::MetadataVar);
969 std::string Name = Lex.getStrVal();
970 Lex.Lex();
971
972 if (parseToken(lltok::equal, "expected '=' here") ||
973 parseToken(lltok::exclaim, "Expected '!' here") ||
974 parseToken(lltok::lbrace, "Expected '{' here"))
975 return true;
976
977 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
978 if (Lex.getKind() != lltok::rbrace)
979 do {
980 MDNode *N = nullptr;
981 // parse DIExpressions inline as a special case. They are still MDNodes,
982 // so they can still appear in named metadata. Remove this logic if they
983 // become plain Metadata.
984 if (Lex.getKind() == lltok::MetadataVar &&
985 Lex.getStrVal() == "DIExpression") {
986 if (parseDIExpression(N, /*IsDistinct=*/false))
987 return true;
988 // DIArgLists should only appear inline in a function, as they may
989 // contain LocalAsMetadata arguments which require a function context.
990 } else if (Lex.getKind() == lltok::MetadataVar &&
991 Lex.getStrVal() == "DIArgList") {
992 return tokError("found DIArgList outside of function");
993 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
994 parseMDNodeID(N)) {
995 return true;
996 }
997 NMD->addOperand(N);
998 } while (EatIfPresent(lltok::comma));
999
1000 return parseToken(lltok::rbrace, "expected end of metadata node");
1001}
1002
1003/// parseStandaloneMetadata:
1004/// !42 = !{...}
1005bool LLParser::parseStandaloneMetadata() {
1006 assert(Lex.getKind() == lltok::exclaim);
1007 Lex.Lex();
1008 unsigned MetadataID = 0;
1009
1010 MDNode *Init;
1011 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1012 return true;
1013
1014 // Detect common error, from old metadata syntax.
1015 if (Lex.getKind() == lltok::Type)
1016 return tokError("unexpected type in metadata definition");
1017
1018 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1019 if (Lex.getKind() == lltok::MetadataVar) {
1020 if (parseSpecializedMDNode(Init, IsDistinct))
1021 return true;
1022 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1023 parseMDTuple(Init, IsDistinct))
1024 return true;
1025
1026 // See if this was forward referenced, if so, handle it.
1027 auto FI = ForwardRefMDNodes.find(MetadataID);
1028 if (FI != ForwardRefMDNodes.end()) {
1029 auto *ToReplace = FI->second.first.get();
1030 // DIAssignID has its own special forward-reference "replacement" for
1031 // attachments (the temporary attachments are never actually attached).
1032 if (isa<DIAssignID>(Init)) {
1033 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1034 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1035 "Inst unexpectedly already has DIAssignID attachment");
1036 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1037 }
1038 }
1039
1040 ToReplace->replaceAllUsesWith(Init);
1041 ForwardRefMDNodes.erase(FI);
1042
1043 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1044 } else {
1045 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1046 if (!Inserted)
1047 return tokError("Metadata id is already used");
1048 It->second.reset(Init);
1049 }
1050
1051 return false;
1052}
1053
1054// Skips a single module summary entry.
1055bool LLParser::skipModuleSummaryEntry() {
1056 // Each module summary entry consists of a tag for the entry
1057 // type, followed by a colon, then the fields which may be surrounded by
1058 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1059 // support is in place we will look for the tokens corresponding to the
1060 // expected tags.
1061 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1062 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1063 Lex.getKind() != lltok::kw_blockcount)
1064 return tokError(
1065 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1066 "start of summary entry");
1067 if (Lex.getKind() == lltok::kw_flags)
1068 return parseSummaryIndexFlags();
1069 if (Lex.getKind() == lltok::kw_blockcount)
1070 return parseBlockCount();
1071 Lex.Lex();
1072 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1073 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1074 return true;
1075 // Now walk through the parenthesized entry, until the number of open
1076 // parentheses goes back down to 0 (the first '(' was parsed above).
1077 unsigned NumOpenParen = 1;
1078 do {
1079 switch (Lex.getKind()) {
1080 case lltok::lparen:
1081 NumOpenParen++;
1082 break;
1083 case lltok::rparen:
1084 NumOpenParen--;
1085 break;
1086 case lltok::Eof:
1087 return tokError("found end of file while parsing summary entry");
1088 default:
1089 // Skip everything in between parentheses.
1090 break;
1091 }
1092 Lex.Lex();
1093 } while (NumOpenParen > 0);
1094 return false;
1095}
1096
1097/// SummaryEntry
1098/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1099bool LLParser::parseSummaryEntry() {
1100 assert(Lex.getKind() == lltok::SummaryID);
1101 unsigned SummaryID = Lex.getUIntVal();
1102
1103 // For summary entries, colons should be treated as distinct tokens,
1104 // not an indication of the end of a label token.
1105 Lex.setIgnoreColonInIdentifiers(true);
1106
1107 Lex.Lex();
1108 if (parseToken(lltok::equal, "expected '=' here"))
1109 return true;
1110
1111 // If we don't have an index object, skip the summary entry.
1112 if (!Index)
1113 return skipModuleSummaryEntry();
1114
1115 bool result = false;
1116 switch (Lex.getKind()) {
1117 case lltok::kw_gv:
1118 result = parseGVEntry(SummaryID);
1119 break;
1120 case lltok::kw_module:
1121 result = parseModuleEntry(SummaryID);
1122 break;
1123 case lltok::kw_typeid:
1124 result = parseTypeIdEntry(SummaryID);
1125 break;
1127 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1128 break;
1129 case lltok::kw_flags:
1130 result = parseSummaryIndexFlags();
1131 break;
1133 result = parseBlockCount();
1134 break;
1135 default:
1136 result = error(Lex.getLoc(), "unexpected summary kind");
1137 break;
1138 }
1139 Lex.setIgnoreColonInIdentifiers(false);
1140 return result;
1141}
1142
1151
1152// If there was an explicit dso_local, update GV. In the absence of an explicit
1153// dso_local we keep the default value.
1154static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1155 if (DSOLocal)
1156 GV.setDSOLocal(true);
1157}
1158
1159/// parseAliasOrIFunc:
1160/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1161/// OptionalVisibility OptionalDLLStorageClass
1162/// OptionalThreadLocal OptionalUnnamedAddr
1163/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1164///
1165/// AliaseeOrResolver
1166/// ::= TypeAndValue
1167///
1168/// SymbolAttrs
1169/// ::= ',' 'partition' StringConstant
1170///
1171/// Everything through OptionalUnnamedAddr has already been parsed.
1172///
1173bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1174 LocTy NameLoc, unsigned L, unsigned Visibility,
1175 unsigned DLLStorageClass, bool DSOLocal,
1177 GlobalVariable::UnnamedAddr UnnamedAddr) {
1178 bool IsAlias;
1179 if (Lex.getKind() == lltok::kw_alias)
1180 IsAlias = true;
1181 else if (Lex.getKind() == lltok::kw_ifunc)
1182 IsAlias = false;
1183 else
1184 llvm_unreachable("Not an alias or ifunc!");
1185 Lex.Lex();
1186
1188
1189 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1190 return error(NameLoc, "invalid linkage type for alias");
1191
1192 if (!isValidVisibilityForLinkage(Visibility, L))
1193 return error(NameLoc,
1194 "symbol with local linkage must have default visibility");
1195
1196 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1197 return error(NameLoc,
1198 "symbol with local linkage cannot have a DLL storage class");
1199
1200 Type *Ty;
1201 LocTy ExplicitTypeLoc = Lex.getLoc();
1202 if (parseType(Ty) ||
1203 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1204 return true;
1205
1206 Constant *Aliasee;
1207 LocTy AliaseeLoc = Lex.getLoc();
1208 if (Lex.getKind() != lltok::kw_bitcast &&
1209 Lex.getKind() != lltok::kw_getelementptr &&
1210 Lex.getKind() != lltok::kw_addrspacecast &&
1211 Lex.getKind() != lltok::kw_inttoptr) {
1212 if (parseGlobalTypeAndValue(Aliasee))
1213 return true;
1214 } else {
1215 // The bitcast dest type is not present, it is implied by the dest type.
1216 ValID ID;
1217 if (parseValID(ID, /*PFS=*/nullptr))
1218 return true;
1219 if (ID.Kind != ValID::t_Constant)
1220 return error(AliaseeLoc, "invalid aliasee");
1221 Aliasee = ID.ConstantVal;
1222 }
1223
1224 Type *AliaseeType = Aliasee->getType();
1225 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1226 if (!PTy)
1227 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1228 unsigned AddrSpace = PTy->getAddressSpace();
1229
1230 GlobalValue *GVal = nullptr;
1231
1232 // See if the alias was forward referenced, if so, prepare to replace the
1233 // forward reference.
1234 if (!Name.empty()) {
1235 auto I = ForwardRefVals.find(Name);
1236 if (I != ForwardRefVals.end()) {
1237 GVal = I->second.first;
1238 ForwardRefVals.erase(Name);
1239 } else if (M->getNamedValue(Name)) {
1240 return error(NameLoc, "redefinition of global '@" + Name + "'");
1241 }
1242 } else {
1243 auto I = ForwardRefValIDs.find(NameID);
1244 if (I != ForwardRefValIDs.end()) {
1245 GVal = I->second.first;
1246 ForwardRefValIDs.erase(I);
1247 }
1248 }
1249
1250 // Okay, create the alias/ifunc but do not insert it into the module yet.
1251 std::unique_ptr<GlobalAlias> GA;
1252 std::unique_ptr<GlobalIFunc> GI;
1253 GlobalValue *GV;
1254 if (IsAlias) {
1255 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1256 /*Parent=*/nullptr));
1257 GV = GA.get();
1258 } else {
1259 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1260 /*Parent=*/nullptr));
1261 GV = GI.get();
1262 }
1263 GV->setThreadLocalMode(TLM);
1266 GV->setUnnamedAddr(UnnamedAddr);
1267 maybeSetDSOLocal(DSOLocal, *GV);
1268
1269 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1270 // Now parse them if there are any.
1271 while (Lex.getKind() == lltok::comma) {
1272 Lex.Lex();
1273
1274 if (Lex.getKind() == lltok::kw_partition) {
1275 Lex.Lex();
1276 GV->setPartition(Lex.getStrVal());
1277 if (parseToken(lltok::StringConstant, "expected partition string"))
1278 return true;
1279 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1280 if (parseGlobalObjectMetadataAttachment(*GI))
1281 return true;
1282 } else {
1283 return tokError("unknown alias or ifunc property!");
1284 }
1285 }
1286
1287 if (Name.empty())
1288 NumberedVals.add(NameID, GV);
1289
1290 if (GVal) {
1291 // Verify that types agree.
1292 if (GVal->getType() != GV->getType())
1293 return error(
1294 ExplicitTypeLoc,
1295 "forward reference and definition of alias have different types");
1296
1297 // If they agree, just RAUW the old value with the alias and remove the
1298 // forward ref info.
1299 GVal->replaceAllUsesWith(GV);
1300 GVal->eraseFromParent();
1301 }
1302
1303 // Insert into the module, we know its name won't collide now.
1304 if (IsAlias)
1305 M->insertAlias(GA.release());
1306 else
1307 M->insertIFunc(GI.release());
1308 assert(GV->getName() == Name && "Should not be a name conflict!");
1309
1310 return false;
1311}
1312
1313static bool isSanitizer(lltok::Kind Kind) {
1314 switch (Kind) {
1317 case lltok::kw_sanitize_memtag:
1319 return true;
1320 default:
1321 return false;
1322 }
1323}
1324
1325bool LLParser::parseSanitizer(GlobalVariable *GV) {
1326 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1328 if (GV->hasSanitizerMetadata())
1329 Meta = GV->getSanitizerMetadata();
1330
1331 switch (Lex.getKind()) {
1333 Meta.NoAddress = true;
1334 break;
1336 Meta.NoHWAddress = true;
1337 break;
1338 case lltok::kw_sanitize_memtag:
1339 Meta.Memtag = true;
1340 break;
1342 Meta.IsDynInit = true;
1343 break;
1344 default:
1345 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1346 }
1347 GV->setSanitizerMetadata(Meta);
1348 Lex.Lex();
1349 return false;
1350}
1351
1352/// parseGlobal
1353/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1354/// OptionalVisibility OptionalDLLStorageClass
1355/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1356/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1357/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1358/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1359/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1360/// Const OptionalAttrs
1361///
1362/// Everything up to and including OptionalUnnamedAddr has been parsed
1363/// already.
1364///
1365bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1366 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1367 unsigned Visibility, unsigned DLLStorageClass,
1368 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1369 GlobalVariable::UnnamedAddr UnnamedAddr) {
1370 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1371 return error(NameLoc,
1372 "symbol with local linkage must have default visibility");
1373
1374 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1375 return error(NameLoc,
1376 "symbol with local linkage cannot have a DLL storage class");
1377
1378 unsigned AddrSpace;
1379 bool IsConstant, IsExternallyInitialized;
1380 LocTy IsExternallyInitializedLoc;
1381 LocTy TyLoc;
1382
1383 Type *Ty = nullptr;
1384 if (parseOptionalAddrSpace(AddrSpace) ||
1385 parseOptionalToken(lltok::kw_externally_initialized,
1386 IsExternallyInitialized,
1387 &IsExternallyInitializedLoc) ||
1388 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1389 return true;
1390
1391 // If the linkage is specified and is external, then no initializer is
1392 // present.
1393 Constant *Init = nullptr;
1394 if (!HasLinkage ||
1397 if (parseGlobalValue(Ty, Init))
1398 return true;
1399 }
1400
1402 return error(TyLoc, "invalid type for global variable");
1403
1404 GlobalValue *GVal = nullptr;
1405
1406 // See if the global was forward referenced, if so, use the global.
1407 if (!Name.empty()) {
1408 auto I = ForwardRefVals.find(Name);
1409 if (I != ForwardRefVals.end()) {
1410 GVal = I->second.first;
1411 ForwardRefVals.erase(I);
1412 } else if (M->getNamedValue(Name)) {
1413 return error(NameLoc, "redefinition of global '@" + Name + "'");
1414 }
1415 } else {
1416 // Handle @"", where a name is syntactically specified, but semantically
1417 // missing.
1418 if (NameID == (unsigned)-1)
1419 NameID = NumberedVals.getNext();
1420
1421 auto I = ForwardRefValIDs.find(NameID);
1422 if (I != ForwardRefValIDs.end()) {
1423 GVal = I->second.first;
1424 ForwardRefValIDs.erase(I);
1425 }
1426 }
1427
1428 GlobalVariable *GV = new GlobalVariable(
1429 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1431
1432 if (Name.empty())
1433 NumberedVals.add(NameID, GV);
1434
1435 // Set the parsed properties on the global.
1436 if (Init)
1437 GV->setInitializer(Init);
1438 GV->setConstant(IsConstant);
1440 maybeSetDSOLocal(DSOLocal, *GV);
1443 GV->setExternallyInitialized(IsExternallyInitialized);
1444 GV->setThreadLocalMode(TLM);
1445 GV->setUnnamedAddr(UnnamedAddr);
1446
1447 if (GVal) {
1448 if (GVal->getAddressSpace() != AddrSpace)
1449 return error(
1450 TyLoc,
1451 "forward reference and definition of global have different types");
1452
1453 GVal->replaceAllUsesWith(GV);
1454 GVal->eraseFromParent();
1455 }
1456
1457 // parse attributes on the global.
1458 while (Lex.getKind() == lltok::comma) {
1459 Lex.Lex();
1460
1461 if (Lex.getKind() == lltok::kw_section) {
1462 Lex.Lex();
1463 GV->setSection(Lex.getStrVal());
1464 if (parseToken(lltok::StringConstant, "expected global section string"))
1465 return true;
1466 } else if (Lex.getKind() == lltok::kw_partition) {
1467 Lex.Lex();
1468 GV->setPartition(Lex.getStrVal());
1469 if (parseToken(lltok::StringConstant, "expected partition string"))
1470 return true;
1471 } else if (Lex.getKind() == lltok::kw_align) {
1472 MaybeAlign Alignment;
1473 if (parseOptionalAlignment(Alignment))
1474 return true;
1475 if (Alignment)
1476 GV->setAlignment(*Alignment);
1477 } else if (Lex.getKind() == lltok::kw_code_model) {
1479 if (parseOptionalCodeModel(CodeModel))
1480 return true;
1481 GV->setCodeModel(CodeModel);
1482 } else if (Lex.getKind() == lltok::MetadataVar) {
1483 if (parseGlobalObjectMetadataAttachment(*GV))
1484 return true;
1485 } else if (isSanitizer(Lex.getKind())) {
1486 if (parseSanitizer(GV))
1487 return true;
1488 } else {
1489 Comdat *C;
1490 if (parseOptionalComdat(Name, C))
1491 return true;
1492 if (C)
1493 GV->setComdat(C);
1494 else
1495 return tokError("unknown global variable property!");
1496 }
1497 }
1498
1499 AttrBuilder Attrs(M->getContext());
1500 LocTy BuiltinLoc;
1501 std::vector<unsigned> FwdRefAttrGrps;
1502 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1503 return true;
1504 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1505 GV->setAttributes(AttributeSet::get(Context, Attrs));
1506 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1507 }
1508
1509 return false;
1510}
1511
1512/// parseUnnamedAttrGrp
1513/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1514bool LLParser::parseUnnamedAttrGrp() {
1515 assert(Lex.getKind() == lltok::kw_attributes);
1516 LocTy AttrGrpLoc = Lex.getLoc();
1517 Lex.Lex();
1518
1519 if (Lex.getKind() != lltok::AttrGrpID)
1520 return tokError("expected attribute group id");
1521
1522 unsigned VarID = Lex.getUIntVal();
1523 std::vector<unsigned> unused;
1524 LocTy BuiltinLoc;
1525 Lex.Lex();
1526
1527 if (parseToken(lltok::equal, "expected '=' here") ||
1528 parseToken(lltok::lbrace, "expected '{' here"))
1529 return true;
1530
1531 auto R = NumberedAttrBuilders.find(VarID);
1532 if (R == NumberedAttrBuilders.end())
1533 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1534
1535 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1536 parseToken(lltok::rbrace, "expected end of attribute group"))
1537 return true;
1538
1539 if (!R->second.hasAttributes())
1540 return error(AttrGrpLoc, "attribute group has no attributes");
1541
1542 return false;
1543}
1544
1546 switch (Kind) {
1547#define GET_ATTR_NAMES
1548#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1549 case lltok::kw_##DISPLAY_NAME: \
1550 return Attribute::ENUM_NAME;
1551#include "llvm/IR/Attributes.inc"
1552 default:
1553 return Attribute::None;
1554 }
1555}
1556
1557bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1558 bool InAttrGroup) {
1559 if (Attribute::isTypeAttrKind(Attr))
1560 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1561
1562 switch (Attr) {
1563 case Attribute::Alignment: {
1564 MaybeAlign Alignment;
1565 if (InAttrGroup) {
1566 uint32_t Value = 0;
1567 Lex.Lex();
1568 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1569 return true;
1570 Alignment = Align(Value);
1571 } else {
1572 if (parseOptionalAlignment(Alignment, true))
1573 return true;
1574 }
1575 B.addAlignmentAttr(Alignment);
1576 return false;
1577 }
1578 case Attribute::StackAlignment: {
1579 unsigned Alignment;
1580 if (InAttrGroup) {
1581 Lex.Lex();
1582 if (parseToken(lltok::equal, "expected '=' here") ||
1583 parseUInt32(Alignment))
1584 return true;
1585 } else {
1586 if (parseOptionalStackAlignment(Alignment))
1587 return true;
1588 }
1589 B.addStackAlignmentAttr(Alignment);
1590 return false;
1591 }
1592 case Attribute::AllocSize: {
1593 unsigned ElemSizeArg;
1594 std::optional<unsigned> NumElemsArg;
1595 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1596 return true;
1597 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1598 return false;
1599 }
1600 case Attribute::VScaleRange: {
1601 unsigned MinValue, MaxValue;
1602 if (parseVScaleRangeArguments(MinValue, MaxValue))
1603 return true;
1604 B.addVScaleRangeAttr(MinValue,
1605 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1606 return false;
1607 }
1608 case Attribute::Dereferenceable: {
1609 uint64_t Bytes;
1610 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1611 return true;
1612 B.addDereferenceableAttr(Bytes);
1613 return false;
1614 }
1615 case Attribute::DereferenceableOrNull: {
1616 uint64_t Bytes;
1617 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1618 return true;
1619 B.addDereferenceableOrNullAttr(Bytes);
1620 return false;
1621 }
1622 case Attribute::UWTable: {
1624 if (parseOptionalUWTableKind(Kind))
1625 return true;
1626 B.addUWTableAttr(Kind);
1627 return false;
1628 }
1629 case Attribute::AllocKind: {
1631 if (parseAllocKind(Kind))
1632 return true;
1633 B.addAllocKindAttr(Kind);
1634 return false;
1635 }
1636 case Attribute::Memory: {
1637 std::optional<MemoryEffects> ME = parseMemoryAttr();
1638 if (!ME)
1639 return true;
1640 B.addMemoryAttr(*ME);
1641 return false;
1642 }
1643 case Attribute::NoFPClass: {
1644 if (FPClassTest NoFPClass =
1645 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1646 B.addNoFPClassAttr(NoFPClass);
1647 return false;
1648 }
1649
1650 return true;
1651 }
1652 case Attribute::Range:
1653 return parseRangeAttr(B);
1654 case Attribute::Initializes:
1655 return parseInitializesAttr(B);
1656 case Attribute::Captures:
1657 return parseCapturesAttr(B);
1658 default:
1659 B.addAttribute(Attr);
1660 Lex.Lex();
1661 return false;
1662 }
1663}
1664
1666 switch (Kind) {
1667 case lltok::kw_readnone:
1668 ME &= MemoryEffects::none();
1669 return true;
1670 case lltok::kw_readonly:
1672 return true;
1673 case lltok::kw_writeonly:
1675 return true;
1678 return true;
1681 return true;
1684 return true;
1685 default:
1686 return false;
1687 }
1688}
1689
1690/// parseFnAttributeValuePairs
1691/// ::= <attr> | <attr> '=' <value>
1692bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1693 std::vector<unsigned> &FwdRefAttrGrps,
1694 bool InAttrGrp, LocTy &BuiltinLoc) {
1695 bool HaveError = false;
1696
1697 B.clear();
1698
1700 while (true) {
1701 lltok::Kind Token = Lex.getKind();
1702 if (Token == lltok::rbrace)
1703 break; // Finished.
1704
1705 if (Token == lltok::StringConstant) {
1706 if (parseStringAttribute(B))
1707 return true;
1708 continue;
1709 }
1710
1711 if (Token == lltok::AttrGrpID) {
1712 // Allow a function to reference an attribute group:
1713 //
1714 // define void @foo() #1 { ... }
1715 if (InAttrGrp) {
1716 HaveError |= error(
1717 Lex.getLoc(),
1718 "cannot have an attribute group reference in an attribute group");
1719 } else {
1720 // Save the reference to the attribute group. We'll fill it in later.
1721 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1722 }
1723 Lex.Lex();
1724 continue;
1725 }
1726
1727 SMLoc Loc = Lex.getLoc();
1728 if (Token == lltok::kw_builtin)
1729 BuiltinLoc = Loc;
1730
1731 if (upgradeMemoryAttr(ME, Token)) {
1732 Lex.Lex();
1733 continue;
1734 }
1735
1737 if (Attr == Attribute::None) {
1738 if (!InAttrGrp)
1739 break;
1740 return error(Lex.getLoc(), "unterminated attribute group");
1741 }
1742
1743 if (parseEnumAttribute(Attr, B, InAttrGrp))
1744 return true;
1745
1746 // As a hack, we allow function alignment to be initially parsed as an
1747 // attribute on a function declaration/definition or added to an attribute
1748 // group and later moved to the alignment field.
1749 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1750 HaveError |= error(Loc, "this attribute does not apply to functions");
1751 }
1752
1753 if (ME != MemoryEffects::unknown())
1754 B.addMemoryAttr(ME);
1755 return HaveError;
1756}
1757
1758//===----------------------------------------------------------------------===//
1759// GlobalValue Reference/Resolution Routines.
1760//===----------------------------------------------------------------------===//
1761
1763 // The used global type does not matter. We will later RAUW it with a
1764 // global/function of the correct type.
1765 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1768 PTy->getAddressSpace());
1769}
1770
1771Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1772 Value *Val) {
1773 Type *ValTy = Val->getType();
1774 if (ValTy == Ty)
1775 return Val;
1776 if (Ty->isLabelTy())
1777 error(Loc, "'" + Name + "' is not a basic block");
1778 else
1779 error(Loc, "'" + Name + "' defined with type '" +
1780 getTypeString(Val->getType()) + "' but expected '" +
1781 getTypeString(Ty) + "'");
1782 return nullptr;
1783}
1784
1785/// getGlobalVal - Get a value with the specified name or ID, creating a
1786/// forward reference record if needed. This can return null if the value
1787/// exists but does not have the right type.
1788GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1789 LocTy Loc) {
1791 if (!PTy) {
1792 error(Loc, "global variable reference must have pointer type");
1793 return nullptr;
1794 }
1795
1796 // Look this name up in the normal function symbol table.
1797 GlobalValue *Val =
1798 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1799
1800 // If this is a forward reference for the value, see if we already created a
1801 // forward ref record.
1802 if (!Val) {
1803 auto I = ForwardRefVals.find(Name);
1804 if (I != ForwardRefVals.end())
1805 Val = I->second.first;
1806 }
1807
1808 // If we have the value in the symbol table or fwd-ref table, return it.
1809 if (Val)
1811 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1812
1813 // Otherwise, create a new forward reference for this value and remember it.
1814 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1815 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1816 return FwdVal;
1817}
1818
1819GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1821 if (!PTy) {
1822 error(Loc, "global variable reference must have pointer type");
1823 return nullptr;
1824 }
1825
1826 GlobalValue *Val = NumberedVals.get(ID);
1827
1828 // If this is a forward reference for the value, see if we already created a
1829 // forward ref record.
1830 if (!Val) {
1831 auto I = ForwardRefValIDs.find(ID);
1832 if (I != ForwardRefValIDs.end())
1833 Val = I->second.first;
1834 }
1835
1836 // If we have the value in the symbol table or fwd-ref table, return it.
1837 if (Val)
1839 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1840
1841 // Otherwise, create a new forward reference for this value and remember it.
1842 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1843 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1844 return FwdVal;
1845}
1846
1847//===----------------------------------------------------------------------===//
1848// Comdat Reference/Resolution Routines.
1849//===----------------------------------------------------------------------===//
1850
1851Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1852 // Look this name up in the comdat symbol table.
1853 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1854 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1855 if (I != ComdatSymTab.end())
1856 return &I->second;
1857
1858 // Otherwise, create a new forward reference for this value and remember it.
1859 Comdat *C = M->getOrInsertComdat(Name);
1860 ForwardRefComdats[Name] = Loc;
1861 return C;
1862}
1863
1864//===----------------------------------------------------------------------===//
1865// Helper Routines.
1866//===----------------------------------------------------------------------===//
1867
1868/// parseToken - If the current token has the specified kind, eat it and return
1869/// success. Otherwise, emit the specified error and return failure.
1870bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1871 if (Lex.getKind() != T)
1872 return tokError(ErrMsg);
1873 Lex.Lex();
1874 return false;
1875}
1876
1877/// parseStringConstant
1878/// ::= StringConstant
1879bool LLParser::parseStringConstant(std::string &Result) {
1880 if (Lex.getKind() != lltok::StringConstant)
1881 return tokError("expected string constant");
1882 Result = Lex.getStrVal();
1883 Lex.Lex();
1884 return false;
1885}
1886
1887/// parseUInt32
1888/// ::= uint32
1889bool LLParser::parseUInt32(uint32_t &Val) {
1890 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1891 return tokError("expected integer");
1892 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1893 if (Val64 != unsigned(Val64))
1894 return tokError("expected 32-bit integer (too large)");
1895 Val = Val64;
1896 Lex.Lex();
1897 return false;
1898}
1899
1900/// parseUInt64
1901/// ::= uint64
1902bool LLParser::parseUInt64(uint64_t &Val) {
1903 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1904 return tokError("expected integer");
1905 Val = Lex.getAPSIntVal().getLimitedValue();
1906 Lex.Lex();
1907 return false;
1908}
1909
1910/// parseTLSModel
1911/// := 'localdynamic'
1912/// := 'initialexec'
1913/// := 'localexec'
1914bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1915 switch (Lex.getKind()) {
1916 default:
1917 return tokError("expected localdynamic, initialexec or localexec");
1920 break;
1923 break;
1926 break;
1927 }
1928
1929 Lex.Lex();
1930 return false;
1931}
1932
1933/// parseOptionalThreadLocal
1934/// := /*empty*/
1935/// := 'thread_local'
1936/// := 'thread_local' '(' tlsmodel ')'
1937bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1939 if (!EatIfPresent(lltok::kw_thread_local))
1940 return false;
1941
1943 if (Lex.getKind() == lltok::lparen) {
1944 Lex.Lex();
1945 return parseTLSModel(TLM) ||
1946 parseToken(lltok::rparen, "expected ')' after thread local model");
1947 }
1948 return false;
1949}
1950
1951/// parseOptionalAddrSpace
1952/// := /*empty*/
1953/// := 'addrspace' '(' uint32 ')'
1954bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1955 AddrSpace = DefaultAS;
1956 if (!EatIfPresent(lltok::kw_addrspace))
1957 return false;
1958
1959 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1960 if (Lex.getKind() == lltok::StringConstant) {
1961 auto AddrSpaceStr = Lex.getStrVal();
1962 if (AddrSpaceStr == "A") {
1963 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1964 } else if (AddrSpaceStr == "G") {
1965 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1966 } else if (AddrSpaceStr == "P") {
1967 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1968 } else {
1969 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1970 }
1971 Lex.Lex();
1972 return false;
1973 }
1974 if (Lex.getKind() != lltok::APSInt)
1975 return tokError("expected integer or string constant");
1976 SMLoc Loc = Lex.getLoc();
1977 if (parseUInt32(AddrSpace))
1978 return true;
1979 if (!isUInt<24>(AddrSpace))
1980 return error(Loc, "invalid address space, must be a 24-bit integer");
1981 return false;
1982 };
1983
1984 return parseToken(lltok::lparen, "expected '(' in address space") ||
1985 ParseAddrspaceValue(AddrSpace) ||
1986 parseToken(lltok::rparen, "expected ')' in address space");
1987}
1988
1989/// parseStringAttribute
1990/// := StringConstant
1991/// := StringConstant '=' StringConstant
1992bool LLParser::parseStringAttribute(AttrBuilder &B) {
1993 std::string Attr = Lex.getStrVal();
1994 Lex.Lex();
1995 std::string Val;
1996 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1997 return true;
1998 B.addAttribute(Attr, Val);
1999 return false;
2000}
2001
2002/// Parse a potentially empty list of parameter or return attributes.
2003bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2004 bool HaveError = false;
2005
2006 B.clear();
2007
2008 while (true) {
2009 lltok::Kind Token = Lex.getKind();
2010 if (Token == lltok::StringConstant) {
2011 if (parseStringAttribute(B))
2012 return true;
2013 continue;
2014 }
2015
2016 if (Token == lltok::kw_nocapture) {
2017 Lex.Lex();
2018 B.addCapturesAttr(CaptureInfo::none());
2019 continue;
2020 }
2021
2022 SMLoc Loc = Lex.getLoc();
2024 if (Attr == Attribute::None)
2025 return HaveError;
2026
2027 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2028 return true;
2029
2030 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2031 HaveError |= error(Loc, "this attribute does not apply to parameters");
2032 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2033 HaveError |= error(Loc, "this attribute does not apply to return values");
2034 }
2035}
2036
2037static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2038 HasLinkage = true;
2039 switch (Kind) {
2040 default:
2041 HasLinkage = false;
2043 case lltok::kw_private:
2045 case lltok::kw_internal:
2047 case lltok::kw_weak:
2049 case lltok::kw_weak_odr:
2051 case lltok::kw_linkonce:
2059 case lltok::kw_common:
2063 case lltok::kw_external:
2065 }
2066}
2067
2068/// parseOptionalLinkage
2069/// ::= /*empty*/
2070/// ::= 'private'
2071/// ::= 'internal'
2072/// ::= 'weak'
2073/// ::= 'weak_odr'
2074/// ::= 'linkonce'
2075/// ::= 'linkonce_odr'
2076/// ::= 'available_externally'
2077/// ::= 'appending'
2078/// ::= 'common'
2079/// ::= 'extern_weak'
2080/// ::= 'external'
2081bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2082 unsigned &Visibility,
2083 unsigned &DLLStorageClass, bool &DSOLocal) {
2084 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2085 if (HasLinkage)
2086 Lex.Lex();
2087 parseOptionalDSOLocal(DSOLocal);
2088 parseOptionalVisibility(Visibility);
2089 parseOptionalDLLStorageClass(DLLStorageClass);
2090
2091 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2092 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2093 }
2094
2095 return false;
2096}
2097
2098void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2099 switch (Lex.getKind()) {
2100 default:
2101 DSOLocal = false;
2102 break;
2104 DSOLocal = true;
2105 Lex.Lex();
2106 break;
2108 DSOLocal = false;
2109 Lex.Lex();
2110 break;
2111 }
2112}
2113
2114/// parseOptionalVisibility
2115/// ::= /*empty*/
2116/// ::= 'default'
2117/// ::= 'hidden'
2118/// ::= 'protected'
2119///
2120void LLParser::parseOptionalVisibility(unsigned &Res) {
2121 switch (Lex.getKind()) {
2122 default:
2124 return;
2125 case lltok::kw_default:
2127 break;
2128 case lltok::kw_hidden:
2130 break;
2133 break;
2134 }
2135 Lex.Lex();
2136}
2137
2138bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2140 switch (Kind) {
2141 default:
2142 return tokError("unknown import kind. Expect definition or declaration.");
2145 return false;
2148 return false;
2149 }
2150}
2151
2152/// parseOptionalDLLStorageClass
2153/// ::= /*empty*/
2154/// ::= 'dllimport'
2155/// ::= 'dllexport'
2156///
2157void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2158 switch (Lex.getKind()) {
2159 default:
2161 return;
2164 break;
2167 break;
2168 }
2169 Lex.Lex();
2170}
2171
2172/// parseOptionalCallingConv
2173/// ::= /*empty*/
2174/// ::= 'ccc'
2175/// ::= 'fastcc'
2176/// ::= 'intel_ocl_bicc'
2177/// ::= 'coldcc'
2178/// ::= 'cfguard_checkcc'
2179/// ::= 'x86_stdcallcc'
2180/// ::= 'x86_fastcallcc'
2181/// ::= 'x86_thiscallcc'
2182/// ::= 'x86_vectorcallcc'
2183/// ::= 'arm_apcscc'
2184/// ::= 'arm_aapcscc'
2185/// ::= 'arm_aapcs_vfpcc'
2186/// ::= 'aarch64_vector_pcs'
2187/// ::= 'aarch64_sve_vector_pcs'
2188/// ::= 'aarch64_sme_preservemost_from_x0'
2189/// ::= 'aarch64_sme_preservemost_from_x1'
2190/// ::= 'aarch64_sme_preservemost_from_x2'
2191/// ::= 'msp430_intrcc'
2192/// ::= 'avr_intrcc'
2193/// ::= 'avr_signalcc'
2194/// ::= 'ptx_kernel'
2195/// ::= 'ptx_device'
2196/// ::= 'spir_func'
2197/// ::= 'spir_kernel'
2198/// ::= 'x86_64_sysvcc'
2199/// ::= 'win64cc'
2200/// ::= 'anyregcc'
2201/// ::= 'preserve_mostcc'
2202/// ::= 'preserve_allcc'
2203/// ::= 'preserve_nonecc'
2204/// ::= 'ghccc'
2205/// ::= 'swiftcc'
2206/// ::= 'swifttailcc'
2207/// ::= 'x86_intrcc'
2208/// ::= 'hhvmcc'
2209/// ::= 'hhvm_ccc'
2210/// ::= 'cxx_fast_tlscc'
2211/// ::= 'amdgpu_vs'
2212/// ::= 'amdgpu_ls'
2213/// ::= 'amdgpu_hs'
2214/// ::= 'amdgpu_es'
2215/// ::= 'amdgpu_gs'
2216/// ::= 'amdgpu_ps'
2217/// ::= 'amdgpu_cs'
2218/// ::= 'amdgpu_cs_chain'
2219/// ::= 'amdgpu_cs_chain_preserve'
2220/// ::= 'amdgpu_kernel'
2221/// ::= 'tailcc'
2222/// ::= 'm68k_rtdcc'
2223/// ::= 'graalcc'
2224/// ::= 'riscv_vector_cc'
2225/// ::= 'riscv_vls_cc'
2226/// ::= 'cc' UINT
2227///
2228bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2229 switch (Lex.getKind()) {
2230 default: CC = CallingConv::C; return false;
2231 case lltok::kw_ccc: CC = CallingConv::C; break;
2232 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2233 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2246 break;
2249 break;
2252 break;
2255 break;
2265 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2266 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2270 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2271 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2274 case lltok::kw_hhvmcc:
2276 break;
2277 case lltok::kw_hhvm_ccc:
2279 break;
2291 break;
2294 break;
2298 break;
2299 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2301 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2304 break;
2306 // Default ABI_VLEN
2308 Lex.Lex();
2309 if (!EatIfPresent(lltok::lparen))
2310 break;
2311 uint32_t ABIVlen;
2312 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2313 return true;
2314 switch (ABIVlen) {
2315 default:
2316 return tokError("unknown RISC-V ABI VLEN");
2317#define CC_VLS_CASE(ABIVlen) \
2318 case ABIVlen: \
2319 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2320 break;
2321 CC_VLS_CASE(32)
2322 CC_VLS_CASE(64)
2323 CC_VLS_CASE(128)
2324 CC_VLS_CASE(256)
2325 CC_VLS_CASE(512)
2326 CC_VLS_CASE(1024)
2327 CC_VLS_CASE(2048)
2328 CC_VLS_CASE(4096)
2329 CC_VLS_CASE(8192)
2330 CC_VLS_CASE(16384)
2331 CC_VLS_CASE(32768)
2332 CC_VLS_CASE(65536)
2333#undef CC_VLS_CASE
2334 }
2335 return false;
2338 break;
2341 break;
2344 break;
2345 case lltok::kw_cc: {
2346 Lex.Lex();
2347 return parseUInt32(CC);
2348 }
2349 }
2350
2351 Lex.Lex();
2352 return false;
2353}
2354
2355/// parseMetadataAttachment
2356/// ::= !dbg !42
2357bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2358 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2359
2360 std::string Name = Lex.getStrVal();
2361 Kind = M->getMDKindID(Name);
2362 Lex.Lex();
2363
2364 return parseMDNode(MD);
2365}
2366
2367/// parseInstructionMetadata
2368/// ::= !dbg !42 (',' !dbg !57)*
2369bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2370 do {
2371 if (Lex.getKind() != lltok::MetadataVar)
2372 return tokError("expected metadata after comma");
2373
2374 unsigned MDK;
2375 MDNode *N;
2376 if (parseMetadataAttachment(MDK, N))
2377 return true;
2378
2379 if (MDK == LLVMContext::MD_DIAssignID)
2380 TempDIAssignIDAttachments[N].push_back(&Inst);
2381 else
2382 Inst.setMetadata(MDK, N);
2383
2384 if (MDK == LLVMContext::MD_tbaa)
2385 InstsWithTBAATag.push_back(&Inst);
2386
2387 // If this is the end of the list, we're done.
2388 } while (EatIfPresent(lltok::comma));
2389 return false;
2390}
2391
2392/// parseGlobalObjectMetadataAttachment
2393/// ::= !dbg !57
2394bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2395 unsigned MDK;
2396 MDNode *N;
2397 if (parseMetadataAttachment(MDK, N))
2398 return true;
2399
2400 GO.addMetadata(MDK, *N);
2401 return false;
2402}
2403
2404/// parseOptionalFunctionMetadata
2405/// ::= (!dbg !57)*
2406bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2407 while (Lex.getKind() == lltok::MetadataVar)
2408 if (parseGlobalObjectMetadataAttachment(F))
2409 return true;
2410 return false;
2411}
2412
2413/// parseOptionalAlignment
2414/// ::= /* empty */
2415/// ::= 'align' 4
2416bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2417 Alignment = std::nullopt;
2418 if (!EatIfPresent(lltok::kw_align))
2419 return false;
2420 LocTy AlignLoc = Lex.getLoc();
2421 uint64_t Value = 0;
2422
2423 LocTy ParenLoc = Lex.getLoc();
2424 bool HaveParens = false;
2425 if (AllowParens) {
2426 if (EatIfPresent(lltok::lparen))
2427 HaveParens = true;
2428 }
2429
2430 if (parseUInt64(Value))
2431 return true;
2432
2433 if (HaveParens && !EatIfPresent(lltok::rparen))
2434 return error(ParenLoc, "expected ')'");
2435
2436 if (!isPowerOf2_64(Value))
2437 return error(AlignLoc, "alignment is not a power of two");
2439 return error(AlignLoc, "huge alignments are not supported yet");
2440 Alignment = Align(Value);
2441 return false;
2442}
2443
2444/// parseOptionalCodeModel
2445/// ::= /* empty */
2446/// ::= 'code_model' "large"
2447bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2448 Lex.Lex();
2449 auto StrVal = Lex.getStrVal();
2450 auto ErrMsg = "expected global code model string";
2451 if (StrVal == "tiny")
2452 model = CodeModel::Tiny;
2453 else if (StrVal == "small")
2454 model = CodeModel::Small;
2455 else if (StrVal == "kernel")
2456 model = CodeModel::Kernel;
2457 else if (StrVal == "medium")
2458 model = CodeModel::Medium;
2459 else if (StrVal == "large")
2460 model = CodeModel::Large;
2461 else
2462 return tokError(ErrMsg);
2463 if (parseToken(lltok::StringConstant, ErrMsg))
2464 return true;
2465 return false;
2466}
2467
2468/// parseOptionalDerefAttrBytes
2469/// ::= /* empty */
2470/// ::= AttrKind '(' 4 ')'
2471///
2472/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2473bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2474 uint64_t &Bytes) {
2475 assert((AttrKind == lltok::kw_dereferenceable ||
2476 AttrKind == lltok::kw_dereferenceable_or_null) &&
2477 "contract!");
2478
2479 Bytes = 0;
2480 if (!EatIfPresent(AttrKind))
2481 return false;
2482 LocTy ParenLoc = Lex.getLoc();
2483 if (!EatIfPresent(lltok::lparen))
2484 return error(ParenLoc, "expected '('");
2485 LocTy DerefLoc = Lex.getLoc();
2486 if (parseUInt64(Bytes))
2487 return true;
2488 ParenLoc = Lex.getLoc();
2489 if (!EatIfPresent(lltok::rparen))
2490 return error(ParenLoc, "expected ')'");
2491 if (!Bytes)
2492 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2493 return false;
2494}
2495
2496bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2497 Lex.Lex();
2499 if (!EatIfPresent(lltok::lparen))
2500 return false;
2501 LocTy KindLoc = Lex.getLoc();
2502 if (Lex.getKind() == lltok::kw_sync)
2504 else if (Lex.getKind() == lltok::kw_async)
2506 else
2507 return error(KindLoc, "expected unwind table kind");
2508 Lex.Lex();
2509 return parseToken(lltok::rparen, "expected ')'");
2510}
2511
2512bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2513 Lex.Lex();
2514 LocTy ParenLoc = Lex.getLoc();
2515 if (!EatIfPresent(lltok::lparen))
2516 return error(ParenLoc, "expected '('");
2517 LocTy KindLoc = Lex.getLoc();
2518 std::string Arg;
2519 if (parseStringConstant(Arg))
2520 return error(KindLoc, "expected allockind value");
2521 for (StringRef A : llvm::split(Arg, ",")) {
2522 if (A == "alloc") {
2524 } else if (A == "realloc") {
2526 } else if (A == "free") {
2528 } else if (A == "uninitialized") {
2530 } else if (A == "zeroed") {
2532 } else if (A == "aligned") {
2534 } else {
2535 return error(KindLoc, Twine("unknown allockind ") + A);
2536 }
2537 }
2538 ParenLoc = Lex.getLoc();
2539 if (!EatIfPresent(lltok::rparen))
2540 return error(ParenLoc, "expected ')'");
2541 if (Kind == AllocFnKind::Unknown)
2542 return error(KindLoc, "expected allockind value");
2543 return false;
2544}
2545
2546static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2547 switch (Tok) {
2548 case lltok::kw_argmem:
2549 return IRMemLocation::ArgMem;
2552 case lltok::kw_errnomem:
2558 default:
2559 return std::nullopt;
2560 }
2561}
2562
2563static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2564 switch (Tok) {
2565 case lltok::kw_none:
2566 return ModRefInfo::NoModRef;
2567 case lltok::kw_read:
2568 return ModRefInfo::Ref;
2569 case lltok::kw_write:
2570 return ModRefInfo::Mod;
2572 return ModRefInfo::ModRef;
2573 default:
2574 return std::nullopt;
2575 }
2576}
2577
2578std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2580
2581 // We use syntax like memory(argmem: read), so the colon should not be
2582 // interpreted as a label terminator.
2583 Lex.setIgnoreColonInIdentifiers(true);
2584 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2585
2586 Lex.Lex();
2587 if (!EatIfPresent(lltok::lparen)) {
2588 tokError("expected '('");
2589 return std::nullopt;
2590 }
2591
2592 bool SeenLoc = false;
2593 do {
2594 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2595 if (Loc) {
2596 Lex.Lex();
2597 if (!EatIfPresent(lltok::colon)) {
2598 tokError("expected ':' after location");
2599 return std::nullopt;
2600 }
2601 }
2602
2603 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2604 if (!MR) {
2605 if (!Loc)
2606 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2607 "or access kind (none, read, write, readwrite)");
2608 else
2609 tokError("expected access kind (none, read, write, readwrite)");
2610 return std::nullopt;
2611 }
2612
2613 Lex.Lex();
2614 if (Loc) {
2615 SeenLoc = true;
2616 ME = ME.getWithModRef(*Loc, *MR);
2617 } else {
2618 if (SeenLoc) {
2619 tokError("default access kind must be specified first");
2620 return std::nullopt;
2621 }
2622 ME = MemoryEffects(*MR);
2623 }
2624
2625 if (EatIfPresent(lltok::rparen))
2626 return ME;
2627 } while (EatIfPresent(lltok::comma));
2628
2629 tokError("unterminated memory attribute");
2630 return std::nullopt;
2631}
2632
2633static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2634 switch (Tok) {
2635 case lltok::kw_all:
2636 return fcAllFlags;
2637 case lltok::kw_nan:
2638 return fcNan;
2639 case lltok::kw_snan:
2640 return fcSNan;
2641 case lltok::kw_qnan:
2642 return fcQNan;
2643 case lltok::kw_inf:
2644 return fcInf;
2645 case lltok::kw_ninf:
2646 return fcNegInf;
2647 case lltok::kw_pinf:
2648 return fcPosInf;
2649 case lltok::kw_norm:
2650 return fcNormal;
2651 case lltok::kw_nnorm:
2652 return fcNegNormal;
2653 case lltok::kw_pnorm:
2654 return fcPosNormal;
2655 case lltok::kw_sub:
2656 return fcSubnormal;
2657 case lltok::kw_nsub:
2658 return fcNegSubnormal;
2659 case lltok::kw_psub:
2660 return fcPosSubnormal;
2661 case lltok::kw_zero:
2662 return fcZero;
2663 case lltok::kw_nzero:
2664 return fcNegZero;
2665 case lltok::kw_pzero:
2666 return fcPosZero;
2667 default:
2668 return 0;
2669 }
2670}
2671
2672unsigned LLParser::parseNoFPClassAttr() {
2673 unsigned Mask = fcNone;
2674
2675 Lex.Lex();
2676 if (!EatIfPresent(lltok::lparen)) {
2677 tokError("expected '('");
2678 return 0;
2679 }
2680
2681 do {
2682 uint64_t Value = 0;
2683 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2684 if (TestMask != 0) {
2685 Mask |= TestMask;
2686 // TODO: Disallow overlapping masks to avoid copy paste errors
2687 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2688 !parseUInt64(Value)) {
2689 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2690 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2691 return 0;
2692 }
2693
2694 if (!EatIfPresent(lltok::rparen)) {
2695 error(Lex.getLoc(), "expected ')'");
2696 return 0;
2697 }
2698
2699 return Value;
2700 } else {
2701 error(Lex.getLoc(), "expected nofpclass test mask");
2702 return 0;
2703 }
2704
2705 Lex.Lex();
2706 if (EatIfPresent(lltok::rparen))
2707 return Mask;
2708 } while (1);
2709
2710 llvm_unreachable("unterminated nofpclass attribute");
2711}
2712
2713/// parseOptionalCommaAlign
2714/// ::=
2715/// ::= ',' align 4
2716///
2717/// This returns with AteExtraComma set to true if it ate an excess comma at the
2718/// end.
2719bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2720 bool &AteExtraComma) {
2721 AteExtraComma = false;
2722 while (EatIfPresent(lltok::comma)) {
2723 // Metadata at the end is an early exit.
2724 if (Lex.getKind() == lltok::MetadataVar) {
2725 AteExtraComma = true;
2726 return false;
2727 }
2728
2729 if (Lex.getKind() != lltok::kw_align)
2730 return error(Lex.getLoc(), "expected metadata or 'align'");
2731
2732 if (parseOptionalAlignment(Alignment))
2733 return true;
2734 }
2735
2736 return false;
2737}
2738
2739/// parseOptionalCommaAddrSpace
2740/// ::=
2741/// ::= ',' addrspace(1)
2742///
2743/// This returns with AteExtraComma set to true if it ate an excess comma at the
2744/// end.
2745bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2746 bool &AteExtraComma) {
2747 AteExtraComma = false;
2748 while (EatIfPresent(lltok::comma)) {
2749 // Metadata at the end is an early exit.
2750 if (Lex.getKind() == lltok::MetadataVar) {
2751 AteExtraComma = true;
2752 return false;
2753 }
2754
2755 Loc = Lex.getLoc();
2756 if (Lex.getKind() != lltok::kw_addrspace)
2757 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2758
2759 if (parseOptionalAddrSpace(AddrSpace))
2760 return true;
2761 }
2762
2763 return false;
2764}
2765
2766bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2767 std::optional<unsigned> &HowManyArg) {
2768 Lex.Lex();
2769
2770 auto StartParen = Lex.getLoc();
2771 if (!EatIfPresent(lltok::lparen))
2772 return error(StartParen, "expected '('");
2773
2774 if (parseUInt32(BaseSizeArg))
2775 return true;
2776
2777 if (EatIfPresent(lltok::comma)) {
2778 auto HowManyAt = Lex.getLoc();
2779 unsigned HowMany;
2780 if (parseUInt32(HowMany))
2781 return true;
2782 if (HowMany == BaseSizeArg)
2783 return error(HowManyAt,
2784 "'allocsize' indices can't refer to the same parameter");
2785 HowManyArg = HowMany;
2786 } else
2787 HowManyArg = std::nullopt;
2788
2789 auto EndParen = Lex.getLoc();
2790 if (!EatIfPresent(lltok::rparen))
2791 return error(EndParen, "expected ')'");
2792 return false;
2793}
2794
2795bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2796 unsigned &MaxValue) {
2797 Lex.Lex();
2798
2799 auto StartParen = Lex.getLoc();
2800 if (!EatIfPresent(lltok::lparen))
2801 return error(StartParen, "expected '('");
2802
2803 if (parseUInt32(MinValue))
2804 return true;
2805
2806 if (EatIfPresent(lltok::comma)) {
2807 if (parseUInt32(MaxValue))
2808 return true;
2809 } else
2810 MaxValue = MinValue;
2811
2812 auto EndParen = Lex.getLoc();
2813 if (!EatIfPresent(lltok::rparen))
2814 return error(EndParen, "expected ')'");
2815 return false;
2816}
2817
2818/// parseScopeAndOrdering
2819/// if isAtomic: ::= SyncScope? AtomicOrdering
2820/// else: ::=
2821///
2822/// This sets Scope and Ordering to the parsed values.
2823bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2824 AtomicOrdering &Ordering) {
2825 if (!IsAtomic)
2826 return false;
2827
2828 return parseScope(SSID) || parseOrdering(Ordering);
2829}
2830
2831/// parseScope
2832/// ::= syncscope("singlethread" | "<target scope>")?
2833///
2834/// This sets synchronization scope ID to the ID of the parsed value.
2835bool LLParser::parseScope(SyncScope::ID &SSID) {
2836 SSID = SyncScope::System;
2837 if (EatIfPresent(lltok::kw_syncscope)) {
2838 auto StartParenAt = Lex.getLoc();
2839 if (!EatIfPresent(lltok::lparen))
2840 return error(StartParenAt, "Expected '(' in syncscope");
2841
2842 std::string SSN;
2843 auto SSNAt = Lex.getLoc();
2844 if (parseStringConstant(SSN))
2845 return error(SSNAt, "Expected synchronization scope name");
2846
2847 auto EndParenAt = Lex.getLoc();
2848 if (!EatIfPresent(lltok::rparen))
2849 return error(EndParenAt, "Expected ')' in syncscope");
2850
2851 SSID = Context.getOrInsertSyncScopeID(SSN);
2852 }
2853
2854 return false;
2855}
2856
2857/// parseOrdering
2858/// ::= AtomicOrdering
2859///
2860/// This sets Ordering to the parsed value.
2861bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2862 switch (Lex.getKind()) {
2863 default:
2864 return tokError("Expected ordering on atomic instruction");
2867 // Not specified yet:
2868 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2872 case lltok::kw_seq_cst:
2874 break;
2875 }
2876 Lex.Lex();
2877 return false;
2878}
2879
2880/// parseOptionalStackAlignment
2881/// ::= /* empty */
2882/// ::= 'alignstack' '(' 4 ')'
2883bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2884 Alignment = 0;
2885 if (!EatIfPresent(lltok::kw_alignstack))
2886 return false;
2887 LocTy ParenLoc = Lex.getLoc();
2888 if (!EatIfPresent(lltok::lparen))
2889 return error(ParenLoc, "expected '('");
2890 LocTy AlignLoc = Lex.getLoc();
2891 if (parseUInt32(Alignment))
2892 return true;
2893 ParenLoc = Lex.getLoc();
2894 if (!EatIfPresent(lltok::rparen))
2895 return error(ParenLoc, "expected ')'");
2896 if (!isPowerOf2_32(Alignment))
2897 return error(AlignLoc, "stack alignment is not a power of two");
2898 return false;
2899}
2900
2901/// parseIndexList - This parses the index list for an insert/extractvalue
2902/// instruction. This sets AteExtraComma in the case where we eat an extra
2903/// comma at the end of the line and find that it is followed by metadata.
2904/// Clients that don't allow metadata can call the version of this function that
2905/// only takes one argument.
2906///
2907/// parseIndexList
2908/// ::= (',' uint32)+
2909///
2910bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2911 bool &AteExtraComma) {
2912 AteExtraComma = false;
2913
2914 if (Lex.getKind() != lltok::comma)
2915 return tokError("expected ',' as start of index list");
2916
2917 while (EatIfPresent(lltok::comma)) {
2918 if (Lex.getKind() == lltok::MetadataVar) {
2919 if (Indices.empty())
2920 return tokError("expected index");
2921 AteExtraComma = true;
2922 return false;
2923 }
2924 unsigned Idx = 0;
2925 if (parseUInt32(Idx))
2926 return true;
2927 Indices.push_back(Idx);
2928 }
2929
2930 return false;
2931}
2932
2933//===----------------------------------------------------------------------===//
2934// Type Parsing.
2935//===----------------------------------------------------------------------===//
2936
2937/// parseType - parse a type.
2938bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2939 SMLoc TypeLoc = Lex.getLoc();
2940 switch (Lex.getKind()) {
2941 default:
2942 return tokError(Msg);
2943 case lltok::Type:
2944 // Type ::= 'float' | 'void' (etc)
2945 Result = Lex.getTyVal();
2946 Lex.Lex();
2947
2948 // Handle "ptr" opaque pointer type.
2949 //
2950 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2951 if (Result->isPointerTy()) {
2952 unsigned AddrSpace;
2953 if (parseOptionalAddrSpace(AddrSpace))
2954 return true;
2955 Result = PointerType::get(getContext(), AddrSpace);
2956
2957 // Give a nice error for 'ptr*'.
2958 if (Lex.getKind() == lltok::star)
2959 return tokError("ptr* is invalid - use ptr instead");
2960
2961 // Fall through to parsing the type suffixes only if this 'ptr' is a
2962 // function return. Otherwise, return success, implicitly rejecting other
2963 // suffixes.
2964 if (Lex.getKind() != lltok::lparen)
2965 return false;
2966 }
2967 break;
2968 case lltok::kw_target: {
2969 // Type ::= TargetExtType
2970 if (parseTargetExtType(Result))
2971 return true;
2972 break;
2973 }
2974 case lltok::lbrace:
2975 // Type ::= StructType
2976 if (parseAnonStructType(Result, false))
2977 return true;
2978 break;
2979 case lltok::lsquare:
2980 // Type ::= '[' ... ']'
2981 Lex.Lex(); // eat the lsquare.
2982 if (parseArrayVectorType(Result, false))
2983 return true;
2984 break;
2985 case lltok::less: // Either vector or packed struct.
2986 // Type ::= '<' ... '>'
2987 Lex.Lex();
2988 if (Lex.getKind() == lltok::lbrace) {
2989 if (parseAnonStructType(Result, true) ||
2990 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2991 return true;
2992 } else if (parseArrayVectorType(Result, true))
2993 return true;
2994 break;
2995 case lltok::LocalVar: {
2996 // Type ::= %foo
2997 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2998
2999 // If the type hasn't been defined yet, create a forward definition and
3000 // remember where that forward def'n was seen (in case it never is defined).
3001 if (!Entry.first) {
3002 Entry.first = StructType::create(Context, Lex.getStrVal());
3003 Entry.second = Lex.getLoc();
3004 }
3005 Result = Entry.first;
3006 Lex.Lex();
3007 break;
3008 }
3009
3010 case lltok::LocalVarID: {
3011 // Type ::= %4
3012 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3013
3014 // If the type hasn't been defined yet, create a forward definition and
3015 // remember where that forward def'n was seen (in case it never is defined).
3016 if (!Entry.first) {
3017 Entry.first = StructType::create(Context);
3018 Entry.second = Lex.getLoc();
3019 }
3020 Result = Entry.first;
3021 Lex.Lex();
3022 break;
3023 }
3024 }
3025
3026 // parse the type suffixes.
3027 while (true) {
3028 switch (Lex.getKind()) {
3029 // End of type.
3030 default:
3031 if (!AllowVoid && Result->isVoidTy())
3032 return error(TypeLoc, "void type only allowed for function results");
3033 return false;
3034
3035 // Type ::= Type '*'
3036 case lltok::star:
3037 if (Result->isLabelTy())
3038 return tokError("basic block pointers are invalid");
3039 if (Result->isVoidTy())
3040 return tokError("pointers to void are invalid - use i8* instead");
3042 return tokError("pointer to this type is invalid");
3043 Result = PointerType::getUnqual(Context);
3044 Lex.Lex();
3045 break;
3046
3047 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3048 case lltok::kw_addrspace: {
3049 if (Result->isLabelTy())
3050 return tokError("basic block pointers are invalid");
3051 if (Result->isVoidTy())
3052 return tokError("pointers to void are invalid; use i8* instead");
3054 return tokError("pointer to this type is invalid");
3055 unsigned AddrSpace;
3056 if (parseOptionalAddrSpace(AddrSpace) ||
3057 parseToken(lltok::star, "expected '*' in address space"))
3058 return true;
3059
3060 Result = PointerType::get(Context, AddrSpace);
3061 break;
3062 }
3063
3064 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3065 case lltok::lparen:
3066 if (parseFunctionType(Result))
3067 return true;
3068 break;
3069 }
3070 }
3071}
3072
3073/// parseParameterList
3074/// ::= '(' ')'
3075/// ::= '(' Arg (',' Arg)* ')'
3076/// Arg
3077/// ::= Type OptionalAttributes Value OptionalAttributes
3078bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3079 PerFunctionState &PFS, bool IsMustTailCall,
3080 bool InVarArgsFunc) {
3081 if (parseToken(lltok::lparen, "expected '(' in call"))
3082 return true;
3083
3084 while (Lex.getKind() != lltok::rparen) {
3085 // If this isn't the first argument, we need a comma.
3086 if (!ArgList.empty() &&
3087 parseToken(lltok::comma, "expected ',' in argument list"))
3088 return true;
3089
3090 // parse an ellipsis if this is a musttail call in a variadic function.
3091 if (Lex.getKind() == lltok::dotdotdot) {
3092 const char *Msg = "unexpected ellipsis in argument list for ";
3093 if (!IsMustTailCall)
3094 return tokError(Twine(Msg) + "non-musttail call");
3095 if (!InVarArgsFunc)
3096 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3097 Lex.Lex(); // Lex the '...', it is purely for readability.
3098 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3099 }
3100
3101 // parse the argument.
3102 LocTy ArgLoc;
3103 Type *ArgTy = nullptr;
3104 Value *V;
3105 if (parseType(ArgTy, ArgLoc))
3106 return true;
3108 return error(ArgLoc, "invalid type for function argument");
3109
3110 AttrBuilder ArgAttrs(M->getContext());
3111
3112 if (ArgTy->isMetadataTy()) {
3113 if (parseMetadataAsValue(V, PFS))
3114 return true;
3115 } else {
3116 // Otherwise, handle normal operands.
3117 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3118 return true;
3119 }
3120 ArgList.push_back(ParamInfo(
3121 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3122 }
3123
3124 if (IsMustTailCall && InVarArgsFunc)
3125 return tokError("expected '...' at end of argument list for musttail call "
3126 "in varargs function");
3127
3128 Lex.Lex(); // Lex the ')'.
3129 return false;
3130}
3131
3132/// parseRequiredTypeAttr
3133/// ::= attrname(<ty>)
3134bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3135 Attribute::AttrKind AttrKind) {
3136 Type *Ty = nullptr;
3137 if (!EatIfPresent(AttrToken))
3138 return true;
3139 if (!EatIfPresent(lltok::lparen))
3140 return error(Lex.getLoc(), "expected '('");
3141 if (parseType(Ty))
3142 return true;
3143 if (!EatIfPresent(lltok::rparen))
3144 return error(Lex.getLoc(), "expected ')'");
3145
3146 B.addTypeAttr(AttrKind, Ty);
3147 return false;
3148}
3149
3150/// parseRangeAttr
3151/// ::= range(<ty> <n>,<n>)
3152bool LLParser::parseRangeAttr(AttrBuilder &B) {
3153 Lex.Lex();
3154
3155 APInt Lower;
3156 APInt Upper;
3157 Type *Ty = nullptr;
3158 LocTy TyLoc;
3159
3160 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3161 if (Lex.getKind() != lltok::APSInt)
3162 return tokError("expected integer");
3163 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3164 return tokError(
3165 "integer is too large for the bit width of specified type");
3166 Val = Lex.getAPSIntVal().extend(BitWidth);
3167 Lex.Lex();
3168 return false;
3169 };
3170
3171 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3172 return true;
3173 if (!Ty->isIntegerTy())
3174 return error(TyLoc, "the range must have integer type!");
3175
3176 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3177
3178 if (ParseAPSInt(BitWidth, Lower) ||
3179 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3180 return true;
3181 if (Lower == Upper && !Lower.isZero())
3182 return tokError("the range represent the empty set but limits aren't 0!");
3183
3184 if (parseToken(lltok::rparen, "expected ')'"))
3185 return true;
3186
3187 B.addRangeAttr(ConstantRange(Lower, Upper));
3188 return false;
3189}
3190
3191/// parseInitializesAttr
3192/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3193bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3194 Lex.Lex();
3195
3196 auto ParseAPSInt = [&](APInt &Val) {
3197 if (Lex.getKind() != lltok::APSInt)
3198 return tokError("expected integer");
3199 Val = Lex.getAPSIntVal().extend(64);
3200 Lex.Lex();
3201 return false;
3202 };
3203
3204 if (parseToken(lltok::lparen, "expected '('"))
3205 return true;
3206
3208 // Parse each constant range.
3209 do {
3210 APInt Lower, Upper;
3211 if (parseToken(lltok::lparen, "expected '('"))
3212 return true;
3213
3214 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3215 ParseAPSInt(Upper))
3216 return true;
3217
3218 if (Lower == Upper)
3219 return tokError("the range should not represent the full or empty set!");
3220
3221 if (parseToken(lltok::rparen, "expected ')'"))
3222 return true;
3223
3224 RangeList.push_back(ConstantRange(Lower, Upper));
3225 } while (EatIfPresent(lltok::comma));
3226
3227 if (parseToken(lltok::rparen, "expected ')'"))
3228 return true;
3229
3230 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3231 if (!CRLOrNull.has_value())
3232 return tokError("Invalid (unordered or overlapping) range list");
3233 B.addInitializesAttr(*CRLOrNull);
3234 return false;
3235}
3236
3237bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3239 std::optional<CaptureComponents> Ret;
3240
3241 // We use syntax like captures(ret: address, provenance), so the colon
3242 // should not be interpreted as a label terminator.
3243 Lex.setIgnoreColonInIdentifiers(true);
3244 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
3245
3246 Lex.Lex();
3247 if (parseToken(lltok::lparen, "expected '('"))
3248 return true;
3249
3250 CaptureComponents *Current = &Other;
3251 bool SeenComponent = false;
3252 while (true) {
3253 if (EatIfPresent(lltok::kw_ret)) {
3254 if (parseToken(lltok::colon, "expected ':'"))
3255 return true;
3256 if (Ret)
3257 return tokError("duplicate 'ret' location");
3259 Current = &*Ret;
3260 SeenComponent = false;
3261 }
3262
3263 if (EatIfPresent(lltok::kw_none)) {
3264 if (SeenComponent)
3265 return tokError("cannot use 'none' with other component");
3266 *Current = CaptureComponents::None;
3267 } else {
3268 if (SeenComponent && capturesNothing(*Current))
3269 return tokError("cannot use 'none' with other component");
3270
3271 if (EatIfPresent(lltok::kw_address_is_null))
3273 else if (EatIfPresent(lltok::kw_address))
3274 *Current |= CaptureComponents::Address;
3275 else if (EatIfPresent(lltok::kw_provenance))
3277 else if (EatIfPresent(lltok::kw_read_provenance))
3279 else
3280 return tokError("expected one of 'none', 'address', 'address_is_null', "
3281 "'provenance' or 'read_provenance'");
3282 }
3283
3284 SeenComponent = true;
3285 if (EatIfPresent(lltok::rparen))
3286 break;
3287
3288 if (parseToken(lltok::comma, "expected ',' or ')'"))
3289 return true;
3290 }
3291
3292 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3293 return false;
3294}
3295
3296/// parseOptionalOperandBundles
3297/// ::= /*empty*/
3298/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3299///
3300/// OperandBundle
3301/// ::= bundle-tag '(' ')'
3302/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3303///
3304/// bundle-tag ::= String Constant
3305bool LLParser::parseOptionalOperandBundles(
3306 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3307 LocTy BeginLoc = Lex.getLoc();
3308 if (!EatIfPresent(lltok::lsquare))
3309 return false;
3310
3311 while (Lex.getKind() != lltok::rsquare) {
3312 // If this isn't the first operand bundle, we need a comma.
3313 if (!BundleList.empty() &&
3314 parseToken(lltok::comma, "expected ',' in input list"))
3315 return true;
3316
3317 std::string Tag;
3318 if (parseStringConstant(Tag))
3319 return true;
3320
3321 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3322 return true;
3323
3324 std::vector<Value *> Inputs;
3325 while (Lex.getKind() != lltok::rparen) {
3326 // If this isn't the first input, we need a comma.
3327 if (!Inputs.empty() &&
3328 parseToken(lltok::comma, "expected ',' in input list"))
3329 return true;
3330
3331 Type *Ty = nullptr;
3332 Value *Input = nullptr;
3333 if (parseType(Ty))
3334 return true;
3335 if (Ty->isMetadataTy()) {
3336 if (parseMetadataAsValue(Input, PFS))
3337 return true;
3338 } else if (parseValue(Ty, Input, PFS)) {
3339 return true;
3340 }
3341 Inputs.push_back(Input);
3342 }
3343
3344 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3345
3346 Lex.Lex(); // Lex the ')'.
3347 }
3348
3349 if (BundleList.empty())
3350 return error(BeginLoc, "operand bundle set must not be empty");
3351
3352 Lex.Lex(); // Lex the ']'.
3353 return false;
3354}
3355
3356bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3357 unsigned NextID, unsigned ID) {
3358 if (ID < NextID)
3359 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3360 Twine(NextID) + "' or greater");
3361
3362 return false;
3363}
3364
3365/// parseArgumentList - parse the argument list for a function type or function
3366/// prototype.
3367/// ::= '(' ArgTypeListI ')'
3368/// ArgTypeListI
3369/// ::= /*empty*/
3370/// ::= '...'
3371/// ::= ArgTypeList ',' '...'
3372/// ::= ArgType (',' ArgType)*
3373///
3374bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3375 SmallVectorImpl<unsigned> &UnnamedArgNums,
3376 bool &IsVarArg) {
3377 unsigned CurValID = 0;
3378 IsVarArg = false;
3379 assert(Lex.getKind() == lltok::lparen);
3380 Lex.Lex(); // eat the (.
3381
3382 if (Lex.getKind() != lltok::rparen) {
3383 do {
3384 // Handle ... at end of arg list.
3385 if (EatIfPresent(lltok::dotdotdot)) {
3386 IsVarArg = true;
3387 break;
3388 }
3389
3390 // Otherwise must be an argument type.
3391 LocTy TypeLoc = Lex.getLoc();
3392 Type *ArgTy = nullptr;
3393 AttrBuilder Attrs(M->getContext());
3394 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3395 return true;
3396
3397 if (ArgTy->isVoidTy())
3398 return error(TypeLoc, "argument can not have void type");
3399
3400 std::string Name;
3401 if (Lex.getKind() == lltok::LocalVar) {
3402 Name = Lex.getStrVal();
3403 Lex.Lex();
3404 } else {
3405 unsigned ArgID;
3406 if (Lex.getKind() == lltok::LocalVarID) {
3407 ArgID = Lex.getUIntVal();
3408 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3409 return true;
3410 Lex.Lex();
3411 } else {
3412 ArgID = CurValID;
3413 }
3414 UnnamedArgNums.push_back(ArgID);
3415 CurValID = ArgID + 1;
3416 }
3417
3419 return error(TypeLoc, "invalid type for function argument");
3420
3421 ArgList.emplace_back(TypeLoc, ArgTy,
3422 AttributeSet::get(ArgTy->getContext(), Attrs),
3423 std::move(Name));
3424 } while (EatIfPresent(lltok::comma));
3425 }
3426
3427 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3428}
3429
3430/// parseFunctionType
3431/// ::= Type ArgumentList OptionalAttrs
3432bool LLParser::parseFunctionType(Type *&Result) {
3433 assert(Lex.getKind() == lltok::lparen);
3434
3436 return tokError("invalid function return type");
3437
3439 bool IsVarArg;
3440 SmallVector<unsigned> UnnamedArgNums;
3441 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3442 return true;
3443
3444 // Reject names on the arguments lists.
3445 for (const ArgInfo &Arg : ArgList) {
3446 if (!Arg.Name.empty())
3447 return error(Arg.Loc, "argument name invalid in function type");
3448 if (Arg.Attrs.hasAttributes())
3449 return error(Arg.Loc, "argument attributes invalid in function type");
3450 }
3451
3452 SmallVector<Type*, 16> ArgListTy;
3453 for (const ArgInfo &Arg : ArgList)
3454 ArgListTy.push_back(Arg.Ty);
3455
3456 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3457 return false;
3458}
3459
3460/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3461/// other structs.
3462bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3464 if (parseStructBody(Elts))
3465 return true;
3466
3467 Result = StructType::get(Context, Elts, Packed);
3468 return false;
3469}
3470
3471/// parseStructDefinition - parse a struct in a 'type' definition.
3472bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3473 std::pair<Type *, LocTy> &Entry,
3474 Type *&ResultTy) {
3475 // If the type was already defined, diagnose the redefinition.
3476 if (Entry.first && !Entry.second.isValid())
3477 return error(TypeLoc, "redefinition of type");
3478
3479 // If we have opaque, just return without filling in the definition for the
3480 // struct. This counts as a definition as far as the .ll file goes.
3481 if (EatIfPresent(lltok::kw_opaque)) {
3482 // This type is being defined, so clear the location to indicate this.
3483 Entry.second = SMLoc();
3484
3485 // If this type number has never been uttered, create it.
3486 if (!Entry.first)
3487 Entry.first = StructType::create(Context, Name);
3488 ResultTy = Entry.first;
3489 return false;
3490 }
3491
3492 // If the type starts with '<', then it is either a packed struct or a vector.
3493 bool isPacked = EatIfPresent(lltok::less);
3494
3495 // If we don't have a struct, then we have a random type alias, which we
3496 // accept for compatibility with old files. These types are not allowed to be
3497 // forward referenced and not allowed to be recursive.
3498 if (Lex.getKind() != lltok::lbrace) {
3499 if (Entry.first)
3500 return error(TypeLoc, "forward references to non-struct type");
3501
3502 ResultTy = nullptr;
3503 if (isPacked)
3504 return parseArrayVectorType(ResultTy, true);
3505 return parseType(ResultTy);
3506 }
3507
3508 // This type is being defined, so clear the location to indicate this.
3509 Entry.second = SMLoc();
3510
3511 // If this type number has never been uttered, create it.
3512 if (!Entry.first)
3513 Entry.first = StructType::create(Context, Name);
3514
3515 StructType *STy = cast<StructType>(Entry.first);
3516
3518 if (parseStructBody(Body) ||
3519 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3520 return true;
3521
3522 if (auto E = STy->setBodyOrError(Body, isPacked))
3523 return tokError(toString(std::move(E)));
3524
3525 ResultTy = STy;
3526 return false;
3527}
3528
3529/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3530/// StructType
3531/// ::= '{' '}'
3532/// ::= '{' Type (',' Type)* '}'
3533/// ::= '<' '{' '}' '>'
3534/// ::= '<' '{' Type (',' Type)* '}' '>'
3535bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3536 assert(Lex.getKind() == lltok::lbrace);
3537 Lex.Lex(); // Consume the '{'
3538
3539 // Handle the empty struct.
3540 if (EatIfPresent(lltok::rbrace))
3541 return false;
3542
3543 LocTy EltTyLoc = Lex.getLoc();
3544 Type *Ty = nullptr;
3545 if (parseType(Ty))
3546 return true;
3547 Body.push_back(Ty);
3548
3550 return error(EltTyLoc, "invalid element type for struct");
3551
3552 while (EatIfPresent(lltok::comma)) {
3553 EltTyLoc = Lex.getLoc();
3554 if (parseType(Ty))
3555 return true;
3556
3558 return error(EltTyLoc, "invalid element type for struct");
3559
3560 Body.push_back(Ty);
3561 }
3562
3563 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3564}
3565
3566/// parseArrayVectorType - parse an array or vector type, assuming the first
3567/// token has already been consumed.
3568/// Type
3569/// ::= '[' APSINTVAL 'x' Types ']'
3570/// ::= '<' APSINTVAL 'x' Types '>'
3571/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3572bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3573 bool Scalable = false;
3574
3575 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3576 Lex.Lex(); // consume the 'vscale'
3577 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3578 return true;
3579
3580 Scalable = true;
3581 }
3582
3583 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3584 Lex.getAPSIntVal().getBitWidth() > 64)
3585 return tokError("expected number in address space");
3586
3587 LocTy SizeLoc = Lex.getLoc();
3588 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3589 Lex.Lex();
3590
3591 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3592 return true;
3593
3594 LocTy TypeLoc = Lex.getLoc();
3595 Type *EltTy = nullptr;
3596 if (parseType(EltTy))
3597 return true;
3598
3599 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3600 "expected end of sequential type"))
3601 return true;
3602
3603 if (IsVector) {
3604 if (Size == 0)
3605 return error(SizeLoc, "zero element vector is illegal");
3606 if ((unsigned)Size != Size)
3607 return error(SizeLoc, "size too large for vector");
3609 return error(TypeLoc, "invalid vector element type");
3610 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3611 } else {
3613 return error(TypeLoc, "invalid array element type");
3614 Result = ArrayType::get(EltTy, Size);
3615 }
3616 return false;
3617}
3618
3619/// parseTargetExtType - handle target extension type syntax
3620/// TargetExtType
3621/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3622///
3623/// TargetExtTypeParams
3624/// ::= /*empty*/
3625/// ::= ',' Type TargetExtTypeParams
3626///
3627/// TargetExtIntParams
3628/// ::= /*empty*/
3629/// ::= ',' uint32 TargetExtIntParams
3630bool LLParser::parseTargetExtType(Type *&Result) {
3631 Lex.Lex(); // Eat the 'target' keyword.
3632
3633 // Get the mandatory type name.
3634 std::string TypeName;
3635 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3636 parseStringConstant(TypeName))
3637 return true;
3638
3639 // Parse all of the integer and type parameters at the same time; the use of
3640 // SeenInt will allow us to catch cases where type parameters follow integer
3641 // parameters.
3642 SmallVector<Type *> TypeParams;
3643 SmallVector<unsigned> IntParams;
3644 bool SeenInt = false;
3645 while (Lex.getKind() == lltok::comma) {
3646 Lex.Lex(); // Eat the comma.
3647
3648 if (Lex.getKind() == lltok::APSInt) {
3649 SeenInt = true;
3650 unsigned IntVal;
3651 if (parseUInt32(IntVal))
3652 return true;
3653 IntParams.push_back(IntVal);
3654 } else if (SeenInt) {
3655 // The only other kind of parameter we support is type parameters, which
3656 // must precede the integer parameters. This is therefore an error.
3657 return tokError("expected uint32 param");
3658 } else {
3659 Type *TypeParam;
3660 if (parseType(TypeParam, /*AllowVoid=*/true))
3661 return true;
3662 TypeParams.push_back(TypeParam);
3663 }
3664 }
3665
3666 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3667 return true;
3668
3669 auto TTy =
3670 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3671 if (auto E = TTy.takeError())
3672 return tokError(toString(std::move(E)));
3673
3674 Result = *TTy;
3675 return false;
3676}
3677
3678//===----------------------------------------------------------------------===//
3679// Function Semantic Analysis.
3680//===----------------------------------------------------------------------===//
3681
3682LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3683 int functionNumber,
3684 ArrayRef<unsigned> UnnamedArgNums)
3685 : P(p), F(f), FunctionNumber(functionNumber) {
3686
3687 // Insert unnamed arguments into the NumberedVals list.
3688 auto It = UnnamedArgNums.begin();
3689 for (Argument &A : F.args()) {
3690 if (!A.hasName()) {
3691 unsigned ArgNum = *It++;
3692 NumberedVals.add(ArgNum, &A);
3693 }
3694 }
3695}
3696
3697LLParser::PerFunctionState::~PerFunctionState() {
3698 // If there were any forward referenced non-basicblock values, delete them.
3699
3700 for (const auto &P : ForwardRefVals) {
3701 if (isa<BasicBlock>(P.second.first))
3702 continue;
3703 P.second.first->replaceAllUsesWith(
3704 PoisonValue::get(P.second.first->getType()));
3705 P.second.first->deleteValue();
3706 }
3707
3708 for (const auto &P : ForwardRefValIDs) {
3709 if (isa<BasicBlock>(P.second.first))
3710 continue;
3711 P.second.first->replaceAllUsesWith(
3712 PoisonValue::get(P.second.first->getType()));
3713 P.second.first->deleteValue();
3714 }
3715}
3716
3717bool LLParser::PerFunctionState::finishFunction() {
3718 if (!ForwardRefVals.empty())
3719 return P.error(ForwardRefVals.begin()->second.second,
3720 "use of undefined value '%" + ForwardRefVals.begin()->first +
3721 "'");
3722 if (!ForwardRefValIDs.empty())
3723 return P.error(ForwardRefValIDs.begin()->second.second,
3724 "use of undefined value '%" +
3725 Twine(ForwardRefValIDs.begin()->first) + "'");
3726 return false;
3727}
3728
3729/// getVal - Get a value with the specified name or ID, creating a
3730/// forward reference record if needed. This can return null if the value
3731/// exists but does not have the right type.
3732Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3733 LocTy Loc) {
3734 // Look this name up in the normal function symbol table.
3735 Value *Val = F.getValueSymbolTable()->lookup(Name);
3736
3737 // If this is a forward reference for the value, see if we already created a
3738 // forward ref record.
3739 if (!Val) {
3740 auto I = ForwardRefVals.find(Name);
3741 if (I != ForwardRefVals.end())
3742 Val = I->second.first;
3743 }
3744
3745 // If we have the value in the symbol table or fwd-ref table, return it.
3746 if (Val)
3747 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3748
3749 // Don't make placeholders with invalid type.
3750 if (!Ty->isFirstClassType()) {
3751 P.error(Loc, "invalid use of a non-first-class type");
3752 return nullptr;
3753 }
3754
3755 // Otherwise, create a new forward reference for this value and remember it.
3756 Value *FwdVal;
3757 if (Ty->isLabelTy()) {
3758 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3759 } else {
3760 FwdVal = new Argument(Ty, Name);
3761 }
3762 if (FwdVal->getName() != Name) {
3763 P.error(Loc, "name is too long which can result in name collisions, "
3764 "consider making the name shorter or "
3765 "increasing -non-global-value-max-name-size");
3766 return nullptr;
3767 }
3768
3769 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3770 return FwdVal;
3771}
3772
3773Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3774 // Look this name up in the normal function symbol table.
3775 Value *Val = NumberedVals.get(ID);
3776
3777 // If this is a forward reference for the value, see if we already created a
3778 // forward ref record.
3779 if (!Val) {
3780 auto I = ForwardRefValIDs.find(ID);
3781 if (I != ForwardRefValIDs.end())
3782 Val = I->second.first;
3783 }
3784
3785 // If we have the value in the symbol table or fwd-ref table, return it.
3786 if (Val)
3787 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3788
3789 if (!Ty->isFirstClassType()) {
3790 P.error(Loc, "invalid use of a non-first-class type");
3791 return nullptr;
3792 }
3793
3794 // Otherwise, create a new forward reference for this value and remember it.
3795 Value *FwdVal;
3796 if (Ty->isLabelTy()) {
3797 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3798 } else {
3799 FwdVal = new Argument(Ty);
3800 }
3801
3802 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3803 return FwdVal;
3804}
3805
3806/// setInstName - After an instruction is parsed and inserted into its
3807/// basic block, this installs its name.
3808bool LLParser::PerFunctionState::setInstName(int NameID,
3809 const std::string &NameStr,
3810 LocTy NameLoc, Instruction *Inst) {
3811 // If this instruction has void type, it cannot have a name or ID specified.
3812 if (Inst->getType()->isVoidTy()) {
3813 if (NameID != -1 || !NameStr.empty())
3814 return P.error(NameLoc, "instructions returning void cannot have a name");
3815 return false;
3816 }
3817
3818 // If this was a numbered instruction, verify that the instruction is the
3819 // expected value and resolve any forward references.
3820 if (NameStr.empty()) {
3821 // If neither a name nor an ID was specified, just use the next ID.
3822 if (NameID == -1)
3823 NameID = NumberedVals.getNext();
3824
3825 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3826 NameID))
3827 return true;
3828
3829 auto FI = ForwardRefValIDs.find(NameID);
3830 if (FI != ForwardRefValIDs.end()) {
3831 Value *Sentinel = FI->second.first;
3832 if (Sentinel->getType() != Inst->getType())
3833 return P.error(NameLoc, "instruction forward referenced with type '" +
3834 getTypeString(FI->second.first->getType()) +
3835 "'");
3836
3837 Sentinel->replaceAllUsesWith(Inst);
3838 Sentinel->deleteValue();
3839 ForwardRefValIDs.erase(FI);
3840 }
3841
3842 NumberedVals.add(NameID, Inst);
3843 return false;
3844 }
3845
3846 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3847 auto FI = ForwardRefVals.find(NameStr);
3848 if (FI != ForwardRefVals.end()) {
3849 Value *Sentinel = FI->second.first;
3850 if (Sentinel->getType() != Inst->getType())
3851 return P.error(NameLoc, "instruction forward referenced with type '" +
3852 getTypeString(FI->second.first->getType()) +
3853 "'");
3854
3855 Sentinel->replaceAllUsesWith(Inst);
3856 Sentinel->deleteValue();
3857 ForwardRefVals.erase(FI);
3858 }
3859
3860 // Set the name on the instruction.
3861 Inst->setName(NameStr);
3862
3863 if (Inst->getName() != NameStr)
3864 return P.error(NameLoc, "multiple definition of local value named '" +
3865 NameStr + "'");
3866 return false;
3867}
3868
3869/// getBB - Get a basic block with the specified name or ID, creating a
3870/// forward reference record if needed.
3871BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3872 LocTy Loc) {
3874 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3875}
3876
3877BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3879 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3880}
3881
3882/// defineBB - Define the specified basic block, which is either named or
3883/// unnamed. If there is an error, this returns null otherwise it returns
3884/// the block being defined.
3885BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3886 int NameID, LocTy Loc) {
3887 BasicBlock *BB;
3888 if (Name.empty()) {
3889 if (NameID != -1) {
3890 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3891 return nullptr;
3892 } else {
3893 NameID = NumberedVals.getNext();
3894 }
3895 BB = getBB(NameID, Loc);
3896 if (!BB) {
3897 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3898 return nullptr;
3899 }
3900 } else {
3901 BB = getBB(Name, Loc);
3902 if (!BB) {
3903 P.error(Loc, "unable to create block named '" + Name + "'");
3904 return nullptr;
3905 }
3906 }
3907
3908 // Move the block to the end of the function. Forward ref'd blocks are
3909 // inserted wherever they happen to be referenced.
3910 F.splice(F.end(), &F, BB->getIterator());
3911
3912 // Remove the block from forward ref sets.
3913 if (Name.empty()) {
3914 ForwardRefValIDs.erase(NameID);
3915 NumberedVals.add(NameID, BB);
3916 } else {
3917 // BB forward references are already in the function symbol table.
3918 ForwardRefVals.erase(Name);
3919 }
3920
3921 return BB;
3922}
3923
3924//===----------------------------------------------------------------------===//
3925// Constants.
3926//===----------------------------------------------------------------------===//
3927
3928/// parseValID - parse an abstract value that doesn't necessarily have a
3929/// type implied. For example, if we parse "4" we don't know what integer type
3930/// it has. The value will later be combined with its type and checked for
3931/// basic correctness. PFS is used to convert function-local operands of
3932/// metadata (since metadata operands are not just parsed here but also
3933/// converted to values). PFS can be null when we are not parsing metadata
3934/// values inside a function.
3935bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3936 ID.Loc = Lex.getLoc();
3937 switch (Lex.getKind()) {
3938 default:
3939 return tokError("expected value token");
3940 case lltok::GlobalID: // @42
3941 ID.UIntVal = Lex.getUIntVal();
3942 ID.Kind = ValID::t_GlobalID;
3943 break;
3944 case lltok::GlobalVar: // @foo
3945 ID.StrVal = Lex.getStrVal();
3946 ID.Kind = ValID::t_GlobalName;
3947 break;
3948 case lltok::LocalVarID: // %42
3949 ID.UIntVal = Lex.getUIntVal();
3950 ID.Kind = ValID::t_LocalID;
3951 break;
3952 case lltok::LocalVar: // %foo
3953 ID.StrVal = Lex.getStrVal();
3954 ID.Kind = ValID::t_LocalName;
3955 break;
3956 case lltok::APSInt:
3957 ID.APSIntVal = Lex.getAPSIntVal();
3958 ID.Kind = ValID::t_APSInt;
3959 break;
3960 case lltok::APFloat:
3961 ID.APFloatVal = Lex.getAPFloatVal();
3962 ID.Kind = ValID::t_APFloat;
3963 break;
3964 case lltok::kw_true:
3965 ID.ConstantVal = ConstantInt::getTrue(Context);
3966 ID.Kind = ValID::t_Constant;
3967 break;
3968 case lltok::kw_false:
3969 ID.ConstantVal = ConstantInt::getFalse(Context);
3970 ID.Kind = ValID::t_Constant;
3971 break;
3972 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3973 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3974 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3975 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3976 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3977
3978 case lltok::lbrace: {
3979 // ValID ::= '{' ConstVector '}'
3980 Lex.Lex();
3982 if (parseGlobalValueVector(Elts) ||
3983 parseToken(lltok::rbrace, "expected end of struct constant"))
3984 return true;
3985
3986 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3987 ID.UIntVal = Elts.size();
3988 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3989 Elts.size() * sizeof(Elts[0]));
3991 return false;
3992 }
3993 case lltok::less: {
3994 // ValID ::= '<' ConstVector '>' --> Vector.
3995 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3996 Lex.Lex();
3997 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3998
4000 LocTy FirstEltLoc = Lex.getLoc();
4001 if (parseGlobalValueVector(Elts) ||
4002 (isPackedStruct &&
4003 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4004 parseToken(lltok::greater, "expected end of constant"))
4005 return true;
4006
4007 if (isPackedStruct) {
4008 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4009 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4010 Elts.size() * sizeof(Elts[0]));
4011 ID.UIntVal = Elts.size();
4013 return false;
4014 }
4015
4016 if (Elts.empty())
4017 return error(ID.Loc, "constant vector must not be empty");
4018
4019 if (!Elts[0]->getType()->isIntegerTy() &&
4020 !Elts[0]->getType()->isFloatingPointTy() &&
4021 !Elts[0]->getType()->isPointerTy())
4022 return error(
4023 FirstEltLoc,
4024 "vector elements must have integer, pointer or floating point type");
4025
4026 // Verify that all the vector elements have the same type.
4027 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4028 if (Elts[i]->getType() != Elts[0]->getType())
4029 return error(FirstEltLoc, "vector element #" + Twine(i) +
4030 " is not of type '" +
4031 getTypeString(Elts[0]->getType()));
4032
4033 ID.ConstantVal = ConstantVector::get(Elts);
4034 ID.Kind = ValID::t_Constant;
4035 return false;
4036 }
4037 case lltok::lsquare: { // Array Constant
4038 Lex.Lex();
4040 LocTy FirstEltLoc = Lex.getLoc();
4041 if (parseGlobalValueVector(Elts) ||
4042 parseToken(lltok::rsquare, "expected end of array constant"))
4043 return true;
4044
4045 // Handle empty element.
4046 if (Elts.empty()) {
4047 // Use undef instead of an array because it's inconvenient to determine
4048 // the element type at this point, there being no elements to examine.
4049 ID.Kind = ValID::t_EmptyArray;
4050 return false;
4051 }
4052
4053 if (!Elts[0]->getType()->isFirstClassType())
4054 return error(FirstEltLoc, "invalid array element type: " +
4055 getTypeString(Elts[0]->getType()));
4056
4057 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4058
4059 // Verify all elements are correct type!
4060 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4061 if (Elts[i]->getType() != Elts[0]->getType())
4062 return error(FirstEltLoc, "array element #" + Twine(i) +
4063 " is not of type '" +
4064 getTypeString(Elts[0]->getType()));
4065 }
4066
4067 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4068 ID.Kind = ValID::t_Constant;
4069 return false;
4070 }
4071 case lltok::kw_c: // c "foo"
4072 Lex.Lex();
4073 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4074 false);
4075 if (parseToken(lltok::StringConstant, "expected string"))
4076 return true;
4077 ID.Kind = ValID::t_Constant;
4078 return false;
4079
4080 case lltok::kw_asm: {
4081 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4082 // STRINGCONSTANT
4083 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4084 Lex.Lex();
4085 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4086 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4087 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4088 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4089 parseStringConstant(ID.StrVal) ||
4090 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4091 parseToken(lltok::StringConstant, "expected constraint string"))
4092 return true;
4093 ID.StrVal2 = Lex.getStrVal();
4094 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4095 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4096 ID.Kind = ValID::t_InlineAsm;
4097 return false;
4098 }
4099
4101 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4102 Lex.Lex();
4103
4104 ValID Fn, Label;
4105
4106 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4107 parseValID(Fn, PFS) ||
4108 parseToken(lltok::comma,
4109 "expected comma in block address expression") ||
4110 parseValID(Label, PFS) ||
4111 parseToken(lltok::rparen, "expected ')' in block address expression"))
4112 return true;
4113
4115 return error(Fn.Loc, "expected function name in blockaddress");
4116 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4117 return error(Label.Loc, "expected basic block name in blockaddress");
4118
4119 // Try to find the function (but skip it if it's forward-referenced).
4120 GlobalValue *GV = nullptr;
4121 if (Fn.Kind == ValID::t_GlobalID) {
4122 GV = NumberedVals.get(Fn.UIntVal);
4123 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4124 GV = M->getNamedValue(Fn.StrVal);
4125 }
4126 Function *F = nullptr;
4127 if (GV) {
4128 // Confirm that it's actually a function with a definition.
4129 if (!isa<Function>(GV))
4130 return error(Fn.Loc, "expected function name in blockaddress");
4131 F = cast<Function>(GV);
4132 if (F->isDeclaration())
4133 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4134 }
4135
4136 if (!F) {
4137 // Make a global variable as a placeholder for this reference.
4138 GlobalValue *&FwdRef =
4139 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4140 if (!FwdRef) {
4141 unsigned FwdDeclAS;
4142 if (ExpectedTy) {
4143 // If we know the type that the blockaddress is being assigned to,
4144 // we can use the address space of that type.
4145 if (!ExpectedTy->isPointerTy())
4146 return error(ID.Loc,
4147 "type of blockaddress must be a pointer and not '" +
4148 getTypeString(ExpectedTy) + "'");
4149 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4150 } else if (PFS) {
4151 // Otherwise, we default the address space of the current function.
4152 FwdDeclAS = PFS->getFunction().getAddressSpace();
4153 } else {
4154 llvm_unreachable("Unknown address space for blockaddress");
4155 }
4156 FwdRef = new GlobalVariable(
4157 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4158 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4159 }
4160
4161 ID.ConstantVal = FwdRef;
4162 ID.Kind = ValID::t_Constant;
4163 return false;
4164 }
4165
4166 // We found the function; now find the basic block. Don't use PFS, since we
4167 // might be inside a constant expression.
4168 BasicBlock *BB;
4169 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4170 if (Label.Kind == ValID::t_LocalID)
4171 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4172 else
4173 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4174 if (!BB)
4175 return error(Label.Loc, "referenced value is not a basic block");
4176 } else {
4177 if (Label.Kind == ValID::t_LocalID)
4178 return error(Label.Loc, "cannot take address of numeric label after "
4179 "the function is defined");
4181 F->getValueSymbolTable()->lookup(Label.StrVal));
4182 if (!BB)
4183 return error(Label.Loc, "referenced value is not a basic block");
4184 }
4185
4186 ID.ConstantVal = BlockAddress::get(F, BB);
4187 ID.Kind = ValID::t_Constant;
4188 return false;
4189 }
4190
4192 // ValID ::= 'dso_local_equivalent' @foo
4193 Lex.Lex();
4194
4195 ValID Fn;
4196
4197 if (parseValID(Fn, PFS))
4198 return true;
4199
4201 return error(Fn.Loc,
4202 "expected global value name in dso_local_equivalent");
4203
4204 // Try to find the function (but skip it if it's forward-referenced).
4205 GlobalValue *GV = nullptr;
4206 if (Fn.Kind == ValID::t_GlobalID) {
4207 GV = NumberedVals.get(Fn.UIntVal);
4208 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4209 GV = M->getNamedValue(Fn.StrVal);
4210 }
4211
4212 if (!GV) {
4213 // Make a placeholder global variable as a placeholder for this reference.
4214 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4215 ? ForwardRefDSOLocalEquivalentIDs
4216 : ForwardRefDSOLocalEquivalentNames;
4217 GlobalValue *&FwdRef = FwdRefMap[Fn];
4218 if (!FwdRef) {
4219 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4220 GlobalValue::InternalLinkage, nullptr, "",
4222 }
4223
4224 ID.ConstantVal = FwdRef;
4225 ID.Kind = ValID::t_Constant;
4226 return false;
4227 }
4228
4229 if (!GV->getValueType()->isFunctionTy())
4230 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4231 "in dso_local_equivalent");
4232
4233 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4234 ID.Kind = ValID::t_Constant;
4235 return false;
4236 }
4237
4238 case lltok::kw_no_cfi: {
4239 // ValID ::= 'no_cfi' @foo
4240 Lex.Lex();
4241
4242 if (parseValID(ID, PFS))
4243 return true;
4244
4245 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4246 return error(ID.Loc, "expected global value name in no_cfi");
4247
4248 ID.NoCFI = true;
4249 return false;
4250 }
4251 case lltok::kw_ptrauth: {
4252 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4253 // (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4254 Lex.Lex();
4255
4256 Constant *Ptr, *Key;
4257 Constant *Disc = nullptr, *AddrDisc = nullptr;
4258
4259 if (parseToken(lltok::lparen,
4260 "expected '(' in constant ptrauth expression") ||
4261 parseGlobalTypeAndValue(Ptr) ||
4262 parseToken(lltok::comma,
4263 "expected comma in constant ptrauth expression") ||
4264 parseGlobalTypeAndValue(Key))
4265 return true;
4266 // If present, parse the optional disc/addrdisc.
4267 if (EatIfPresent(lltok::comma))
4268 if (parseGlobalTypeAndValue(Disc) ||
4269 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4270 return true;
4271 if (parseToken(lltok::rparen,
4272 "expected ')' in constant ptrauth expression"))
4273 return true;
4274
4275 if (!Ptr->getType()->isPointerTy())
4276 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4277
4278 auto *KeyC = dyn_cast<ConstantInt>(Key);
4279 if (!KeyC || KeyC->getBitWidth() != 32)
4280 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4281
4282 ConstantInt *DiscC = nullptr;
4283 if (Disc) {
4284 DiscC = dyn_cast<ConstantInt>(Disc);
4285 if (!DiscC || DiscC->getBitWidth() != 64)
4286 return error(
4287 ID.Loc,
4288 "constant ptrauth integer discriminator must be i64 constant");
4289 } else {
4290 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4291 }
4292
4293 if (AddrDisc) {
4294 if (!AddrDisc->getType()->isPointerTy())
4295 return error(
4296 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4297 } else {
4298 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4299 }
4300
4301 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4302 ID.Kind = ValID::t_Constant;
4303 return false;
4304 }
4305
4306 case lltok::kw_trunc:
4307 case lltok::kw_bitcast:
4309 case lltok::kw_inttoptr:
4311 case lltok::kw_ptrtoint: {
4312 unsigned Opc = Lex.getUIntVal();
4313 Type *DestTy = nullptr;
4314 Constant *SrcVal;
4315 Lex.Lex();
4316 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4317 parseGlobalTypeAndValue(SrcVal) ||
4318 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4319 parseType(DestTy) ||
4320 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4321 return true;
4322 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4323 return error(ID.Loc, "invalid cast opcode for cast from '" +
4324 getTypeString(SrcVal->getType()) + "' to '" +
4325 getTypeString(DestTy) + "'");
4327 SrcVal, DestTy);
4328 ID.Kind = ValID::t_Constant;
4329 return false;
4330 }
4332 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4334 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4335 case lltok::kw_udiv:
4336 return error(ID.Loc, "udiv constexprs are no longer supported");
4337 case lltok::kw_sdiv:
4338 return error(ID.Loc, "sdiv constexprs are no longer supported");
4339 case lltok::kw_urem:
4340 return error(ID.Loc, "urem constexprs are no longer supported");
4341 case lltok::kw_srem:
4342 return error(ID.Loc, "srem constexprs are no longer supported");
4343 case lltok::kw_fadd:
4344 return error(ID.Loc, "fadd constexprs are no longer supported");
4345 case lltok::kw_fsub:
4346 return error(ID.Loc, "fsub constexprs are no longer supported");
4347 case lltok::kw_fmul:
4348 return error(ID.Loc, "fmul constexprs are no longer supported");
4349 case lltok::kw_fdiv:
4350 return error(ID.Loc, "fdiv constexprs are no longer supported");
4351 case lltok::kw_frem:
4352 return error(ID.Loc, "frem constexprs are no longer supported");
4353 case lltok::kw_and:
4354 return error(ID.Loc, "and constexprs are no longer supported");
4355 case lltok::kw_or:
4356 return error(ID.Loc, "or constexprs are no longer supported");
4357 case lltok::kw_lshr:
4358 return error(ID.Loc, "lshr constexprs are no longer supported");
4359 case lltok::kw_ashr:
4360 return error(ID.Loc, "ashr constexprs are no longer supported");
4361 case lltok::kw_shl:
4362 return error(ID.Loc, "shl constexprs are no longer supported");
4363 case lltok::kw_mul:
4364 return error(ID.Loc, "mul constexprs are no longer supported");
4365 case lltok::kw_fneg:
4366 return error(ID.Loc, "fneg constexprs are no longer supported");
4367 case lltok::kw_select:
4368 return error(ID.Loc, "select constexprs are no longer supported");
4369 case lltok::kw_zext:
4370 return error(ID.Loc, "zext constexprs are no longer supported");
4371 case lltok::kw_sext:
4372 return error(ID.Loc, "sext constexprs are no longer supported");
4373 case lltok::kw_fptrunc:
4374 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4375 case lltok::kw_fpext:
4376 return error(ID.Loc, "fpext constexprs are no longer supported");
4377 case lltok::kw_uitofp:
4378 return error(ID.Loc, "uitofp constexprs are no longer supported");
4379 case lltok::kw_sitofp:
4380 return error(ID.Loc, "sitofp constexprs are no longer supported");
4381 case lltok::kw_fptoui:
4382 return error(ID.Loc, "fptoui constexprs are no longer supported");
4383 case lltok::kw_fptosi:
4384 return error(ID.Loc, "fptosi constexprs are no longer supported");
4385 case lltok::kw_icmp:
4386 return error(ID.Loc, "icmp constexprs are no longer supported");
4387 case lltok::kw_fcmp:
4388 return error(ID.Loc, "fcmp constexprs are no longer supported");
4389
4390 // Binary Operators.
4391 case lltok::kw_add:
4392 case lltok::kw_sub:
4393 case lltok::kw_xor: {
4394 bool NUW = false;
4395 bool NSW = false;
4396 unsigned Opc = Lex.getUIntVal();
4397 Constant *Val0, *Val1;
4398 Lex.Lex();
4399 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4400 Opc == Instruction::Mul) {
4401 if (EatIfPresent(lltok::kw_nuw))
4402 NUW = true;
4403 if (EatIfPresent(lltok::kw_nsw)) {
4404 NSW = true;
4405 if (EatIfPresent(lltok::kw_nuw))
4406 NUW = true;
4407 }
4408 }
4409 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4410 parseGlobalTypeAndValue(Val0) ||
4411 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4412 parseGlobalTypeAndValue(Val1) ||
4413 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4414 return true;
4415 if (Val0->getType() != Val1->getType())
4416 return error(ID.Loc, "operands of constexpr must have same type");
4417 // Check that the type is valid for the operator.
4418 if (!Val0->getType()->isIntOrIntVectorTy())
4419 return error(ID.Loc,
4420 "constexpr requires integer or integer vector operands");
4421 unsigned Flags = 0;
4424 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4425 ID.Kind = ValID::t_Constant;
4426 return false;
4427 }
4428
4429 case lltok::kw_splat: {
4430 Lex.Lex();
4431 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4432 return true;
4433 Constant *C;
4434 if (parseGlobalTypeAndValue(C))
4435 return true;
4436 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4437 return true;
4438
4439 ID.ConstantVal = C;
4441 return false;
4442 }
4443
4448 unsigned Opc = Lex.getUIntVal();
4450 GEPNoWrapFlags NW;
4451 bool HasInRange = false;
4452 APSInt InRangeStart;
4453 APSInt InRangeEnd;
4454 Type *Ty;
4455 Lex.Lex();
4456
4457 if (Opc == Instruction::GetElementPtr) {
4458 while (true) {
4459 if (EatIfPresent(lltok::kw_inbounds))
4461 else if (EatIfPresent(lltok::kw_nusw))
4463 else if (EatIfPresent(lltok::kw_nuw))
4465 else
4466 break;
4467 }
4468
4469 if (EatIfPresent(lltok::kw_inrange)) {
4470 if (parseToken(lltok::lparen, "expected '('"))
4471 return true;
4472 if (Lex.getKind() != lltok::APSInt)
4473 return tokError("expected integer");
4474 InRangeStart = Lex.getAPSIntVal();
4475 Lex.Lex();
4476 if (parseToken(lltok::comma, "expected ','"))
4477 return true;
4478 if (Lex.getKind() != lltok::APSInt)
4479 return tokError("expected integer");
4480 InRangeEnd = Lex.getAPSIntVal();
4481 Lex.Lex();
4482 if (parseToken(lltok::rparen, "expected ')'"))
4483 return true;
4484 HasInRange = true;
4485 }
4486 }
4487
4488 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4489 return true;
4490
4491 if (Opc == Instruction::GetElementPtr) {
4492 if (parseType(Ty) ||
4493 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4494 return true;
4495 }
4496
4497 if (parseGlobalValueVector(Elts) ||
4498 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4499 return true;
4500
4501 if (Opc == Instruction::GetElementPtr) {
4502 if (Elts.size() == 0 ||
4503 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4504 return error(ID.Loc, "base of getelementptr must be a pointer");
4505
4506 Type *BaseType = Elts[0]->getType();
4507 std::optional<ConstantRange> InRange;
4508 if (HasInRange) {
4509 unsigned IndexWidth =
4510 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4511 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4512 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4513 if (InRangeStart.sge(InRangeEnd))
4514 return error(ID.Loc, "expected end to be larger than start");
4515 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4516 }
4517
4518 unsigned GEPWidth =
4519 BaseType->isVectorTy()
4520 ? cast<FixedVectorType>(BaseType)->getNumElements()
4521 : 0;
4522
4523 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4524 for (Constant *Val : Indices) {
4525 Type *ValTy = Val->getType();
4526 if (!ValTy->isIntOrIntVectorTy())
4527 return error(ID.Loc, "getelementptr index must be an integer");
4528 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4529 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4530 if (GEPWidth && (ValNumEl != GEPWidth))
4531 return error(
4532 ID.Loc,
4533 "getelementptr vector index has a wrong number of elements");
4534 // GEPWidth may have been unknown because the base is a scalar,
4535 // but it is known now.
4536 GEPWidth = ValNumEl;
4537 }
4538 }
4539
4540 SmallPtrSet<Type*, 4> Visited;
4541 if (!Indices.empty() && !Ty->isSized(&Visited))
4542 return error(ID.Loc, "base element of getelementptr must be sized");
4543
4545 return error(ID.Loc, "invalid base element for constant getelementptr");
4546
4547 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4548 return error(ID.Loc, "invalid getelementptr indices");
4549
4550 ID.ConstantVal =
4551 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4552 } else if (Opc == Instruction::ShuffleVector) {
4553 if (Elts.size() != 3)
4554 return error(ID.Loc, "expected three operands to shufflevector");
4555 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4556 return error(ID.Loc, "invalid operands to shufflevector");
4557 SmallVector<int, 16> Mask;
4559 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4560 } else if (Opc == Instruction::ExtractElement) {
4561 if (Elts.size() != 2)
4562 return error(ID.Loc, "expected two operands to extractelement");
4563 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4564 return error(ID.Loc, "invalid extractelement operands");
4565 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4566 } else {
4567 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4568 if (Elts.size() != 3)
4569 return error(ID.Loc, "expected three operands to insertelement");
4570 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4571 return error(ID.Loc, "invalid insertelement operands");
4572 ID.ConstantVal =
4573 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4574 }
4575
4576 ID.Kind = ValID::t_Constant;
4577 return false;
4578 }
4579 }
4580
4581 Lex.Lex();
4582 return false;
4583}
4584
4585/// parseGlobalValue - parse a global value with the specified type.
4586bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4587 C = nullptr;
4588 ValID ID;
4589 Value *V = nullptr;
4590 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4591 convertValIDToValue(Ty, ID, V, nullptr);
4592 if (V && !(C = dyn_cast<Constant>(V)))
4593 return error(ID.Loc, "global values must be constants");
4594 return Parsed;
4595}
4596
4597bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4598 Type *Ty = nullptr;
4599 return parseType(Ty) || parseGlobalValue(Ty, V);
4600}
4601
4602bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4603 C = nullptr;
4604
4605 LocTy KwLoc = Lex.getLoc();
4606 if (!EatIfPresent(lltok::kw_comdat))
4607 return false;
4608
4609 if (EatIfPresent(lltok::lparen)) {
4610 if (Lex.getKind() != lltok::ComdatVar)
4611 return tokError("expected comdat variable");
4612 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4613 Lex.Lex();
4614 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4615 return true;
4616 } else {
4617 if (GlobalName.empty())
4618 return tokError("comdat cannot be unnamed");
4619 C = getComdat(std::string(GlobalName), KwLoc);
4620 }
4621
4622 return false;
4623}
4624
4625/// parseGlobalValueVector
4626/// ::= /*empty*/
4627/// ::= TypeAndValue (',' TypeAndValue)*
4628bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4629 // Empty list.
4630 if (Lex.getKind() == lltok::rbrace ||
4631 Lex.getKind() == lltok::rsquare ||
4632 Lex.getKind() == lltok::greater ||
4633 Lex.getKind() == lltok::rparen)
4634 return false;
4635
4636 do {
4637 // Let the caller deal with inrange.
4638 if (Lex.getKind() == lltok::kw_inrange)
4639 return false;
4640
4641 Constant *C;
4642 if (parseGlobalTypeAndValue(C))
4643 return true;
4644 Elts.push_back(C);
4645 } while (EatIfPresent(lltok::comma));
4646
4647 return false;
4648}
4649
4650bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4652 if (parseMDNodeVector(Elts))
4653 return true;
4654
4655 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4656 return false;
4657}
4658
4659/// MDNode:
4660/// ::= !{ ... }
4661/// ::= !7
4662/// ::= !DILocation(...)
4663bool LLParser::parseMDNode(MDNode *&N) {
4664 if (Lex.getKind() == lltok::MetadataVar)
4665 return parseSpecializedMDNode(N);
4666
4667 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4668}
4669
4670bool LLParser::parseMDNodeTail(MDNode *&N) {
4671 // !{ ... }
4672 if (Lex.getKind() == lltok::lbrace)
4673 return parseMDTuple(N);
4674
4675 // !42
4676 return parseMDNodeID(N);
4677}
4678
4679namespace {
4680
4681/// Structure to represent an optional metadata field.
4682template <class FieldTy> struct MDFieldImpl {
4683 typedef MDFieldImpl ImplTy;
4684 FieldTy Val;
4685 bool Seen;
4686
4687 void assign(FieldTy Val) {
4688 Seen = true;
4689 this->Val = std::move(Val);
4690 }
4691
4692 explicit MDFieldImpl(FieldTy Default)
4693 : Val(std::move(Default)), Seen(false) {}
4694};
4695
4696/// Structure to represent an optional metadata field that
4697/// can be of either type (A or B) and encapsulates the
4698/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4699/// to reimplement the specifics for representing each Field.
4700template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4701 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4702 FieldTypeA A;
4703 FieldTypeB B;
4704 bool Seen;
4705
4706 enum {
4707 IsInvalid = 0,
4708 IsTypeA = 1,
4709 IsTypeB = 2
4710 } WhatIs;
4711
4712 void assign(FieldTypeA A) {
4713 Seen = true;
4714 this->A = std::move(A);
4715 WhatIs = IsTypeA;
4716 }
4717
4718 void assign(FieldTypeB B) {
4719 Seen = true;
4720 this->B = std::move(B);
4721 WhatIs = IsTypeB;
4722 }
4723
4724 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4725 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4726 WhatIs(IsInvalid) {}
4727};
4728
4729struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4730 uint64_t Max;
4731
4732 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4733 : ImplTy(Default), Max(Max) {}
4734};
4735
4736struct LineField : public MDUnsignedField {
4737 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4738};
4739
4740struct ColumnField : public MDUnsignedField {
4741 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4742};
4743
4744struct DwarfTagField : public MDUnsignedField {
4745 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4746 DwarfTagField(dwarf::Tag DefaultTag)
4747 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4748};
4749
4750struct DwarfMacinfoTypeField : public MDUnsignedField {
4751 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4752 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4753 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4754};
4755
4756struct DwarfAttEncodingField : public MDUnsignedField {
4757 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4758};
4759
4760struct DwarfVirtualityField : public MDUnsignedField {
4761 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4762};
4763
4764struct DwarfLangField : public MDUnsignedField {
4765 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4766};
4767
4768struct DwarfSourceLangNameField : public MDUnsignedField {
4769 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4770};
4771
4772struct DwarfCCField : public MDUnsignedField {
4773 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4774};
4775
4776struct DwarfEnumKindField : public MDUnsignedField {
4777 DwarfEnumKindField()
4778 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4779 dwarf::DW_APPLE_ENUM_KIND_max) {}
4780};
4781
4782struct EmissionKindField : public MDUnsignedField {
4783 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4784};
4785
4786struct FixedPointKindField : public MDUnsignedField {
4787 FixedPointKindField()
4788 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4789};
4790
4791struct NameTableKindField : public MDUnsignedField {
4792 NameTableKindField()
4793 : MDUnsignedField(
4794 0, (unsigned)
4795 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4796};
4797
4798struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4799 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4800};
4801
4802struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4803 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4804};
4805
4806struct MDAPSIntField : public MDFieldImpl<APSInt> {
4807 MDAPSIntField() : ImplTy(APSInt()) {}
4808};
4809
4810struct MDSignedField : public MDFieldImpl<int64_t> {
4811 int64_t Min = INT64_MIN;
4812 int64_t Max = INT64_MAX;
4813
4814 MDSignedField(int64_t Default = 0)
4815 : ImplTy(Default) {}
4816 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4817 : ImplTy(Default), Min(Min), Max(Max) {}
4818};
4819
4820struct MDBoolField : public MDFieldImpl<bool> {
4821 MDBoolField(bool Default = false) : ImplTy(Default) {}
4822};
4823
4824struct MDField : public MDFieldImpl<Metadata *> {
4825 bool AllowNull;
4826
4827 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4828};
4829
4830struct MDStringField : public MDFieldImpl<MDString *> {
4831 enum class EmptyIs {
4832 Null, //< Allow empty input string, map to nullptr
4833 Empty, //< Allow empty input string, map to an empty MDString
4834 Error, //< Disallow empty string, map to an error
4835 } EmptyIs;
4836 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
4837 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4838};
4839
4840struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4841 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4842};
4843
4844struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4845 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4846};
4847
4848struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4849 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4850 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4851
4852 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4853 bool AllowNull = true)
4854 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4855
4856 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4857 bool isMDField() const { return WhatIs == IsTypeB; }
4858 int64_t getMDSignedValue() const {
4859 assert(isMDSignedField() && "Wrong field type");
4860 return A.Val;
4861 }
4862 Metadata *getMDFieldValue() const {
4863 assert(isMDField() && "Wrong field type");
4864 return B.Val;
4865 }
4866};
4867
4868struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4869 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
4870 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
4871
4872 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
4873 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
4874
4875 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
4876 bool isMDField() const { return WhatIs == IsTypeB; }
4877 uint64_t getMDUnsignedValue() const {
4878 assert(isMDUnsignedField() && "Wrong field type");
4879 return A.Val;
4880 }
4881 Metadata *getMDFieldValue() const {
4882 assert(isMDField() && "Wrong field type");
4883 return B.Val;
4884 }
4885
4886 Metadata *getValueAsMetadata(LLVMContext &Context) const {
4887 if (isMDUnsignedField())
4889 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
4890 if (isMDField())
4891 return getMDFieldValue();
4892 return nullptr;
4893 }
4894};
4895
4896} // end anonymous namespace
4897
4898namespace llvm {
4899
4900template <>
4901bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4902 if (Lex.getKind() != lltok::APSInt)
4903 return tokError("expected integer");
4904
4905 Result.assign(Lex.getAPSIntVal());
4906 Lex.Lex();
4907 return false;
4908}
4909
4910template <>
4911bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4912 MDUnsignedField &Result) {
4913 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4914 return tokError("expected unsigned integer");
4915
4916 auto &U = Lex.getAPSIntVal();
4917 if (U.ugt(Result.Max))
4918 return tokError("value for '" + Name + "' too large, limit is " +
4919 Twine(Result.Max));
4920 Result.assign(U.getZExtValue());
4921 assert(Result.Val <= Result.Max && "Expected value in range");
4922 Lex.Lex();
4923 return false;
4924}
4925
4926template <>
4927bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4928 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4929}
4930template <>
4931bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4932 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4933}
4934
4935template <>
4936bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4937 if (Lex.getKind() == lltok::APSInt)
4938 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4939
4940 if (Lex.getKind() != lltok::DwarfTag)
4941 return tokError("expected DWARF tag");
4942
4943 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4945 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4946 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4947
4948 Result.assign(Tag);
4949 Lex.Lex();
4950 return false;
4951}
4952
4953template <>
4954bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4955 DwarfMacinfoTypeField &Result) {
4956 if (Lex.getKind() == lltok::APSInt)
4957 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4958
4959 if (Lex.getKind() != lltok::DwarfMacinfo)
4960 return tokError("expected DWARF macinfo type");
4961
4962 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4963 if (Macinfo == dwarf::DW_MACINFO_invalid)
4964 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4965 Lex.getStrVal() + "'");
4966 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4967
4968 Result.assign(Macinfo);
4969 Lex.Lex();
4970 return false;
4971}
4972
4973template <>
4974bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4975 DwarfVirtualityField &Result) {
4976 if (Lex.getKind() == lltok::APSInt)
4977 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4978
4979 if (Lex.getKind() != lltok::DwarfVirtuality)
4980 return tokError("expected DWARF virtuality code");
4981
4982 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4983 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4984 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4985 Lex.getStrVal() + "'");
4986 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4987 Result.assign(Virtuality);
4988 Lex.Lex();
4989 return false;
4990}
4991
4992template <>
4993bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4994 DwarfEnumKindField &Result) {
4995 if (Lex.getKind() == lltok::APSInt)
4996 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4997
4998 if (Lex.getKind() != lltok::DwarfEnumKind)
4999 return tokError("expected DWARF enum kind code");
5000
5001 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5002 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5003 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5004 Lex.getStrVal() + "'");
5005 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5006 Result.assign(EnumKind);
5007 Lex.Lex();
5008 return false;
5009}
5010
5011template <>
5012bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5013 if (Lex.getKind() == lltok::APSInt)
5014 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5015
5016 if (Lex.getKind() != lltok::DwarfLang)
5017 return tokError("expected DWARF language");
5018
5019 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5020 if (!Lang)
5021 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5022 "'");
5023 assert(Lang <= Result.Max && "Expected valid DWARF language");
5024 Result.assign(Lang);
5025 Lex.Lex();
5026 return false;
5027}
5028
5029template <>
5030bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5031 DwarfSourceLangNameField &Result) {
5032 if (Lex.getKind() == lltok::APSInt)
5033 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5034
5035 if (Lex.getKind() != lltok::DwarfSourceLangName)
5036 return tokError("expected DWARF source language name");
5037
5038 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5039 if (!Lang)
5040 return tokError("invalid DWARF source language name" + Twine(" '") +
5041 Lex.getStrVal() + "'");
5042 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5043 Result.assign(Lang);
5044 Lex.Lex();
5045 return false;
5046}
5047
5048template <>
5049bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5050 if (Lex.getKind() == lltok::APSInt)
5051 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5052
5053 if (Lex.getKind() != lltok::DwarfCC)
5054 return tokError("expected DWARF calling convention");
5055
5056 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5057 if (!CC)
5058 return tokError("invalid DWARF calling convention" + Twine(" '") +
5059 Lex.getStrVal() + "'");
5060 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5061 Result.assign(CC);
5062 Lex.Lex();
5063 return false;
5064}
5065
5066template <>
5067bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5068 EmissionKindField &Result) {
5069 if (Lex.getKind() == lltok::APSInt)
5070 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5071
5072 if (Lex.getKind() != lltok::EmissionKind)
5073 return tokError("expected emission kind");
5074
5075 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5076 if (!Kind)
5077 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5078 "'");
5079 assert(*Kind <= Result.Max && "Expected valid emission kind");
5080 Result.assign(*Kind);
5081 Lex.Lex();
5082 return false;
5083}
5084
5085template <>
5086bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5087 FixedPointKindField &Result) {
5088 if (Lex.getKind() == lltok::APSInt)
5089 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5090
5091 if (Lex.getKind() != lltok::FixedPointKind)
5092 return tokError("expected fixed-point kind");
5093
5094 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5095 if (!Kind)
5096 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5097 "'");
5098 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5099 Result.assign(*Kind);
5100 Lex.Lex();
5101 return false;
5102}
5103
5104template <>
5105bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5106 NameTableKindField &Result) {
5107 if (Lex.getKind() == lltok::APSInt)
5108 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5109
5110 if (Lex.getKind() != lltok::NameTableKind)
5111 return tokError("expected nameTable kind");
5112
5113 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5114 if (!Kind)
5115 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5116 "'");
5117 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5118 Result.assign((unsigned)*Kind);
5119 Lex.Lex();
5120 return false;
5121}
5122
5123template <>
5124bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5125 DwarfAttEncodingField &Result) {
5126 if (Lex.getKind() == lltok::APSInt)
5127 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5128
5129 if (Lex.getKind() != lltok::DwarfAttEncoding)
5130 return tokError("expected DWARF type attribute encoding");
5131
5132 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5133 if (!Encoding)
5134 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5135 Lex.getStrVal() + "'");
5136 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5137 Result.assign(Encoding);
5138 Lex.Lex();
5139 return false;
5140}
5141
5142/// DIFlagField
5143/// ::= uint32
5144/// ::= DIFlagVector
5145/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5146template <>
5147bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5148
5149 // parser for a single flag.
5150 auto parseFlag = [&](DINode::DIFlags &Val) {
5151 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5152 uint32_t TempVal = static_cast<uint32_t>(Val);
5153 bool Res = parseUInt32(TempVal);
5154 Val = static_cast<DINode::DIFlags>(TempVal);
5155 return Res;
5156 }
5157
5158 if (Lex.getKind() != lltok::DIFlag)
5159 return tokError("expected debug info flag");
5160
5161 Val = DINode::getFlag(Lex.getStrVal());
5162 if (!Val)
5163 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5164 "'");
5165 Lex.Lex();
5166 return false;
5167 };
5168
5169 // parse the flags and combine them together.
5170 DINode::DIFlags Combined = DINode::FlagZero;
5171 do {
5172 DINode::DIFlags Val;
5173 if (parseFlag(Val))
5174 return true;
5175 Combined |= Val;
5176 } while (EatIfPresent(lltok::bar));
5177
5178 Result.assign(Combined);
5179 return false;
5180}
5181
5182/// DISPFlagField
5183/// ::= uint32
5184/// ::= DISPFlagVector
5185/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5186template <>
5187bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5188
5189 // parser for a single flag.
5190 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5191 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5192 uint32_t TempVal = static_cast<uint32_t>(Val);
5193 bool Res = parseUInt32(TempVal);
5194 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5195 return Res;
5196 }
5197
5198 if (Lex.getKind() != lltok::DISPFlag)
5199 return tokError("expected debug info flag");
5200
5201 Val = DISubprogram::getFlag(Lex.getStrVal());
5202 if (!Val)
5203 return tokError(Twine("invalid subprogram debug info flag '") +
5204 Lex.getStrVal() + "'");
5205 Lex.Lex();
5206 return false;
5207 };
5208
5209 // parse the flags and combine them together.
5210 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5211 do {
5213 if (parseFlag(Val))
5214 return true;
5215 Combined |= Val;
5216 } while (EatIfPresent(lltok::bar));
5217
5218 Result.assign(Combined);
5219 return false;
5220}
5221
5222template <>
5223bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5224 if (Lex.getKind() != lltok::APSInt)
5225 return tokError("expected signed integer");
5226
5227 auto &S = Lex.getAPSIntVal();
5228 if (S < Result.Min)
5229 return tokError("value for '" + Name + "' too small, limit is " +
5230 Twine(Result.Min));
5231 if (S > Result.Max)
5232 return tokError("value for '" + Name + "' too large, limit is " +
5233 Twine(Result.Max));
5234 Result.assign(S.getExtValue());
5235 assert(Result.Val >= Result.Min && "Expected value in range");
5236 assert(Result.Val <= Result.Max && "Expected value in range");
5237 Lex.Lex();
5238 return false;
5239}
5240
5241template <>
5242bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5243 switch (Lex.getKind()) {
5244 default:
5245 return tokError("expected 'true' or 'false'");
5246 case lltok::kw_true:
5247 Result.assign(true);
5248 break;
5249 case lltok::kw_false:
5250 Result.assign(false);
5251 break;
5252 }
5253 Lex.Lex();
5254 return false;
5255}
5256
5257template <>
5258bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5259 if (Lex.getKind() == lltok::kw_null) {
5260 if (!Result.AllowNull)
5261 return tokError("'" + Name + "' cannot be null");
5262 Lex.Lex();
5263 Result.assign(nullptr);
5264 return false;
5265 }
5266
5267 Metadata *MD;
5268 if (parseMetadata(MD, nullptr))
5269 return true;
5270
5271 Result.assign(MD);
5272 return false;
5273}
5274
5275template <>
5276bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5277 MDSignedOrMDField &Result) {
5278 // Try to parse a signed int.
5279 if (Lex.getKind() == lltok::APSInt) {
5280 MDSignedField Res = Result.A;
5281 if (!parseMDField(Loc, Name, Res)) {
5282 Result.assign(Res);
5283 return false;
5284 }
5285 return true;
5286 }
5287
5288 // Otherwise, try to parse as an MDField.
5289 MDField Res = Result.B;
5290 if (!parseMDField(Loc, Name, Res)) {
5291 Result.assign(Res);
5292 return false;
5293 }
5294
5295 return true;
5296}
5297
5298template <>
5299bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5300 MDUnsignedOrMDField &Result) {
5301 // Try to parse an unsigned int.
5302 if (Lex.getKind() == lltok::APSInt) {
5303 MDUnsignedField Res = Result.A;
5304 if (!parseMDField(Loc, Name, Res)) {
5305 Result.assign(Res);
5306 return false;
5307 }
5308 return true;
5309 }
5310
5311 // Otherwise, try to parse as an MDField.
5312 MDField Res = Result.B;
5313 if (!parseMDField(Loc, Name, Res)) {
5314 Result.assign(Res);
5315 return false;
5316 }
5317
5318 return true;
5319}
5320
5321template <>
5322bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5323 LocTy ValueLoc = Lex.getLoc();
5324 std::string S;
5325 if (parseStringConstant(S))
5326 return true;
5327
5328 if (S.empty()) {
5329 switch (Result.EmptyIs) {
5330 case MDStringField::EmptyIs::Null:
5331 Result.assign(nullptr);
5332 return false;
5333 case MDStringField::EmptyIs::Empty:
5334 break;
5335 case MDStringField::EmptyIs::Error:
5336 return error(ValueLoc, "'" + Name + "' cannot be empty");
5337 }
5338 }
5339
5340 Result.assign(MDString::get(Context, S));
5341 return false;
5342}
5343
5344template <>
5345bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5347 if (parseMDNodeVector(MDs))
5348 return true;
5349
5350 Result.assign(std::move(MDs));
5351 return false;
5352}
5353
5354template <>
5355bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5356 ChecksumKindField &Result) {
5357 std::optional<DIFile::ChecksumKind> CSKind =
5358 DIFile::getChecksumKind(Lex.getStrVal());
5359
5360 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5361 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5362 "'");
5363
5364 Result.assign(*CSKind);
5365 Lex.Lex();
5366 return false;
5367}
5368
5369} // end namespace llvm
5370
5371template <class ParserTy>
5372bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5373 do {
5374 if (Lex.getKind() != lltok::LabelStr)
5375 return tokError("expected field label here");
5376
5377 if (ParseField())
5378 return true;
5379 } while (EatIfPresent(lltok::comma));
5380
5381 return false;
5382}
5383
5384template <class ParserTy>
5385bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5386 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5387 Lex.Lex();
5388
5389 if (parseToken(lltok::lparen, "expected '(' here"))
5390 return true;
5391 if (Lex.getKind() != lltok::rparen)
5392 if (parseMDFieldsImplBody(ParseField))
5393 return true;
5394
5395 ClosingLoc = Lex.getLoc();
5396 return parseToken(lltok::rparen, "expected ')' here");
5397}
5398
5399template <class FieldTy>
5400bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5401 if (Result.Seen)
5402 return tokError("field '" + Name + "' cannot be specified more than once");
5403
5404 LocTy Loc = Lex.getLoc();
5405 Lex.Lex();
5406 return parseMDField(Loc, Name, Result);
5407}
5408
5409bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5410 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5411
5412#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5413 if (Lex.getStrVal() == #CLASS) \
5414 return parse##CLASS(N, IsDistinct);
5415#include "llvm/IR/Metadata.def"
5416
5417 return tokError("expected metadata type");
5418}
5419
5420#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5421#define NOP_FIELD(NAME, TYPE, INIT)
5422#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5423 if (!NAME.Seen) \
5424 return error(ClosingLoc, "missing required field '" #NAME "'");
5425#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5426 if (Lex.getStrVal() == #NAME) \
5427 return parseMDField(#NAME, NAME);
5428#define PARSE_MD_FIELDS() \
5429 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5430 do { \
5431 LocTy ClosingLoc; \
5432 if (parseMDFieldsImpl( \
5433 [&]() -> bool { \
5434 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5435 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5436 "'"); \
5437 }, \
5438 ClosingLoc)) \
5439 return true; \
5440 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5441 } while (false)
5442#define GET_OR_DISTINCT(CLASS, ARGS) \
5443 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5444
5445/// parseDILocationFields:
5446/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5447/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5448bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5449#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5450 OPTIONAL(line, LineField, ); \
5451 OPTIONAL(column, ColumnField, ); \
5452 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5453 OPTIONAL(inlinedAt, MDField, ); \
5454 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5455 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5456 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5458#undef VISIT_MD_FIELDS
5459
5460 Result = GET_OR_DISTINCT(
5461 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5462 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5463 return false;
5464}
5465
5466/// parseDIAssignID:
5467/// ::= distinct !DIAssignID()
5468bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5469 if (!IsDistinct)
5470 return tokError("missing 'distinct', required for !DIAssignID()");
5471
5472 Lex.Lex();
5473
5474 // Now eat the parens.
5475 if (parseToken(lltok::lparen, "expected '(' here"))
5476 return true;
5477 if (parseToken(lltok::rparen, "expected ')' here"))
5478 return true;
5479
5481 return false;
5482}
5483
5484/// parseGenericDINode:
5485/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5486bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5487#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5488 REQUIRED(tag, DwarfTagField, ); \
5489 OPTIONAL(header, MDStringField, ); \
5490 OPTIONAL(operands, MDFieldList, );
5492#undef VISIT_MD_FIELDS
5493
5494 Result = GET_OR_DISTINCT(GenericDINode,
5495 (Context, tag.Val, header.Val, operands.Val));
5496 return false;
5497}
5498
5499/// parseDISubrangeType:
5500/// ::= !DISubrangeType(name: "whatever", file: !0,
5501/// line: 7, scope: !1, baseType: !2, size: 32,
5502/// align: 32, flags: 0, lowerBound: !3
5503/// upperBound: !4, stride: !5, bias: !6)
5504bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5505#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5506 OPTIONAL(name, MDStringField, ); \
5507 OPTIONAL(file, MDField, ); \
5508 OPTIONAL(line, LineField, ); \
5509 OPTIONAL(scope, MDField, ); \
5510 OPTIONAL(baseType, MDField, ); \
5511 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5512 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5513 OPTIONAL(flags, DIFlagField, ); \
5514 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5515 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5516 OPTIONAL(stride, MDSignedOrMDField, ); \
5517 OPTIONAL(bias, MDSignedOrMDField, );
5519#undef VISIT_MD_FIELDS
5520
5521 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5522 if (Bound.isMDSignedField())
5524 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5525 if (Bound.isMDField())
5526 return Bound.getMDFieldValue();
5527 return nullptr;
5528 };
5529
5530 Metadata *LowerBound = convToMetadata(lowerBound);
5531 Metadata *UpperBound = convToMetadata(upperBound);
5532 Metadata *Stride = convToMetadata(stride);
5533 Metadata *Bias = convToMetadata(bias);
5534
5536 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5537 size.getValueAsMetadata(Context), align.Val, flags.Val,
5538 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5539
5540 return false;
5541}
5542
5543/// parseDISubrange:
5544/// ::= !DISubrange(count: 30, lowerBound: 2)
5545/// ::= !DISubrange(count: !node, lowerBound: 2)
5546/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5547bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5548#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5549 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5550 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5551 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5552 OPTIONAL(stride, MDSignedOrMDField, );
5554#undef VISIT_MD_FIELDS
5555
5556 Metadata *Count = nullptr;
5557 Metadata *LowerBound = nullptr;
5558 Metadata *UpperBound = nullptr;
5559 Metadata *Stride = nullptr;
5560
5561 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5562 if (Bound.isMDSignedField())
5564 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5565 if (Bound.isMDField())
5566 return Bound.getMDFieldValue();
5567 return nullptr;
5568 };
5569
5570 Count = convToMetadata(count);
5571 LowerBound = convToMetadata(lowerBound);
5572 UpperBound = convToMetadata(upperBound);
5573 Stride = convToMetadata(stride);
5574
5575 Result = GET_OR_DISTINCT(DISubrange,
5576 (Context, Count, LowerBound, UpperBound, Stride));
5577
5578 return false;
5579}
5580
5581/// parseDIGenericSubrange:
5582/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5583/// !node3)
5584bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5585#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5586 OPTIONAL(count, MDSignedOrMDField, ); \
5587 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5588 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5589 OPTIONAL(stride, MDSignedOrMDField, );
5591#undef VISIT_MD_FIELDS
5592
5593 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5594 if (Bound.isMDSignedField())
5595 return DIExpression::get(
5596 Context, {dwarf::DW_OP_consts,
5597 static_cast<uint64_t>(Bound.getMDSignedValue())});
5598 if (Bound.isMDField())
5599 return Bound.getMDFieldValue();
5600 return nullptr;
5601 };
5602
5603 Metadata *Count = ConvToMetadata(count);
5604 Metadata *LowerBound = ConvToMetadata(lowerBound);
5605 Metadata *UpperBound = ConvToMetadata(upperBound);
5606 Metadata *Stride = ConvToMetadata(stride);
5607
5608 Result = GET_OR_DISTINCT(DIGenericSubrange,
5609 (Context, Count, LowerBound, UpperBound, Stride));
5610
5611 return false;
5612}
5613
5614/// parseDIEnumerator:
5615/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5616bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5617#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5618 REQUIRED(name, MDStringField, ); \
5619 REQUIRED(value, MDAPSIntField, ); \
5620 OPTIONAL(isUnsigned, MDBoolField, (false));
5622#undef VISIT_MD_FIELDS
5623
5624 if (isUnsigned.Val && value.Val.isNegative())
5625 return tokError("unsigned enumerator with negative value");
5626
5627 APSInt Value(value.Val);
5628 // Add a leading zero so that unsigned values with the msb set are not
5629 // mistaken for negative values when used for signed enumerators.
5630 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5631 Value = Value.zext(Value.getBitWidth() + 1);
5632
5633 Result =
5634 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5635
5636 return false;
5637}
5638
5639/// parseDIBasicType:
5640/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5641/// encoding: DW_ATE_encoding, flags: 0)
5642bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5643#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5644 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5645 OPTIONAL(name, MDStringField, ); \
5646 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5647 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5648 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5649 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5650 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5651 OPTIONAL(flags, DIFlagField, );
5653#undef VISIT_MD_FIELDS
5654
5656 DIBasicType,
5657 (Context, tag.Val, name.Val, size.getValueAsMetadata(Context), align.Val,
5658 encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5659 return false;
5660}
5661
5662/// parseDIFixedPointType:
5663/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5664/// align: 32, encoding: DW_ATE_signed_fixed,
5665/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5666/// denominator: 8)
5667bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5668#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5669 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5670 OPTIONAL(name, MDStringField, ); \
5671 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5672 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5673 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5674 OPTIONAL(flags, DIFlagField, ); \
5675 OPTIONAL(kind, FixedPointKindField, ); \
5676 OPTIONAL(factor, MDSignedField, ); \
5677 OPTIONAL(numerator, MDAPSIntField, ); \
5678 OPTIONAL(denominator, MDAPSIntField, );
5680#undef VISIT_MD_FIELDS
5681
5682 Result = GET_OR_DISTINCT(DIFixedPointType,
5683 (Context, tag.Val, name.Val,
5684 size.getValueAsMetadata(Context), align.Val,
5685 encoding.Val, flags.Val, kind.Val, factor.Val,
5686 numerator.Val, denominator.Val));
5687 return false;
5688}
5689
5690/// parseDIStringType:
5691/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5692bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5693#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5694 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5695 OPTIONAL(name, MDStringField, ); \
5696 OPTIONAL(stringLength, MDField, ); \
5697 OPTIONAL(stringLengthExpression, MDField, ); \
5698 OPTIONAL(stringLocationExpression, MDField, ); \
5699 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5700 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5701 OPTIONAL(encoding, DwarfAttEncodingField, );
5703#undef VISIT_MD_FIELDS
5704
5706 DIStringType,
5707 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5708 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5709 align.Val, encoding.Val));
5710 return false;
5711}
5712
5713/// parseDIDerivedType:
5714/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5715/// line: 7, scope: !1, baseType: !2, size: 32,
5716/// align: 32, offset: 0, flags: 0, extraData: !3,
5717/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5718/// ptrAuthIsAddressDiscriminated: true,
5719/// ptrAuthExtraDiscriminator: 0x1234,
5720/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5721/// )
5722bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5723#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5724 REQUIRED(tag, DwarfTagField, ); \
5725 OPTIONAL(name, MDStringField, ); \
5726 OPTIONAL(file, MDField, ); \
5727 OPTIONAL(line, LineField, ); \
5728 OPTIONAL(scope, MDField, ); \
5729 REQUIRED(baseType, MDField, ); \
5730 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5731 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5732 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5733 OPTIONAL(flags, DIFlagField, ); \
5734 OPTIONAL(extraData, MDField, ); \
5735 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5736 OPTIONAL(annotations, MDField, ); \
5737 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5738 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5739 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5740 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5741 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5743#undef VISIT_MD_FIELDS
5744
5745 std::optional<unsigned> DWARFAddressSpace;
5746 if (dwarfAddressSpace.Val != UINT32_MAX)
5747 DWARFAddressSpace = dwarfAddressSpace.Val;
5748 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5749 if (ptrAuthKey.Val)
5750 PtrAuthData.emplace(
5751 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5752 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5753 ptrAuthAuthenticatesNullValues.Val);
5754
5756 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5757 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5758 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5759 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5760 return false;
5761}
5762
5763bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5764#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5765 REQUIRED(tag, DwarfTagField, ); \
5766 OPTIONAL(name, MDStringField, ); \
5767 OPTIONAL(file, MDField, ); \
5768 OPTIONAL(line, LineField, ); \
5769 OPTIONAL(scope, MDField, ); \
5770 OPTIONAL(baseType, MDField, ); \
5771 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5772 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5773 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5774 OPTIONAL(flags, DIFlagField, ); \
5775 OPTIONAL(elements, MDField, ); \
5776 OPTIONAL(runtimeLang, DwarfLangField, ); \
5777 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5778 OPTIONAL(vtableHolder, MDField, ); \
5779 OPTIONAL(templateParams, MDField, ); \
5780 OPTIONAL(identifier, MDStringField, ); \
5781 OPTIONAL(discriminator, MDField, ); \
5782 OPTIONAL(dataLocation, MDField, ); \
5783 OPTIONAL(associated, MDField, ); \
5784 OPTIONAL(allocated, MDField, ); \
5785 OPTIONAL(rank, MDSignedOrMDField, ); \
5786 OPTIONAL(annotations, MDField, ); \
5787 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5788 OPTIONAL(specification, MDField, ); \
5789 OPTIONAL(bitStride, MDField, );
5791#undef VISIT_MD_FIELDS
5792
5793 Metadata *Rank = nullptr;
5794 if (rank.isMDSignedField())
5796 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5797 else if (rank.isMDField())
5798 Rank = rank.getMDFieldValue();
5799
5800 std::optional<unsigned> EnumKind;
5801 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5802 EnumKind = enumKind.Val;
5803
5804 // If this has an identifier try to build an ODR type.
5805 if (identifier.Val)
5806 if (auto *CT = DICompositeType::buildODRType(
5807 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5808 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
5809 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5810 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5811 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5812 dataLocation.Val, associated.Val, allocated.Val, Rank,
5813 annotations.Val, bitStride.Val)) {
5814 Result = CT;
5815 return false;
5816 }
5817
5818 // Create a new node, and save it in the context if it belongs in the type
5819 // map.
5821 DICompositeType,
5822 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5823 size.getValueAsMetadata(Context), align.Val,
5824 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5825 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5826 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5827 allocated.Val, Rank, annotations.Val, specification.Val,
5828 num_extra_inhabitants.Val, bitStride.Val));
5829 return false;
5830}
5831
5832bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5833#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5834 OPTIONAL(flags, DIFlagField, ); \
5835 OPTIONAL(cc, DwarfCCField, ); \
5836 REQUIRED(types, MDField, );
5838#undef VISIT_MD_FIELDS
5839
5840 Result = GET_OR_DISTINCT(DISubroutineType,
5841 (Context, flags.Val, cc.Val, types.Val));
5842 return false;
5843}
5844
5845/// parseDIFileType:
5846/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5847/// checksumkind: CSK_MD5,
5848/// checksum: "000102030405060708090a0b0c0d0e0f",
5849/// source: "source file contents")
5850bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5851 // The default constructed value for checksumkind is required, but will never
5852 // be used, as the parser checks if the field was actually Seen before using
5853 // the Val.
5854#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5855 REQUIRED(filename, MDStringField, ); \
5856 REQUIRED(directory, MDStringField, ); \
5857 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5858 OPTIONAL(checksum, MDStringField, ); \
5859 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5861#undef VISIT_MD_FIELDS
5862
5863 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5864 if (checksumkind.Seen && checksum.Seen)
5865 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5866 else if (checksumkind.Seen || checksum.Seen)
5867 return tokError("'checksumkind' and 'checksum' must be provided together");
5868
5869 MDString *Source = nullptr;
5870 if (source.Seen)
5871 Source = source.Val;
5873 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5874 return false;
5875}
5876
5877/// parseDICompileUnit:
5878/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5879/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5880/// splitDebugFilename: "abc.debug",
5881/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5882/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5883/// sysroot: "/", sdk: "MacOSX.sdk")
5884bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5885 if (!IsDistinct)
5886 return tokError("missing 'distinct', required for !DICompileUnit");
5887
5888 LocTy Loc = Lex.getLoc();
5889
5890#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5891 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5892 OPTIONAL(language, DwarfLangField, ); \
5893 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
5894 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
5895 OPTIONAL(producer, MDStringField, ); \
5896 OPTIONAL(isOptimized, MDBoolField, ); \
5897 OPTIONAL(flags, MDStringField, ); \
5898 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5899 OPTIONAL(splitDebugFilename, MDStringField, ); \
5900 OPTIONAL(emissionKind, EmissionKindField, ); \
5901 OPTIONAL(enums, MDField, ); \
5902 OPTIONAL(retainedTypes, MDField, ); \
5903 OPTIONAL(globals, MDField, ); \
5904 OPTIONAL(imports, MDField, ); \
5905 OPTIONAL(macros, MDField, ); \
5906 OPTIONAL(dwoId, MDUnsignedField, ); \
5907 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5908 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5909 OPTIONAL(nameTableKind, NameTableKindField, ); \
5910 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5911 OPTIONAL(sysroot, MDStringField, ); \
5912 OPTIONAL(sdk, MDStringField, );
5914#undef VISIT_MD_FIELDS
5915
5916 if (!language.Seen && !sourceLanguageName.Seen)
5917 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
5918 "required for !DICompileUnit");
5919
5920 if (language.Seen && sourceLanguageName.Seen)
5921 return error(Loc, "can only specify one of 'language' and "
5922 "'sourceLanguageName' on !DICompileUnit");
5923
5924 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
5925 return error(Loc, "'sourceLanguageVersion' requires an associated "
5926 "'sourceLanguageName' on !DICompileUnit");
5927
5929 Context,
5930 language.Seen ? DISourceLanguageName(language.Val)
5931 : DISourceLanguageName(sourceLanguageName.Val,
5932 sourceLanguageVersion.Val),
5933 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
5934 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
5935 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
5936 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
5937 sysroot.Val, sdk.Val);
5938 return false;
5939}
5940
5941/// parseDISubprogram:
5942/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5943/// file: !1, line: 7, type: !2, isLocal: false,
5944/// isDefinition: true, scopeLine: 8, containingType: !3,
5945/// virtuality: DW_VIRTUALTIY_pure_virtual,
5946/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5947/// spFlags: 10, isOptimized: false, templateParams: !4,
5948/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5949/// annotations: !8)
5950bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5951 auto Loc = Lex.getLoc();
5952#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5953 OPTIONAL(scope, MDField, ); \
5954 OPTIONAL(name, MDStringField, ); \
5955 OPTIONAL(linkageName, MDStringField, ); \
5956 OPTIONAL(file, MDField, ); \
5957 OPTIONAL(line, LineField, ); \
5958 OPTIONAL(type, MDField, ); \
5959 OPTIONAL(isLocal, MDBoolField, ); \
5960 OPTIONAL(isDefinition, MDBoolField, (true)); \
5961 OPTIONAL(scopeLine, LineField, ); \
5962 OPTIONAL(containingType, MDField, ); \
5963 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5964 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5965 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5966 OPTIONAL(flags, DIFlagField, ); \
5967 OPTIONAL(spFlags, DISPFlagField, ); \
5968 OPTIONAL(isOptimized, MDBoolField, ); \
5969 OPTIONAL(unit, MDField, ); \
5970 OPTIONAL(templateParams, MDField, ); \
5971 OPTIONAL(declaration, MDField, ); \
5972 OPTIONAL(retainedNodes, MDField, ); \
5973 OPTIONAL(thrownTypes, MDField, ); \
5974 OPTIONAL(annotations, MDField, ); \
5975 OPTIONAL(targetFuncName, MDStringField, ); \
5976 OPTIONAL(keyInstructions, MDBoolField, );
5978#undef VISIT_MD_FIELDS
5979
5980 // An explicit spFlags field takes precedence over individual fields in
5981 // older IR versions.
5982 DISubprogram::DISPFlags SPFlags =
5983 spFlags.Seen ? spFlags.Val
5984 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5985 isOptimized.Val, virtuality.Val);
5986 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5987 return error(
5988 Loc,
5989 "missing 'distinct', required for !DISubprogram that is a Definition");
5991 DISubprogram,
5992 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5993 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5994 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5995 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5996 targetFuncName.Val, keyInstructions.Val));
5997 return false;
5998}
5999
6000/// parseDILexicalBlock:
6001/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6002bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6003#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6004 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6005 OPTIONAL(file, MDField, ); \
6006 OPTIONAL(line, LineField, ); \
6007 OPTIONAL(column, ColumnField, );
6009#undef VISIT_MD_FIELDS
6010
6012 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6013 return false;
6014}
6015
6016/// parseDILexicalBlockFile:
6017/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6018bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6019#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6020 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6021 OPTIONAL(file, MDField, ); \
6022 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6024#undef VISIT_MD_FIELDS
6025
6026 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6027 (Context, scope.Val, file.Val, discriminator.Val));
6028 return false;
6029}
6030
6031/// parseDICommonBlock:
6032/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6033bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6034#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6035 REQUIRED(scope, MDField, ); \
6036 OPTIONAL(declaration, MDField, ); \
6037 OPTIONAL(name, MDStringField, ); \
6038 OPTIONAL(file, MDField, ); \
6039 OPTIONAL(line, LineField, );
6041#undef VISIT_MD_FIELDS
6042
6043 Result = GET_OR_DISTINCT(DICommonBlock,
6044 (Context, scope.Val, declaration.Val, name.Val,
6045 file.Val, line.Val));
6046 return false;
6047}
6048
6049/// parseDINamespace:
6050/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6051bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6052#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6053 REQUIRED(scope, MDField, ); \
6054 OPTIONAL(name, MDStringField, ); \
6055 OPTIONAL(exportSymbols, MDBoolField, );
6057#undef VISIT_MD_FIELDS
6058
6059 Result = GET_OR_DISTINCT(DINamespace,
6060 (Context, scope.Val, name.Val, exportSymbols.Val));
6061 return false;
6062}
6063
6064/// parseDIMacro:
6065/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6066/// "SomeValue")
6067bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6068#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6069 REQUIRED(type, DwarfMacinfoTypeField, ); \
6070 OPTIONAL(line, LineField, ); \
6071 REQUIRED(name, MDStringField, ); \
6072 OPTIONAL(value, MDStringField, );
6074#undef VISIT_MD_FIELDS
6075
6076 Result = GET_OR_DISTINCT(DIMacro,
6077 (Context, type.Val, line.Val, name.Val, value.Val));
6078 return false;
6079}
6080
6081/// parseDIMacroFile:
6082/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6083bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6084#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6085 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6086 OPTIONAL(line, LineField, ); \
6087 REQUIRED(file, MDField, ); \
6088 OPTIONAL(nodes, MDField, );
6090#undef VISIT_MD_FIELDS
6091
6092 Result = GET_OR_DISTINCT(DIMacroFile,
6093 (Context, type.Val, line.Val, file.Val, nodes.Val));
6094 return false;
6095}
6096
6097/// parseDIModule:
6098/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6099/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6100/// file: !1, line: 4, isDecl: false)
6101bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6102#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6103 REQUIRED(scope, MDField, ); \
6104 REQUIRED(name, MDStringField, ); \
6105 OPTIONAL(configMacros, MDStringField, ); \
6106 OPTIONAL(includePath, MDStringField, ); \
6107 OPTIONAL(apinotes, MDStringField, ); \
6108 OPTIONAL(file, MDField, ); \
6109 OPTIONAL(line, LineField, ); \
6110 OPTIONAL(isDecl, MDBoolField, );
6112#undef VISIT_MD_FIELDS
6113
6114 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6115 configMacros.Val, includePath.Val,
6116 apinotes.Val, line.Val, isDecl.Val));
6117 return false;
6118}
6119
6120/// parseDITemplateTypeParameter:
6121/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6122bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6123#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6124 OPTIONAL(name, MDStringField, ); \
6125 REQUIRED(type, MDField, ); \
6126 OPTIONAL(defaulted, MDBoolField, );
6128#undef VISIT_MD_FIELDS
6129
6130 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6131 (Context, name.Val, type.Val, defaulted.Val));
6132 return false;
6133}
6134
6135/// parseDITemplateValueParameter:
6136/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6137/// name: "V", type: !1, defaulted: false,
6138/// value: i32 7)
6139bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6140#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6141 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6142 OPTIONAL(name, MDStringField, ); \
6143 OPTIONAL(type, MDField, ); \
6144 OPTIONAL(defaulted, MDBoolField, ); \
6145 REQUIRED(value, MDField, );
6146
6148#undef VISIT_MD_FIELDS
6149
6151 DITemplateValueParameter,
6152 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6153 return false;
6154}
6155
6156/// parseDIGlobalVariable:
6157/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6158/// file: !1, line: 7, type: !2, isLocal: false,
6159/// isDefinition: true, templateParams: !3,
6160/// declaration: !4, align: 8)
6161bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6162#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6163 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6164 OPTIONAL(scope, MDField, ); \
6165 OPTIONAL(linkageName, MDStringField, ); \
6166 OPTIONAL(file, MDField, ); \
6167 OPTIONAL(line, LineField, ); \
6168 OPTIONAL(type, MDField, ); \
6169 OPTIONAL(isLocal, MDBoolField, ); \
6170 OPTIONAL(isDefinition, MDBoolField, (true)); \
6171 OPTIONAL(templateParams, MDField, ); \
6172 OPTIONAL(declaration, MDField, ); \
6173 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6174 OPTIONAL(annotations, MDField, );
6176#undef VISIT_MD_FIELDS
6177
6178 Result =
6179 GET_OR_DISTINCT(DIGlobalVariable,
6180 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6181 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6182 declaration.Val, templateParams.Val, align.Val,
6183 annotations.Val));
6184 return false;
6185}
6186
6187/// parseDILocalVariable:
6188/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6189/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6190/// align: 8)
6191/// ::= !DILocalVariable(scope: !0, name: "foo",
6192/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6193/// align: 8)
6194bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6195#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6196 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6197 OPTIONAL(name, MDStringField, ); \
6198 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6199 OPTIONAL(file, MDField, ); \
6200 OPTIONAL(line, LineField, ); \
6201 OPTIONAL(type, MDField, ); \
6202 OPTIONAL(flags, DIFlagField, ); \
6203 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6204 OPTIONAL(annotations, MDField, );
6206#undef VISIT_MD_FIELDS
6207
6208 Result = GET_OR_DISTINCT(DILocalVariable,
6209 (Context, scope.Val, name.Val, file.Val, line.Val,
6210 type.Val, arg.Val, flags.Val, align.Val,
6211 annotations.Val));
6212 return false;
6213}
6214
6215/// parseDILabel:
6216/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6217bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6218#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6219 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6220 REQUIRED(name, MDStringField, ); \
6221 REQUIRED(file, MDField, ); \
6222 REQUIRED(line, LineField, ); \
6223 OPTIONAL(column, ColumnField, ); \
6224 OPTIONAL(isArtificial, MDBoolField, ); \
6225 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6227#undef VISIT_MD_FIELDS
6228
6229 std::optional<unsigned> CoroSuspendIdx =
6230 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6231 : std::nullopt;
6232
6233 Result = GET_OR_DISTINCT(DILabel,
6234 (Context, scope.Val, name.Val, file.Val, line.Val,
6235 column.Val, isArtificial.Val, CoroSuspendIdx));
6236 return false;
6237}
6238
6239/// parseDIExpressionBody:
6240/// ::= (0, 7, -1)
6241bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6242 if (parseToken(lltok::lparen, "expected '(' here"))
6243 return true;
6244
6245 SmallVector<uint64_t, 8> Elements;
6246 if (Lex.getKind() != lltok::rparen)
6247 do {
6248 if (Lex.getKind() == lltok::DwarfOp) {
6249 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6250 Lex.Lex();
6251 Elements.push_back(Op);
6252 continue;
6253 }
6254 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6255 }
6256
6257 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6258 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6259 Lex.Lex();
6260 Elements.push_back(Op);
6261 continue;
6262 }
6263 return tokError(Twine("invalid DWARF attribute encoding '") +
6264 Lex.getStrVal() + "'");
6265 }
6266
6267 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6268 return tokError("expected unsigned integer");
6269
6270 auto &U = Lex.getAPSIntVal();
6271 if (U.ugt(UINT64_MAX))
6272 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6273 Elements.push_back(U.getZExtValue());
6274 Lex.Lex();
6275 } while (EatIfPresent(lltok::comma));
6276
6277 if (parseToken(lltok::rparen, "expected ')' here"))
6278 return true;
6279
6280 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6281 return false;
6282}
6283
6284/// parseDIExpression:
6285/// ::= !DIExpression(0, 7, -1)
6286bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6287 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6288 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6289 Lex.Lex();
6290
6291 return parseDIExpressionBody(Result, IsDistinct);
6292}
6293
6294/// ParseDIArgList:
6295/// ::= !DIArgList(i32 7, i64 %0)
6296bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6297 assert(PFS && "Expected valid function state");
6298 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6299 Lex.Lex();
6300
6301 if (parseToken(lltok::lparen, "expected '(' here"))
6302 return true;
6303
6305 if (Lex.getKind() != lltok::rparen)
6306 do {
6307 Metadata *MD;
6308 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6309 return true;
6310 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6311 } while (EatIfPresent(lltok::comma));
6312
6313 if (parseToken(lltok::rparen, "expected ')' here"))
6314 return true;
6315
6316 MD = DIArgList::get(Context, Args);
6317 return false;
6318}
6319
6320/// parseDIGlobalVariableExpression:
6321/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6322bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6323 bool IsDistinct) {
6324#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6325 REQUIRED(var, MDField, ); \
6326 REQUIRED(expr, MDField, );
6328#undef VISIT_MD_FIELDS
6329
6330 Result =
6331 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6332 return false;
6333}
6334
6335/// parseDIObjCProperty:
6336/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6337/// getter: "getFoo", attributes: 7, type: !2)
6338bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6339#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6340 OPTIONAL(name, MDStringField, ); \
6341 OPTIONAL(file, MDField, ); \
6342 OPTIONAL(line, LineField, ); \
6343 OPTIONAL(setter, MDStringField, ); \
6344 OPTIONAL(getter, MDStringField, ); \
6345 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6346 OPTIONAL(type, MDField, );
6348#undef VISIT_MD_FIELDS
6349
6350 Result = GET_OR_DISTINCT(DIObjCProperty,
6351 (Context, name.Val, file.Val, line.Val, getter.Val,
6352 setter.Val, attributes.Val, type.Val));
6353 return false;
6354}
6355
6356/// parseDIImportedEntity:
6357/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6358/// line: 7, name: "foo", elements: !2)
6359bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6360#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6361 REQUIRED(tag, DwarfTagField, ); \
6362 REQUIRED(scope, MDField, ); \
6363 OPTIONAL(entity, MDField, ); \
6364 OPTIONAL(file, MDField, ); \
6365 OPTIONAL(line, LineField, ); \
6366 OPTIONAL(name, MDStringField, ); \
6367 OPTIONAL(elements, MDField, );
6369#undef VISIT_MD_FIELDS
6370
6371 Result = GET_OR_DISTINCT(DIImportedEntity,
6372 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6373 line.Val, name.Val, elements.Val));
6374 return false;
6375}
6376
6377#undef PARSE_MD_FIELD
6378#undef NOP_FIELD
6379#undef REQUIRE_FIELD
6380#undef DECLARE_FIELD
6381
6382/// parseMetadataAsValue
6383/// ::= metadata i32 %local
6384/// ::= metadata i32 @global
6385/// ::= metadata i32 7
6386/// ::= metadata !0
6387/// ::= metadata !{...}
6388/// ::= metadata !"string"
6389bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6390 // Note: the type 'metadata' has already been parsed.
6391 Metadata *MD;
6392 if (parseMetadata(MD, &PFS))
6393 return true;
6394
6395 V = MetadataAsValue::get(Context, MD);
6396 return false;
6397}
6398
6399/// parseValueAsMetadata
6400/// ::= i32 %local
6401/// ::= i32 @global
6402/// ::= i32 7
6403bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6404 PerFunctionState *PFS) {
6405 Type *Ty;
6406 LocTy Loc;
6407 if (parseType(Ty, TypeMsg, Loc))
6408 return true;
6409 if (Ty->isMetadataTy())
6410 return error(Loc, "invalid metadata-value-metadata roundtrip");
6411
6412 Value *V;
6413 if (parseValue(Ty, V, PFS))
6414 return true;
6415
6416 MD = ValueAsMetadata::get(V);
6417 return false;
6418}
6419
6420/// parseMetadata
6421/// ::= i32 %local
6422/// ::= i32 @global
6423/// ::= i32 7
6424/// ::= !42
6425/// ::= !{...}
6426/// ::= !"string"
6427/// ::= !DILocation(...)
6428bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6429 if (Lex.getKind() == lltok::MetadataVar) {
6430 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6431 // so parsing this requires a Function State.
6432 if (Lex.getStrVal() == "DIArgList") {
6433 Metadata *AL;
6434 if (parseDIArgList(AL, PFS))
6435 return true;
6436 MD = AL;
6437 return false;
6438 }
6439 MDNode *N;
6440 if (parseSpecializedMDNode(N)) {
6441 return true;
6442 }
6443 MD = N;
6444 return false;
6445 }
6446
6447 // ValueAsMetadata:
6448 // <type> <value>
6449 if (Lex.getKind() != lltok::exclaim)
6450 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6451
6452 // '!'.
6453 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6454 Lex.Lex();
6455
6456 // MDString:
6457 // ::= '!' STRINGCONSTANT
6458 if (Lex.getKind() == lltok::StringConstant) {
6459 MDString *S;
6460 if (parseMDString(S))
6461 return true;
6462 MD = S;
6463 return false;
6464 }
6465
6466 // MDNode:
6467 // !{ ... }
6468 // !7
6469 MDNode *N;
6470 if (parseMDNodeTail(N))
6471 return true;
6472 MD = N;
6473 return false;
6474}
6475
6476//===----------------------------------------------------------------------===//
6477// Function Parsing.
6478//===----------------------------------------------------------------------===//
6479
6480bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6481 PerFunctionState *PFS) {
6482 if (Ty->isFunctionTy())
6483 return error(ID.Loc, "functions are not values, refer to them as pointers");
6484
6485 switch (ID.Kind) {
6486 case ValID::t_LocalID:
6487 if (!PFS)
6488 return error(ID.Loc, "invalid use of function-local name");
6489 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6490 return V == nullptr;
6491 case ValID::t_LocalName:
6492 if (!PFS)
6493 return error(ID.Loc, "invalid use of function-local name");
6494 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6495 return V == nullptr;
6496 case ValID::t_InlineAsm: {
6497 if (!ID.FTy)
6498 return error(ID.Loc, "invalid type for inline asm constraint string");
6499 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6500 return error(ID.Loc, toString(std::move(Err)));
6501 V = InlineAsm::get(
6502 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6503 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6504 return false;
6505 }
6507 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6508 if (V && ID.NoCFI)
6510 return V == nullptr;
6511 case ValID::t_GlobalID:
6512 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6513 if (V && ID.NoCFI)
6515 return V == nullptr;
6516 case ValID::t_APSInt:
6517 if (!Ty->isIntegerTy())
6518 return error(ID.Loc, "integer constant must have integer type");
6519 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6520 V = ConstantInt::get(Context, ID.APSIntVal);
6521 return false;
6522 case ValID::t_APFloat:
6523 if (!Ty->isFloatingPointTy() ||
6524 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6525 return error(ID.Loc, "floating point constant invalid for type");
6526
6527 // The lexer has no type info, so builds all half, bfloat, float, and double
6528 // FP constants as double. Fix this here. Long double does not need this.
6529 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6530 // Check for signaling before potentially converting and losing that info.
6531 bool IsSNAN = ID.APFloatVal.isSignaling();
6532 bool Ignored;
6533 if (Ty->isHalfTy())
6535 &Ignored);
6536 else if (Ty->isBFloatTy())
6537 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6538 &Ignored);
6539 else if (Ty->isFloatTy())
6541 &Ignored);
6542 if (IsSNAN) {
6543 // The convert call above may quiet an SNaN, so manufacture another
6544 // SNaN. The bitcast works because the payload (significand) parameter
6545 // is truncated to fit.
6546 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6547 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6548 ID.APFloatVal.isNegative(), &Payload);
6549 }
6550 }
6551 V = ConstantFP::get(Context, ID.APFloatVal);
6552
6553 if (V->getType() != Ty)
6554 return error(ID.Loc, "floating point constant does not have type '" +
6555 getTypeString(Ty) + "'");
6556
6557 return false;
6558 case ValID::t_Null:
6559 if (!Ty->isPointerTy())
6560 return error(ID.Loc, "null must be a pointer type");
6562 return false;
6563 case ValID::t_Undef:
6564 // FIXME: LabelTy should not be a first-class type.
6565 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6566 return error(ID.Loc, "invalid type for undef constant");
6567 V = UndefValue::get(Ty);
6568 return false;
6570 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6571 return error(ID.Loc, "invalid empty array initializer");
6572 V = PoisonValue::get(Ty);
6573 return false;
6574 case ValID::t_Zero:
6575 // FIXME: LabelTy should not be a first-class type.
6576 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6577 return error(ID.Loc, "invalid type for null constant");
6578 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6579 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6580 return error(ID.Loc, "invalid type for null constant");
6582 return false;
6583 case ValID::t_None:
6584 if (!Ty->isTokenTy())
6585 return error(ID.Loc, "invalid type for none constant");
6587 return false;
6588 case ValID::t_Poison:
6589 // FIXME: LabelTy should not be a first-class type.
6590 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6591 return error(ID.Loc, "invalid type for poison constant");
6592 V = PoisonValue::get(Ty);
6593 return false;
6594 case ValID::t_Constant:
6595 if (ID.ConstantVal->getType() != Ty)
6596 return error(ID.Loc, "constant expression type mismatch: got type '" +
6597 getTypeString(ID.ConstantVal->getType()) +
6598 "' but expected '" + getTypeString(Ty) + "'");
6599 V = ID.ConstantVal;
6600 return false;
6602 if (!Ty->isVectorTy())
6603 return error(ID.Loc, "vector constant must have vector type");
6604 if (ID.ConstantVal->getType() != Ty->getScalarType())
6605 return error(ID.Loc, "constant expression type mismatch: got type '" +
6606 getTypeString(ID.ConstantVal->getType()) +
6607 "' but expected '" +
6608 getTypeString(Ty->getScalarType()) + "'");
6609 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6610 ID.ConstantVal);
6611 return false;
6614 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6615 if (ST->getNumElements() != ID.UIntVal)
6616 return error(ID.Loc,
6617 "initializer with struct type has wrong # elements");
6618 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6619 return error(ID.Loc, "packed'ness of initializer and type don't match");
6620
6621 // Verify that the elements are compatible with the structtype.
6622 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6623 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6624 return error(
6625 ID.Loc,
6626 "element " + Twine(i) +
6627 " of struct initializer doesn't match struct element type");
6628
6630 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6631 } else
6632 return error(ID.Loc, "constant expression type mismatch");
6633 return false;
6634 }
6635 llvm_unreachable("Invalid ValID");
6636}
6637
6638bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6639 C = nullptr;
6640 ValID ID;
6641 auto Loc = Lex.getLoc();
6642 if (parseValID(ID, /*PFS=*/nullptr))
6643 return true;
6644 switch (ID.Kind) {
6645 case ValID::t_APSInt:
6646 case ValID::t_APFloat:
6647 case ValID::t_Undef:
6648 case ValID::t_Poison:
6649 case ValID::t_Zero:
6650 case ValID::t_Constant:
6654 Value *V;
6655 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6656 return true;
6657 assert(isa<Constant>(V) && "Expected a constant value");
6658 C = cast<Constant>(V);
6659 return false;
6660 }
6661 case ValID::t_Null:
6663 return false;
6664 default:
6665 return error(Loc, "expected a constant value");
6666 }
6667}
6668
6669bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6670 V = nullptr;
6671 ValID ID;
6672 return parseValID(ID, PFS, Ty) ||
6673 convertValIDToValue(Ty, ID, V, PFS);
6674}
6675
6676bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6677 Type *Ty = nullptr;
6678 return parseType(Ty) || parseValue(Ty, V, PFS);
6679}
6680
6681bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6682 PerFunctionState &PFS) {
6683 Value *V;
6684 Loc = Lex.getLoc();
6685 if (parseTypeAndValue(V, PFS))
6686 return true;
6687 if (!isa<BasicBlock>(V))
6688 return error(Loc, "expected a basic block");
6689 BB = cast<BasicBlock>(V);
6690 return false;
6691}
6692
6694 // Exit early for the common (non-debug-intrinsic) case.
6695 // We can make this the only check when we begin supporting all "llvm.dbg"
6696 // intrinsics in the new debug info format.
6697 if (!Name.starts_with("llvm.dbg."))
6698 return false;
6700 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6701 FnID == Intrinsic::dbg_assign;
6702}
6703
6704/// FunctionHeader
6705/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6706/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6707/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6708/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6709bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6710 unsigned &FunctionNumber,
6711 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6712 // parse the linkage.
6713 LocTy LinkageLoc = Lex.getLoc();
6714 unsigned Linkage;
6715 unsigned Visibility;
6716 unsigned DLLStorageClass;
6717 bool DSOLocal;
6718 AttrBuilder RetAttrs(M->getContext());
6719 unsigned CC;
6720 bool HasLinkage;
6721 Type *RetType = nullptr;
6722 LocTy RetTypeLoc = Lex.getLoc();
6723 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6724 DSOLocal) ||
6725 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6726 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6727 return true;
6728
6729 // Verify that the linkage is ok.
6732 break; // always ok.
6734 if (IsDefine)
6735 return error(LinkageLoc, "invalid linkage for function definition");
6736 break;
6744 if (!IsDefine)
6745 return error(LinkageLoc, "invalid linkage for function declaration");
6746 break;
6749 return error(LinkageLoc, "invalid function linkage type");
6750 }
6751
6752 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6753 return error(LinkageLoc,
6754 "symbol with local linkage must have default visibility");
6755
6756 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6757 return error(LinkageLoc,
6758 "symbol with local linkage cannot have a DLL storage class");
6759
6760 if (!FunctionType::isValidReturnType(RetType))
6761 return error(RetTypeLoc, "invalid function return type");
6762
6763 LocTy NameLoc = Lex.getLoc();
6764
6765 std::string FunctionName;
6766 if (Lex.getKind() == lltok::GlobalVar) {
6767 FunctionName = Lex.getStrVal();
6768 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6769 FunctionNumber = Lex.getUIntVal();
6770 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6771 FunctionNumber))
6772 return true;
6773 } else {
6774 return tokError("expected function name");
6775 }
6776
6777 Lex.Lex();
6778
6779 if (Lex.getKind() != lltok::lparen)
6780 return tokError("expected '(' in function argument list");
6781
6783 bool IsVarArg;
6784 AttrBuilder FuncAttrs(M->getContext());
6785 std::vector<unsigned> FwdRefAttrGrps;
6786 LocTy BuiltinLoc;
6787 std::string Section;
6788 std::string Partition;
6789 MaybeAlign Alignment;
6790 std::string GC;
6792 unsigned AddrSpace = 0;
6793 Constant *Prefix = nullptr;
6794 Constant *Prologue = nullptr;
6795 Constant *PersonalityFn = nullptr;
6796 Comdat *C;
6797
6798 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6799 parseOptionalUnnamedAddr(UnnamedAddr) ||
6800 parseOptionalProgramAddrSpace(AddrSpace) ||
6801 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6802 BuiltinLoc) ||
6803 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6804 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6805 parseOptionalComdat(FunctionName, C) ||
6806 parseOptionalAlignment(Alignment) ||
6807 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6808 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6809 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6810 (EatIfPresent(lltok::kw_personality) &&
6811 parseGlobalTypeAndValue(PersonalityFn)))
6812 return true;
6813
6814 if (FuncAttrs.contains(Attribute::Builtin))
6815 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6816
6817 // If the alignment was parsed as an attribute, move to the alignment field.
6818 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6819 Alignment = A;
6820 FuncAttrs.removeAttribute(Attribute::Alignment);
6821 }
6822
6823 // Okay, if we got here, the function is syntactically valid. Convert types
6824 // and do semantic checks.
6825 std::vector<Type*> ParamTypeList;
6827
6828 for (const ArgInfo &Arg : ArgList) {
6829 ParamTypeList.push_back(Arg.Ty);
6830 Attrs.push_back(Arg.Attrs);
6831 }
6832
6833 AttributeList PAL =
6834 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6835 AttributeSet::get(Context, RetAttrs), Attrs);
6836
6837 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6838 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6839
6840 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6841 PointerType *PFT = PointerType::get(Context, AddrSpace);
6842
6843 Fn = nullptr;
6844 GlobalValue *FwdFn = nullptr;
6845 if (!FunctionName.empty()) {
6846 // If this was a definition of a forward reference, remove the definition
6847 // from the forward reference table and fill in the forward ref.
6848 auto FRVI = ForwardRefVals.find(FunctionName);
6849 if (FRVI != ForwardRefVals.end()) {
6850 FwdFn = FRVI->second.first;
6851 if (FwdFn->getType() != PFT)
6852 return error(FRVI->second.second,
6853 "invalid forward reference to "
6854 "function '" +
6855 FunctionName +
6856 "' with wrong type: "
6857 "expected '" +
6858 getTypeString(PFT) + "' but was '" +
6859 getTypeString(FwdFn->getType()) + "'");
6860 ForwardRefVals.erase(FRVI);
6861 } else if ((Fn = M->getFunction(FunctionName))) {
6862 // Reject redefinitions.
6863 return error(NameLoc,
6864 "invalid redefinition of function '" + FunctionName + "'");
6865 } else if (M->getNamedValue(FunctionName)) {
6866 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6867 }
6868
6869 } else {
6870 // Handle @"", where a name is syntactically specified, but semantically
6871 // missing.
6872 if (FunctionNumber == (unsigned)-1)
6873 FunctionNumber = NumberedVals.getNext();
6874
6875 // If this is a definition of a forward referenced function, make sure the
6876 // types agree.
6877 auto I = ForwardRefValIDs.find(FunctionNumber);
6878 if (I != ForwardRefValIDs.end()) {
6879 FwdFn = I->second.first;
6880 if (FwdFn->getType() != PFT)
6881 return error(NameLoc, "type of definition and forward reference of '@" +
6882 Twine(FunctionNumber) +
6883 "' disagree: "
6884 "expected '" +
6885 getTypeString(PFT) + "' but was '" +
6886 getTypeString(FwdFn->getType()) + "'");
6887 ForwardRefValIDs.erase(I);
6888 }
6889 }
6890
6892 FunctionName, M);
6893
6894 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6895
6896 if (FunctionName.empty())
6897 NumberedVals.add(FunctionNumber, Fn);
6898
6900 maybeSetDSOLocal(DSOLocal, *Fn);
6903 Fn->setCallingConv(CC);
6904 Fn->setAttributes(PAL);
6905 Fn->setUnnamedAddr(UnnamedAddr);
6906 if (Alignment)
6907 Fn->setAlignment(*Alignment);
6908 Fn->setSection(Section);
6909 Fn->setPartition(Partition);
6910 Fn->setComdat(C);
6911 Fn->setPersonalityFn(PersonalityFn);
6912 if (!GC.empty()) Fn->setGC(GC);
6913 Fn->setPrefixData(Prefix);
6914 Fn->setPrologueData(Prologue);
6915 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6916
6917 // Add all of the arguments we parsed to the function.
6918 Function::arg_iterator ArgIt = Fn->arg_begin();
6919 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6920 // If the argument has a name, insert it into the argument symbol table.
6921 if (ArgList[i].Name.empty()) continue;
6922
6923 // Set the name, if it conflicted, it will be auto-renamed.
6924 ArgIt->setName(ArgList[i].Name);
6925
6926 if (ArgIt->getName() != ArgList[i].Name)
6927 return error(ArgList[i].Loc,
6928 "redefinition of argument '%" + ArgList[i].Name + "'");
6929 }
6930
6931 if (FwdFn) {
6932 FwdFn->replaceAllUsesWith(Fn);
6933 FwdFn->eraseFromParent();
6934 }
6935
6936 if (IsDefine)
6937 return false;
6938
6939 // Check the declaration has no block address forward references.
6940 ValID ID;
6941 if (FunctionName.empty()) {
6942 ID.Kind = ValID::t_GlobalID;
6943 ID.UIntVal = FunctionNumber;
6944 } else {
6945 ID.Kind = ValID::t_GlobalName;
6946 ID.StrVal = FunctionName;
6947 }
6948 auto Blocks = ForwardRefBlockAddresses.find(ID);
6949 if (Blocks != ForwardRefBlockAddresses.end())
6950 return error(Blocks->first.Loc,
6951 "cannot take blockaddress inside a declaration");
6952 return false;
6953}
6954
6955bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6956 ValID ID;
6957 if (FunctionNumber == -1) {
6958 ID.Kind = ValID::t_GlobalName;
6959 ID.StrVal = std::string(F.getName());
6960 } else {
6961 ID.Kind = ValID::t_GlobalID;
6962 ID.UIntVal = FunctionNumber;
6963 }
6964
6965 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6966 if (Blocks == P.ForwardRefBlockAddresses.end())
6967 return false;
6968
6969 for (const auto &I : Blocks->second) {
6970 const ValID &BBID = I.first;
6971 GlobalValue *GV = I.second;
6972
6973 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6974 "Expected local id or name");
6975 BasicBlock *BB;
6976 if (BBID.Kind == ValID::t_LocalName)
6977 BB = getBB(BBID.StrVal, BBID.Loc);
6978 else
6979 BB = getBB(BBID.UIntVal, BBID.Loc);
6980 if (!BB)
6981 return P.error(BBID.Loc, "referenced value is not a basic block");
6982
6983 Value *ResolvedVal = BlockAddress::get(&F, BB);
6984 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6985 ResolvedVal);
6986 if (!ResolvedVal)
6987 return true;
6988 GV->replaceAllUsesWith(ResolvedVal);
6989 GV->eraseFromParent();
6990 }
6991
6992 P.ForwardRefBlockAddresses.erase(Blocks);
6993 return false;
6994}
6995
6996/// parseFunctionBody
6997/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6998bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6999 ArrayRef<unsigned> UnnamedArgNums) {
7000 if (Lex.getKind() != lltok::lbrace)
7001 return tokError("expected '{' in function body");
7002 Lex.Lex(); // eat the {.
7003
7004 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7005
7006 // Resolve block addresses and allow basic blocks to be forward-declared
7007 // within this function.
7008 if (PFS.resolveForwardRefBlockAddresses())
7009 return true;
7010 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7011
7012 // We need at least one basic block.
7013 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7014 return tokError("function body requires at least one basic block");
7015
7016 while (Lex.getKind() != lltok::rbrace &&
7017 Lex.getKind() != lltok::kw_uselistorder)
7018 if (parseBasicBlock(PFS))
7019 return true;
7020
7021 while (Lex.getKind() != lltok::rbrace)
7022 if (parseUseListOrder(&PFS))
7023 return true;
7024
7025 // Eat the }.
7026 Lex.Lex();
7027
7028 // Verify function is ok.
7029 return PFS.finishFunction();
7030}
7031
7032/// parseBasicBlock
7033/// ::= (LabelStr|LabelID)? Instruction*
7034bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7035 FileLoc BBStart(Lex.getTokLineColumnPos());
7036
7037 // If this basic block starts out with a name, remember it.
7038 std::string Name;
7039 int NameID = -1;
7040 LocTy NameLoc = Lex.getLoc();
7041 if (Lex.getKind() == lltok::LabelStr) {
7042 Name = Lex.getStrVal();
7043 Lex.Lex();
7044 } else if (Lex.getKind() == lltok::LabelID) {
7045 NameID = Lex.getUIntVal();
7046 Lex.Lex();
7047 }
7048
7049 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7050 if (!BB)
7051 return true;
7052
7053 std::string NameStr;
7054
7055 // Parse the instructions and debug values in this block until we get a
7056 // terminator.
7057 Instruction *Inst;
7058 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7059 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7060 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7061 do {
7062 // Handle debug records first - there should always be an instruction
7063 // following the debug records, i.e. they cannot appear after the block
7064 // terminator.
7065 while (Lex.getKind() == lltok::hash) {
7066 if (SeenOldDbgInfoFormat)
7067 return error(Lex.getLoc(), "debug record should not appear in a module "
7068 "containing debug info intrinsics");
7069 SeenNewDbgInfoFormat = true;
7070 Lex.Lex();
7071
7072 DbgRecord *DR;
7073 if (parseDebugRecord(DR, PFS))
7074 return true;
7075 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7076 }
7077
7078 FileLoc InstStart(Lex.getTokLineColumnPos());
7079 // This instruction may have three possibilities for a name: a) none
7080 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7081 LocTy NameLoc = Lex.getLoc();
7082 int NameID = -1;
7083 NameStr = "";
7084
7085 if (Lex.getKind() == lltok::LocalVarID) {
7086 NameID = Lex.getUIntVal();
7087 Lex.Lex();
7088 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7089 return true;
7090 } else if (Lex.getKind() == lltok::LocalVar) {
7091 NameStr = Lex.getStrVal();
7092 Lex.Lex();
7093 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7094 return true;
7095 }
7096
7097 switch (parseInstruction(Inst, BB, PFS)) {
7098 default:
7099 llvm_unreachable("Unknown parseInstruction result!");
7100 case InstError: return true;
7101 case InstNormal:
7102 Inst->insertInto(BB, BB->end());
7103
7104 // With a normal result, we check to see if the instruction is followed by
7105 // a comma and metadata.
7106 if (EatIfPresent(lltok::comma))
7107 if (parseInstructionMetadata(*Inst))
7108 return true;
7109 break;
7110 case InstExtraComma:
7111 Inst->insertInto(BB, BB->end());
7112
7113 // If the instruction parser ate an extra comma at the end of it, it
7114 // *must* be followed by metadata.
7115 if (parseInstructionMetadata(*Inst))
7116 return true;
7117 break;
7118 }
7119
7120 // Set the name on the instruction.
7121 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7122 return true;
7123
7124 // Attach any preceding debug values to this instruction.
7125 for (DbgRecordPtr &DR : TrailingDbgRecord)
7126 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7127 TrailingDbgRecord.clear();
7128 if (ParserContext) {
7129 ParserContext->addInstructionLocation(
7130 Inst, FileLocRange(InstStart, Lex.getPrevTokEndLineColumnPos()));
7131 }
7132 } while (!Inst->isTerminator());
7133
7134 if (ParserContext)
7135 ParserContext->addBlockLocation(
7136 BB, FileLocRange(BBStart, Lex.getPrevTokEndLineColumnPos()));
7137
7138 assert(TrailingDbgRecord.empty() &&
7139 "All debug values should have been attached to an instruction.");
7140
7141 return false;
7142}
7143
7144/// parseDebugRecord
7145/// ::= #dbg_label '(' MDNode ')'
7146/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7147/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7148bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7149 using RecordKind = DbgRecord::Kind;
7150 using LocType = DbgVariableRecord::LocationType;
7151 LocTy DVRLoc = Lex.getLoc();
7152 if (Lex.getKind() != lltok::DbgRecordType)
7153 return error(DVRLoc, "expected debug record type here");
7154 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7155 .Case("declare", RecordKind::ValueKind)
7156 .Case("value", RecordKind::ValueKind)
7157 .Case("assign", RecordKind::ValueKind)
7158 .Case("label", RecordKind::LabelKind)
7159 .Case("declare_value", RecordKind::ValueKind);
7160
7161 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7162 // full DbgVariableRecord processing stage.
7163 if (RecordType == RecordKind::LabelKind) {
7164 Lex.Lex();
7165 if (parseToken(lltok::lparen, "Expected '(' here"))
7166 return true;
7167 MDNode *Label;
7168 if (parseMDNode(Label))
7169 return true;
7170 if (parseToken(lltok::comma, "Expected ',' here"))
7171 return true;
7172 MDNode *DbgLoc;
7173 if (parseMDNode(DbgLoc))
7174 return true;
7175 if (parseToken(lltok::rparen, "Expected ')' here"))
7176 return true;
7178 return false;
7179 }
7180
7181 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7182 .Case("declare", LocType::Declare)
7183 .Case("value", LocType::Value)
7184 .Case("assign", LocType::Assign)
7185 .Case("declare_value", LocType::DeclareValue);
7186
7187 Lex.Lex();
7188 if (parseToken(lltok::lparen, "Expected '(' here"))
7189 return true;
7190
7191 // Parse Value field.
7192 Metadata *ValLocMD;
7193 if (parseMetadata(ValLocMD, &PFS))
7194 return true;
7195 if (parseToken(lltok::comma, "Expected ',' here"))
7196 return true;
7197
7198 // Parse Variable field.
7199 MDNode *Variable;
7200 if (parseMDNode(Variable))
7201 return true;
7202 if (parseToken(lltok::comma, "Expected ',' here"))
7203 return true;
7204
7205 // Parse Expression field.
7206 MDNode *Expression;
7207 if (parseMDNode(Expression))
7208 return true;
7209 if (parseToken(lltok::comma, "Expected ',' here"))
7210 return true;
7211
7212 // Parse additional fields for #dbg_assign.
7213 MDNode *AssignID = nullptr;
7214 Metadata *AddressLocation = nullptr;
7215 MDNode *AddressExpression = nullptr;
7216 if (ValueType == LocType::Assign) {
7217 // Parse DIAssignID.
7218 if (parseMDNode(AssignID))
7219 return true;
7220 if (parseToken(lltok::comma, "Expected ',' here"))
7221 return true;
7222
7223 // Parse address ValueAsMetadata.
7224 if (parseMetadata(AddressLocation, &PFS))
7225 return true;
7226 if (parseToken(lltok::comma, "Expected ',' here"))
7227 return true;
7228
7229 // Parse address DIExpression.
7230 if (parseMDNode(AddressExpression))
7231 return true;
7232 if (parseToken(lltok::comma, "Expected ',' here"))
7233 return true;
7234 }
7235
7236 /// Parse DILocation.
7237 MDNode *DebugLoc;
7238 if (parseMDNode(DebugLoc))
7239 return true;
7240
7241 if (parseToken(lltok::rparen, "Expected ')' here"))
7242 return true;
7244 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7245 AddressExpression, DebugLoc);
7246 return false;
7247}
7248//===----------------------------------------------------------------------===//
7249// Instruction Parsing.
7250//===----------------------------------------------------------------------===//
7251
7252/// parseInstruction - parse one of the many different instructions.
7253///
7254int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7255 PerFunctionState &PFS) {
7256 lltok::Kind Token = Lex.getKind();
7257 if (Token == lltok::Eof)
7258 return tokError("found end of file when expecting more instructions");
7259 LocTy Loc = Lex.getLoc();
7260 unsigned KeywordVal = Lex.getUIntVal();
7261 Lex.Lex(); // Eat the keyword.
7262
7263 switch (Token) {
7264 default:
7265 return error(Loc, "expected instruction opcode");
7266 // Terminator Instructions.
7267 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7268 case lltok::kw_ret:
7269 return parseRet(Inst, BB, PFS);
7270 case lltok::kw_br:
7271 return parseBr(Inst, PFS);
7272 case lltok::kw_switch:
7273 return parseSwitch(Inst, PFS);
7275 return parseIndirectBr(Inst, PFS);
7276 case lltok::kw_invoke:
7277 return parseInvoke(Inst, PFS);
7278 case lltok::kw_resume:
7279 return parseResume(Inst, PFS);
7281 return parseCleanupRet(Inst, PFS);
7282 case lltok::kw_catchret:
7283 return parseCatchRet(Inst, PFS);
7285 return parseCatchSwitch(Inst, PFS);
7286 case lltok::kw_catchpad:
7287 return parseCatchPad(Inst, PFS);
7289 return parseCleanupPad(Inst, PFS);
7290 case lltok::kw_callbr:
7291 return parseCallBr(Inst, PFS);
7292 // Unary Operators.
7293 case lltok::kw_fneg: {
7294 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7295 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7296 if (Res != 0)
7297 return Res;
7298 if (FMF.any())
7299 Inst->setFastMathFlags(FMF);
7300 return false;
7301 }
7302 // Binary Operators.
7303 case lltok::kw_add:
7304 case lltok::kw_sub:
7305 case lltok::kw_mul:
7306 case lltok::kw_shl: {
7307 bool NUW = EatIfPresent(lltok::kw_nuw);
7308 bool NSW = EatIfPresent(lltok::kw_nsw);
7309 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7310
7311 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7312 return true;
7313
7314 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7315 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7316 return false;
7317 }
7318 case lltok::kw_fadd:
7319 case lltok::kw_fsub:
7320 case lltok::kw_fmul:
7321 case lltok::kw_fdiv:
7322 case lltok::kw_frem: {
7323 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7324 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7325 if (Res != 0)
7326 return Res;
7327 if (FMF.any())
7328 Inst->setFastMathFlags(FMF);
7329 return 0;
7330 }
7331
7332 case lltok::kw_sdiv:
7333 case lltok::kw_udiv:
7334 case lltok::kw_lshr:
7335 case lltok::kw_ashr: {
7336 bool Exact = EatIfPresent(lltok::kw_exact);
7337
7338 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7339 return true;
7340 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7341 return false;
7342 }
7343
7344 case lltok::kw_urem:
7345 case lltok::kw_srem:
7346 return parseArithmetic(Inst, PFS, KeywordVal,
7347 /*IsFP*/ false);
7348 case lltok::kw_or: {
7349 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7350 if (parseLogical(Inst, PFS, KeywordVal))
7351 return true;
7352 if (Disjoint)
7353 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7354 return false;
7355 }
7356 case lltok::kw_and:
7357 case lltok::kw_xor:
7358 return parseLogical(Inst, PFS, KeywordVal);
7359 case lltok::kw_icmp: {
7360 bool SameSign = EatIfPresent(lltok::kw_samesign);
7361 if (parseCompare(Inst, PFS, KeywordVal))
7362 return true;
7363 if (SameSign)
7364 cast<ICmpInst>(Inst)->setSameSign();
7365 return false;
7366 }
7367 case lltok::kw_fcmp: {
7368 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7369 int Res = parseCompare(Inst, PFS, KeywordVal);
7370 if (Res != 0)
7371 return Res;
7372 if (FMF.any())
7373 Inst->setFastMathFlags(FMF);
7374 return 0;
7375 }
7376
7377 // Casts.
7378 case lltok::kw_uitofp:
7379 case lltok::kw_zext: {
7380 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7381 bool Res = parseCast(Inst, PFS, KeywordVal);
7382 if (Res != 0)
7383 return Res;
7384 if (NonNeg)
7385 Inst->setNonNeg();
7386 return 0;
7387 }
7388 case lltok::kw_trunc: {
7389 bool NUW = EatIfPresent(lltok::kw_nuw);
7390 bool NSW = EatIfPresent(lltok::kw_nsw);
7391 if (!NUW)
7392 NUW = EatIfPresent(lltok::kw_nuw);
7393 if (parseCast(Inst, PFS, KeywordVal))
7394 return true;
7395 if (NUW)
7396 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7397 if (NSW)
7398 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7399 return false;
7400 }
7401 case lltok::kw_sext:
7402 case lltok::kw_bitcast:
7404 case lltok::kw_sitofp:
7405 case lltok::kw_fptoui:
7406 case lltok::kw_fptosi:
7407 case lltok::kw_inttoptr:
7409 case lltok::kw_ptrtoint:
7410 return parseCast(Inst, PFS, KeywordVal);
7411 case lltok::kw_fptrunc:
7412 case lltok::kw_fpext: {
7413 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7414 if (parseCast(Inst, PFS, KeywordVal))
7415 return true;
7416 if (FMF.any())
7417 Inst->setFastMathFlags(FMF);
7418 return false;
7419 }
7420
7421 // Other.
7422 case lltok::kw_select: {
7423 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7424 int Res = parseSelect(Inst, PFS);
7425 if (Res != 0)
7426 return Res;
7427 if (FMF.any()) {
7428 if (!isa<FPMathOperator>(Inst))
7429 return error(Loc, "fast-math-flags specified for select without "
7430 "floating-point scalar or vector return type");
7431 Inst->setFastMathFlags(FMF);
7432 }
7433 return 0;
7434 }
7435 case lltok::kw_va_arg:
7436 return parseVAArg(Inst, PFS);
7438 return parseExtractElement(Inst, PFS);
7440 return parseInsertElement(Inst, PFS);
7442 return parseShuffleVector(Inst, PFS);
7443 case lltok::kw_phi: {
7444 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7445 int Res = parsePHI(Inst, PFS);
7446 if (Res != 0)
7447 return Res;
7448 if (FMF.any()) {
7449 if (!isa<FPMathOperator>(Inst))
7450 return error(Loc, "fast-math-flags specified for phi without "
7451 "floating-point scalar or vector return type");
7452 Inst->setFastMathFlags(FMF);
7453 }
7454 return 0;
7455 }
7457 return parseLandingPad(Inst, PFS);
7458 case lltok::kw_freeze:
7459 return parseFreeze(Inst, PFS);
7460 // Call.
7461 case lltok::kw_call:
7462 return parseCall(Inst, PFS, CallInst::TCK_None);
7463 case lltok::kw_tail:
7464 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7465 case lltok::kw_musttail:
7466 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7467 case lltok::kw_notail:
7468 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7469 // Memory.
7470 case lltok::kw_alloca:
7471 return parseAlloc(Inst, PFS);
7472 case lltok::kw_load:
7473 return parseLoad(Inst, PFS);
7474 case lltok::kw_store:
7475 return parseStore(Inst, PFS);
7476 case lltok::kw_cmpxchg:
7477 return parseCmpXchg(Inst, PFS);
7479 return parseAtomicRMW(Inst, PFS);
7480 case lltok::kw_fence:
7481 return parseFence(Inst, PFS);
7483 return parseGetElementPtr(Inst, PFS);
7485 return parseExtractValue(Inst, PFS);
7487 return parseInsertValue(Inst, PFS);
7488 }
7489}
7490
7491/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7492bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7493 if (Opc == Instruction::FCmp) {
7494 switch (Lex.getKind()) {
7495 default:
7496 return tokError("expected fcmp predicate (e.g. 'oeq')");
7497 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7498 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7499 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7500 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7501 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7502 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7503 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7504 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7505 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7506 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7507 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7508 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7509 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7510 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7511 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7512 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7513 }
7514 } else {
7515 switch (Lex.getKind()) {
7516 default:
7517 return tokError("expected icmp predicate (e.g. 'eq')");
7518 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7519 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7520 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7521 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7522 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7523 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7524 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7525 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7526 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7527 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7528 }
7529 }
7530 Lex.Lex();
7531 return false;
7532}
7533
7534//===----------------------------------------------------------------------===//
7535// Terminator Instructions.
7536//===----------------------------------------------------------------------===//
7537
7538/// parseRet - parse a return instruction.
7539/// ::= 'ret' void (',' !dbg, !1)*
7540/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7541bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7542 PerFunctionState &PFS) {
7543 SMLoc TypeLoc = Lex.getLoc();
7544 Type *Ty = nullptr;
7545 if (parseType(Ty, true /*void allowed*/))
7546 return true;
7547
7548 Type *ResType = PFS.getFunction().getReturnType();
7549
7550 if (Ty->isVoidTy()) {
7551 if (!ResType->isVoidTy())
7552 return error(TypeLoc, "value doesn't match function result type '" +
7553 getTypeString(ResType) + "'");
7554
7555 Inst = ReturnInst::Create(Context);
7556 return false;
7557 }
7558
7559 Value *RV;
7560 if (parseValue(Ty, RV, PFS))
7561 return true;
7562
7563 if (ResType != RV->getType())
7564 return error(TypeLoc, "value doesn't match function result type '" +
7565 getTypeString(ResType) + "'");
7566
7567 Inst = ReturnInst::Create(Context, RV);
7568 return false;
7569}
7570
7571/// parseBr
7572/// ::= 'br' TypeAndValue
7573/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7574bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7575 LocTy Loc, Loc2;
7576 Value *Op0;
7577 BasicBlock *Op1, *Op2;
7578 if (parseTypeAndValue(Op0, Loc, PFS))
7579 return true;
7580
7581 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7582 Inst = BranchInst::Create(BB);
7583 return false;
7584 }
7585
7586 if (Op0->getType() != Type::getInt1Ty(Context))
7587 return error(Loc, "branch condition must have 'i1' type");
7588
7589 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7590 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7591 parseToken(lltok::comma, "expected ',' after true destination") ||
7592 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7593 return true;
7594
7595 Inst = BranchInst::Create(Op1, Op2, Op0);
7596 return false;
7597}
7598
7599/// parseSwitch
7600/// Instruction
7601/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7602/// JumpTable
7603/// ::= (TypeAndValue ',' TypeAndValue)*
7604bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7605 LocTy CondLoc, BBLoc;
7606 Value *Cond;
7607 BasicBlock *DefaultBB;
7608 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7609 parseToken(lltok::comma, "expected ',' after switch condition") ||
7610 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7611 parseToken(lltok::lsquare, "expected '[' with switch table"))
7612 return true;
7613
7614 if (!Cond->getType()->isIntegerTy())
7615 return error(CondLoc, "switch condition must have integer type");
7616
7617 // parse the jump table pairs.
7618 SmallPtrSet<Value*, 32> SeenCases;
7620 while (Lex.getKind() != lltok::rsquare) {
7621 Value *Constant;
7622 BasicBlock *DestBB;
7623
7624 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7625 parseToken(lltok::comma, "expected ',' after case value") ||
7626 parseTypeAndBasicBlock(DestBB, PFS))
7627 return true;
7628
7629 if (!SeenCases.insert(Constant).second)
7630 return error(CondLoc, "duplicate case value in switch");
7631 if (!isa<ConstantInt>(Constant))
7632 return error(CondLoc, "case value is not a constant integer");
7633
7634 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7635 }
7636
7637 Lex.Lex(); // Eat the ']'.
7638
7639 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7640 for (const auto &[OnVal, Dest] : Table)
7641 SI->addCase(OnVal, Dest);
7642 Inst = SI;
7643 return false;
7644}
7645
7646/// parseIndirectBr
7647/// Instruction
7648/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7649bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7650 LocTy AddrLoc;
7651 Value *Address;
7652 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7653 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7654 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7655 return true;
7656
7657 if (!Address->getType()->isPointerTy())
7658 return error(AddrLoc, "indirectbr address must have pointer type");
7659
7660 // parse the destination list.
7661 SmallVector<BasicBlock*, 16> DestList;
7662
7663 if (Lex.getKind() != lltok::rsquare) {
7664 BasicBlock *DestBB;
7665 if (parseTypeAndBasicBlock(DestBB, PFS))
7666 return true;
7667 DestList.push_back(DestBB);
7668
7669 while (EatIfPresent(lltok::comma)) {
7670 if (parseTypeAndBasicBlock(DestBB, PFS))
7671 return true;
7672 DestList.push_back(DestBB);
7673 }
7674 }
7675
7676 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7677 return true;
7678
7679 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7680 for (BasicBlock *Dest : DestList)
7681 IBI->addDestination(Dest);
7682 Inst = IBI;
7683 return false;
7684}
7685
7686// If RetType is a non-function pointer type, then this is the short syntax
7687// for the call, which means that RetType is just the return type. Infer the
7688// rest of the function argument types from the arguments that are present.
7689bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7690 FunctionType *&FuncTy) {
7691 FuncTy = dyn_cast<FunctionType>(RetType);
7692 if (!FuncTy) {
7693 // Pull out the types of all of the arguments...
7694 SmallVector<Type *, 8> ParamTypes;
7695 ParamTypes.reserve(ArgList.size());
7696 for (const ParamInfo &Arg : ArgList)
7697 ParamTypes.push_back(Arg.V->getType());
7698
7699 if (!FunctionType::isValidReturnType(RetType))
7700 return true;
7701
7702 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7703 }
7704 return false;
7705}
7706
7707/// parseInvoke
7708/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7709/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7710bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7711 LocTy CallLoc = Lex.getLoc();
7712 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7713 std::vector<unsigned> FwdRefAttrGrps;
7714 LocTy NoBuiltinLoc;
7715 unsigned CC;
7716 unsigned InvokeAddrSpace;
7717 Type *RetType = nullptr;
7718 LocTy RetTypeLoc;
7719 ValID CalleeID;
7722
7723 BasicBlock *NormalBB, *UnwindBB;
7724 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7725 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7726 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7727 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7728 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7729 NoBuiltinLoc) ||
7730 parseOptionalOperandBundles(BundleList, PFS) ||
7731 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7732 parseTypeAndBasicBlock(NormalBB, PFS) ||
7733 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7734 parseTypeAndBasicBlock(UnwindBB, PFS))
7735 return true;
7736
7737 // If RetType is a non-function pointer type, then this is the short syntax
7738 // for the call, which means that RetType is just the return type. Infer the
7739 // rest of the function argument types from the arguments that are present.
7740 FunctionType *Ty;
7741 if (resolveFunctionType(RetType, ArgList, Ty))
7742 return error(RetTypeLoc, "Invalid result type for LLVM function");
7743
7744 CalleeID.FTy = Ty;
7745
7746 // Look up the callee.
7747 Value *Callee;
7748 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7749 Callee, &PFS))
7750 return true;
7751
7752 // Set up the Attribute for the function.
7753 SmallVector<Value *, 8> Args;
7755
7756 // Loop through FunctionType's arguments and ensure they are specified
7757 // correctly. Also, gather any parameter attributes.
7758 FunctionType::param_iterator I = Ty->param_begin();
7759 FunctionType::param_iterator E = Ty->param_end();
7760 for (const ParamInfo &Arg : ArgList) {
7761 Type *ExpectedTy = nullptr;
7762 if (I != E) {
7763 ExpectedTy = *I++;
7764 } else if (!Ty->isVarArg()) {
7765 return error(Arg.Loc, "too many arguments specified");
7766 }
7767
7768 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7769 return error(Arg.Loc, "argument is not of expected type '" +
7770 getTypeString(ExpectedTy) + "'");
7771 Args.push_back(Arg.V);
7772 ArgAttrs.push_back(Arg.Attrs);
7773 }
7774
7775 if (I != E)
7776 return error(CallLoc, "not enough parameters specified for call");
7777
7778 // Finish off the Attribute and check them
7779 AttributeList PAL =
7780 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7781 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7782
7783 InvokeInst *II =
7784 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7785 II->setCallingConv(CC);
7786 II->setAttributes(PAL);
7787 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7788 Inst = II;
7789 return false;
7790}
7791
7792/// parseResume
7793/// ::= 'resume' TypeAndValue
7794bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7795 Value *Exn; LocTy ExnLoc;
7796 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7797 return true;
7798
7799 ResumeInst *RI = ResumeInst::Create(Exn);
7800 Inst = RI;
7801 return false;
7802}
7803
7804bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7805 PerFunctionState &PFS) {
7806 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7807 return true;
7808
7809 while (Lex.getKind() != lltok::rsquare) {
7810 // If this isn't the first argument, we need a comma.
7811 if (!Args.empty() &&
7812 parseToken(lltok::comma, "expected ',' in argument list"))
7813 return true;
7814
7815 // parse the argument.
7816 LocTy ArgLoc;
7817 Type *ArgTy = nullptr;
7818 if (parseType(ArgTy, ArgLoc))
7819 return true;
7820
7821 Value *V;
7822 if (ArgTy->isMetadataTy()) {
7823 if (parseMetadataAsValue(V, PFS))
7824 return true;
7825 } else {
7826 if (parseValue(ArgTy, V, PFS))
7827 return true;
7828 }
7829 Args.push_back(V);
7830 }
7831
7832 Lex.Lex(); // Lex the ']'.
7833 return false;
7834}
7835
7836/// parseCleanupRet
7837/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7838bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7839 Value *CleanupPad = nullptr;
7840
7841 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7842 return true;
7843
7844 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7845 return true;
7846
7847 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7848 return true;
7849
7850 BasicBlock *UnwindBB = nullptr;
7851 if (Lex.getKind() == lltok::kw_to) {
7852 Lex.Lex();
7853 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7854 return true;
7855 } else {
7856 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7857 return true;
7858 }
7859 }
7860
7861 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7862 return false;
7863}
7864
7865/// parseCatchRet
7866/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7867bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7868 Value *CatchPad = nullptr;
7869
7870 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7871 return true;
7872
7873 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7874 return true;
7875
7876 BasicBlock *BB;
7877 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7878 parseTypeAndBasicBlock(BB, PFS))
7879 return true;
7880
7881 Inst = CatchReturnInst::Create(CatchPad, BB);
7882 return false;
7883}
7884
7885/// parseCatchSwitch
7886/// ::= 'catchswitch' within Parent
7887bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7888 Value *ParentPad;
7889
7890 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7891 return true;
7892
7893 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7894 Lex.getKind() != lltok::LocalVarID)
7895 return tokError("expected scope value for catchswitch");
7896
7897 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7898 return true;
7899
7900 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7901 return true;
7902
7904 do {
7905 BasicBlock *DestBB;
7906 if (parseTypeAndBasicBlock(DestBB, PFS))
7907 return true;
7908 Table.push_back(DestBB);
7909 } while (EatIfPresent(lltok::comma));
7910
7911 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7912 return true;
7913
7914 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7915 return true;
7916
7917 BasicBlock *UnwindBB = nullptr;
7918 if (EatIfPresent(lltok::kw_to)) {
7919 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7920 return true;
7921 } else {
7922 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7923 return true;
7924 }
7925
7926 auto *CatchSwitch =
7927 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7928 for (BasicBlock *DestBB : Table)
7929 CatchSwitch->addHandler(DestBB);
7930 Inst = CatchSwitch;
7931 return false;
7932}
7933
7934/// parseCatchPad
7935/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7936bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7937 Value *CatchSwitch = nullptr;
7938
7939 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7940 return true;
7941
7942 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7943 return tokError("expected scope value for catchpad");
7944
7945 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7946 return true;
7947
7948 SmallVector<Value *, 8> Args;
7949 if (parseExceptionArgs(Args, PFS))
7950 return true;
7951
7952 Inst = CatchPadInst::Create(CatchSwitch, Args);
7953 return false;
7954}
7955
7956/// parseCleanupPad
7957/// ::= 'cleanuppad' within Parent ParamList
7958bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7959 Value *ParentPad = nullptr;
7960
7961 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7962 return true;
7963
7964 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7965 Lex.getKind() != lltok::LocalVarID)
7966 return tokError("expected scope value for cleanuppad");
7967
7968 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7969 return true;
7970
7971 SmallVector<Value *, 8> Args;
7972 if (parseExceptionArgs(Args, PFS))
7973 return true;
7974
7975 Inst = CleanupPadInst::Create(ParentPad, Args);
7976 return false;
7977}
7978
7979//===----------------------------------------------------------------------===//
7980// Unary Operators.
7981//===----------------------------------------------------------------------===//
7982
7983/// parseUnaryOp
7984/// ::= UnaryOp TypeAndValue ',' Value
7985///
7986/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7987/// operand is allowed.
7988bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7989 unsigned Opc, bool IsFP) {
7990 LocTy Loc; Value *LHS;
7991 if (parseTypeAndValue(LHS, Loc, PFS))
7992 return true;
7993
7994 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7996
7997 if (!Valid)
7998 return error(Loc, "invalid operand type for instruction");
7999
8001 return false;
8002}
8003
8004/// parseCallBr
8005/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8006/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8007/// '[' LabelList ']'
8008bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8009 LocTy CallLoc = Lex.getLoc();
8010 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8011 std::vector<unsigned> FwdRefAttrGrps;
8012 LocTy NoBuiltinLoc;
8013 unsigned CC;
8014 Type *RetType = nullptr;
8015 LocTy RetTypeLoc;
8016 ValID CalleeID;
8019
8020 BasicBlock *DefaultDest;
8021 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8022 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8023 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8024 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8025 NoBuiltinLoc) ||
8026 parseOptionalOperandBundles(BundleList, PFS) ||
8027 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8028 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8029 parseToken(lltok::lsquare, "expected '[' in callbr"))
8030 return true;
8031
8032 // parse the destination list.
8033 SmallVector<BasicBlock *, 16> IndirectDests;
8034
8035 if (Lex.getKind() != lltok::rsquare) {
8036 BasicBlock *DestBB;
8037 if (parseTypeAndBasicBlock(DestBB, PFS))
8038 return true;
8039 IndirectDests.push_back(DestBB);
8040
8041 while (EatIfPresent(lltok::comma)) {
8042 if (parseTypeAndBasicBlock(DestBB, PFS))
8043 return true;
8044 IndirectDests.push_back(DestBB);
8045 }
8046 }
8047
8048 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8049 return true;
8050
8051 // If RetType is a non-function pointer type, then this is the short syntax
8052 // for the call, which means that RetType is just the return type. Infer the
8053 // rest of the function argument types from the arguments that are present.
8054 FunctionType *Ty;
8055 if (resolveFunctionType(RetType, ArgList, Ty))
8056 return error(RetTypeLoc, "Invalid result type for LLVM function");
8057
8058 CalleeID.FTy = Ty;
8059
8060 // Look up the callee.
8061 Value *Callee;
8062 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8063 &PFS))
8064 return true;
8065
8066 // Set up the Attribute for the function.
8067 SmallVector<Value *, 8> Args;
8069
8070 // Loop through FunctionType's arguments and ensure they are specified
8071 // correctly. Also, gather any parameter attributes.
8072 FunctionType::param_iterator I = Ty->param_begin();
8073 FunctionType::param_iterator E = Ty->param_end();
8074 for (const ParamInfo &Arg : ArgList) {
8075 Type *ExpectedTy = nullptr;
8076 if (I != E) {
8077 ExpectedTy = *I++;
8078 } else if (!Ty->isVarArg()) {
8079 return error(Arg.Loc, "too many arguments specified");
8080 }
8081
8082 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8083 return error(Arg.Loc, "argument is not of expected type '" +
8084 getTypeString(ExpectedTy) + "'");
8085 Args.push_back(Arg.V);
8086 ArgAttrs.push_back(Arg.Attrs);
8087 }
8088
8089 if (I != E)
8090 return error(CallLoc, "not enough parameters specified for call");
8091
8092 // Finish off the Attribute and check them
8093 AttributeList PAL =
8094 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8095 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8096
8097 CallBrInst *CBI =
8098 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8099 BundleList);
8100 CBI->setCallingConv(CC);
8101 CBI->setAttributes(PAL);
8102 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8103 Inst = CBI;
8104 return false;
8105}
8106
8107//===----------------------------------------------------------------------===//
8108// Binary Operators.
8109//===----------------------------------------------------------------------===//
8110
8111/// parseArithmetic
8112/// ::= ArithmeticOps TypeAndValue ',' Value
8113///
8114/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8115/// operand is allowed.
8116bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8117 unsigned Opc, bool IsFP) {
8118 LocTy Loc; Value *LHS, *RHS;
8119 if (parseTypeAndValue(LHS, Loc, PFS) ||
8120 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8121 parseValue(LHS->getType(), RHS, PFS))
8122 return true;
8123
8124 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8126
8127 if (!Valid)
8128 return error(Loc, "invalid operand type for instruction");
8129
8131 return false;
8132}
8133
8134/// parseLogical
8135/// ::= ArithmeticOps TypeAndValue ',' Value {
8136bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8137 unsigned Opc) {
8138 LocTy Loc; Value *LHS, *RHS;
8139 if (parseTypeAndValue(LHS, Loc, PFS) ||
8140 parseToken(lltok::comma, "expected ',' in logical operation") ||
8141 parseValue(LHS->getType(), RHS, PFS))
8142 return true;
8143
8144 if (!LHS->getType()->isIntOrIntVectorTy())
8145 return error(Loc,
8146 "instruction requires integer or integer vector operands");
8147
8149 return false;
8150}
8151
8152/// parseCompare
8153/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8154/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8155bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8156 unsigned Opc) {
8157 // parse the integer/fp comparison predicate.
8158 LocTy Loc;
8159 unsigned Pred;
8160 Value *LHS, *RHS;
8161 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8162 parseToken(lltok::comma, "expected ',' after compare value") ||
8163 parseValue(LHS->getType(), RHS, PFS))
8164 return true;
8165
8166 if (Opc == Instruction::FCmp) {
8167 if (!LHS->getType()->isFPOrFPVectorTy())
8168 return error(Loc, "fcmp requires floating point operands");
8169 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8170 } else {
8171 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8172 if (!LHS->getType()->isIntOrIntVectorTy() &&
8174 return error(Loc, "icmp requires integer operands");
8175 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8176 }
8177 return false;
8178}
8179
8180//===----------------------------------------------------------------------===//
8181// Other Instructions.
8182//===----------------------------------------------------------------------===//
8183
8184/// parseCast
8185/// ::= CastOpc TypeAndValue 'to' Type
8186bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8187 unsigned Opc) {
8188 LocTy Loc;
8189 Value *Op;
8190 Type *DestTy = nullptr;
8191 if (parseTypeAndValue(Op, Loc, PFS) ||
8192 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8193 parseType(DestTy))
8194 return true;
8195
8197 return error(Loc, "invalid cast opcode for cast from '" +
8198 getTypeString(Op->getType()) + "' to '" +
8199 getTypeString(DestTy) + "'");
8200 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8201 return false;
8202}
8203
8204/// parseSelect
8205/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8206bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8207 LocTy Loc;
8208 Value *Op0, *Op1, *Op2;
8209 if (parseTypeAndValue(Op0, Loc, PFS) ||
8210 parseToken(lltok::comma, "expected ',' after select condition") ||
8211 parseTypeAndValue(Op1, PFS) ||
8212 parseToken(lltok::comma, "expected ',' after select value") ||
8213 parseTypeAndValue(Op2, PFS))
8214 return true;
8215
8216 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8217 return error(Loc, Reason);
8218
8219 Inst = SelectInst::Create(Op0, Op1, Op2);
8220 return false;
8221}
8222
8223/// parseVAArg
8224/// ::= 'va_arg' TypeAndValue ',' Type
8225bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8226 Value *Op;
8227 Type *EltTy = nullptr;
8228 LocTy TypeLoc;
8229 if (parseTypeAndValue(Op, PFS) ||
8230 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8231 parseType(EltTy, TypeLoc))
8232 return true;
8233
8234 if (!EltTy->isFirstClassType())
8235 return error(TypeLoc, "va_arg requires operand with first class type");
8236
8237 Inst = new VAArgInst(Op, EltTy);
8238 return false;
8239}
8240
8241/// parseExtractElement
8242/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8243bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8244 LocTy Loc;
8245 Value *Op0, *Op1;
8246 if (parseTypeAndValue(Op0, Loc, PFS) ||
8247 parseToken(lltok::comma, "expected ',' after extract value") ||
8248 parseTypeAndValue(Op1, PFS))
8249 return true;
8250
8252 return error(Loc, "invalid extractelement operands");
8253
8254 Inst = ExtractElementInst::Create(Op0, Op1);
8255 return false;
8256}
8257
8258/// parseInsertElement
8259/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8260bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8261 LocTy Loc;
8262 Value *Op0, *Op1, *Op2;
8263 if (parseTypeAndValue(Op0, Loc, PFS) ||
8264 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8265 parseTypeAndValue(Op1, PFS) ||
8266 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8267 parseTypeAndValue(Op2, PFS))
8268 return true;
8269
8270 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8271 return error(Loc, "invalid insertelement operands");
8272
8273 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8274 return false;
8275}
8276
8277/// parseShuffleVector
8278/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8279bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8280 LocTy Loc;
8281 Value *Op0, *Op1, *Op2;
8282 if (parseTypeAndValue(Op0, Loc, PFS) ||
8283 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8284 parseTypeAndValue(Op1, PFS) ||
8285 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8286 parseTypeAndValue(Op2, PFS))
8287 return true;
8288
8289 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8290 return error(Loc, "invalid shufflevector operands");
8291
8292 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8293 return false;
8294}
8295
8296/// parsePHI
8297/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8298int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8299 Type *Ty = nullptr; LocTy TypeLoc;
8300 Value *Op0, *Op1;
8301
8302 if (parseType(Ty, TypeLoc))
8303 return true;
8304
8305 if (!Ty->isFirstClassType())
8306 return error(TypeLoc, "phi node must have first class type");
8307
8308 bool First = true;
8309 bool AteExtraComma = false;
8311
8312 while (true) {
8313 if (First) {
8314 if (Lex.getKind() != lltok::lsquare)
8315 break;
8316 First = false;
8317 } else if (!EatIfPresent(lltok::comma))
8318 break;
8319
8320 if (Lex.getKind() == lltok::MetadataVar) {
8321 AteExtraComma = true;
8322 break;
8323 }
8324
8325 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8326 parseValue(Ty, Op0, PFS) ||
8327 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8328 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8329 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8330 return true;
8331
8332 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8333 }
8334
8335 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8336 for (const auto &[Val, BB] : PHIVals)
8337 PN->addIncoming(Val, BB);
8338 Inst = PN;
8339 return AteExtraComma ? InstExtraComma : InstNormal;
8340}
8341
8342/// parseLandingPad
8343/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8344/// Clause
8345/// ::= 'catch' TypeAndValue
8346/// ::= 'filter'
8347/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8348bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8349 Type *Ty = nullptr; LocTy TyLoc;
8350
8351 if (parseType(Ty, TyLoc))
8352 return true;
8353
8354 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8355 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8356
8357 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8359 if (EatIfPresent(lltok::kw_catch))
8361 else if (EatIfPresent(lltok::kw_filter))
8363 else
8364 return tokError("expected 'catch' or 'filter' clause type");
8365
8366 Value *V;
8367 LocTy VLoc;
8368 if (parseTypeAndValue(V, VLoc, PFS))
8369 return true;
8370
8371 // A 'catch' type expects a non-array constant. A filter clause expects an
8372 // array constant.
8373 if (CT == LandingPadInst::Catch) {
8374 if (isa<ArrayType>(V->getType()))
8375 return error(VLoc, "'catch' clause has an invalid type");
8376 } else {
8377 if (!isa<ArrayType>(V->getType()))
8378 return error(VLoc, "'filter' clause has an invalid type");
8379 }
8380
8382 if (!CV)
8383 return error(VLoc, "clause argument must be a constant");
8384 LP->addClause(CV);
8385 }
8386
8387 Inst = LP.release();
8388 return false;
8389}
8390
8391/// parseFreeze
8392/// ::= 'freeze' Type Value
8393bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8394 LocTy Loc;
8395 Value *Op;
8396 if (parseTypeAndValue(Op, Loc, PFS))
8397 return true;
8398
8399 Inst = new FreezeInst(Op);
8400 return false;
8401}
8402
8403/// parseCall
8404/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8405/// OptionalAttrs Type Value ParameterList OptionalAttrs
8406/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8407/// OptionalAttrs Type Value ParameterList OptionalAttrs
8408/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8409/// OptionalAttrs Type Value ParameterList OptionalAttrs
8410/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8411/// OptionalAttrs Type Value ParameterList OptionalAttrs
8412bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8414 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8415 std::vector<unsigned> FwdRefAttrGrps;
8416 LocTy BuiltinLoc;
8417 unsigned CallAddrSpace;
8418 unsigned CC;
8419 Type *RetType = nullptr;
8420 LocTy RetTypeLoc;
8421 ValID CalleeID;
8424 LocTy CallLoc = Lex.getLoc();
8425
8426 if (TCK != CallInst::TCK_None &&
8427 parseToken(lltok::kw_call,
8428 "expected 'tail call', 'musttail call', or 'notail call'"))
8429 return true;
8430
8431 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8432
8433 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8434 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8435 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8436 parseValID(CalleeID, &PFS) ||
8437 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8438 PFS.getFunction().isVarArg()) ||
8439 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8440 parseOptionalOperandBundles(BundleList, PFS))
8441 return true;
8442
8443 // If RetType is a non-function pointer type, then this is the short syntax
8444 // for the call, which means that RetType is just the return type. Infer the
8445 // rest of the function argument types from the arguments that are present.
8446 FunctionType *Ty;
8447 if (resolveFunctionType(RetType, ArgList, Ty))
8448 return error(RetTypeLoc, "Invalid result type for LLVM function");
8449
8450 CalleeID.FTy = Ty;
8451
8452 // Look up the callee.
8453 Value *Callee;
8454 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8455 Callee, &PFS))
8456 return true;
8457
8458 // Set up the Attribute for the function.
8460
8461 SmallVector<Value*, 8> Args;
8462
8463 // Loop through FunctionType's arguments and ensure they are specified
8464 // correctly. Also, gather any parameter attributes.
8465 FunctionType::param_iterator I = Ty->param_begin();
8466 FunctionType::param_iterator E = Ty->param_end();
8467 for (const ParamInfo &Arg : ArgList) {
8468 Type *ExpectedTy = nullptr;
8469 if (I != E) {
8470 ExpectedTy = *I++;
8471 } else if (!Ty->isVarArg()) {
8472 return error(Arg.Loc, "too many arguments specified");
8473 }
8474
8475 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8476 return error(Arg.Loc, "argument is not of expected type '" +
8477 getTypeString(ExpectedTy) + "'");
8478 Args.push_back(Arg.V);
8479 Attrs.push_back(Arg.Attrs);
8480 }
8481
8482 if (I != E)
8483 return error(CallLoc, "not enough parameters specified for call");
8484
8485 // Finish off the Attribute and check them
8486 AttributeList PAL =
8487 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8488 AttributeSet::get(Context, RetAttrs), Attrs);
8489
8490 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8491 CI->setTailCallKind(TCK);
8492 CI->setCallingConv(CC);
8493 if (FMF.any()) {
8494 if (!isa<FPMathOperator>(CI)) {
8495 CI->deleteValue();
8496 return error(CallLoc, "fast-math-flags specified for call without "
8497 "floating-point scalar or vector return type");
8498 }
8499 CI->setFastMathFlags(FMF);
8500 }
8501
8502 if (CalleeID.Kind == ValID::t_GlobalName &&
8503 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8504 if (SeenNewDbgInfoFormat) {
8505 CI->deleteValue();
8506 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8507 "using non-intrinsic debug info");
8508 }
8509 SeenOldDbgInfoFormat = true;
8510 }
8511 CI->setAttributes(PAL);
8512 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8513 Inst = CI;
8514 return false;
8515}
8516
8517//===----------------------------------------------------------------------===//
8518// Memory Instructions.
8519//===----------------------------------------------------------------------===//
8520
8521/// parseAlloc
8522/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8523/// (',' 'align' i32)? (',', 'addrspace(n))?
8524int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8525 Value *Size = nullptr;
8526 LocTy SizeLoc, TyLoc, ASLoc;
8527 MaybeAlign Alignment;
8528 unsigned AddrSpace = 0;
8529 Type *Ty = nullptr;
8530
8531 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8532 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8533
8534 if (parseType(Ty, TyLoc))
8535 return true;
8536
8538 return error(TyLoc, "invalid type for alloca");
8539
8540 bool AteExtraComma = false;
8541 if (EatIfPresent(lltok::comma)) {
8542 if (Lex.getKind() == lltok::kw_align) {
8543 if (parseOptionalAlignment(Alignment))
8544 return true;
8545 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8546 return true;
8547 } else if (Lex.getKind() == lltok::kw_addrspace) {
8548 ASLoc = Lex.getLoc();
8549 if (parseOptionalAddrSpace(AddrSpace))
8550 return true;
8551 } else if (Lex.getKind() == lltok::MetadataVar) {
8552 AteExtraComma = true;
8553 } else {
8554 if (parseTypeAndValue(Size, SizeLoc, PFS))
8555 return true;
8556 if (EatIfPresent(lltok::comma)) {
8557 if (Lex.getKind() == lltok::kw_align) {
8558 if (parseOptionalAlignment(Alignment))
8559 return true;
8560 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8561 return true;
8562 } else if (Lex.getKind() == lltok::kw_addrspace) {
8563 ASLoc = Lex.getLoc();
8564 if (parseOptionalAddrSpace(AddrSpace))
8565 return true;
8566 } else if (Lex.getKind() == lltok::MetadataVar) {
8567 AteExtraComma = true;
8568 }
8569 }
8570 }
8571 }
8572
8573 if (Size && !Size->getType()->isIntegerTy())
8574 return error(SizeLoc, "element count must have integer type");
8575
8576 SmallPtrSet<Type *, 4> Visited;
8577 if (!Alignment && !Ty->isSized(&Visited))
8578 return error(TyLoc, "Cannot allocate unsized type");
8579 if (!Alignment)
8580 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8581 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8582 AI->setUsedWithInAlloca(IsInAlloca);
8583 AI->setSwiftError(IsSwiftError);
8584 Inst = AI;
8585 return AteExtraComma ? InstExtraComma : InstNormal;
8586}
8587
8588/// parseLoad
8589/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8590/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8591/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8592int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8593 Value *Val; LocTy Loc;
8594 MaybeAlign Alignment;
8595 bool AteExtraComma = false;
8596 bool isAtomic = false;
8599
8600 if (Lex.getKind() == lltok::kw_atomic) {
8601 isAtomic = true;
8602 Lex.Lex();
8603 }
8604
8605 bool isVolatile = false;
8606 if (Lex.getKind() == lltok::kw_volatile) {
8607 isVolatile = true;
8608 Lex.Lex();
8609 }
8610
8611 Type *Ty;
8612 LocTy ExplicitTypeLoc = Lex.getLoc();
8613 if (parseType(Ty) ||
8614 parseToken(lltok::comma, "expected comma after load's type") ||
8615 parseTypeAndValue(Val, Loc, PFS) ||
8616 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8617 parseOptionalCommaAlign(Alignment, AteExtraComma))
8618 return true;
8619
8620 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8621 return error(Loc, "load operand must be a pointer to a first class type");
8622 if (isAtomic && !Alignment)
8623 return error(Loc, "atomic load must have explicit non-zero alignment");
8624 if (Ordering == AtomicOrdering::Release ||
8626 return error(Loc, "atomic load cannot use Release ordering");
8627
8628 SmallPtrSet<Type *, 4> Visited;
8629 if (!Alignment && !Ty->isSized(&Visited))
8630 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8631 if (!Alignment)
8632 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8633 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8634 return AteExtraComma ? InstExtraComma : InstNormal;
8635}
8636
8637/// parseStore
8638
8639/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8640/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8641/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8642int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8643 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8644 MaybeAlign Alignment;
8645 bool AteExtraComma = false;
8646 bool isAtomic = false;
8649
8650 if (Lex.getKind() == lltok::kw_atomic) {
8651 isAtomic = true;
8652 Lex.Lex();
8653 }
8654
8655 bool isVolatile = false;
8656 if (Lex.getKind() == lltok::kw_volatile) {
8657 isVolatile = true;
8658 Lex.Lex();
8659 }
8660
8661 if (parseTypeAndValue(Val, Loc, PFS) ||
8662 parseToken(lltok::comma, "expected ',' after store operand") ||
8663 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8664 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8665 parseOptionalCommaAlign(Alignment, AteExtraComma))
8666 return true;
8667
8668 if (!Ptr->getType()->isPointerTy())
8669 return error(PtrLoc, "store operand must be a pointer");
8670 if (!Val->getType()->isFirstClassType())
8671 return error(Loc, "store operand must be a first class value");
8672 if (isAtomic && !Alignment)
8673 return error(Loc, "atomic store must have explicit non-zero alignment");
8674 if (Ordering == AtomicOrdering::Acquire ||
8676 return error(Loc, "atomic store cannot use Acquire ordering");
8677 SmallPtrSet<Type *, 4> Visited;
8678 if (!Alignment && !Val->getType()->isSized(&Visited))
8679 return error(Loc, "storing unsized types is not allowed");
8680 if (!Alignment)
8681 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8682
8683 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8684 return AteExtraComma ? InstExtraComma : InstNormal;
8685}
8686
8687/// parseCmpXchg
8688/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8689/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8690/// 'Align'?
8691int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8692 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8693 bool AteExtraComma = false;
8694 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8695 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8697 bool isVolatile = false;
8698 bool isWeak = false;
8699 MaybeAlign Alignment;
8700
8701 if (EatIfPresent(lltok::kw_weak))
8702 isWeak = true;
8703
8704 if (EatIfPresent(lltok::kw_volatile))
8705 isVolatile = true;
8706
8707 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8708 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8709 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8710 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8711 parseTypeAndValue(New, NewLoc, PFS) ||
8712 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8713 parseOrdering(FailureOrdering) ||
8714 parseOptionalCommaAlign(Alignment, AteExtraComma))
8715 return true;
8716
8717 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8718 return tokError("invalid cmpxchg success ordering");
8719 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8720 return tokError("invalid cmpxchg failure ordering");
8721 if (!Ptr->getType()->isPointerTy())
8722 return error(PtrLoc, "cmpxchg operand must be a pointer");
8723 if (Cmp->getType() != New->getType())
8724 return error(NewLoc, "compare value and new value type do not match");
8725 if (!New->getType()->isFirstClassType())
8726 return error(NewLoc, "cmpxchg operand must be a first class value");
8727
8728 const Align DefaultAlignment(
8729 PFS.getFunction().getDataLayout().getTypeStoreSize(
8730 Cmp->getType()));
8731
8732 AtomicCmpXchgInst *CXI =
8733 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8734 SuccessOrdering, FailureOrdering, SSID);
8735 CXI->setVolatile(isVolatile);
8736 CXI->setWeak(isWeak);
8737
8738 Inst = CXI;
8739 return AteExtraComma ? InstExtraComma : InstNormal;
8740}
8741
8742/// parseAtomicRMW
8743/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8744/// 'singlethread'? AtomicOrdering
8745int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8746 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8747 bool AteExtraComma = false;
8750 bool isVolatile = false;
8751 bool IsFP = false;
8753 MaybeAlign Alignment;
8754
8755 if (EatIfPresent(lltok::kw_volatile))
8756 isVolatile = true;
8757
8758 switch (Lex.getKind()) {
8759 default:
8760 return tokError("expected binary operation in atomicrmw");
8774 break;
8777 break;
8780 break;
8781 case lltok::kw_usub_sat:
8783 break;
8784 case lltok::kw_fadd:
8786 IsFP = true;
8787 break;
8788 case lltok::kw_fsub:
8790 IsFP = true;
8791 break;
8792 case lltok::kw_fmax:
8794 IsFP = true;
8795 break;
8796 case lltok::kw_fmin:
8798 IsFP = true;
8799 break;
8800 case lltok::kw_fmaximum:
8802 IsFP = true;
8803 break;
8804 case lltok::kw_fminimum:
8806 IsFP = true;
8807 break;
8808 }
8809 Lex.Lex(); // Eat the operation.
8810
8811 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8812 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8813 parseTypeAndValue(Val, ValLoc, PFS) ||
8814 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8815 parseOptionalCommaAlign(Alignment, AteExtraComma))
8816 return true;
8817
8818 if (Ordering == AtomicOrdering::Unordered)
8819 return tokError("atomicrmw cannot be unordered");
8820 if (!Ptr->getType()->isPointerTy())
8821 return error(PtrLoc, "atomicrmw operand must be a pointer");
8822 if (Val->getType()->isScalableTy())
8823 return error(ValLoc, "atomicrmw operand may not be scalable");
8824
8826 if (!Val->getType()->isIntegerTy() &&
8827 !Val->getType()->isFloatingPointTy() &&
8828 !Val->getType()->isPointerTy()) {
8829 return error(
8830 ValLoc,
8832 " operand must be an integer, floating point, or pointer type");
8833 }
8834 } else if (IsFP) {
8835 if (!Val->getType()->isFPOrFPVectorTy()) {
8836 return error(ValLoc, "atomicrmw " +
8838 " operand must be a floating point type");
8839 }
8840 } else {
8841 if (!Val->getType()->isIntegerTy()) {
8842 return error(ValLoc, "atomicrmw " +
8844 " operand must be an integer");
8845 }
8846 }
8847
8848 unsigned Size =
8849 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8850 Val->getType());
8851 if (Size < 8 || (Size & (Size - 1)))
8852 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8853 " integer");
8854 const Align DefaultAlignment(
8855 PFS.getFunction().getDataLayout().getTypeStoreSize(
8856 Val->getType()));
8857 AtomicRMWInst *RMWI =
8858 new AtomicRMWInst(Operation, Ptr, Val,
8859 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8860 RMWI->setVolatile(isVolatile);
8861 Inst = RMWI;
8862 return AteExtraComma ? InstExtraComma : InstNormal;
8863}
8864
8865/// parseFence
8866/// ::= 'fence' 'singlethread'? AtomicOrdering
8867int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8870 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8871 return true;
8872
8873 if (Ordering == AtomicOrdering::Unordered)
8874 return tokError("fence cannot be unordered");
8875 if (Ordering == AtomicOrdering::Monotonic)
8876 return tokError("fence cannot be monotonic");
8877
8878 Inst = new FenceInst(Context, Ordering, SSID);
8879 return InstNormal;
8880}
8881
8882/// parseGetElementPtr
8883/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8884int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8885 Value *Ptr = nullptr;
8886 Value *Val = nullptr;
8887 LocTy Loc, EltLoc;
8888 GEPNoWrapFlags NW;
8889
8890 while (true) {
8891 if (EatIfPresent(lltok::kw_inbounds))
8893 else if (EatIfPresent(lltok::kw_nusw))
8895 else if (EatIfPresent(lltok::kw_nuw))
8897 else
8898 break;
8899 }
8900
8901 Type *Ty = nullptr;
8902 if (parseType(Ty) ||
8903 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8904 parseTypeAndValue(Ptr, Loc, PFS))
8905 return true;
8906
8907 Type *BaseType = Ptr->getType();
8908 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8909 if (!BasePointerType)
8910 return error(Loc, "base of getelementptr must be a pointer");
8911
8912 SmallVector<Value*, 16> Indices;
8913 bool AteExtraComma = false;
8914 // GEP returns a vector of pointers if at least one of parameters is a vector.
8915 // All vector parameters should have the same vector width.
8916 ElementCount GEPWidth = BaseType->isVectorTy()
8917 ? cast<VectorType>(BaseType)->getElementCount()
8919
8920 while (EatIfPresent(lltok::comma)) {
8921 if (Lex.getKind() == lltok::MetadataVar) {
8922 AteExtraComma = true;
8923 break;
8924 }
8925 if (parseTypeAndValue(Val, EltLoc, PFS))
8926 return true;
8927 if (!Val->getType()->isIntOrIntVectorTy())
8928 return error(EltLoc, "getelementptr index must be an integer");
8929
8930 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8931 ElementCount ValNumEl = ValVTy->getElementCount();
8932 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8933 return error(
8934 EltLoc,
8935 "getelementptr vector index has a wrong number of elements");
8936 GEPWidth = ValNumEl;
8937 }
8938 Indices.push_back(Val);
8939 }
8940
8941 SmallPtrSet<Type*, 4> Visited;
8942 if (!Indices.empty() && !Ty->isSized(&Visited))
8943 return error(Loc, "base element of getelementptr must be sized");
8944
8945 auto *STy = dyn_cast<StructType>(Ty);
8946 if (STy && STy->isScalableTy())
8947 return error(Loc, "getelementptr cannot target structure that contains "
8948 "scalable vector type");
8949
8950 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8951 return error(Loc, "invalid getelementptr indices");
8952 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8953 Inst = GEP;
8954 GEP->setNoWrapFlags(NW);
8955 return AteExtraComma ? InstExtraComma : InstNormal;
8956}
8957
8958/// parseExtractValue
8959/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8960int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8961 Value *Val; LocTy Loc;
8962 SmallVector<unsigned, 4> Indices;
8963 bool AteExtraComma;
8964 if (parseTypeAndValue(Val, Loc, PFS) ||
8965 parseIndexList(Indices, AteExtraComma))
8966 return true;
8967
8968 if (!Val->getType()->isAggregateType())
8969 return error(Loc, "extractvalue operand must be aggregate type");
8970
8971 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8972 return error(Loc, "invalid indices for extractvalue");
8973 Inst = ExtractValueInst::Create(Val, Indices);
8974 return AteExtraComma ? InstExtraComma : InstNormal;
8975}
8976
8977/// parseInsertValue
8978/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8979int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8980 Value *Val0, *Val1; LocTy Loc0, Loc1;
8981 SmallVector<unsigned, 4> Indices;
8982 bool AteExtraComma;
8983 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8984 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8985 parseTypeAndValue(Val1, Loc1, PFS) ||
8986 parseIndexList(Indices, AteExtraComma))
8987 return true;
8988
8989 if (!Val0->getType()->isAggregateType())
8990 return error(Loc0, "insertvalue operand must be aggregate type");
8991
8992 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8993 if (!IndexedType)
8994 return error(Loc0, "invalid indices for insertvalue");
8995 if (IndexedType != Val1->getType())
8996 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8997 getTypeString(Val1->getType()) + "' instead of '" +
8998 getTypeString(IndexedType) + "'");
8999 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9000 return AteExtraComma ? InstExtraComma : InstNormal;
9001}
9002
9003//===----------------------------------------------------------------------===//
9004// Embedded metadata.
9005//===----------------------------------------------------------------------===//
9006
9007/// parseMDNodeVector
9008/// ::= { Element (',' Element)* }
9009/// Element
9010/// ::= 'null' | Metadata
9011bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9012 if (parseToken(lltok::lbrace, "expected '{' here"))
9013 return true;
9014
9015 // Check for an empty list.
9016 if (EatIfPresent(lltok::rbrace))
9017 return false;
9018
9019 do {
9020 if (EatIfPresent(lltok::kw_null)) {
9021 Elts.push_back(nullptr);
9022 continue;
9023 }
9024
9025 Metadata *MD;
9026 if (parseMetadata(MD, nullptr))
9027 return true;
9028 Elts.push_back(MD);
9029 } while (EatIfPresent(lltok::comma));
9030
9031 return parseToken(lltok::rbrace, "expected end of metadata node");
9032}
9033
9034//===----------------------------------------------------------------------===//
9035// Use-list order directives.
9036//===----------------------------------------------------------------------===//
9037bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9038 SMLoc Loc) {
9039 if (!V->hasUseList())
9040 return false;
9041 if (V->use_empty())
9042 return error(Loc, "value has no uses");
9043
9044 unsigned NumUses = 0;
9045 SmallDenseMap<const Use *, unsigned, 16> Order;
9046 for (const Use &U : V->uses()) {
9047 if (++NumUses > Indexes.size())
9048 break;
9049 Order[&U] = Indexes[NumUses - 1];
9050 }
9051 if (NumUses < 2)
9052 return error(Loc, "value only has one use");
9053 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9054 return error(Loc,
9055 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9056
9057 V->sortUseList([&](const Use &L, const Use &R) {
9058 return Order.lookup(&L) < Order.lookup(&R);
9059 });
9060 return false;
9061}
9062
9063/// parseUseListOrderIndexes
9064/// ::= '{' uint32 (',' uint32)+ '}'
9065bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9066 SMLoc Loc = Lex.getLoc();
9067 if (parseToken(lltok::lbrace, "expected '{' here"))
9068 return true;
9069 if (Lex.getKind() == lltok::rbrace)
9070 return tokError("expected non-empty list of uselistorder indexes");
9071
9072 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9073 // indexes should be distinct numbers in the range [0, size-1], and should
9074 // not be in order.
9075 unsigned Offset = 0;
9076 unsigned Max = 0;
9077 bool IsOrdered = true;
9078 assert(Indexes.empty() && "Expected empty order vector");
9079 do {
9080 unsigned Index;
9081 if (parseUInt32(Index))
9082 return true;
9083
9084 // Update consistency checks.
9085 Offset += Index - Indexes.size();
9086 Max = std::max(Max, Index);
9087 IsOrdered &= Index == Indexes.size();
9088
9089 Indexes.push_back(Index);
9090 } while (EatIfPresent(lltok::comma));
9091
9092 if (parseToken(lltok::rbrace, "expected '}' here"))
9093 return true;
9094
9095 if (Indexes.size() < 2)
9096 return error(Loc, "expected >= 2 uselistorder indexes");
9097 if (Offset != 0 || Max >= Indexes.size())
9098 return error(Loc,
9099 "expected distinct uselistorder indexes in range [0, size)");
9100 if (IsOrdered)
9101 return error(Loc, "expected uselistorder indexes to change the order");
9102
9103 return false;
9104}
9105
9106/// parseUseListOrder
9107/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9108bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9109 SMLoc Loc = Lex.getLoc();
9110 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9111 return true;
9112
9113 Value *V;
9114 SmallVector<unsigned, 16> Indexes;
9115 if (parseTypeAndValue(V, PFS) ||
9116 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9117 parseUseListOrderIndexes(Indexes))
9118 return true;
9119
9120 return sortUseListOrder(V, Indexes, Loc);
9121}
9122
9123/// parseUseListOrderBB
9124/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9125bool LLParser::parseUseListOrderBB() {
9126 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9127 SMLoc Loc = Lex.getLoc();
9128 Lex.Lex();
9129
9130 ValID Fn, Label;
9131 SmallVector<unsigned, 16> Indexes;
9132 if (parseValID(Fn, /*PFS=*/nullptr) ||
9133 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9134 parseValID(Label, /*PFS=*/nullptr) ||
9135 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9136 parseUseListOrderIndexes(Indexes))
9137 return true;
9138
9139 // Check the function.
9140 GlobalValue *GV;
9141 if (Fn.Kind == ValID::t_GlobalName)
9142 GV = M->getNamedValue(Fn.StrVal);
9143 else if (Fn.Kind == ValID::t_GlobalID)
9144 GV = NumberedVals.get(Fn.UIntVal);
9145 else
9146 return error(Fn.Loc, "expected function name in uselistorder_bb");
9147 if (!GV)
9148 return error(Fn.Loc,
9149 "invalid function forward reference in uselistorder_bb");
9150 auto *F = dyn_cast<Function>(GV);
9151 if (!F)
9152 return error(Fn.Loc, "expected function name in uselistorder_bb");
9153 if (F->isDeclaration())
9154 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9155
9156 // Check the basic block.
9157 if (Label.Kind == ValID::t_LocalID)
9158 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9159 if (Label.Kind != ValID::t_LocalName)
9160 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9161 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9162 if (!V)
9163 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9164 if (!isa<BasicBlock>(V))
9165 return error(Label.Loc, "expected basic block in uselistorder_bb");
9166
9167 return sortUseListOrder(V, Indexes, Loc);
9168}
9169
9170/// ModuleEntry
9171/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9172/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9173bool LLParser::parseModuleEntry(unsigned ID) {
9174 assert(Lex.getKind() == lltok::kw_module);
9175 Lex.Lex();
9176
9177 std::string Path;
9178 if (parseToken(lltok::colon, "expected ':' here") ||
9179 parseToken(lltok::lparen, "expected '(' here") ||
9180 parseToken(lltok::kw_path, "expected 'path' here") ||
9181 parseToken(lltok::colon, "expected ':' here") ||
9182 parseStringConstant(Path) ||
9183 parseToken(lltok::comma, "expected ',' here") ||
9184 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9185 parseToken(lltok::colon, "expected ':' here") ||
9186 parseToken(lltok::lparen, "expected '(' here"))
9187 return true;
9188
9189 ModuleHash Hash;
9190 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9191 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9192 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9193 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9194 parseUInt32(Hash[4]))
9195 return true;
9196
9197 if (parseToken(lltok::rparen, "expected ')' here") ||
9198 parseToken(lltok::rparen, "expected ')' here"))
9199 return true;
9200
9201 auto ModuleEntry = Index->addModule(Path, Hash);
9202 ModuleIdMap[ID] = ModuleEntry->first();
9203
9204 return false;
9205}
9206
9207/// TypeIdEntry
9208/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9209bool LLParser::parseTypeIdEntry(unsigned ID) {
9210 assert(Lex.getKind() == lltok::kw_typeid);
9211 Lex.Lex();
9212
9213 std::string Name;
9214 if (parseToken(lltok::colon, "expected ':' here") ||
9215 parseToken(lltok::lparen, "expected '(' here") ||
9216 parseToken(lltok::kw_name, "expected 'name' here") ||
9217 parseToken(lltok::colon, "expected ':' here") ||
9218 parseStringConstant(Name))
9219 return true;
9220
9221 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9222 if (parseToken(lltok::comma, "expected ',' here") ||
9223 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9224 return true;
9225
9226 // Check if this ID was forward referenced, and if so, update the
9227 // corresponding GUIDs.
9228 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9229 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9230 for (auto TIDRef : FwdRefTIDs->second) {
9231 assert(!*TIDRef.first &&
9232 "Forward referenced type id GUID expected to be 0");
9233 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9234 }
9235 ForwardRefTypeIds.erase(FwdRefTIDs);
9236 }
9237
9238 return false;
9239}
9240
9241/// TypeIdSummary
9242/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9243bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9244 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9245 parseToken(lltok::colon, "expected ':' here") ||
9246 parseToken(lltok::lparen, "expected '(' here") ||
9247 parseTypeTestResolution(TIS.TTRes))
9248 return true;
9249
9250 if (EatIfPresent(lltok::comma)) {
9251 // Expect optional wpdResolutions field
9252 if (parseOptionalWpdResolutions(TIS.WPDRes))
9253 return true;
9254 }
9255
9256 if (parseToken(lltok::rparen, "expected ')' here"))
9257 return true;
9258
9259 return false;
9260}
9261
9263 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9264
9265/// TypeIdCompatibleVtableEntry
9266/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9267/// TypeIdCompatibleVtableInfo
9268/// ')'
9269bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9271 Lex.Lex();
9272
9273 std::string Name;
9274 if (parseToken(lltok::colon, "expected ':' here") ||
9275 parseToken(lltok::lparen, "expected '(' here") ||
9276 parseToken(lltok::kw_name, "expected 'name' here") ||
9277 parseToken(lltok::colon, "expected ':' here") ||
9278 parseStringConstant(Name))
9279 return true;
9280
9282 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9283 if (parseToken(lltok::comma, "expected ',' here") ||
9284 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9285 parseToken(lltok::colon, "expected ':' here") ||
9286 parseToken(lltok::lparen, "expected '(' here"))
9287 return true;
9288
9289 IdToIndexMapType IdToIndexMap;
9290 // parse each call edge
9291 do {
9293 if (parseToken(lltok::lparen, "expected '(' here") ||
9294 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9295 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9296 parseToken(lltok::comma, "expected ',' here"))
9297 return true;
9298
9299 LocTy Loc = Lex.getLoc();
9300 unsigned GVId;
9301 ValueInfo VI;
9302 if (parseGVReference(VI, GVId))
9303 return true;
9304
9305 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9306 // forward reference. We will save the location of the ValueInfo needing an
9307 // update, but can only do so once the std::vector is finalized.
9308 if (VI == EmptyVI)
9309 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9310 TI.push_back({Offset, VI});
9311
9312 if (parseToken(lltok::rparen, "expected ')' in call"))
9313 return true;
9314 } while (EatIfPresent(lltok::comma));
9315
9316 // Now that the TI vector is finalized, it is safe to save the locations
9317 // of any forward GV references that need updating later.
9318 for (auto I : IdToIndexMap) {
9319 auto &Infos = ForwardRefValueInfos[I.first];
9320 for (auto P : I.second) {
9321 assert(TI[P.first].VTableVI == EmptyVI &&
9322 "Forward referenced ValueInfo expected to be empty");
9323 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9324 }
9325 }
9326
9327 if (parseToken(lltok::rparen, "expected ')' here") ||
9328 parseToken(lltok::rparen, "expected ')' here"))
9329 return true;
9330
9331 // Check if this ID was forward referenced, and if so, update the
9332 // corresponding GUIDs.
9333 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9334 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9335 for (auto TIDRef : FwdRefTIDs->second) {
9336 assert(!*TIDRef.first &&
9337 "Forward referenced type id GUID expected to be 0");
9338 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9339 }
9340 ForwardRefTypeIds.erase(FwdRefTIDs);
9341 }
9342
9343 return false;
9344}
9345
9346/// TypeTestResolution
9347/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9348/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9349/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9350/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9351/// [',' 'inlinesBits' ':' UInt64]? ')'
9352bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9353 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9354 parseToken(lltok::colon, "expected ':' here") ||
9355 parseToken(lltok::lparen, "expected '(' here") ||
9356 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9357 parseToken(lltok::colon, "expected ':' here"))
9358 return true;
9359
9360 switch (Lex.getKind()) {
9361 case lltok::kw_unknown:
9363 break;
9364 case lltok::kw_unsat:
9366 break;
9369 break;
9370 case lltok::kw_inline:
9372 break;
9373 case lltok::kw_single:
9375 break;
9376 case lltok::kw_allOnes:
9378 break;
9379 default:
9380 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9381 }
9382 Lex.Lex();
9383
9384 if (parseToken(lltok::comma, "expected ',' here") ||
9385 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9386 parseToken(lltok::colon, "expected ':' here") ||
9387 parseUInt32(TTRes.SizeM1BitWidth))
9388 return true;
9389
9390 // parse optional fields
9391 while (EatIfPresent(lltok::comma)) {
9392 switch (Lex.getKind()) {
9394 Lex.Lex();
9395 if (parseToken(lltok::colon, "expected ':'") ||
9396 parseUInt64(TTRes.AlignLog2))
9397 return true;
9398 break;
9399 case lltok::kw_sizeM1:
9400 Lex.Lex();
9401 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9402 return true;
9403 break;
9404 case lltok::kw_bitMask: {
9405 unsigned Val;
9406 Lex.Lex();
9407 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9408 return true;
9409 assert(Val <= 0xff);
9410 TTRes.BitMask = (uint8_t)Val;
9411 break;
9412 }
9414 Lex.Lex();
9415 if (parseToken(lltok::colon, "expected ':'") ||
9416 parseUInt64(TTRes.InlineBits))
9417 return true;
9418 break;
9419 default:
9420 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9421 }
9422 }
9423
9424 if (parseToken(lltok::rparen, "expected ')' here"))
9425 return true;
9426
9427 return false;
9428}
9429
9430/// OptionalWpdResolutions
9431/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9432/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9433bool LLParser::parseOptionalWpdResolutions(
9434 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9435 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9436 parseToken(lltok::colon, "expected ':' here") ||
9437 parseToken(lltok::lparen, "expected '(' here"))
9438 return true;
9439
9440 do {
9441 uint64_t Offset;
9442 WholeProgramDevirtResolution WPDRes;
9443 if (parseToken(lltok::lparen, "expected '(' here") ||
9444 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9445 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9446 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9447 parseToken(lltok::rparen, "expected ')' here"))
9448 return true;
9449 WPDResMap[Offset] = WPDRes;
9450 } while (EatIfPresent(lltok::comma));
9451
9452 if (parseToken(lltok::rparen, "expected ')' here"))
9453 return true;
9454
9455 return false;
9456}
9457
9458/// WpdRes
9459/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9460/// [',' OptionalResByArg]? ')'
9461/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9462/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9463/// [',' OptionalResByArg]? ')'
9464/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9465/// [',' OptionalResByArg]? ')'
9466bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9467 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9468 parseToken(lltok::colon, "expected ':' here") ||
9469 parseToken(lltok::lparen, "expected '(' here") ||
9470 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9471 parseToken(lltok::colon, "expected ':' here"))
9472 return true;
9473
9474 switch (Lex.getKind()) {
9475 case lltok::kw_indir:
9477 break;
9480 break;
9483 break;
9484 default:
9485 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9486 }
9487 Lex.Lex();
9488
9489 // parse optional fields
9490 while (EatIfPresent(lltok::comma)) {
9491 switch (Lex.getKind()) {
9493 Lex.Lex();
9494 if (parseToken(lltok::colon, "expected ':' here") ||
9495 parseStringConstant(WPDRes.SingleImplName))
9496 return true;
9497 break;
9498 case lltok::kw_resByArg:
9499 if (parseOptionalResByArg(WPDRes.ResByArg))
9500 return true;
9501 break;
9502 default:
9503 return error(Lex.getLoc(),
9504 "expected optional WholeProgramDevirtResolution field");
9505 }
9506 }
9507
9508 if (parseToken(lltok::rparen, "expected ')' here"))
9509 return true;
9510
9511 return false;
9512}
9513
9514/// OptionalResByArg
9515/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9516/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9517/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9518/// 'virtualConstProp' )
9519/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9520/// [',' 'bit' ':' UInt32]? ')'
9521bool LLParser::parseOptionalResByArg(
9522 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9523 &ResByArg) {
9524 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9525 parseToken(lltok::colon, "expected ':' here") ||
9526 parseToken(lltok::lparen, "expected '(' here"))
9527 return true;
9528
9529 do {
9530 std::vector<uint64_t> Args;
9531 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9532 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9533 parseToken(lltok::colon, "expected ':' here") ||
9534 parseToken(lltok::lparen, "expected '(' here") ||
9535 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9536 parseToken(lltok::colon, "expected ':' here"))
9537 return true;
9538
9539 WholeProgramDevirtResolution::ByArg ByArg;
9540 switch (Lex.getKind()) {
9541 case lltok::kw_indir:
9543 break;
9546 break;
9549 break;
9552 break;
9553 default:
9554 return error(Lex.getLoc(),
9555 "unexpected WholeProgramDevirtResolution::ByArg kind");
9556 }
9557 Lex.Lex();
9558
9559 // parse optional fields
9560 while (EatIfPresent(lltok::comma)) {
9561 switch (Lex.getKind()) {
9562 case lltok::kw_info:
9563 Lex.Lex();
9564 if (parseToken(lltok::colon, "expected ':' here") ||
9565 parseUInt64(ByArg.Info))
9566 return true;
9567 break;
9568 case lltok::kw_byte:
9569 Lex.Lex();
9570 if (parseToken(lltok::colon, "expected ':' here") ||
9571 parseUInt32(ByArg.Byte))
9572 return true;
9573 break;
9574 case lltok::kw_bit:
9575 Lex.Lex();
9576 if (parseToken(lltok::colon, "expected ':' here") ||
9577 parseUInt32(ByArg.Bit))
9578 return true;
9579 break;
9580 default:
9581 return error(Lex.getLoc(),
9582 "expected optional whole program devirt field");
9583 }
9584 }
9585
9586 if (parseToken(lltok::rparen, "expected ')' here"))
9587 return true;
9588
9589 ResByArg[Args] = ByArg;
9590 } while (EatIfPresent(lltok::comma));
9591
9592 if (parseToken(lltok::rparen, "expected ')' here"))
9593 return true;
9594
9595 return false;
9596}
9597
9598/// OptionalResByArg
9599/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9600bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9601 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9602 parseToken(lltok::colon, "expected ':' here") ||
9603 parseToken(lltok::lparen, "expected '(' here"))
9604 return true;
9605
9606 do {
9607 uint64_t Val;
9608 if (parseUInt64(Val))
9609 return true;
9610 Args.push_back(Val);
9611 } while (EatIfPresent(lltok::comma));
9612
9613 if (parseToken(lltok::rparen, "expected ')' here"))
9614 return true;
9615
9616 return false;
9617}
9618
9619static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9620
9621static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9622 bool ReadOnly = Fwd->isReadOnly();
9623 bool WriteOnly = Fwd->isWriteOnly();
9624 assert(!(ReadOnly && WriteOnly));
9625 *Fwd = Resolved;
9626 if (ReadOnly)
9627 Fwd->setReadOnly();
9628 if (WriteOnly)
9629 Fwd->setWriteOnly();
9630}
9631
9632/// Stores the given Name/GUID and associated summary into the Index.
9633/// Also updates any forward references to the associated entry ID.
9634bool LLParser::addGlobalValueToIndex(
9635 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9636 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9637 // First create the ValueInfo utilizing the Name or GUID.
9638 ValueInfo VI;
9639 if (GUID != 0) {
9640 assert(Name.empty());
9641 VI = Index->getOrInsertValueInfo(GUID);
9642 } else {
9643 assert(!Name.empty());
9644 if (M) {
9645 auto *GV = M->getNamedValue(Name);
9646 if (!GV)
9647 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9648
9649 VI = Index->getOrInsertValueInfo(GV);
9650 } else {
9651 assert(
9652 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9653 "Need a source_filename to compute GUID for local");
9655 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9656 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9657 }
9658 }
9659
9660 // Resolve forward references from calls/refs
9661 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9662 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9663 for (auto VIRef : FwdRefVIs->second) {
9664 assert(VIRef.first->getRef() == FwdVIRef &&
9665 "Forward referenced ValueInfo expected to be empty");
9666 resolveFwdRef(VIRef.first, VI);
9667 }
9668 ForwardRefValueInfos.erase(FwdRefVIs);
9669 }
9670
9671 // Resolve forward references from aliases
9672 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9673 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9674 for (auto AliaseeRef : FwdRefAliasees->second) {
9675 assert(!AliaseeRef.first->hasAliasee() &&
9676 "Forward referencing alias already has aliasee");
9677 assert(Summary && "Aliasee must be a definition");
9678 AliaseeRef.first->setAliasee(VI, Summary.get());
9679 }
9680 ForwardRefAliasees.erase(FwdRefAliasees);
9681 }
9682
9683 // Add the summary if one was provided.
9684 if (Summary)
9685 Index->addGlobalValueSummary(VI, std::move(Summary));
9686
9687 // Save the associated ValueInfo for use in later references by ID.
9688 if (ID == NumberedValueInfos.size())
9689 NumberedValueInfos.push_back(VI);
9690 else {
9691 // Handle non-continuous numbers (to make test simplification easier).
9692 if (ID > NumberedValueInfos.size())
9693 NumberedValueInfos.resize(ID + 1);
9694 NumberedValueInfos[ID] = VI;
9695 }
9696
9697 return false;
9698}
9699
9700/// parseSummaryIndexFlags
9701/// ::= 'flags' ':' UInt64
9702bool LLParser::parseSummaryIndexFlags() {
9703 assert(Lex.getKind() == lltok::kw_flags);
9704 Lex.Lex();
9705
9706 if (parseToken(lltok::colon, "expected ':' here"))
9707 return true;
9708 uint64_t Flags;
9709 if (parseUInt64(Flags))
9710 return true;
9711 if (Index)
9712 Index->setFlags(Flags);
9713 return false;
9714}
9715
9716/// parseBlockCount
9717/// ::= 'blockcount' ':' UInt64
9718bool LLParser::parseBlockCount() {
9719 assert(Lex.getKind() == lltok::kw_blockcount);
9720 Lex.Lex();
9721
9722 if (parseToken(lltok::colon, "expected ':' here"))
9723 return true;
9724 uint64_t BlockCount;
9725 if (parseUInt64(BlockCount))
9726 return true;
9727 if (Index)
9728 Index->setBlockCount(BlockCount);
9729 return false;
9730}
9731
9732/// parseGVEntry
9733/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9734/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9735/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9736bool LLParser::parseGVEntry(unsigned ID) {
9737 assert(Lex.getKind() == lltok::kw_gv);
9738 Lex.Lex();
9739
9740 if (parseToken(lltok::colon, "expected ':' here") ||
9741 parseToken(lltok::lparen, "expected '(' here"))
9742 return true;
9743
9744 LocTy Loc = Lex.getLoc();
9745 std::string Name;
9747 switch (Lex.getKind()) {
9748 case lltok::kw_name:
9749 Lex.Lex();
9750 if (parseToken(lltok::colon, "expected ':' here") ||
9751 parseStringConstant(Name))
9752 return true;
9753 // Can't create GUID/ValueInfo until we have the linkage.
9754 break;
9755 case lltok::kw_guid:
9756 Lex.Lex();
9757 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9758 return true;
9759 break;
9760 default:
9761 return error(Lex.getLoc(), "expected name or guid tag");
9762 }
9763
9764 if (!EatIfPresent(lltok::comma)) {
9765 // No summaries. Wrap up.
9766 if (parseToken(lltok::rparen, "expected ')' here"))
9767 return true;
9768 // This was created for a call to an external or indirect target.
9769 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9770 // created for indirect calls with VP. A Name with no GUID came from
9771 // an external definition. We pass ExternalLinkage since that is only
9772 // used when the GUID must be computed from Name, and in that case
9773 // the symbol must have external linkage.
9774 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9775 nullptr, Loc);
9776 }
9777
9778 // Have a list of summaries
9779 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9780 parseToken(lltok::colon, "expected ':' here") ||
9781 parseToken(lltok::lparen, "expected '(' here"))
9782 return true;
9783 do {
9784 switch (Lex.getKind()) {
9785 case lltok::kw_function:
9786 if (parseFunctionSummary(Name, GUID, ID))
9787 return true;
9788 break;
9789 case lltok::kw_variable:
9790 if (parseVariableSummary(Name, GUID, ID))
9791 return true;
9792 break;
9793 case lltok::kw_alias:
9794 if (parseAliasSummary(Name, GUID, ID))
9795 return true;
9796 break;
9797 default:
9798 return error(Lex.getLoc(), "expected summary type");
9799 }
9800 } while (EatIfPresent(lltok::comma));
9801
9802 if (parseToken(lltok::rparen, "expected ')' here") ||
9803 parseToken(lltok::rparen, "expected ')' here"))
9804 return true;
9805
9806 return false;
9807}
9808
9809/// FunctionSummary
9810/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9811/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9812/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9813/// [',' OptionalRefs]? ')'
9814bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9815 unsigned ID) {
9816 LocTy Loc = Lex.getLoc();
9817 assert(Lex.getKind() == lltok::kw_function);
9818 Lex.Lex();
9819
9820 StringRef ModulePath;
9821 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9823 /*NotEligibleToImport=*/false,
9824 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9826 unsigned InstCount;
9828 FunctionSummary::TypeIdInfo TypeIdInfo;
9829 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9831 std::vector<CallsiteInfo> Callsites;
9832 std::vector<AllocInfo> Allocs;
9833 // Default is all-zeros (conservative values).
9834 FunctionSummary::FFlags FFlags = {};
9835 if (parseToken(lltok::colon, "expected ':' here") ||
9836 parseToken(lltok::lparen, "expected '(' here") ||
9837 parseModuleReference(ModulePath) ||
9838 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9839 parseToken(lltok::comma, "expected ',' here") ||
9840 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9841 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9842 return true;
9843
9844 // parse optional fields
9845 while (EatIfPresent(lltok::comma)) {
9846 switch (Lex.getKind()) {
9848 if (parseOptionalFFlags(FFlags))
9849 return true;
9850 break;
9851 case lltok::kw_calls:
9852 if (parseOptionalCalls(Calls))
9853 return true;
9854 break;
9856 if (parseOptionalTypeIdInfo(TypeIdInfo))
9857 return true;
9858 break;
9859 case lltok::kw_refs:
9860 if (parseOptionalRefs(Refs))
9861 return true;
9862 break;
9863 case lltok::kw_params:
9864 if (parseOptionalParamAccesses(ParamAccesses))
9865 return true;
9866 break;
9867 case lltok::kw_allocs:
9868 if (parseOptionalAllocs(Allocs))
9869 return true;
9870 break;
9872 if (parseOptionalCallsites(Callsites))
9873 return true;
9874 break;
9875 default:
9876 return error(Lex.getLoc(), "expected optional function summary field");
9877 }
9878 }
9879
9880 if (parseToken(lltok::rparen, "expected ')' here"))
9881 return true;
9882
9883 auto FS = std::make_unique<FunctionSummary>(
9884 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9885 std::move(TypeIdInfo.TypeTests),
9886 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9887 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9888 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9889 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9890 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9891
9892 FS->setModulePath(ModulePath);
9893
9894 return addGlobalValueToIndex(Name, GUID,
9896 std::move(FS), Loc);
9897}
9898
9899/// VariableSummary
9900/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9901/// [',' OptionalRefs]? ')'
9902bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9903 unsigned ID) {
9904 LocTy Loc = Lex.getLoc();
9905 assert(Lex.getKind() == lltok::kw_variable);
9906 Lex.Lex();
9907
9908 StringRef ModulePath;
9909 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9911 /*NotEligibleToImport=*/false,
9912 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9914 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9915 /* WriteOnly */ false,
9916 /* Constant */ false,
9919 VTableFuncList VTableFuncs;
9920 if (parseToken(lltok::colon, "expected ':' here") ||
9921 parseToken(lltok::lparen, "expected '(' here") ||
9922 parseModuleReference(ModulePath) ||
9923 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9924 parseToken(lltok::comma, "expected ',' here") ||
9925 parseGVarFlags(GVarFlags))
9926 return true;
9927
9928 // parse optional fields
9929 while (EatIfPresent(lltok::comma)) {
9930 switch (Lex.getKind()) {
9932 if (parseOptionalVTableFuncs(VTableFuncs))
9933 return true;
9934 break;
9935 case lltok::kw_refs:
9936 if (parseOptionalRefs(Refs))
9937 return true;
9938 break;
9939 default:
9940 return error(Lex.getLoc(), "expected optional variable summary field");
9941 }
9942 }
9943
9944 if (parseToken(lltok::rparen, "expected ')' here"))
9945 return true;
9946
9947 auto GS =
9948 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9949
9950 GS->setModulePath(ModulePath);
9951 GS->setVTableFuncs(std::move(VTableFuncs));
9952
9953 return addGlobalValueToIndex(Name, GUID,
9955 std::move(GS), Loc);
9956}
9957
9958/// AliasSummary
9959/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9960/// 'aliasee' ':' GVReference ')'
9961bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9962 unsigned ID) {
9963 assert(Lex.getKind() == lltok::kw_alias);
9964 LocTy Loc = Lex.getLoc();
9965 Lex.Lex();
9966
9967 StringRef ModulePath;
9968 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9970 /*NotEligibleToImport=*/false,
9971 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9973 if (parseToken(lltok::colon, "expected ':' here") ||
9974 parseToken(lltok::lparen, "expected '(' here") ||
9975 parseModuleReference(ModulePath) ||
9976 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9977 parseToken(lltok::comma, "expected ',' here") ||
9978 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9979 parseToken(lltok::colon, "expected ':' here"))
9980 return true;
9981
9982 ValueInfo AliaseeVI;
9983 unsigned GVId;
9984 if (parseGVReference(AliaseeVI, GVId))
9985 return true;
9986
9987 if (parseToken(lltok::rparen, "expected ')' here"))
9988 return true;
9989
9990 auto AS = std::make_unique<AliasSummary>(GVFlags);
9991
9992 AS->setModulePath(ModulePath);
9993
9994 // Record forward reference if the aliasee is not parsed yet.
9995 if (AliaseeVI.getRef() == FwdVIRef) {
9996 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9997 } else {
9998 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9999 assert(Summary && "Aliasee must be a definition");
10000 AS->setAliasee(AliaseeVI, Summary);
10001 }
10002
10003 return addGlobalValueToIndex(Name, GUID,
10005 std::move(AS), Loc);
10006}
10007
10008/// Flag
10009/// ::= [0|1]
10010bool LLParser::parseFlag(unsigned &Val) {
10011 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10012 return tokError("expected integer");
10013 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10014 Lex.Lex();
10015 return false;
10016}
10017
10018/// OptionalFFlags
10019/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10020/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10021/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10022/// [',' 'noInline' ':' Flag]? ')'
10023/// [',' 'alwaysInline' ':' Flag]? ')'
10024/// [',' 'noUnwind' ':' Flag]? ')'
10025/// [',' 'mayThrow' ':' Flag]? ')'
10026/// [',' 'hasUnknownCall' ':' Flag]? ')'
10027/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10028
10029bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10030 assert(Lex.getKind() == lltok::kw_funcFlags);
10031 Lex.Lex();
10032
10033 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10034 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10035 return true;
10036
10037 do {
10038 unsigned Val = 0;
10039 switch (Lex.getKind()) {
10040 case lltok::kw_readNone:
10041 Lex.Lex();
10042 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10043 return true;
10044 FFlags.ReadNone = Val;
10045 break;
10046 case lltok::kw_readOnly:
10047 Lex.Lex();
10048 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10049 return true;
10050 FFlags.ReadOnly = Val;
10051 break;
10053 Lex.Lex();
10054 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10055 return true;
10056 FFlags.NoRecurse = Val;
10057 break;
10059 Lex.Lex();
10060 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10061 return true;
10062 FFlags.ReturnDoesNotAlias = Val;
10063 break;
10064 case lltok::kw_noInline:
10065 Lex.Lex();
10066 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10067 return true;
10068 FFlags.NoInline = Val;
10069 break;
10071 Lex.Lex();
10072 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10073 return true;
10074 FFlags.AlwaysInline = Val;
10075 break;
10076 case lltok::kw_noUnwind:
10077 Lex.Lex();
10078 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10079 return true;
10080 FFlags.NoUnwind = Val;
10081 break;
10082 case lltok::kw_mayThrow:
10083 Lex.Lex();
10084 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10085 return true;
10086 FFlags.MayThrow = Val;
10087 break;
10089 Lex.Lex();
10090 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10091 return true;
10092 FFlags.HasUnknownCall = Val;
10093 break;
10095 Lex.Lex();
10096 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10097 return true;
10098 FFlags.MustBeUnreachable = Val;
10099 break;
10100 default:
10101 return error(Lex.getLoc(), "expected function flag type");
10102 }
10103 } while (EatIfPresent(lltok::comma));
10104
10105 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10106 return true;
10107
10108 return false;
10109}
10110
10111/// OptionalCalls
10112/// := 'calls' ':' '(' Call [',' Call]* ')'
10113/// Call ::= '(' 'callee' ':' GVReference
10114/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10115/// [ ',' 'tail' ]? ')'
10116bool LLParser::parseOptionalCalls(
10117 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10118 assert(Lex.getKind() == lltok::kw_calls);
10119 Lex.Lex();
10120
10121 if (parseToken(lltok::colon, "expected ':' in calls") ||
10122 parseToken(lltok::lparen, "expected '(' in calls"))
10123 return true;
10124
10125 IdToIndexMapType IdToIndexMap;
10126 // parse each call edge
10127 do {
10128 ValueInfo VI;
10129 if (parseToken(lltok::lparen, "expected '(' in call") ||
10130 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10131 parseToken(lltok::colon, "expected ':'"))
10132 return true;
10133
10134 LocTy Loc = Lex.getLoc();
10135 unsigned GVId;
10136 if (parseGVReference(VI, GVId))
10137 return true;
10138
10140 unsigned RelBF = 0;
10141 unsigned HasTailCall = false;
10142
10143 // parse optional fields
10144 while (EatIfPresent(lltok::comma)) {
10145 switch (Lex.getKind()) {
10146 case lltok::kw_hotness:
10147 Lex.Lex();
10148 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10149 return true;
10150 break;
10151 case lltok::kw_relbf:
10152 Lex.Lex();
10153 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10154 return true;
10155 break;
10156 case lltok::kw_tail:
10157 Lex.Lex();
10158 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10159 return true;
10160 break;
10161 default:
10162 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10163 }
10164 }
10165 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
10166 return tokError("Expected only one of hotness or relbf");
10167 // Keep track of the Call array index needing a forward reference.
10168 // We will save the location of the ValueInfo needing an update, but
10169 // can only do so once the std::vector is finalized.
10170 if (VI.getRef() == FwdVIRef)
10171 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10172 Calls.push_back(
10173 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
10174
10175 if (parseToken(lltok::rparen, "expected ')' in call"))
10176 return true;
10177 } while (EatIfPresent(lltok::comma));
10178
10179 // Now that the Calls vector is finalized, it is safe to save the locations
10180 // of any forward GV references that need updating later.
10181 for (auto I : IdToIndexMap) {
10182 auto &Infos = ForwardRefValueInfos[I.first];
10183 for (auto P : I.second) {
10184 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10185 "Forward referenced ValueInfo expected to be empty");
10186 Infos.emplace_back(&Calls[P.first].first, P.second);
10187 }
10188 }
10189
10190 if (parseToken(lltok::rparen, "expected ')' in calls"))
10191 return true;
10192
10193 return false;
10194}
10195
10196/// Hotness
10197/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10198bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10199 switch (Lex.getKind()) {
10200 case lltok::kw_unknown:
10202 break;
10203 case lltok::kw_cold:
10205 break;
10206 case lltok::kw_none:
10208 break;
10209 case lltok::kw_hot:
10211 break;
10212 case lltok::kw_critical:
10214 break;
10215 default:
10216 return error(Lex.getLoc(), "invalid call edge hotness");
10217 }
10218 Lex.Lex();
10219 return false;
10220}
10221
10222/// OptionalVTableFuncs
10223/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10224/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10225bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10226 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10227 Lex.Lex();
10228
10229 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10230 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10231 return true;
10232
10233 IdToIndexMapType IdToIndexMap;
10234 // parse each virtual function pair
10235 do {
10236 ValueInfo VI;
10237 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10238 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10239 parseToken(lltok::colon, "expected ':'"))
10240 return true;
10241
10242 LocTy Loc = Lex.getLoc();
10243 unsigned GVId;
10244 if (parseGVReference(VI, GVId))
10245 return true;
10246
10247 uint64_t Offset;
10248 if (parseToken(lltok::comma, "expected comma") ||
10249 parseToken(lltok::kw_offset, "expected offset") ||
10250 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10251 return true;
10252
10253 // Keep track of the VTableFuncs array index needing a forward reference.
10254 // We will save the location of the ValueInfo needing an update, but
10255 // can only do so once the std::vector is finalized.
10256 if (VI == EmptyVI)
10257 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10258 VTableFuncs.push_back({VI, Offset});
10259
10260 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10261 return true;
10262 } while (EatIfPresent(lltok::comma));
10263
10264 // Now that the VTableFuncs vector is finalized, it is safe to save the
10265 // locations of any forward GV references that need updating later.
10266 for (auto I : IdToIndexMap) {
10267 auto &Infos = ForwardRefValueInfos[I.first];
10268 for (auto P : I.second) {
10269 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10270 "Forward referenced ValueInfo expected to be empty");
10271 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10272 }
10273 }
10274
10275 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10276 return true;
10277
10278 return false;
10279}
10280
10281/// ParamNo := 'param' ':' UInt64
10282bool LLParser::parseParamNo(uint64_t &ParamNo) {
10283 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10284 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10285 return true;
10286 return false;
10287}
10288
10289/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10290bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10291 APSInt Lower;
10292 APSInt Upper;
10293 auto ParseAPSInt = [&](APSInt &Val) {
10294 if (Lex.getKind() != lltok::APSInt)
10295 return tokError("expected integer");
10296 Val = Lex.getAPSIntVal();
10297 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10298 Val.setIsSigned(true);
10299 Lex.Lex();
10300 return false;
10301 };
10302 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10303 parseToken(lltok::colon, "expected ':' here") ||
10304 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10305 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10306 parseToken(lltok::rsquare, "expected ']' here"))
10307 return true;
10308
10309 ++Upper;
10310 Range =
10311 (Lower == Upper && !Lower.isMaxValue())
10312 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10313 : ConstantRange(Lower, Upper);
10314
10315 return false;
10316}
10317
10318/// ParamAccessCall
10319/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10320bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10321 IdLocListType &IdLocList) {
10322 if (parseToken(lltok::lparen, "expected '(' here") ||
10323 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10324 parseToken(lltok::colon, "expected ':' here"))
10325 return true;
10326
10327 unsigned GVId;
10328 ValueInfo VI;
10329 LocTy Loc = Lex.getLoc();
10330 if (parseGVReference(VI, GVId))
10331 return true;
10332
10333 Call.Callee = VI;
10334 IdLocList.emplace_back(GVId, Loc);
10335
10336 if (parseToken(lltok::comma, "expected ',' here") ||
10337 parseParamNo(Call.ParamNo) ||
10338 parseToken(lltok::comma, "expected ',' here") ||
10339 parseParamAccessOffset(Call.Offsets))
10340 return true;
10341
10342 if (parseToken(lltok::rparen, "expected ')' here"))
10343 return true;
10344
10345 return false;
10346}
10347
10348/// ParamAccess
10349/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10350/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10351bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10352 IdLocListType &IdLocList) {
10353 if (parseToken(lltok::lparen, "expected '(' here") ||
10354 parseParamNo(Param.ParamNo) ||
10355 parseToken(lltok::comma, "expected ',' here") ||
10356 parseParamAccessOffset(Param.Use))
10357 return true;
10358
10359 if (EatIfPresent(lltok::comma)) {
10360 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10361 parseToken(lltok::colon, "expected ':' here") ||
10362 parseToken(lltok::lparen, "expected '(' here"))
10363 return true;
10364 do {
10365 FunctionSummary::ParamAccess::Call Call;
10366 if (parseParamAccessCall(Call, IdLocList))
10367 return true;
10368 Param.Calls.push_back(Call);
10369 } while (EatIfPresent(lltok::comma));
10370
10371 if (parseToken(lltok::rparen, "expected ')' here"))
10372 return true;
10373 }
10374
10375 if (parseToken(lltok::rparen, "expected ')' here"))
10376 return true;
10377
10378 return false;
10379}
10380
10381/// OptionalParamAccesses
10382/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10383bool LLParser::parseOptionalParamAccesses(
10384 std::vector<FunctionSummary::ParamAccess> &Params) {
10385 assert(Lex.getKind() == lltok::kw_params);
10386 Lex.Lex();
10387
10388 if (parseToken(lltok::colon, "expected ':' here") ||
10389 parseToken(lltok::lparen, "expected '(' here"))
10390 return true;
10391
10392 IdLocListType VContexts;
10393 size_t CallsNum = 0;
10394 do {
10395 FunctionSummary::ParamAccess ParamAccess;
10396 if (parseParamAccess(ParamAccess, VContexts))
10397 return true;
10398 CallsNum += ParamAccess.Calls.size();
10399 assert(VContexts.size() == CallsNum);
10400 (void)CallsNum;
10401 Params.emplace_back(std::move(ParamAccess));
10402 } while (EatIfPresent(lltok::comma));
10403
10404 if (parseToken(lltok::rparen, "expected ')' here"))
10405 return true;
10406
10407 // Now that the Params is finalized, it is safe to save the locations
10408 // of any forward GV references that need updating later.
10409 IdLocListType::const_iterator ItContext = VContexts.begin();
10410 for (auto &PA : Params) {
10411 for (auto &C : PA.Calls) {
10412 if (C.Callee.getRef() == FwdVIRef)
10413 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10414 ItContext->second);
10415 ++ItContext;
10416 }
10417 }
10418 assert(ItContext == VContexts.end());
10419
10420 return false;
10421}
10422
10423/// OptionalRefs
10424/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10425bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10426 assert(Lex.getKind() == lltok::kw_refs);
10427 Lex.Lex();
10428
10429 if (parseToken(lltok::colon, "expected ':' in refs") ||
10430 parseToken(lltok::lparen, "expected '(' in refs"))
10431 return true;
10432
10433 struct ValueContext {
10434 ValueInfo VI;
10435 unsigned GVId;
10436 LocTy Loc;
10437 };
10438 std::vector<ValueContext> VContexts;
10439 // parse each ref edge
10440 do {
10441 ValueContext VC;
10442 VC.Loc = Lex.getLoc();
10443 if (parseGVReference(VC.VI, VC.GVId))
10444 return true;
10445 VContexts.push_back(VC);
10446 } while (EatIfPresent(lltok::comma));
10447
10448 // Sort value contexts so that ones with writeonly
10449 // and readonly ValueInfo are at the end of VContexts vector.
10450 // See FunctionSummary::specialRefCounts()
10451 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10452 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10453 });
10454
10455 IdToIndexMapType IdToIndexMap;
10456 for (auto &VC : VContexts) {
10457 // Keep track of the Refs array index needing a forward reference.
10458 // We will save the location of the ValueInfo needing an update, but
10459 // can only do so once the std::vector is finalized.
10460 if (VC.VI.getRef() == FwdVIRef)
10461 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10462 Refs.push_back(VC.VI);
10463 }
10464
10465 // Now that the Refs vector is finalized, it is safe to save the locations
10466 // of any forward GV references that need updating later.
10467 for (auto I : IdToIndexMap) {
10468 auto &Infos = ForwardRefValueInfos[I.first];
10469 for (auto P : I.second) {
10470 assert(Refs[P.first].getRef() == FwdVIRef &&
10471 "Forward referenced ValueInfo expected to be empty");
10472 Infos.emplace_back(&Refs[P.first], P.second);
10473 }
10474 }
10475
10476 if (parseToken(lltok::rparen, "expected ')' in refs"))
10477 return true;
10478
10479 return false;
10480}
10481
10482/// OptionalTypeIdInfo
10483/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10484/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10485/// [',' TypeCheckedLoadConstVCalls]? ')'
10486bool LLParser::parseOptionalTypeIdInfo(
10487 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10488 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10489 Lex.Lex();
10490
10491 if (parseToken(lltok::colon, "expected ':' here") ||
10492 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10493 return true;
10494
10495 do {
10496 switch (Lex.getKind()) {
10498 if (parseTypeTests(TypeIdInfo.TypeTests))
10499 return true;
10500 break;
10502 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10503 TypeIdInfo.TypeTestAssumeVCalls))
10504 return true;
10505 break;
10507 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10508 TypeIdInfo.TypeCheckedLoadVCalls))
10509 return true;
10510 break;
10512 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10513 TypeIdInfo.TypeTestAssumeConstVCalls))
10514 return true;
10515 break;
10517 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10518 TypeIdInfo.TypeCheckedLoadConstVCalls))
10519 return true;
10520 break;
10521 default:
10522 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10523 }
10524 } while (EatIfPresent(lltok::comma));
10525
10526 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10527 return true;
10528
10529 return false;
10530}
10531
10532/// TypeTests
10533/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10534/// [',' (SummaryID | UInt64)]* ')'
10535bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10536 assert(Lex.getKind() == lltok::kw_typeTests);
10537 Lex.Lex();
10538
10539 if (parseToken(lltok::colon, "expected ':' here") ||
10540 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10541 return true;
10542
10543 IdToIndexMapType IdToIndexMap;
10544 do {
10546 if (Lex.getKind() == lltok::SummaryID) {
10547 unsigned ID = Lex.getUIntVal();
10548 LocTy Loc = Lex.getLoc();
10549 // Keep track of the TypeTests array index needing a forward reference.
10550 // We will save the location of the GUID needing an update, but
10551 // can only do so once the std::vector is finalized.
10552 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10553 Lex.Lex();
10554 } else if (parseUInt64(GUID))
10555 return true;
10556 TypeTests.push_back(GUID);
10557 } while (EatIfPresent(lltok::comma));
10558
10559 // Now that the TypeTests vector is finalized, it is safe to save the
10560 // locations of any forward GV references that need updating later.
10561 for (auto I : IdToIndexMap) {
10562 auto &Ids = ForwardRefTypeIds[I.first];
10563 for (auto P : I.second) {
10564 assert(TypeTests[P.first] == 0 &&
10565 "Forward referenced type id GUID expected to be 0");
10566 Ids.emplace_back(&TypeTests[P.first], P.second);
10567 }
10568 }
10569
10570 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10571 return true;
10572
10573 return false;
10574}
10575
10576/// VFuncIdList
10577/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10578bool LLParser::parseVFuncIdList(
10579 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10580 assert(Lex.getKind() == Kind);
10581 Lex.Lex();
10582
10583 if (parseToken(lltok::colon, "expected ':' here") ||
10584 parseToken(lltok::lparen, "expected '(' here"))
10585 return true;
10586
10587 IdToIndexMapType IdToIndexMap;
10588 do {
10589 FunctionSummary::VFuncId VFuncId;
10590 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10591 return true;
10592 VFuncIdList.push_back(VFuncId);
10593 } while (EatIfPresent(lltok::comma));
10594
10595 if (parseToken(lltok::rparen, "expected ')' here"))
10596 return true;
10597
10598 // Now that the VFuncIdList vector is finalized, it is safe to save the
10599 // locations of any forward GV references that need updating later.
10600 for (auto I : IdToIndexMap) {
10601 auto &Ids = ForwardRefTypeIds[I.first];
10602 for (auto P : I.second) {
10603 assert(VFuncIdList[P.first].GUID == 0 &&
10604 "Forward referenced type id GUID expected to be 0");
10605 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10606 }
10607 }
10608
10609 return false;
10610}
10611
10612/// ConstVCallList
10613/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10614bool LLParser::parseConstVCallList(
10615 lltok::Kind Kind,
10616 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10617 assert(Lex.getKind() == Kind);
10618 Lex.Lex();
10619
10620 if (parseToken(lltok::colon, "expected ':' here") ||
10621 parseToken(lltok::lparen, "expected '(' here"))
10622 return true;
10623
10624 IdToIndexMapType IdToIndexMap;
10625 do {
10626 FunctionSummary::ConstVCall ConstVCall;
10627 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10628 return true;
10629 ConstVCallList.push_back(ConstVCall);
10630 } while (EatIfPresent(lltok::comma));
10631
10632 if (parseToken(lltok::rparen, "expected ')' here"))
10633 return true;
10634
10635 // Now that the ConstVCallList vector is finalized, it is safe to save the
10636 // locations of any forward GV references that need updating later.
10637 for (auto I : IdToIndexMap) {
10638 auto &Ids = ForwardRefTypeIds[I.first];
10639 for (auto P : I.second) {
10640 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10641 "Forward referenced type id GUID expected to be 0");
10642 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10643 }
10644 }
10645
10646 return false;
10647}
10648
10649/// ConstVCall
10650/// ::= '(' VFuncId ',' Args ')'
10651bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10652 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10653 if (parseToken(lltok::lparen, "expected '(' here") ||
10654 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10655 return true;
10656
10657 if (EatIfPresent(lltok::comma))
10658 if (parseArgs(ConstVCall.Args))
10659 return true;
10660
10661 if (parseToken(lltok::rparen, "expected ')' here"))
10662 return true;
10663
10664 return false;
10665}
10666
10667/// VFuncId
10668/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10669/// 'offset' ':' UInt64 ')'
10670bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10671 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10672 assert(Lex.getKind() == lltok::kw_vFuncId);
10673 Lex.Lex();
10674
10675 if (parseToken(lltok::colon, "expected ':' here") ||
10676 parseToken(lltok::lparen, "expected '(' here"))
10677 return true;
10678
10679 if (Lex.getKind() == lltok::SummaryID) {
10680 VFuncId.GUID = 0;
10681 unsigned ID = Lex.getUIntVal();
10682 LocTy Loc = Lex.getLoc();
10683 // Keep track of the array index needing a forward reference.
10684 // We will save the location of the GUID needing an update, but
10685 // can only do so once the caller's std::vector is finalized.
10686 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10687 Lex.Lex();
10688 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10689 parseToken(lltok::colon, "expected ':' here") ||
10690 parseUInt64(VFuncId.GUID))
10691 return true;
10692
10693 if (parseToken(lltok::comma, "expected ',' here") ||
10694 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10695 parseToken(lltok::colon, "expected ':' here") ||
10696 parseUInt64(VFuncId.Offset) ||
10697 parseToken(lltok::rparen, "expected ')' here"))
10698 return true;
10699
10700 return false;
10701}
10702
10703/// GVFlags
10704/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10705/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10706/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10707/// 'canAutoHide' ':' Flag ',' ')'
10708bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10709 assert(Lex.getKind() == lltok::kw_flags);
10710 Lex.Lex();
10711
10712 if (parseToken(lltok::colon, "expected ':' here") ||
10713 parseToken(lltok::lparen, "expected '(' here"))
10714 return true;
10715
10716 do {
10717 unsigned Flag = 0;
10718 switch (Lex.getKind()) {
10719 case lltok::kw_linkage:
10720 Lex.Lex();
10721 if (parseToken(lltok::colon, "expected ':'"))
10722 return true;
10723 bool HasLinkage;
10724 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10725 assert(HasLinkage && "Linkage not optional in summary entry");
10726 Lex.Lex();
10727 break;
10729 Lex.Lex();
10730 if (parseToken(lltok::colon, "expected ':'"))
10731 return true;
10732 parseOptionalVisibility(Flag);
10733 GVFlags.Visibility = Flag;
10734 break;
10736 Lex.Lex();
10737 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10738 return true;
10739 GVFlags.NotEligibleToImport = Flag;
10740 break;
10741 case lltok::kw_live:
10742 Lex.Lex();
10743 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10744 return true;
10745 GVFlags.Live = Flag;
10746 break;
10747 case lltok::kw_dsoLocal:
10748 Lex.Lex();
10749 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10750 return true;
10751 GVFlags.DSOLocal = Flag;
10752 break;
10754 Lex.Lex();
10755 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10756 return true;
10757 GVFlags.CanAutoHide = Flag;
10758 break;
10760 Lex.Lex();
10761 if (parseToken(lltok::colon, "expected ':'"))
10762 return true;
10764 if (parseOptionalImportType(Lex.getKind(), IK))
10765 return true;
10766 GVFlags.ImportType = static_cast<unsigned>(IK);
10767 Lex.Lex();
10768 break;
10769 default:
10770 return error(Lex.getLoc(), "expected gv flag type");
10771 }
10772 } while (EatIfPresent(lltok::comma));
10773
10774 if (parseToken(lltok::rparen, "expected ')' here"))
10775 return true;
10776
10777 return false;
10778}
10779
10780/// GVarFlags
10781/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10782/// ',' 'writeonly' ':' Flag
10783/// ',' 'constant' ':' Flag ')'
10784bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10785 assert(Lex.getKind() == lltok::kw_varFlags);
10786 Lex.Lex();
10787
10788 if (parseToken(lltok::colon, "expected ':' here") ||
10789 parseToken(lltok::lparen, "expected '(' here"))
10790 return true;
10791
10792 auto ParseRest = [this](unsigned int &Val) {
10793 Lex.Lex();
10794 if (parseToken(lltok::colon, "expected ':'"))
10795 return true;
10796 return parseFlag(Val);
10797 };
10798
10799 do {
10800 unsigned Flag = 0;
10801 switch (Lex.getKind()) {
10802 case lltok::kw_readonly:
10803 if (ParseRest(Flag))
10804 return true;
10805 GVarFlags.MaybeReadOnly = Flag;
10806 break;
10807 case lltok::kw_writeonly:
10808 if (ParseRest(Flag))
10809 return true;
10810 GVarFlags.MaybeWriteOnly = Flag;
10811 break;
10812 case lltok::kw_constant:
10813 if (ParseRest(Flag))
10814 return true;
10815 GVarFlags.Constant = Flag;
10816 break;
10818 if (ParseRest(Flag))
10819 return true;
10820 GVarFlags.VCallVisibility = Flag;
10821 break;
10822 default:
10823 return error(Lex.getLoc(), "expected gvar flag type");
10824 }
10825 } while (EatIfPresent(lltok::comma));
10826 return parseToken(lltok::rparen, "expected ')' here");
10827}
10828
10829/// ModuleReference
10830/// ::= 'module' ':' UInt
10831bool LLParser::parseModuleReference(StringRef &ModulePath) {
10832 // parse module id.
10833 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10834 parseToken(lltok::colon, "expected ':' here") ||
10835 parseToken(lltok::SummaryID, "expected module ID"))
10836 return true;
10837
10838 unsigned ModuleID = Lex.getUIntVal();
10839 auto I = ModuleIdMap.find(ModuleID);
10840 // We should have already parsed all module IDs
10841 assert(I != ModuleIdMap.end());
10842 ModulePath = I->second;
10843 return false;
10844}
10845
10846/// GVReference
10847/// ::= SummaryID
10848bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10849 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10850 if (!ReadOnly)
10851 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10852 if (parseToken(lltok::SummaryID, "expected GV ID"))
10853 return true;
10854
10855 GVId = Lex.getUIntVal();
10856 // Check if we already have a VI for this GV
10857 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10858 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10859 VI = NumberedValueInfos[GVId];
10860 } else
10861 // We will create a forward reference to the stored location.
10862 VI = ValueInfo(false, FwdVIRef);
10863
10864 if (ReadOnly)
10865 VI.setReadOnly();
10866 if (WriteOnly)
10867 VI.setWriteOnly();
10868 return false;
10869}
10870
10871/// OptionalAllocs
10872/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10873/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10874/// ',' MemProfs ')'
10875/// Version ::= UInt32
10876bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10877 assert(Lex.getKind() == lltok::kw_allocs);
10878 Lex.Lex();
10879
10880 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10881 parseToken(lltok::lparen, "expected '(' in allocs"))
10882 return true;
10883
10884 // parse each alloc
10885 do {
10886 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10887 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10888 parseToken(lltok::colon, "expected ':'") ||
10889 parseToken(lltok::lparen, "expected '(' in versions"))
10890 return true;
10891
10892 SmallVector<uint8_t> Versions;
10893 do {
10894 uint8_t V = 0;
10895 if (parseAllocType(V))
10896 return true;
10897 Versions.push_back(V);
10898 } while (EatIfPresent(lltok::comma));
10899
10900 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10901 parseToken(lltok::comma, "expected ',' in alloc"))
10902 return true;
10903
10904 std::vector<MIBInfo> MIBs;
10905 if (parseMemProfs(MIBs))
10906 return true;
10907
10908 Allocs.push_back({Versions, MIBs});
10909
10910 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10911 return true;
10912 } while (EatIfPresent(lltok::comma));
10913
10914 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10915 return true;
10916
10917 return false;
10918}
10919
10920/// MemProfs
10921/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10922/// MemProf ::= '(' 'type' ':' AllocType
10923/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10924/// StackId ::= UInt64
10925bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10926 assert(Lex.getKind() == lltok::kw_memProf);
10927 Lex.Lex();
10928
10929 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10930 parseToken(lltok::lparen, "expected '(' in memprof"))
10931 return true;
10932
10933 // parse each MIB
10934 do {
10935 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10936 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10937 parseToken(lltok::colon, "expected ':'"))
10938 return true;
10939
10940 uint8_t AllocType;
10941 if (parseAllocType(AllocType))
10942 return true;
10943
10944 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10945 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10946 parseToken(lltok::colon, "expected ':'") ||
10947 parseToken(lltok::lparen, "expected '(' in stackIds"))
10948 return true;
10949
10950 SmallVector<unsigned> StackIdIndices;
10951 // Combined index alloc records may not have a stack id list.
10952 if (Lex.getKind() != lltok::rparen) {
10953 do {
10954 uint64_t StackId = 0;
10955 if (parseUInt64(StackId))
10956 return true;
10957 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10958 } while (EatIfPresent(lltok::comma));
10959 }
10960
10961 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10962 return true;
10963
10964 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10965
10966 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10967 return true;
10968 } while (EatIfPresent(lltok::comma));
10969
10970 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10971 return true;
10972
10973 return false;
10974}
10975
10976/// AllocType
10977/// := ('none'|'notcold'|'cold'|'hot')
10978bool LLParser::parseAllocType(uint8_t &AllocType) {
10979 switch (Lex.getKind()) {
10980 case lltok::kw_none:
10982 break;
10983 case lltok::kw_notcold:
10985 break;
10986 case lltok::kw_cold:
10988 break;
10989 case lltok::kw_hot:
10990 AllocType = (uint8_t)AllocationType::Hot;
10991 break;
10992 default:
10993 return error(Lex.getLoc(), "invalid alloc type");
10994 }
10995 Lex.Lex();
10996 return false;
10997}
10998
10999/// OptionalCallsites
11000/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11001/// Callsite ::= '(' 'callee' ':' GVReference
11002/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11003/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11004/// Version ::= UInt32
11005/// StackId ::= UInt64
11006bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11007 assert(Lex.getKind() == lltok::kw_callsites);
11008 Lex.Lex();
11009
11010 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11011 parseToken(lltok::lparen, "expected '(' in callsites"))
11012 return true;
11013
11014 IdToIndexMapType IdToIndexMap;
11015 // parse each callsite
11016 do {
11017 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11018 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11019 parseToken(lltok::colon, "expected ':'"))
11020 return true;
11021
11022 ValueInfo VI;
11023 unsigned GVId = 0;
11024 LocTy Loc = Lex.getLoc();
11025 if (!EatIfPresent(lltok::kw_null)) {
11026 if (parseGVReference(VI, GVId))
11027 return true;
11028 }
11029
11030 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11031 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11032 parseToken(lltok::colon, "expected ':'") ||
11033 parseToken(lltok::lparen, "expected '(' in clones"))
11034 return true;
11035
11036 SmallVector<unsigned> Clones;
11037 do {
11038 unsigned V = 0;
11039 if (parseUInt32(V))
11040 return true;
11041 Clones.push_back(V);
11042 } while (EatIfPresent(lltok::comma));
11043
11044 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11045 parseToken(lltok::comma, "expected ',' in callsite") ||
11046 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11047 parseToken(lltok::colon, "expected ':'") ||
11048 parseToken(lltok::lparen, "expected '(' in stackIds"))
11049 return true;
11050
11051 SmallVector<unsigned> StackIdIndices;
11052 // Synthesized callsite records will not have a stack id list.
11053 if (Lex.getKind() != lltok::rparen) {
11054 do {
11055 uint64_t StackId = 0;
11056 if (parseUInt64(StackId))
11057 return true;
11058 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11059 } while (EatIfPresent(lltok::comma));
11060 }
11061
11062 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11063 return true;
11064
11065 // Keep track of the Callsites array index needing a forward reference.
11066 // We will save the location of the ValueInfo needing an update, but
11067 // can only do so once the SmallVector is finalized.
11068 if (VI.getRef() == FwdVIRef)
11069 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11070 Callsites.push_back({VI, Clones, StackIdIndices});
11071
11072 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11073 return true;
11074 } while (EatIfPresent(lltok::comma));
11075
11076 // Now that the Callsites vector is finalized, it is safe to save the
11077 // locations of any forward GV references that need updating later.
11078 for (auto I : IdToIndexMap) {
11079 auto &Infos = ForwardRefValueInfos[I.first];
11080 for (auto P : I.second) {
11081 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11082 "Forward referenced ValueInfo expected to be empty");
11083 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11084 }
11085 }
11086
11087 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11088 return true;
11089
11090 return false;
11091}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:244
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:151
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:67
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp: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
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:296
static const fltSemantics & BFloat()
Definition APFloat.h:295
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
static const fltSemantics & IEEEhalf()
Definition APFloat.h:294
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1110
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1238
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:120
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h: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:765
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:107
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:88
@ None
No attributes have been set.
Definition Attributes.h:90
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:372
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1387
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1274
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:131
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:157
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h: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:56
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition Type.cpp:403
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:398
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:839
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:451
arg_iterator arg_begin()
Definition Function.h:866
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1038
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:274
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:598
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition Globals.cpp:655
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:245
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:93
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:251
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:228
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:524
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:566
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h: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:123
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:215
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:107
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:94
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:75
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1078
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1577
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
A single uniqued string.
Definition Metadata.h:721
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1537
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1526
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1546
static MemoryEffectsBase readOnly()
Definition ModRef.h:130
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:198
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:140
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:146
static MemoryEffectsBase writeOnly()
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:163
static MemoryEffectsBase none()
Definition ModRef.h:125
static MemoryEffectsBase unknown()
Definition ModRef.h:120
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:183
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:875
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:143
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:413
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:619
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:703
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:538
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:440
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:913
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:287
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:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:281
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:249
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:294
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:258
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:503
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
static constexpr uint64_t MaximumAlignment
Definition Value.h:830
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:598
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:631
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:703
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
@ 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:153
@ kw_riscv_vls_cc
Definition LLToken.h:189
@ kw_cxx_fast_tlscc
Definition LLToken.h:172
@ kw_extractvalue
Definition LLToken.h:366
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:501
@ kw_arm_apcscc
Definition LLToken.h:145
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:140
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:151
@ kw_provenance
Definition LLToken.h:222
@ kw_mustBeUnreachable
Definition LLToken.h:412
@ kw_internal
Definition LLToken.h:54
@ kw_no_sanitize_hwaddress
Definition LLToken.h:480
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:451
@ kw_canAutoHide
Definition LLToken.h:396
@ kw_alwaysInline
Definition LLToken.h:408
@ kw_insertelement
Definition LLToken.h:363
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:192
@ kw_inaccessiblememonly
Definition LLToken.h:215
@ kw_amdgpu_gfx
Definition LLToken.h:183
@ kw_getelementptr
Definition LLToken.h:360
@ kw_m68k_rtdcc
Definition LLToken.h:186
@ kw_preserve_nonecc
Definition LLToken.h:167
@ kw_x86_fastcallcc
Definition LLToken.h:141
@ kw_visibility
Definition LLToken.h:392
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:191
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:454
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:139
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:431
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:149
@ kw_amdgpu_kernel
Definition LLToken.h:182
@ kw_uselistorder
Definition LLToken.h:379
@ kw_blockcount
Definition LLToken.h:390
@ kw_notEligibleToImport
Definition LLToken.h:393
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:143
@ kw_ptx_device
Definition LLToken.h:157
@ kw_personality
Definition LLToken.h:335
@ DwarfEnumKind
Definition LLToken.h:514
@ kw_declaration
Definition LLToken.h:399
@ DwarfAttEncoding
Definition LLToken.h:500
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:158
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:411
@ kw_x86_intrcc
Definition LLToken.h:169
@ kw_addrspacecast
Definition LLToken.h:330
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:498
@ kw_x86_thiscallcc
Definition LLToken.h:142
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:190
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:380
@ NameTableKind
Definition LLToken.h:506
@ kw_inlineBits
Definition LLToken.h:449
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:214
@ kw_blockaddress
Definition LLToken.h:368
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:184
@ kw_landingpad
Definition LLToken.h:334
@ kw_aarch64_vector_pcs
Definition LLToken.h:148
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:430
@ FixedPointKind
Definition LLToken.h:507
@ kw_target_mem1
Definition LLToken.h:210
@ kw_ptx_kernel
Definition LLToken.h:156
@ kw_extractelement
Definition LLToken.h:362
@ kw_branchFunnel
Definition LLToken.h:455
@ kw_typeidCompatibleVTable
Definition LLToken.h:436
@ kw_vTableFuncs
Definition LLToken.h:422
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:429
@ kw_no_sanitize_address
Definition LLToken.h:477
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:216
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:483
@ DwarfSourceLangName
Definition LLToken.h:503
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:181
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:348
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:146
@ kw_read_provenance
Definition LLToken.h:223
@ kw_cleanuppad
Definition LLToken.h:351
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:456
@ kw_target_mem0
Definition LLToken.h:209
@ kw_swifttailcc
Definition LLToken.h:164
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:428
@ kw_attributes
Definition LLToken.h:195
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:459
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:445
@ kw_nodeduplicate
Definition LLToken.h:252
@ kw_avr_signalcc
Definition LLToken.h:155
@ kw_exactmatch
Definition LLToken.h:250
@ kw_unreachable
Definition LLToken.h:346
@ kw_intel_ocl_bicc
Definition LLToken.h:138
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:406
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:150
@ kw_preserve_allcc
Definition LLToken.h:166
@ kw_importType
Definition LLToken.h:397
@ kw_cleanupret
Definition LLToken.h:347
@ kw_shufflevector
Definition LLToken.h:364
@ kw_riscv_vector_cc
Definition LLToken.h:188
@ kw_avr_intrcc
Definition LLToken.h:154
@ kw_definition
Definition LLToken.h:398
@ kw_virtualConstProp
Definition LLToken.h:461
@ kw_vcall_visibility
Definition LLToken.h:450
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:208
@ kw_preserve_mostcc
Definition LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:147
@ kw_typeTestRes
Definition LLToken.h:438
@ kw_x86_regcallcc
Definition LLToken.h:144
@ kw_typeIdInfo
Definition LLToken.h:426
@ kw_amdgpu_cs_chain
Definition LLToken.h:180
@ kw_dso_local_equivalent
Definition LLToken.h:369
@ kw_x86_64_sysvcc
Definition LLToken.h:160
@ DbgRecordType
Definition LLToken.h:513
@ kw_address_is_null
Definition LLToken.h:221
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:152
@ kw_uniqueRetVal
Definition LLToken.h:460
@ kw_insertvalue
Definition LLToken.h:367
@ kw_indirectbr
Definition LLToken.h:343
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:577
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp: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:1655
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:51
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
auto cast_or_null(const Y &Val)
Definition Casting.h: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:301
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
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:339
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:310
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
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ TargetMem0
Represents target specific state.
Definition ModRef.h:70
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h: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:1954
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h: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:320
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
static 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 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.