LLVM 22.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
50#include "llvm/Support/ModRef.h"
53#include <algorithm>
54#include <cassert>
55#include <cstring>
56#include <optional>
57#include <vector>
58
59using namespace llvm;
60
62 "allow-incomplete-ir", cl::init(false), cl::Hidden,
64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
66
67static std::string getTypeString(Type *T) {
68 std::string Result;
69 raw_string_ostream Tmp(Result);
70 Tmp << *T;
71 return Tmp.str();
72}
73
74/// Run: module ::= toplevelentity*
75bool LLParser::Run(bool UpgradeDebugInfo,
76 DataLayoutCallbackTy DataLayoutCallback) {
77 // Prime the lexer.
78 Lex.Lex();
79
80 if (Context.shouldDiscardValueNames())
81 return error(
82 Lex.getLoc(),
83 "Can't read textual IR with a Context that discards named Values");
84
85 if (M) {
86 if (parseTargetDefinitions(DataLayoutCallback))
87 return true;
88 }
89
90 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
91 validateEndOfIndex();
92}
93
95 const SlotMapping *Slots) {
96 restoreParsingState(Slots);
97 Lex.Lex();
98
99 Type *Ty = nullptr;
100 if (parseType(Ty) || parseConstantValue(Ty, C))
101 return true;
102 if (Lex.getKind() != lltok::Eof)
103 return error(Lex.getLoc(), "expected end of string");
104 return false;
105}
106
108 const SlotMapping *Slots) {
109 restoreParsingState(Slots);
110 Lex.Lex();
111
112 Read = 0;
113 SMLoc Start = Lex.getLoc();
114 Ty = nullptr;
115 if (parseType(Ty))
116 return true;
117 SMLoc End = Lex.getLoc();
118 Read = End.getPointer() - Start.getPointer();
119
120 return false;
121}
122
124 const SlotMapping *Slots) {
125 restoreParsingState(Slots);
126 Lex.Lex();
127
128 Read = 0;
129 SMLoc Start = Lex.getLoc();
130 Result = nullptr;
131 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
132 SMLoc End = Lex.getLoc();
133 Read = End.getPointer() - Start.getPointer();
134
135 return Status;
136}
137
138void LLParser::restoreParsingState(const SlotMapping *Slots) {
139 if (!Slots)
140 return;
141 NumberedVals = Slots->GlobalValues;
142 NumberedMetadata = Slots->MetadataNodes;
143 for (const auto &I : Slots->NamedTypes)
144 NamedTypes.insert(
145 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
146 for (const auto &I : Slots->Types)
147 NumberedTypes.insert(
148 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
149}
150
152 // White-list intrinsics that are safe to drop.
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
155 return;
156
158 for (Value *V : II->args())
159 if (auto *MV = dyn_cast<MetadataAsValue>(V))
160 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
161 if (MD->isTemporary())
162 MVs.push_back(MV);
163
164 if (!MVs.empty()) {
165 assert(II->use_empty() && "Cannot have uses");
166 II->eraseFromParent();
167
168 // Also remove no longer used MetadataAsValue wrappers.
169 for (MetadataAsValue *MV : MVs)
170 if (MV->use_empty())
171 delete MV;
172 }
173}
174
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
177 for (Function &F : *M) {
178 F.eraseMetadataIf(Pred);
179 for (Instruction &I : make_early_inc_range(instructions(F))) {
180 I.eraseMetadataIf(Pred);
181
182 if (auto *II = dyn_cast<IntrinsicInst>(&I))
184 }
185 }
186
187 for (GlobalVariable &GV : M->globals())
188 GV.eraseMetadataIf(Pred);
189
190 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
191 // Check whether there is only a single use left, which would be in our
192 // own NumberedMetadata.
193 if (Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(ID);
195 ForwardRefMDNodes.erase(ID);
196 }
197 }
198}
199
200/// validateEndOfModule - Do final validity and basic correctness checks at the
201/// end of the module.
202bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
203 if (!M)
204 return false;
205
206 // We should have already returned an error if we observed both intrinsics and
207 // records in this IR.
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
210
211 // Handle any function attribute group forward references.
212 for (const auto &RAG : ForwardRefAttrGroups) {
213 Value *V = RAG.first;
214 const std::vector<unsigned> &Attrs = RAG.second;
215 AttrBuilder B(Context);
216
217 for (const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
220 B.merge(R->second);
221 }
222
223 if (Function *Fn = dyn_cast<Function>(V)) {
224 AttributeList AS = Fn->getAttributes();
225 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
226 AS = AS.removeFnAttributes(Context);
227
228 FnAttrs.merge(B);
229
230 // If the alignment was parsed as an attribute, move to the alignment
231 // field.
232 if (MaybeAlign A = FnAttrs.getAlignment()) {
233 Fn->setAlignment(*A);
234 FnAttrs.removeAttribute(Attribute::Alignment);
235 }
236
237 AS = AS.addFnAttributes(Context, FnAttrs);
238 Fn->setAttributes(AS);
239 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
240 AttributeList AS = CI->getAttributes();
241 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
242 AS = AS.removeFnAttributes(Context);
243 FnAttrs.merge(B);
244 AS = AS.addFnAttributes(Context, FnAttrs);
245 CI->setAttributes(AS);
246 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
247 AttributeList AS = II->getAttributes();
248 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
249 AS = AS.removeFnAttributes(Context);
250 FnAttrs.merge(B);
251 AS = AS.addFnAttributes(Context, FnAttrs);
252 II->setAttributes(AS);
253 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
254 AttributeList AS = CBI->getAttributes();
255 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
256 AS = AS.removeFnAttributes(Context);
257 FnAttrs.merge(B);
258 AS = AS.addFnAttributes(Context, FnAttrs);
259 CBI->setAttributes(AS);
260 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
261 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
262 Attrs.merge(B);
263 GV->setAttributes(AttributeSet::get(Context,Attrs));
264 } else {
265 llvm_unreachable("invalid object with forward attribute group reference");
266 }
267 }
268
269 // If there are entries in ForwardRefBlockAddresses at this point, the
270 // function was never defined.
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
274
275 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
276 GlobalValue *FwdRef) {
277 GlobalValue *GV = nullptr;
278 if (GVRef.Kind == ValID::t_GlobalName) {
279 GV = M->getNamedValue(GVRef.StrVal);
280 } else {
281 GV = NumberedVals.get(GVRef.UIntVal);
282 }
283
284 if (!GV)
285 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
286 "' referenced by dso_local_equivalent");
287
288 if (!GV->getValueType()->isFunctionTy())
289 return error(GVRef.Loc,
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
292
293 auto *Equiv = DSOLocalEquivalent::get(GV);
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
296 return false;
297 };
298
299 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
300 // point, they are references after the function was defined. Resolve those
301 // now.
302 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
304 return true;
305 }
306 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
308 return true;
309 }
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
312
313 for (const auto &NT : NumberedTypes)
314 if (NT.second.second.isValid())
315 return error(NT.second.second,
316 "use of undefined type '%" + Twine(NT.first) + "'");
317
318 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
319 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
320 if (I->second.second.isValid())
321 return error(I->second.second,
322 "use of undefined type named '" + I->getKey() + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 // Automatically create declarations for intrinsics. Intrinsics can only
333 // be called directly, so the call function type directly determines the
334 // declaration function type.
335 //
336 // Additionally, automatically add the required mangling suffix to the
337 // intrinsic name. This means that we may replace a single forward
338 // declaration with multiple functions here.
339 for (Use &U : make_early_inc_range(Info.first->uses())) {
340 auto *CB = dyn_cast<CallBase>(U.getUser());
341 if (!CB || !CB->isCallee(&U))
342 return error(Info.second, "intrinsic can only be used as callee");
343
344 SmallVector<Type *> OverloadTys;
345 if (IID != Intrinsic::not_intrinsic &&
346 Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
347 OverloadTys)) {
348 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
349 } else {
350 // Try to upgrade the intrinsic.
351 Function *TmpF = Function::Create(CB->getFunctionType(),
353 Function *NewF = nullptr;
354 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
355 if (IID == Intrinsic::not_intrinsic)
356 return error(Info.second, "unknown intrinsic '" + Name + "'");
357 return error(Info.second, "invalid intrinsic signature");
358 }
359
360 U.set(TmpF);
361 UpgradeIntrinsicCall(CB, NewF);
362 if (TmpF->use_empty())
363 TmpF->eraseFromParent();
364 }
365 }
366
367 Info.first->eraseFromParent();
368 ForwardRefVals.erase(Name);
369 continue;
370 }
371
372 // If incomplete IR is allowed, also add declarations for
373 // non-intrinsics.
375 continue;
376
377 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
378 FunctionType *FTy = nullptr;
379 for (Use &U : V->uses()) {
380 auto *CB = dyn_cast<CallBase>(U.getUser());
381 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
382 return nullptr;
383 FTy = CB->getFunctionType();
384 }
385 return FTy;
386 };
387
388 // First check whether this global is only used in calls with the same
389 // type, in which case we'll insert a function. Otherwise, fall back to
390 // using a dummy i8 type.
391 Type *Ty = GetCommonFunctionType(Info.first);
392 if (!Ty)
393 Ty = Type::getInt8Ty(Context);
394
395 GlobalValue *GV;
396 if (auto *FTy = dyn_cast<FunctionType>(Ty))
398 else
399 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
401 /*Initializer*/ nullptr, Name);
402 Info.first->replaceAllUsesWith(GV);
403 Info.first->eraseFromParent();
404 ForwardRefVals.erase(Name);
405 }
406
407 if (!ForwardRefVals.empty())
408 return error(ForwardRefVals.begin()->second.second,
409 "use of undefined value '@" + ForwardRefVals.begin()->first +
410 "'");
411
412 if (!ForwardRefValIDs.empty())
413 return error(ForwardRefValIDs.begin()->second.second,
414 "use of undefined value '@" +
415 Twine(ForwardRefValIDs.begin()->first) + "'");
416
417 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
418 dropUnknownMetadataReferences();
419
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) + "'");
424
425 // Resolve metadata cycles.
426 for (auto &N : NumberedMetadata) {
427 if (N.second && !N.second->isResolved())
428 N.second->resolveCycles();
429 }
430
431 for (auto *Inst : InstsWithTBAATag) {
432 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
433 // With incomplete IR, the tbaa metadata may have been dropped.
435 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
436 if (MD) {
437 auto *UpgradedMD = UpgradeTBAANode(*MD);
438 if (MD != UpgradedMD)
439 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
440 }
441 }
442
443 // Look for intrinsic functions and CallInst that need to be upgraded. We use
444 // make_early_inc_range here because we may remove some functions.
445 for (Function &F : llvm::make_early_inc_range(*M))
447
448 if (UpgradeDebugInfo)
450
455
456 if (!Slots)
457 return false;
458 // Initialize the slot mapping.
459 // Because by this point we've parsed and validated everything, we can "steal"
460 // the mapping from LLParser as it doesn't need it anymore.
461 Slots->GlobalValues = std::move(NumberedVals);
462 Slots->MetadataNodes = std::move(NumberedMetadata);
463 for (const auto &I : NamedTypes)
464 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
465 for (const auto &I : NumberedTypes)
466 Slots->Types.insert(std::make_pair(I.first, I.second.first));
467
468 return false;
469}
470
471/// Do final validity and basic correctness checks at the end of the index.
472bool LLParser::validateEndOfIndex() {
473 if (!Index)
474 return false;
475
476 if (!ForwardRefValueInfos.empty())
477 return error(ForwardRefValueInfos.begin()->second.front().second,
478 "use of undefined summary '^" +
479 Twine(ForwardRefValueInfos.begin()->first) + "'");
480
481 if (!ForwardRefAliasees.empty())
482 return error(ForwardRefAliasees.begin()->second.front().second,
483 "use of undefined summary '^" +
484 Twine(ForwardRefAliasees.begin()->first) + "'");
485
486 if (!ForwardRefTypeIds.empty())
487 return error(ForwardRefTypeIds.begin()->second.front().second,
488 "use of undefined type id summary '^" +
489 Twine(ForwardRefTypeIds.begin()->first) + "'");
490
491 return false;
492}
493
494//===----------------------------------------------------------------------===//
495// Top-Level Entities
496//===----------------------------------------------------------------------===//
497
498bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
499 // Delay parsing of the data layout string until the target triple is known.
500 // Then, pass both the the target triple and the tentative data layout string
501 // to DataLayoutCallback, allowing to override the DL string.
502 // This enables importing modules with invalid DL strings.
503 std::string TentativeDLStr = M->getDataLayoutStr();
504 LocTy DLStrLoc;
505
506 bool Done = false;
507 while (!Done) {
508 switch (Lex.getKind()) {
509 case lltok::kw_target:
510 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
511 return true;
512 break;
514 if (parseSourceFileName())
515 return true;
516 break;
517 default:
518 Done = true;
519 }
520 }
521 // Run the override callback to potentially change the data layout string, and
522 // parse the data layout string.
523 if (auto LayoutOverride =
524 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
525 TentativeDLStr = *LayoutOverride;
526 DLStrLoc = {};
527 }
528 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
529 if (!MaybeDL)
530 return error(DLStrLoc, toString(MaybeDL.takeError()));
531 M->setDataLayout(MaybeDL.get());
532 return false;
533}
534
535bool LLParser::parseTopLevelEntities() {
536 // If there is no Module, then parse just the summary index entries.
537 if (!M) {
538 while (true) {
539 switch (Lex.getKind()) {
540 case lltok::Eof:
541 return false;
542 case lltok::SummaryID:
543 if (parseSummaryEntry())
544 return true;
545 break;
547 if (parseSourceFileName())
548 return true;
549 break;
550 default:
551 // Skip everything else
552 Lex.Lex();
553 }
554 }
555 }
556 while (true) {
557 switch (Lex.getKind()) {
558 default:
559 return tokError("expected top-level entity");
560 case lltok::Eof: return false;
562 if (parseDeclare())
563 return true;
564 break;
565 case lltok::kw_define:
566 if (parseDefine())
567 return true;
568 break;
569 case lltok::kw_module:
570 if (parseModuleAsm())
571 return true;
572 break;
574 if (parseUnnamedType())
575 return true;
576 break;
577 case lltok::LocalVar:
578 if (parseNamedType())
579 return true;
580 break;
581 case lltok::GlobalID:
582 if (parseUnnamedGlobal())
583 return true;
584 break;
585 case lltok::GlobalVar:
586 if (parseNamedGlobal())
587 return true;
588 break;
589 case lltok::ComdatVar: if (parseComdat()) return true; break;
590 case lltok::exclaim:
591 if (parseStandaloneMetadata())
592 return true;
593 break;
594 case lltok::SummaryID:
595 if (parseSummaryEntry())
596 return true;
597 break;
599 if (parseNamedMetadata())
600 return true;
601 break;
603 if (parseUnnamedAttrGrp())
604 return true;
605 break;
607 if (parseUseListOrder())
608 return true;
609 break;
611 if (parseUseListOrderBB())
612 return true;
613 break;
614 }
615 }
616}
617
618/// toplevelentity
619/// ::= 'module' 'asm' STRINGCONSTANT
620bool LLParser::parseModuleAsm() {
621 assert(Lex.getKind() == lltok::kw_module);
622 Lex.Lex();
623
624 std::string AsmStr;
625 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
626 parseStringConstant(AsmStr))
627 return true;
628
629 M->appendModuleInlineAsm(AsmStr);
630 return false;
631}
632
633/// toplevelentity
634/// ::= 'target' 'triple' '=' STRINGCONSTANT
635/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
636bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
637 LocTy &DLStrLoc) {
638 assert(Lex.getKind() == lltok::kw_target);
639 std::string Str;
640 switch (Lex.Lex()) {
641 default:
642 return tokError("unknown target property");
643 case lltok::kw_triple:
644 Lex.Lex();
645 if (parseToken(lltok::equal, "expected '=' after target triple") ||
646 parseStringConstant(Str))
647 return true;
648 M->setTargetTriple(Triple(std::move(Str)));
649 return false;
651 Lex.Lex();
652 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
653 return true;
654 DLStrLoc = Lex.getLoc();
655 if (parseStringConstant(TentativeDLStr))
656 return true;
657 return false;
658 }
659}
660
661/// toplevelentity
662/// ::= 'source_filename' '=' STRINGCONSTANT
663bool LLParser::parseSourceFileName() {
664 assert(Lex.getKind() == lltok::kw_source_filename);
665 Lex.Lex();
666 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
667 parseStringConstant(SourceFileName))
668 return true;
669 if (M)
670 M->setSourceFileName(SourceFileName);
671 return false;
672}
673
674/// parseUnnamedType:
675/// ::= LocalVarID '=' 'type' type
676bool LLParser::parseUnnamedType() {
677 LocTy TypeLoc = Lex.getLoc();
678 unsigned TypeID = Lex.getUIntVal();
679 Lex.Lex(); // eat LocalVarID;
680
681 if (parseToken(lltok::equal, "expected '=' after name") ||
682 parseToken(lltok::kw_type, "expected 'type' after '='"))
683 return true;
684
685 Type *Result = nullptr;
686 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
687 return true;
688
689 if (!isa<StructType>(Result)) {
690 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
691 if (Entry.first)
692 return error(TypeLoc, "non-struct types may not be recursive");
693 Entry.first = Result;
694 Entry.second = SMLoc();
695 }
696
697 return false;
698}
699
700/// toplevelentity
701/// ::= LocalVar '=' 'type' type
702bool LLParser::parseNamedType() {
703 std::string Name = Lex.getStrVal();
704 LocTy NameLoc = Lex.getLoc();
705 Lex.Lex(); // eat LocalVar.
706
707 if (parseToken(lltok::equal, "expected '=' after name") ||
708 parseToken(lltok::kw_type, "expected 'type' after name"))
709 return true;
710
711 Type *Result = nullptr;
712 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
713 return true;
714
715 if (!isa<StructType>(Result)) {
716 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
717 if (Entry.first)
718 return error(NameLoc, "non-struct types may not be recursive");
719 Entry.first = Result;
720 Entry.second = SMLoc();
721 }
722
723 return false;
724}
725
726/// toplevelentity
727/// ::= 'declare' FunctionHeader
728bool LLParser::parseDeclare() {
729 assert(Lex.getKind() == lltok::kw_declare);
730 Lex.Lex();
731
732 std::vector<std::pair<unsigned, MDNode *>> MDs;
733 while (Lex.getKind() == lltok::MetadataVar) {
734 unsigned MDK;
735 MDNode *N;
736 if (parseMetadataAttachment(MDK, N))
737 return true;
738 MDs.push_back({MDK, N});
739 }
740
741 Function *F;
742 unsigned FunctionNumber = -1;
743 SmallVector<unsigned> UnnamedArgNums;
744 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
745 return true;
746 for (auto &MD : MDs)
747 F->addMetadata(MD.first, *MD.second);
748 return false;
749}
750
751/// toplevelentity
752/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
753bool LLParser::parseDefine() {
754 assert(Lex.getKind() == lltok::kw_define);
755 FileLoc FunctionStart(Lex.getTokLineColumnPos());
756 Lex.Lex();
757
758 Function *F;
759 unsigned FunctionNumber = -1;
760 SmallVector<unsigned> UnnamedArgNums;
761 bool RetValue =
762 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
763 parseOptionalFunctionMetadata(*F) ||
764 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
765 if (ParserContext)
766 ParserContext->addFunctionLocation(
767 F, FileLocRange(FunctionStart, Lex.getPrevTokEndLineColumnPos()));
768
769 return RetValue;
770}
771
772/// parseGlobalType
773/// ::= 'constant'
774/// ::= 'global'
775bool LLParser::parseGlobalType(bool &IsConstant) {
776 if (Lex.getKind() == lltok::kw_constant)
777 IsConstant = true;
778 else if (Lex.getKind() == lltok::kw_global)
779 IsConstant = false;
780 else {
781 IsConstant = false;
782 return tokError("expected 'global' or 'constant'");
783 }
784 Lex.Lex();
785 return false;
786}
787
788bool LLParser::parseOptionalUnnamedAddr(
789 GlobalVariable::UnnamedAddr &UnnamedAddr) {
790 if (EatIfPresent(lltok::kw_unnamed_addr))
792 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
794 else
795 UnnamedAddr = GlobalValue::UnnamedAddr::None;
796 return false;
797}
798
799/// parseUnnamedGlobal:
800/// OptionalVisibility (ALIAS | IFUNC) ...
801/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
802/// OptionalDLLStorageClass
803/// ... -> global variable
804/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
805/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
806/// OptionalVisibility
807/// OptionalDLLStorageClass
808/// ... -> global variable
809bool LLParser::parseUnnamedGlobal() {
810 unsigned VarID;
811 std::string Name;
812 LocTy NameLoc = Lex.getLoc();
813
814 // Handle the GlobalID form.
815 if (Lex.getKind() == lltok::GlobalID) {
816 VarID = Lex.getUIntVal();
817 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
818 return true;
819
820 Lex.Lex(); // eat GlobalID;
821 if (parseToken(lltok::equal, "expected '=' after name"))
822 return true;
823 } else {
824 VarID = NumberedVals.getNext();
825 }
826
827 bool HasLinkage;
828 unsigned Linkage, Visibility, DLLStorageClass;
829 bool DSOLocal;
831 GlobalVariable::UnnamedAddr UnnamedAddr;
832 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
833 DSOLocal) ||
834 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
835 return true;
836
837 switch (Lex.getKind()) {
838 default:
839 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
840 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
841 case lltok::kw_alias:
842 case lltok::kw_ifunc:
843 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
844 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
845 }
846}
847
848/// parseNamedGlobal:
849/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
850/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
851/// OptionalVisibility OptionalDLLStorageClass
852/// ... -> global variable
853bool LLParser::parseNamedGlobal() {
854 assert(Lex.getKind() == lltok::GlobalVar);
855 LocTy NameLoc = Lex.getLoc();
856 std::string Name = Lex.getStrVal();
857 Lex.Lex();
858
859 bool HasLinkage;
860 unsigned Linkage, Visibility, DLLStorageClass;
861 bool DSOLocal;
863 GlobalVariable::UnnamedAddr UnnamedAddr;
864 if (parseToken(lltok::equal, "expected '=' in global variable") ||
865 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
866 DSOLocal) ||
867 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
868 return true;
869
870 switch (Lex.getKind()) {
871 default:
872 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
873 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
874 case lltok::kw_alias:
875 case lltok::kw_ifunc:
876 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
877 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
878 }
879}
880
881bool LLParser::parseComdat() {
882 assert(Lex.getKind() == lltok::ComdatVar);
883 std::string Name = Lex.getStrVal();
884 LocTy NameLoc = Lex.getLoc();
885 Lex.Lex();
886
887 if (parseToken(lltok::equal, "expected '=' here"))
888 return true;
889
890 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
891 return tokError("expected comdat type");
892
894 switch (Lex.getKind()) {
895 default:
896 return tokError("unknown selection kind");
897 case lltok::kw_any:
898 SK = Comdat::Any;
899 break;
902 break;
904 SK = Comdat::Largest;
905 break;
908 break;
910 SK = Comdat::SameSize;
911 break;
912 }
913 Lex.Lex();
914
915 // See if the comdat was forward referenced, if so, use the comdat.
916 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
917 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
918 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
919 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
920
921 Comdat *C;
922 if (I != ComdatSymTab.end())
923 C = &I->second;
924 else
925 C = M->getOrInsertComdat(Name);
926 C->setSelectionKind(SK);
927
928 return false;
929}
930
931// MDString:
932// ::= '!' STRINGCONSTANT
933bool LLParser::parseMDString(MDString *&Result) {
934 std::string Str;
935 if (parseStringConstant(Str))
936 return true;
937 Result = MDString::get(Context, Str);
938 return false;
939}
940
941// MDNode:
942// ::= '!' MDNodeNumber
943bool LLParser::parseMDNodeID(MDNode *&Result) {
944 // !{ ..., !42, ... }
945 LocTy IDLoc = Lex.getLoc();
946 unsigned MID = 0;
947 if (parseUInt32(MID))
948 return true;
949
950 // If not a forward reference, just return it now.
951 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
952 if (!Inserted) {
953 Result = It->second;
954 return false;
955 }
956
957 // Otherwise, create MDNode forward reference.
958 auto &FwdRef = ForwardRefMDNodes[MID];
959 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
960
961 Result = FwdRef.first.get();
962 It->second.reset(Result);
963 return false;
964}
965
966/// parseNamedMetadata:
967/// !foo = !{ !1, !2 }
968bool LLParser::parseNamedMetadata() {
969 assert(Lex.getKind() == lltok::MetadataVar);
970 std::string Name = Lex.getStrVal();
971 Lex.Lex();
972
973 if (parseToken(lltok::equal, "expected '=' here") ||
974 parseToken(lltok::exclaim, "Expected '!' here") ||
975 parseToken(lltok::lbrace, "Expected '{' here"))
976 return true;
977
978 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
979 if (Lex.getKind() != lltok::rbrace)
980 do {
981 MDNode *N = nullptr;
982 // parse DIExpressions inline as a special case. They are still MDNodes,
983 // so they can still appear in named metadata. Remove this logic if they
984 // become plain Metadata.
985 if (Lex.getKind() == lltok::MetadataVar &&
986 Lex.getStrVal() == "DIExpression") {
987 if (parseDIExpression(N, /*IsDistinct=*/false))
988 return true;
989 // DIArgLists should only appear inline in a function, as they may
990 // contain LocalAsMetadata arguments which require a function context.
991 } else if (Lex.getKind() == lltok::MetadataVar &&
992 Lex.getStrVal() == "DIArgList") {
993 return tokError("found DIArgList outside of function");
994 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
995 parseMDNodeID(N)) {
996 return true;
997 }
998 NMD->addOperand(N);
999 } while (EatIfPresent(lltok::comma));
1000
1001 return parseToken(lltok::rbrace, "expected end of metadata node");
1002}
1003
1004/// parseStandaloneMetadata:
1005/// !42 = !{...}
1006bool LLParser::parseStandaloneMetadata() {
1007 assert(Lex.getKind() == lltok::exclaim);
1008 Lex.Lex();
1009 unsigned MetadataID = 0;
1010
1011 MDNode *Init;
1012 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1013 return true;
1014
1015 // Detect common error, from old metadata syntax.
1016 if (Lex.getKind() == lltok::Type)
1017 return tokError("unexpected type in metadata definition");
1018
1019 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1020 if (Lex.getKind() == lltok::MetadataVar) {
1021 if (parseSpecializedMDNode(Init, IsDistinct))
1022 return true;
1023 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1024 parseMDTuple(Init, IsDistinct))
1025 return true;
1026
1027 // See if this was forward referenced, if so, handle it.
1028 auto FI = ForwardRefMDNodes.find(MetadataID);
1029 if (FI != ForwardRefMDNodes.end()) {
1030 auto *ToReplace = FI->second.first.get();
1031 // DIAssignID has its own special forward-reference "replacement" for
1032 // attachments (the temporary attachments are never actually attached).
1033 if (isa<DIAssignID>(Init)) {
1034 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1035 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1036 "Inst unexpectedly already has DIAssignID attachment");
1037 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1038 }
1039 }
1040
1041 ToReplace->replaceAllUsesWith(Init);
1042 ForwardRefMDNodes.erase(FI);
1043
1044 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1045 } else {
1046 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1047 if (!Inserted)
1048 return tokError("Metadata id is already used");
1049 It->second.reset(Init);
1050 }
1051
1052 return false;
1053}
1054
1055// Skips a single module summary entry.
1056bool LLParser::skipModuleSummaryEntry() {
1057 // Each module summary entry consists of a tag for the entry
1058 // type, followed by a colon, then the fields which may be surrounded by
1059 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1060 // support is in place we will look for the tokens corresponding to the
1061 // expected tags.
1062 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1063 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1064 Lex.getKind() != lltok::kw_blockcount)
1065 return tokError(
1066 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1067 "start of summary entry");
1068 if (Lex.getKind() == lltok::kw_flags)
1069 return parseSummaryIndexFlags();
1070 if (Lex.getKind() == lltok::kw_blockcount)
1071 return parseBlockCount();
1072 Lex.Lex();
1073 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1074 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1075 return true;
1076 // Now walk through the parenthesized entry, until the number of open
1077 // parentheses goes back down to 0 (the first '(' was parsed above).
1078 unsigned NumOpenParen = 1;
1079 do {
1080 switch (Lex.getKind()) {
1081 case lltok::lparen:
1082 NumOpenParen++;
1083 break;
1084 case lltok::rparen:
1085 NumOpenParen--;
1086 break;
1087 case lltok::Eof:
1088 return tokError("found end of file while parsing summary entry");
1089 default:
1090 // Skip everything in between parentheses.
1091 break;
1092 }
1093 Lex.Lex();
1094 } while (NumOpenParen > 0);
1095 return false;
1096}
1097
1098/// SummaryEntry
1099/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1100bool LLParser::parseSummaryEntry() {
1101 assert(Lex.getKind() == lltok::SummaryID);
1102 unsigned SummaryID = Lex.getUIntVal();
1103
1104 // For summary entries, colons should be treated as distinct tokens,
1105 // not an indication of the end of a label token.
1106 Lex.setIgnoreColonInIdentifiers(true);
1107
1108 Lex.Lex();
1109 if (parseToken(lltok::equal, "expected '=' here"))
1110 return true;
1111
1112 // If we don't have an index object, skip the summary entry.
1113 if (!Index)
1114 return skipModuleSummaryEntry();
1115
1116 bool result = false;
1117 switch (Lex.getKind()) {
1118 case lltok::kw_gv:
1119 result = parseGVEntry(SummaryID);
1120 break;
1121 case lltok::kw_module:
1122 result = parseModuleEntry(SummaryID);
1123 break;
1124 case lltok::kw_typeid:
1125 result = parseTypeIdEntry(SummaryID);
1126 break;
1128 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1129 break;
1130 case lltok::kw_flags:
1131 result = parseSummaryIndexFlags();
1132 break;
1134 result = parseBlockCount();
1135 break;
1136 default:
1137 result = error(Lex.getLoc(), "unexpected summary kind");
1138 break;
1139 }
1140 Lex.setIgnoreColonInIdentifiers(false);
1141 return result;
1142}
1143
1152
1153// If there was an explicit dso_local, update GV. In the absence of an explicit
1154// dso_local we keep the default value.
1155static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1156 if (DSOLocal)
1157 GV.setDSOLocal(true);
1158}
1159
1160/// parseAliasOrIFunc:
1161/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1162/// OptionalVisibility OptionalDLLStorageClass
1163/// OptionalThreadLocal OptionalUnnamedAddr
1164/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1165///
1166/// AliaseeOrResolver
1167/// ::= TypeAndValue
1168///
1169/// SymbolAttrs
1170/// ::= ',' 'partition' StringConstant
1171///
1172/// Everything through OptionalUnnamedAddr has already been parsed.
1173///
1174bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1175 LocTy NameLoc, unsigned L, unsigned Visibility,
1176 unsigned DLLStorageClass, bool DSOLocal,
1178 GlobalVariable::UnnamedAddr UnnamedAddr) {
1179 bool IsAlias;
1180 if (Lex.getKind() == lltok::kw_alias)
1181 IsAlias = true;
1182 else if (Lex.getKind() == lltok::kw_ifunc)
1183 IsAlias = false;
1184 else
1185 llvm_unreachable("Not an alias or ifunc!");
1186 Lex.Lex();
1187
1189
1190 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1191 return error(NameLoc, "invalid linkage type for alias");
1192
1193 if (!isValidVisibilityForLinkage(Visibility, L))
1194 return error(NameLoc,
1195 "symbol with local linkage must have default visibility");
1196
1197 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1198 return error(NameLoc,
1199 "symbol with local linkage cannot have a DLL storage class");
1200
1201 Type *Ty;
1202 LocTy ExplicitTypeLoc = Lex.getLoc();
1203 if (parseType(Ty) ||
1204 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1205 return true;
1206
1207 Constant *Aliasee;
1208 LocTy AliaseeLoc = Lex.getLoc();
1209 if (Lex.getKind() != lltok::kw_bitcast &&
1210 Lex.getKind() != lltok::kw_getelementptr &&
1211 Lex.getKind() != lltok::kw_addrspacecast &&
1212 Lex.getKind() != lltok::kw_inttoptr) {
1213 if (parseGlobalTypeAndValue(Aliasee))
1214 return true;
1215 } else {
1216 // The bitcast dest type is not present, it is implied by the dest type.
1217 ValID ID;
1218 if (parseValID(ID, /*PFS=*/nullptr))
1219 return true;
1220 if (ID.Kind != ValID::t_Constant)
1221 return error(AliaseeLoc, "invalid aliasee");
1222 Aliasee = ID.ConstantVal;
1223 }
1224
1225 Type *AliaseeType = Aliasee->getType();
1226 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1227 if (!PTy)
1228 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1229 unsigned AddrSpace = PTy->getAddressSpace();
1230
1231 GlobalValue *GVal = nullptr;
1232
1233 // See if the alias was forward referenced, if so, prepare to replace the
1234 // forward reference.
1235 if (!Name.empty()) {
1236 auto I = ForwardRefVals.find(Name);
1237 if (I != ForwardRefVals.end()) {
1238 GVal = I->second.first;
1239 ForwardRefVals.erase(Name);
1240 } else if (M->getNamedValue(Name)) {
1241 return error(NameLoc, "redefinition of global '@" + Name + "'");
1242 }
1243 } else {
1244 auto I = ForwardRefValIDs.find(NameID);
1245 if (I != ForwardRefValIDs.end()) {
1246 GVal = I->second.first;
1247 ForwardRefValIDs.erase(I);
1248 }
1249 }
1250
1251 // Okay, create the alias/ifunc but do not insert it into the module yet.
1252 std::unique_ptr<GlobalAlias> GA;
1253 std::unique_ptr<GlobalIFunc> GI;
1254 GlobalValue *GV;
1255 if (IsAlias) {
1256 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1257 /*Parent=*/nullptr));
1258 GV = GA.get();
1259 } else {
1260 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1261 /*Parent=*/nullptr));
1262 GV = GI.get();
1263 }
1264 GV->setThreadLocalMode(TLM);
1267 GV->setUnnamedAddr(UnnamedAddr);
1268 maybeSetDSOLocal(DSOLocal, *GV);
1269
1270 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1271 // Now parse them if there are any.
1272 while (Lex.getKind() == lltok::comma) {
1273 Lex.Lex();
1274
1275 if (Lex.getKind() == lltok::kw_partition) {
1276 Lex.Lex();
1277 GV->setPartition(Lex.getStrVal());
1278 if (parseToken(lltok::StringConstant, "expected partition string"))
1279 return true;
1280 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1281 if (parseGlobalObjectMetadataAttachment(*GI))
1282 return true;
1283 } else {
1284 return tokError("unknown alias or ifunc property!");
1285 }
1286 }
1287
1288 if (Name.empty())
1289 NumberedVals.add(NameID, GV);
1290
1291 if (GVal) {
1292 // Verify that types agree.
1293 if (GVal->getType() != GV->getType())
1294 return error(
1295 ExplicitTypeLoc,
1296 "forward reference and definition of alias have different types");
1297
1298 // If they agree, just RAUW the old value with the alias and remove the
1299 // forward ref info.
1300 GVal->replaceAllUsesWith(GV);
1301 GVal->eraseFromParent();
1302 }
1303
1304 // Insert into the module, we know its name won't collide now.
1305 if (IsAlias)
1306 M->insertAlias(GA.release());
1307 else
1308 M->insertIFunc(GI.release());
1309 assert(GV->getName() == Name && "Should not be a name conflict!");
1310
1311 return false;
1312}
1313
1314static bool isSanitizer(lltok::Kind Kind) {
1315 switch (Kind) {
1318 case lltok::kw_sanitize_memtag:
1320 return true;
1321 default:
1322 return false;
1323 }
1324}
1325
1326bool LLParser::parseSanitizer(GlobalVariable *GV) {
1327 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1329 if (GV->hasSanitizerMetadata())
1330 Meta = GV->getSanitizerMetadata();
1331
1332 switch (Lex.getKind()) {
1334 Meta.NoAddress = true;
1335 break;
1337 Meta.NoHWAddress = true;
1338 break;
1339 case lltok::kw_sanitize_memtag:
1340 Meta.Memtag = true;
1341 break;
1343 Meta.IsDynInit = true;
1344 break;
1345 default:
1346 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1347 }
1348 GV->setSanitizerMetadata(Meta);
1349 Lex.Lex();
1350 return false;
1351}
1352
1353/// parseGlobal
1354/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1355/// OptionalVisibility OptionalDLLStorageClass
1356/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1357/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1358/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1359/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1360/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1361/// Const OptionalAttrs
1362///
1363/// Everything up to and including OptionalUnnamedAddr has been parsed
1364/// already.
1365///
1366bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1367 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1368 unsigned Visibility, unsigned DLLStorageClass,
1369 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1370 GlobalVariable::UnnamedAddr UnnamedAddr) {
1371 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1372 return error(NameLoc,
1373 "symbol with local linkage must have default visibility");
1374
1375 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1376 return error(NameLoc,
1377 "symbol with local linkage cannot have a DLL storage class");
1378
1379 unsigned AddrSpace;
1380 bool IsConstant, IsExternallyInitialized;
1381 LocTy IsExternallyInitializedLoc;
1382 LocTy TyLoc;
1383
1384 Type *Ty = nullptr;
1385 if (parseOptionalAddrSpace(AddrSpace) ||
1386 parseOptionalToken(lltok::kw_externally_initialized,
1387 IsExternallyInitialized,
1388 &IsExternallyInitializedLoc) ||
1389 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1390 return true;
1391
1392 // If the linkage is specified and is external, then no initializer is
1393 // present.
1394 Constant *Init = nullptr;
1395 if (!HasLinkage ||
1398 if (parseGlobalValue(Ty, Init))
1399 return true;
1400 }
1401
1403 return error(TyLoc, "invalid type for global variable");
1404
1405 GlobalValue *GVal = nullptr;
1406
1407 // See if the global was forward referenced, if so, use the global.
1408 if (!Name.empty()) {
1409 auto I = ForwardRefVals.find(Name);
1410 if (I != ForwardRefVals.end()) {
1411 GVal = I->second.first;
1412 ForwardRefVals.erase(I);
1413 } else if (M->getNamedValue(Name)) {
1414 return error(NameLoc, "redefinition of global '@" + Name + "'");
1415 }
1416 } else {
1417 // Handle @"", where a name is syntactically specified, but semantically
1418 // missing.
1419 if (NameID == (unsigned)-1)
1420 NameID = NumberedVals.getNext();
1421
1422 auto I = ForwardRefValIDs.find(NameID);
1423 if (I != ForwardRefValIDs.end()) {
1424 GVal = I->second.first;
1425 ForwardRefValIDs.erase(I);
1426 }
1427 }
1428
1429 GlobalVariable *GV = new GlobalVariable(
1430 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1432
1433 if (Name.empty())
1434 NumberedVals.add(NameID, GV);
1435
1436 // Set the parsed properties on the global.
1437 if (Init)
1438 GV->setInitializer(Init);
1439 GV->setConstant(IsConstant);
1441 maybeSetDSOLocal(DSOLocal, *GV);
1444 GV->setExternallyInitialized(IsExternallyInitialized);
1445 GV->setThreadLocalMode(TLM);
1446 GV->setUnnamedAddr(UnnamedAddr);
1447
1448 if (GVal) {
1449 if (GVal->getAddressSpace() != AddrSpace)
1450 return error(
1451 TyLoc,
1452 "forward reference and definition of global have different types");
1453
1454 GVal->replaceAllUsesWith(GV);
1455 GVal->eraseFromParent();
1456 }
1457
1458 // parse attributes on the global.
1459 while (Lex.getKind() == lltok::comma) {
1460 Lex.Lex();
1461
1462 if (Lex.getKind() == lltok::kw_section) {
1463 Lex.Lex();
1464 GV->setSection(Lex.getStrVal());
1465 if (parseToken(lltok::StringConstant, "expected global section string"))
1466 return true;
1467 } else if (Lex.getKind() == lltok::kw_partition) {
1468 Lex.Lex();
1469 GV->setPartition(Lex.getStrVal());
1470 if (parseToken(lltok::StringConstant, "expected partition string"))
1471 return true;
1472 } else if (Lex.getKind() == lltok::kw_align) {
1473 MaybeAlign Alignment;
1474 if (parseOptionalAlignment(Alignment))
1475 return true;
1476 if (Alignment)
1477 GV->setAlignment(*Alignment);
1478 } else if (Lex.getKind() == lltok::kw_code_model) {
1480 if (parseOptionalCodeModel(CodeModel))
1481 return true;
1482 GV->setCodeModel(CodeModel);
1483 } else if (Lex.getKind() == lltok::MetadataVar) {
1484 if (parseGlobalObjectMetadataAttachment(*GV))
1485 return true;
1486 } else if (isSanitizer(Lex.getKind())) {
1487 if (parseSanitizer(GV))
1488 return true;
1489 } else {
1490 Comdat *C;
1491 if (parseOptionalComdat(Name, C))
1492 return true;
1493 if (C)
1494 GV->setComdat(C);
1495 else
1496 return tokError("unknown global variable property!");
1497 }
1498 }
1499
1500 AttrBuilder Attrs(M->getContext());
1501 LocTy BuiltinLoc;
1502 std::vector<unsigned> FwdRefAttrGrps;
1503 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1504 return true;
1505 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1506 GV->setAttributes(AttributeSet::get(Context, Attrs));
1507 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1508 }
1509
1510 return false;
1511}
1512
1513/// parseUnnamedAttrGrp
1514/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1515bool LLParser::parseUnnamedAttrGrp() {
1516 assert(Lex.getKind() == lltok::kw_attributes);
1517 LocTy AttrGrpLoc = Lex.getLoc();
1518 Lex.Lex();
1519
1520 if (Lex.getKind() != lltok::AttrGrpID)
1521 return tokError("expected attribute group id");
1522
1523 unsigned VarID = Lex.getUIntVal();
1524 std::vector<unsigned> unused;
1525 LocTy BuiltinLoc;
1526 Lex.Lex();
1527
1528 if (parseToken(lltok::equal, "expected '=' here") ||
1529 parseToken(lltok::lbrace, "expected '{' here"))
1530 return true;
1531
1532 auto R = NumberedAttrBuilders.find(VarID);
1533 if (R == NumberedAttrBuilders.end())
1534 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1535
1536 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1537 parseToken(lltok::rbrace, "expected end of attribute group"))
1538 return true;
1539
1540 if (!R->second.hasAttributes())
1541 return error(AttrGrpLoc, "attribute group has no attributes");
1542
1543 return false;
1544}
1545
1547 switch (Kind) {
1548#define GET_ATTR_NAMES
1549#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1550 case lltok::kw_##DISPLAY_NAME: \
1551 return Attribute::ENUM_NAME;
1552#include "llvm/IR/Attributes.inc"
1553 default:
1554 return Attribute::None;
1555 }
1556}
1557
1558bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1559 bool InAttrGroup) {
1560 if (Attribute::isTypeAttrKind(Attr))
1561 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1562
1563 switch (Attr) {
1564 case Attribute::Alignment: {
1565 MaybeAlign Alignment;
1566 if (InAttrGroup) {
1567 uint32_t Value = 0;
1568 Lex.Lex();
1569 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1570 return true;
1571 Alignment = Align(Value);
1572 } else {
1573 if (parseOptionalAlignment(Alignment, true))
1574 return true;
1575 }
1576 B.addAlignmentAttr(Alignment);
1577 return false;
1578 }
1579 case Attribute::StackAlignment: {
1580 unsigned Alignment;
1581 if (InAttrGroup) {
1582 Lex.Lex();
1583 if (parseToken(lltok::equal, "expected '=' here") ||
1584 parseUInt32(Alignment))
1585 return true;
1586 } else {
1587 if (parseOptionalStackAlignment(Alignment))
1588 return true;
1589 }
1590 B.addStackAlignmentAttr(Alignment);
1591 return false;
1592 }
1593 case Attribute::AllocSize: {
1594 unsigned ElemSizeArg;
1595 std::optional<unsigned> NumElemsArg;
1596 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1597 return true;
1598 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1599 return false;
1600 }
1601 case Attribute::VScaleRange: {
1602 unsigned MinValue, MaxValue;
1603 if (parseVScaleRangeArguments(MinValue, MaxValue))
1604 return true;
1605 B.addVScaleRangeAttr(MinValue,
1606 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1607 return false;
1608 }
1609 case Attribute::Dereferenceable: {
1610 uint64_t Bytes;
1611 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1612 return true;
1613 B.addDereferenceableAttr(Bytes);
1614 return false;
1615 }
1616 case Attribute::DereferenceableOrNull: {
1617 uint64_t Bytes;
1618 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1619 return true;
1620 B.addDereferenceableOrNullAttr(Bytes);
1621 return false;
1622 }
1623 case Attribute::UWTable: {
1625 if (parseOptionalUWTableKind(Kind))
1626 return true;
1627 B.addUWTableAttr(Kind);
1628 return false;
1629 }
1630 case Attribute::AllocKind: {
1632 if (parseAllocKind(Kind))
1633 return true;
1634 B.addAllocKindAttr(Kind);
1635 return false;
1636 }
1637 case Attribute::Memory: {
1638 std::optional<MemoryEffects> ME = parseMemoryAttr();
1639 if (!ME)
1640 return true;
1641 B.addMemoryAttr(*ME);
1642 return false;
1643 }
1644 case Attribute::NoFPClass: {
1645 if (FPClassTest NoFPClass =
1646 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1647 B.addNoFPClassAttr(NoFPClass);
1648 return false;
1649 }
1650
1651 return true;
1652 }
1653 case Attribute::Range:
1654 return parseRangeAttr(B);
1655 case Attribute::Initializes:
1656 return parseInitializesAttr(B);
1657 case Attribute::Captures:
1658 return parseCapturesAttr(B);
1659 default:
1660 B.addAttribute(Attr);
1661 Lex.Lex();
1662 return false;
1663 }
1664}
1665
1667 switch (Kind) {
1668 case lltok::kw_readnone:
1669 ME &= MemoryEffects::none();
1670 return true;
1671 case lltok::kw_readonly:
1673 return true;
1674 case lltok::kw_writeonly:
1676 return true;
1679 return true;
1682 return true;
1685 return true;
1686 default:
1687 return false;
1688 }
1689}
1690
1691/// parseFnAttributeValuePairs
1692/// ::= <attr> | <attr> '=' <value>
1693bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1694 std::vector<unsigned> &FwdRefAttrGrps,
1695 bool InAttrGrp, LocTy &BuiltinLoc) {
1696 bool HaveError = false;
1697
1698 B.clear();
1699
1701 while (true) {
1702 lltok::Kind Token = Lex.getKind();
1703 if (Token == lltok::rbrace)
1704 break; // Finished.
1705
1706 if (Token == lltok::StringConstant) {
1707 if (parseStringAttribute(B))
1708 return true;
1709 continue;
1710 }
1711
1712 if (Token == lltok::AttrGrpID) {
1713 // Allow a function to reference an attribute group:
1714 //
1715 // define void @foo() #1 { ... }
1716 if (InAttrGrp) {
1717 HaveError |= error(
1718 Lex.getLoc(),
1719 "cannot have an attribute group reference in an attribute group");
1720 } else {
1721 // Save the reference to the attribute group. We'll fill it in later.
1722 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1723 }
1724 Lex.Lex();
1725 continue;
1726 }
1727
1728 SMLoc Loc = Lex.getLoc();
1729 if (Token == lltok::kw_builtin)
1730 BuiltinLoc = Loc;
1731
1732 if (upgradeMemoryAttr(ME, Token)) {
1733 Lex.Lex();
1734 continue;
1735 }
1736
1738 if (Attr == Attribute::None) {
1739 if (!InAttrGrp)
1740 break;
1741 return error(Lex.getLoc(), "unterminated attribute group");
1742 }
1743
1744 if (parseEnumAttribute(Attr, B, InAttrGrp))
1745 return true;
1746
1747 // As a hack, we allow function alignment to be initially parsed as an
1748 // attribute on a function declaration/definition or added to an attribute
1749 // group and later moved to the alignment field.
1750 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1751 HaveError |= error(Loc, "this attribute does not apply to functions");
1752 }
1753
1754 if (ME != MemoryEffects::unknown())
1755 B.addMemoryAttr(ME);
1756 return HaveError;
1757}
1758
1759//===----------------------------------------------------------------------===//
1760// GlobalValue Reference/Resolution Routines.
1761//===----------------------------------------------------------------------===//
1762
1764 // The used global type does not matter. We will later RAUW it with a
1765 // global/function of the correct type.
1766 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1769 PTy->getAddressSpace());
1770}
1771
1772Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1773 Value *Val) {
1774 Type *ValTy = Val->getType();
1775 if (ValTy == Ty)
1776 return Val;
1777 if (Ty->isLabelTy())
1778 error(Loc, "'" + Name + "' is not a basic block");
1779 else
1780 error(Loc, "'" + Name + "' defined with type '" +
1781 getTypeString(Val->getType()) + "' but expected '" +
1782 getTypeString(Ty) + "'");
1783 return nullptr;
1784}
1785
1786/// getGlobalVal - Get a value with the specified name or ID, creating a
1787/// forward reference record if needed. This can return null if the value
1788/// exists but does not have the right type.
1789GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1790 LocTy Loc) {
1792 if (!PTy) {
1793 error(Loc, "global variable reference must have pointer type");
1794 return nullptr;
1795 }
1796
1797 // Look this name up in the normal function symbol table.
1798 GlobalValue *Val =
1799 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1800
1801 // If this is a forward reference for the value, see if we already created a
1802 // forward ref record.
1803 if (!Val) {
1804 auto I = ForwardRefVals.find(Name);
1805 if (I != ForwardRefVals.end())
1806 Val = I->second.first;
1807 }
1808
1809 // If we have the value in the symbol table or fwd-ref table, return it.
1810 if (Val)
1812 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1813
1814 // Otherwise, create a new forward reference for this value and remember it.
1815 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1816 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1817 return FwdVal;
1818}
1819
1820GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1822 if (!PTy) {
1823 error(Loc, "global variable reference must have pointer type");
1824 return nullptr;
1825 }
1826
1827 GlobalValue *Val = NumberedVals.get(ID);
1828
1829 // If this is a forward reference for the value, see if we already created a
1830 // forward ref record.
1831 if (!Val) {
1832 auto I = ForwardRefValIDs.find(ID);
1833 if (I != ForwardRefValIDs.end())
1834 Val = I->second.first;
1835 }
1836
1837 // If we have the value in the symbol table or fwd-ref table, return it.
1838 if (Val)
1840 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1841
1842 // Otherwise, create a new forward reference for this value and remember it.
1843 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1844 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1845 return FwdVal;
1846}
1847
1848//===----------------------------------------------------------------------===//
1849// Comdat Reference/Resolution Routines.
1850//===----------------------------------------------------------------------===//
1851
1852Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1853 // Look this name up in the comdat symbol table.
1854 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1855 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1856 if (I != ComdatSymTab.end())
1857 return &I->second;
1858
1859 // Otherwise, create a new forward reference for this value and remember it.
1860 Comdat *C = M->getOrInsertComdat(Name);
1861 ForwardRefComdats[Name] = Loc;
1862 return C;
1863}
1864
1865//===----------------------------------------------------------------------===//
1866// Helper Routines.
1867//===----------------------------------------------------------------------===//
1868
1869/// parseToken - If the current token has the specified kind, eat it and return
1870/// success. Otherwise, emit the specified error and return failure.
1871bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1872 if (Lex.getKind() != T)
1873 return tokError(ErrMsg);
1874 Lex.Lex();
1875 return false;
1876}
1877
1878/// parseStringConstant
1879/// ::= StringConstant
1880bool LLParser::parseStringConstant(std::string &Result) {
1881 if (Lex.getKind() != lltok::StringConstant)
1882 return tokError("expected string constant");
1883 Result = Lex.getStrVal();
1884 Lex.Lex();
1885 return false;
1886}
1887
1888/// parseUInt32
1889/// ::= uint32
1890bool LLParser::parseUInt32(uint32_t &Val) {
1891 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1892 return tokError("expected integer");
1893 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1894 if (Val64 != unsigned(Val64))
1895 return tokError("expected 32-bit integer (too large)");
1896 Val = Val64;
1897 Lex.Lex();
1898 return false;
1899}
1900
1901/// parseUInt64
1902/// ::= uint64
1903bool LLParser::parseUInt64(uint64_t &Val) {
1904 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1905 return tokError("expected integer");
1906 Val = Lex.getAPSIntVal().getLimitedValue();
1907 Lex.Lex();
1908 return false;
1909}
1910
1911/// parseTLSModel
1912/// := 'localdynamic'
1913/// := 'initialexec'
1914/// := 'localexec'
1915bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1916 switch (Lex.getKind()) {
1917 default:
1918 return tokError("expected localdynamic, initialexec or localexec");
1921 break;
1924 break;
1927 break;
1928 }
1929
1930 Lex.Lex();
1931 return false;
1932}
1933
1934/// parseOptionalThreadLocal
1935/// := /*empty*/
1936/// := 'thread_local'
1937/// := 'thread_local' '(' tlsmodel ')'
1938bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1940 if (!EatIfPresent(lltok::kw_thread_local))
1941 return false;
1942
1944 if (Lex.getKind() == lltok::lparen) {
1945 Lex.Lex();
1946 return parseTLSModel(TLM) ||
1947 parseToken(lltok::rparen, "expected ')' after thread local model");
1948 }
1949 return false;
1950}
1951
1952/// parseOptionalAddrSpace
1953/// := /*empty*/
1954/// := 'addrspace' '(' uint32 ')'
1955bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1956 AddrSpace = DefaultAS;
1957 if (!EatIfPresent(lltok::kw_addrspace))
1958 return false;
1959
1960 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1961 if (Lex.getKind() == lltok::StringConstant) {
1962 auto AddrSpaceStr = Lex.getStrVal();
1963 if (AddrSpaceStr == "A") {
1964 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1965 } else if (AddrSpaceStr == "G") {
1966 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1967 } else if (AddrSpaceStr == "P") {
1968 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1969 } else {
1970 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1971 }
1972 Lex.Lex();
1973 return false;
1974 }
1975 if (Lex.getKind() != lltok::APSInt)
1976 return tokError("expected integer or string constant");
1977 SMLoc Loc = Lex.getLoc();
1978 if (parseUInt32(AddrSpace))
1979 return true;
1980 if (!isUInt<24>(AddrSpace))
1981 return error(Loc, "invalid address space, must be a 24-bit integer");
1982 return false;
1983 };
1984
1985 return parseToken(lltok::lparen, "expected '(' in address space") ||
1986 ParseAddrspaceValue(AddrSpace) ||
1987 parseToken(lltok::rparen, "expected ')' in address space");
1988}
1989
1990/// parseStringAttribute
1991/// := StringConstant
1992/// := StringConstant '=' StringConstant
1993bool LLParser::parseStringAttribute(AttrBuilder &B) {
1994 std::string Attr = Lex.getStrVal();
1995 Lex.Lex();
1996 std::string Val;
1997 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1998 return true;
1999 B.addAttribute(Attr, Val);
2000 return false;
2001}
2002
2003/// Parse a potentially empty list of parameter or return attributes.
2004bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2005 bool HaveError = false;
2006
2007 B.clear();
2008
2009 while (true) {
2010 lltok::Kind Token = Lex.getKind();
2011 if (Token == lltok::StringConstant) {
2012 if (parseStringAttribute(B))
2013 return true;
2014 continue;
2015 }
2016
2017 if (Token == lltok::kw_nocapture) {
2018 Lex.Lex();
2019 B.addCapturesAttr(CaptureInfo::none());
2020 continue;
2021 }
2022
2023 SMLoc Loc = Lex.getLoc();
2025 if (Attr == Attribute::None)
2026 return HaveError;
2027
2028 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2029 return true;
2030
2031 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2032 HaveError |= error(Loc, "this attribute does not apply to parameters");
2033 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2034 HaveError |= error(Loc, "this attribute does not apply to return values");
2035 }
2036}
2037
2038static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2039 HasLinkage = true;
2040 switch (Kind) {
2041 default:
2042 HasLinkage = false;
2044 case lltok::kw_private:
2046 case lltok::kw_internal:
2048 case lltok::kw_weak:
2050 case lltok::kw_weak_odr:
2052 case lltok::kw_linkonce:
2060 case lltok::kw_common:
2064 case lltok::kw_external:
2066 }
2067}
2068
2069/// parseOptionalLinkage
2070/// ::= /*empty*/
2071/// ::= 'private'
2072/// ::= 'internal'
2073/// ::= 'weak'
2074/// ::= 'weak_odr'
2075/// ::= 'linkonce'
2076/// ::= 'linkonce_odr'
2077/// ::= 'available_externally'
2078/// ::= 'appending'
2079/// ::= 'common'
2080/// ::= 'extern_weak'
2081/// ::= 'external'
2082bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2083 unsigned &Visibility,
2084 unsigned &DLLStorageClass, bool &DSOLocal) {
2085 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2086 if (HasLinkage)
2087 Lex.Lex();
2088 parseOptionalDSOLocal(DSOLocal);
2089 parseOptionalVisibility(Visibility);
2090 parseOptionalDLLStorageClass(DLLStorageClass);
2091
2092 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2093 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2094 }
2095
2096 return false;
2097}
2098
2099void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2100 switch (Lex.getKind()) {
2101 default:
2102 DSOLocal = false;
2103 break;
2105 DSOLocal = true;
2106 Lex.Lex();
2107 break;
2109 DSOLocal = false;
2110 Lex.Lex();
2111 break;
2112 }
2113}
2114
2115/// parseOptionalVisibility
2116/// ::= /*empty*/
2117/// ::= 'default'
2118/// ::= 'hidden'
2119/// ::= 'protected'
2120///
2121void LLParser::parseOptionalVisibility(unsigned &Res) {
2122 switch (Lex.getKind()) {
2123 default:
2125 return;
2126 case lltok::kw_default:
2128 break;
2129 case lltok::kw_hidden:
2131 break;
2134 break;
2135 }
2136 Lex.Lex();
2137}
2138
2139bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2141 switch (Kind) {
2142 default:
2143 return tokError("unknown import kind. Expect definition or declaration.");
2146 return false;
2149 return false;
2150 }
2151}
2152
2153/// parseOptionalDLLStorageClass
2154/// ::= /*empty*/
2155/// ::= 'dllimport'
2156/// ::= 'dllexport'
2157///
2158void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2159 switch (Lex.getKind()) {
2160 default:
2162 return;
2165 break;
2168 break;
2169 }
2170 Lex.Lex();
2171}
2172
2173/// parseOptionalCallingConv
2174/// ::= /*empty*/
2175/// ::= 'ccc'
2176/// ::= 'fastcc'
2177/// ::= 'intel_ocl_bicc'
2178/// ::= 'coldcc'
2179/// ::= 'cfguard_checkcc'
2180/// ::= 'x86_stdcallcc'
2181/// ::= 'x86_fastcallcc'
2182/// ::= 'x86_thiscallcc'
2183/// ::= 'x86_vectorcallcc'
2184/// ::= 'arm_apcscc'
2185/// ::= 'arm_aapcscc'
2186/// ::= 'arm_aapcs_vfpcc'
2187/// ::= 'aarch64_vector_pcs'
2188/// ::= 'aarch64_sve_vector_pcs'
2189/// ::= 'aarch64_sme_preservemost_from_x0'
2190/// ::= 'aarch64_sme_preservemost_from_x1'
2191/// ::= 'aarch64_sme_preservemost_from_x2'
2192/// ::= 'msp430_intrcc'
2193/// ::= 'avr_intrcc'
2194/// ::= 'avr_signalcc'
2195/// ::= 'ptx_kernel'
2196/// ::= 'ptx_device'
2197/// ::= 'spir_func'
2198/// ::= 'spir_kernel'
2199/// ::= 'x86_64_sysvcc'
2200/// ::= 'win64cc'
2201/// ::= 'anyregcc'
2202/// ::= 'preserve_mostcc'
2203/// ::= 'preserve_allcc'
2204/// ::= 'preserve_nonecc'
2205/// ::= 'ghccc'
2206/// ::= 'swiftcc'
2207/// ::= 'swifttailcc'
2208/// ::= 'x86_intrcc'
2209/// ::= 'hhvmcc'
2210/// ::= 'hhvm_ccc'
2211/// ::= 'cxx_fast_tlscc'
2212/// ::= 'amdgpu_vs'
2213/// ::= 'amdgpu_ls'
2214/// ::= 'amdgpu_hs'
2215/// ::= 'amdgpu_es'
2216/// ::= 'amdgpu_gs'
2217/// ::= 'amdgpu_ps'
2218/// ::= 'amdgpu_cs'
2219/// ::= 'amdgpu_cs_chain'
2220/// ::= 'amdgpu_cs_chain_preserve'
2221/// ::= 'amdgpu_kernel'
2222/// ::= 'tailcc'
2223/// ::= 'm68k_rtdcc'
2224/// ::= 'graalcc'
2225/// ::= 'riscv_vector_cc'
2226/// ::= 'riscv_vls_cc'
2227/// ::= 'cc' UINT
2228///
2229bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2230 switch (Lex.getKind()) {
2231 default: CC = CallingConv::C; return false;
2232 case lltok::kw_ccc: CC = CallingConv::C; break;
2233 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2234 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2247 break;
2250 break;
2253 break;
2256 break;
2266 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2267 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2271 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2272 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2275 case lltok::kw_hhvmcc:
2277 break;
2278 case lltok::kw_hhvm_ccc:
2280 break;
2292 break;
2295 break;
2299 break;
2300 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2302 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2305 break;
2307 // Default ABI_VLEN
2309 Lex.Lex();
2310 if (!EatIfPresent(lltok::lparen))
2311 break;
2312 uint32_t ABIVlen;
2313 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2314 return true;
2315 switch (ABIVlen) {
2316 default:
2317 return tokError("unknown RISC-V ABI VLEN");
2318#define CC_VLS_CASE(ABIVlen) \
2319 case ABIVlen: \
2320 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2321 break;
2322 CC_VLS_CASE(32)
2323 CC_VLS_CASE(64)
2324 CC_VLS_CASE(128)
2325 CC_VLS_CASE(256)
2326 CC_VLS_CASE(512)
2327 CC_VLS_CASE(1024)
2328 CC_VLS_CASE(2048)
2329 CC_VLS_CASE(4096)
2330 CC_VLS_CASE(8192)
2331 CC_VLS_CASE(16384)
2332 CC_VLS_CASE(32768)
2333 CC_VLS_CASE(65536)
2334#undef CC_VLS_CASE
2335 }
2336 return false;
2339 break;
2342 break;
2345 break;
2346 case lltok::kw_cc: {
2347 Lex.Lex();
2348 return parseUInt32(CC);
2349 }
2350 }
2351
2352 Lex.Lex();
2353 return false;
2354}
2355
2356/// parseMetadataAttachment
2357/// ::= !dbg !42
2358bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2359 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2360
2361 std::string Name = Lex.getStrVal();
2362 Kind = M->getMDKindID(Name);
2363 Lex.Lex();
2364
2365 return parseMDNode(MD);
2366}
2367
2368/// parseInstructionMetadata
2369/// ::= !dbg !42 (',' !dbg !57)*
2370bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2371 do {
2372 if (Lex.getKind() != lltok::MetadataVar)
2373 return tokError("expected metadata after comma");
2374
2375 unsigned MDK;
2376 MDNode *N;
2377 if (parseMetadataAttachment(MDK, N))
2378 return true;
2379
2380 if (MDK == LLVMContext::MD_DIAssignID)
2381 TempDIAssignIDAttachments[N].push_back(&Inst);
2382 else
2383 Inst.setMetadata(MDK, N);
2384
2385 if (MDK == LLVMContext::MD_tbaa)
2386 InstsWithTBAATag.push_back(&Inst);
2387
2388 // If this is the end of the list, we're done.
2389 } while (EatIfPresent(lltok::comma));
2390 return false;
2391}
2392
2393/// parseGlobalObjectMetadataAttachment
2394/// ::= !dbg !57
2395bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2396 unsigned MDK;
2397 MDNode *N;
2398 if (parseMetadataAttachment(MDK, N))
2399 return true;
2400
2401 GO.addMetadata(MDK, *N);
2402 return false;
2403}
2404
2405/// parseOptionalFunctionMetadata
2406/// ::= (!dbg !57)*
2407bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2408 while (Lex.getKind() == lltok::MetadataVar)
2409 if (parseGlobalObjectMetadataAttachment(F))
2410 return true;
2411 return false;
2412}
2413
2414/// parseOptionalAlignment
2415/// ::= /* empty */
2416/// ::= 'align' 4
2417bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2418 Alignment = std::nullopt;
2419 if (!EatIfPresent(lltok::kw_align))
2420 return false;
2421 LocTy AlignLoc = Lex.getLoc();
2422 uint64_t Value = 0;
2423
2424 LocTy ParenLoc = Lex.getLoc();
2425 bool HaveParens = false;
2426 if (AllowParens) {
2427 if (EatIfPresent(lltok::lparen))
2428 HaveParens = true;
2429 }
2430
2431 if (parseUInt64(Value))
2432 return true;
2433
2434 if (HaveParens && !EatIfPresent(lltok::rparen))
2435 return error(ParenLoc, "expected ')'");
2436
2437 if (!isPowerOf2_64(Value))
2438 return error(AlignLoc, "alignment is not a power of two");
2440 return error(AlignLoc, "huge alignments are not supported yet");
2441 Alignment = Align(Value);
2442 return false;
2443}
2444
2445/// parseOptionalCodeModel
2446/// ::= /* empty */
2447/// ::= 'code_model' "large"
2448bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2449 Lex.Lex();
2450 auto StrVal = Lex.getStrVal();
2451 auto ErrMsg = "expected global code model string";
2452 if (StrVal == "tiny")
2453 model = CodeModel::Tiny;
2454 else if (StrVal == "small")
2455 model = CodeModel::Small;
2456 else if (StrVal == "kernel")
2457 model = CodeModel::Kernel;
2458 else if (StrVal == "medium")
2459 model = CodeModel::Medium;
2460 else if (StrVal == "large")
2461 model = CodeModel::Large;
2462 else
2463 return tokError(ErrMsg);
2464 if (parseToken(lltok::StringConstant, ErrMsg))
2465 return true;
2466 return false;
2467}
2468
2469/// parseOptionalDerefAttrBytes
2470/// ::= /* empty */
2471/// ::= AttrKind '(' 4 ')'
2472///
2473/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2474bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2475 uint64_t &Bytes) {
2476 assert((AttrKind == lltok::kw_dereferenceable ||
2477 AttrKind == lltok::kw_dereferenceable_or_null) &&
2478 "contract!");
2479
2480 Bytes = 0;
2481 if (!EatIfPresent(AttrKind))
2482 return false;
2483 LocTy ParenLoc = Lex.getLoc();
2484 if (!EatIfPresent(lltok::lparen))
2485 return error(ParenLoc, "expected '('");
2486 LocTy DerefLoc = Lex.getLoc();
2487 if (parseUInt64(Bytes))
2488 return true;
2489 ParenLoc = Lex.getLoc();
2490 if (!EatIfPresent(lltok::rparen))
2491 return error(ParenLoc, "expected ')'");
2492 if (!Bytes)
2493 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2494 return false;
2495}
2496
2497bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2498 Lex.Lex();
2500 if (!EatIfPresent(lltok::lparen))
2501 return false;
2502 LocTy KindLoc = Lex.getLoc();
2503 if (Lex.getKind() == lltok::kw_sync)
2505 else if (Lex.getKind() == lltok::kw_async)
2507 else
2508 return error(KindLoc, "expected unwind table kind");
2509 Lex.Lex();
2510 return parseToken(lltok::rparen, "expected ')'");
2511}
2512
2513bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2514 Lex.Lex();
2515 LocTy ParenLoc = Lex.getLoc();
2516 if (!EatIfPresent(lltok::lparen))
2517 return error(ParenLoc, "expected '('");
2518 LocTy KindLoc = Lex.getLoc();
2519 std::string Arg;
2520 if (parseStringConstant(Arg))
2521 return error(KindLoc, "expected allockind value");
2522 for (StringRef A : llvm::split(Arg, ",")) {
2523 if (A == "alloc") {
2525 } else if (A == "realloc") {
2527 } else if (A == "free") {
2529 } else if (A == "uninitialized") {
2531 } else if (A == "zeroed") {
2533 } else if (A == "aligned") {
2535 } else {
2536 return error(KindLoc, Twine("unknown allockind ") + A);
2537 }
2538 }
2539 ParenLoc = Lex.getLoc();
2540 if (!EatIfPresent(lltok::rparen))
2541 return error(ParenLoc, "expected ')'");
2542 if (Kind == AllocFnKind::Unknown)
2543 return error(KindLoc, "expected allockind value");
2544 return false;
2545}
2546
2547static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2548 switch (Tok) {
2549 case lltok::kw_argmem:
2550 return IRMemLocation::ArgMem;
2553 case lltok::kw_errnomem:
2555 default:
2556 return std::nullopt;
2557 }
2558}
2559
2560static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2561 switch (Tok) {
2562 case lltok::kw_none:
2563 return ModRefInfo::NoModRef;
2564 case lltok::kw_read:
2565 return ModRefInfo::Ref;
2566 case lltok::kw_write:
2567 return ModRefInfo::Mod;
2569 return ModRefInfo::ModRef;
2570 default:
2571 return std::nullopt;
2572 }
2573}
2574
2575std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2577
2578 // We use syntax like memory(argmem: read), so the colon should not be
2579 // interpreted as a label terminator.
2580 Lex.setIgnoreColonInIdentifiers(true);
2581 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2582
2583 Lex.Lex();
2584 if (!EatIfPresent(lltok::lparen)) {
2585 tokError("expected '('");
2586 return std::nullopt;
2587 }
2588
2589 bool SeenLoc = false;
2590 do {
2591 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2592 if (Loc) {
2593 Lex.Lex();
2594 if (!EatIfPresent(lltok::colon)) {
2595 tokError("expected ':' after location");
2596 return std::nullopt;
2597 }
2598 }
2599
2600 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2601 if (!MR) {
2602 if (!Loc)
2603 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2604 "or access kind (none, read, write, readwrite)");
2605 else
2606 tokError("expected access kind (none, read, write, readwrite)");
2607 return std::nullopt;
2608 }
2609
2610 Lex.Lex();
2611 if (Loc) {
2612 SeenLoc = true;
2613 ME = ME.getWithModRef(*Loc, *MR);
2614 } else {
2615 if (SeenLoc) {
2616 tokError("default access kind must be specified first");
2617 return std::nullopt;
2618 }
2619 ME = MemoryEffects(*MR);
2620 }
2621
2622 if (EatIfPresent(lltok::rparen))
2623 return ME;
2624 } while (EatIfPresent(lltok::comma));
2625
2626 tokError("unterminated memory attribute");
2627 return std::nullopt;
2628}
2629
2630static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2631 switch (Tok) {
2632 case lltok::kw_all:
2633 return fcAllFlags;
2634 case lltok::kw_nan:
2635 return fcNan;
2636 case lltok::kw_snan:
2637 return fcSNan;
2638 case lltok::kw_qnan:
2639 return fcQNan;
2640 case lltok::kw_inf:
2641 return fcInf;
2642 case lltok::kw_ninf:
2643 return fcNegInf;
2644 case lltok::kw_pinf:
2645 return fcPosInf;
2646 case lltok::kw_norm:
2647 return fcNormal;
2648 case lltok::kw_nnorm:
2649 return fcNegNormal;
2650 case lltok::kw_pnorm:
2651 return fcPosNormal;
2652 case lltok::kw_sub:
2653 return fcSubnormal;
2654 case lltok::kw_nsub:
2655 return fcNegSubnormal;
2656 case lltok::kw_psub:
2657 return fcPosSubnormal;
2658 case lltok::kw_zero:
2659 return fcZero;
2660 case lltok::kw_nzero:
2661 return fcNegZero;
2662 case lltok::kw_pzero:
2663 return fcPosZero;
2664 default:
2665 return 0;
2666 }
2667}
2668
2669unsigned LLParser::parseNoFPClassAttr() {
2670 unsigned Mask = fcNone;
2671
2672 Lex.Lex();
2673 if (!EatIfPresent(lltok::lparen)) {
2674 tokError("expected '('");
2675 return 0;
2676 }
2677
2678 do {
2679 uint64_t Value = 0;
2680 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2681 if (TestMask != 0) {
2682 Mask |= TestMask;
2683 // TODO: Disallow overlapping masks to avoid copy paste errors
2684 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2685 !parseUInt64(Value)) {
2686 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2687 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2688 return 0;
2689 }
2690
2691 if (!EatIfPresent(lltok::rparen)) {
2692 error(Lex.getLoc(), "expected ')'");
2693 return 0;
2694 }
2695
2696 return Value;
2697 } else {
2698 error(Lex.getLoc(), "expected nofpclass test mask");
2699 return 0;
2700 }
2701
2702 Lex.Lex();
2703 if (EatIfPresent(lltok::rparen))
2704 return Mask;
2705 } while (1);
2706
2707 llvm_unreachable("unterminated nofpclass attribute");
2708}
2709
2710/// parseOptionalCommaAlign
2711/// ::=
2712/// ::= ',' align 4
2713///
2714/// This returns with AteExtraComma set to true if it ate an excess comma at the
2715/// end.
2716bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2717 bool &AteExtraComma) {
2718 AteExtraComma = false;
2719 while (EatIfPresent(lltok::comma)) {
2720 // Metadata at the end is an early exit.
2721 if (Lex.getKind() == lltok::MetadataVar) {
2722 AteExtraComma = true;
2723 return false;
2724 }
2725
2726 if (Lex.getKind() != lltok::kw_align)
2727 return error(Lex.getLoc(), "expected metadata or 'align'");
2728
2729 if (parseOptionalAlignment(Alignment))
2730 return true;
2731 }
2732
2733 return false;
2734}
2735
2736/// parseOptionalCommaAddrSpace
2737/// ::=
2738/// ::= ',' addrspace(1)
2739///
2740/// This returns with AteExtraComma set to true if it ate an excess comma at the
2741/// end.
2742bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2743 bool &AteExtraComma) {
2744 AteExtraComma = false;
2745 while (EatIfPresent(lltok::comma)) {
2746 // Metadata at the end is an early exit.
2747 if (Lex.getKind() == lltok::MetadataVar) {
2748 AteExtraComma = true;
2749 return false;
2750 }
2751
2752 Loc = Lex.getLoc();
2753 if (Lex.getKind() != lltok::kw_addrspace)
2754 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2755
2756 if (parseOptionalAddrSpace(AddrSpace))
2757 return true;
2758 }
2759
2760 return false;
2761}
2762
2763bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2764 std::optional<unsigned> &HowManyArg) {
2765 Lex.Lex();
2766
2767 auto StartParen = Lex.getLoc();
2768 if (!EatIfPresent(lltok::lparen))
2769 return error(StartParen, "expected '('");
2770
2771 if (parseUInt32(BaseSizeArg))
2772 return true;
2773
2774 if (EatIfPresent(lltok::comma)) {
2775 auto HowManyAt = Lex.getLoc();
2776 unsigned HowMany;
2777 if (parseUInt32(HowMany))
2778 return true;
2779 if (HowMany == BaseSizeArg)
2780 return error(HowManyAt,
2781 "'allocsize' indices can't refer to the same parameter");
2782 HowManyArg = HowMany;
2783 } else
2784 HowManyArg = std::nullopt;
2785
2786 auto EndParen = Lex.getLoc();
2787 if (!EatIfPresent(lltok::rparen))
2788 return error(EndParen, "expected ')'");
2789 return false;
2790}
2791
2792bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2793 unsigned &MaxValue) {
2794 Lex.Lex();
2795
2796 auto StartParen = Lex.getLoc();
2797 if (!EatIfPresent(lltok::lparen))
2798 return error(StartParen, "expected '('");
2799
2800 if (parseUInt32(MinValue))
2801 return true;
2802
2803 if (EatIfPresent(lltok::comma)) {
2804 if (parseUInt32(MaxValue))
2805 return true;
2806 } else
2807 MaxValue = MinValue;
2808
2809 auto EndParen = Lex.getLoc();
2810 if (!EatIfPresent(lltok::rparen))
2811 return error(EndParen, "expected ')'");
2812 return false;
2813}
2814
2815/// parseScopeAndOrdering
2816/// if isAtomic: ::= SyncScope? AtomicOrdering
2817/// else: ::=
2818///
2819/// This sets Scope and Ordering to the parsed values.
2820bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2821 AtomicOrdering &Ordering) {
2822 if (!IsAtomic)
2823 return false;
2824
2825 return parseScope(SSID) || parseOrdering(Ordering);
2826}
2827
2828/// parseScope
2829/// ::= syncscope("singlethread" | "<target scope>")?
2830///
2831/// This sets synchronization scope ID to the ID of the parsed value.
2832bool LLParser::parseScope(SyncScope::ID &SSID) {
2833 SSID = SyncScope::System;
2834 if (EatIfPresent(lltok::kw_syncscope)) {
2835 auto StartParenAt = Lex.getLoc();
2836 if (!EatIfPresent(lltok::lparen))
2837 return error(StartParenAt, "Expected '(' in syncscope");
2838
2839 std::string SSN;
2840 auto SSNAt = Lex.getLoc();
2841 if (parseStringConstant(SSN))
2842 return error(SSNAt, "Expected synchronization scope name");
2843
2844 auto EndParenAt = Lex.getLoc();
2845 if (!EatIfPresent(lltok::rparen))
2846 return error(EndParenAt, "Expected ')' in syncscope");
2847
2848 SSID = Context.getOrInsertSyncScopeID(SSN);
2849 }
2850
2851 return false;
2852}
2853
2854/// parseOrdering
2855/// ::= AtomicOrdering
2856///
2857/// This sets Ordering to the parsed value.
2858bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2859 switch (Lex.getKind()) {
2860 default:
2861 return tokError("Expected ordering on atomic instruction");
2864 // Not specified yet:
2865 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2869 case lltok::kw_seq_cst:
2871 break;
2872 }
2873 Lex.Lex();
2874 return false;
2875}
2876
2877/// parseOptionalStackAlignment
2878/// ::= /* empty */
2879/// ::= 'alignstack' '(' 4 ')'
2880bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2881 Alignment = 0;
2882 if (!EatIfPresent(lltok::kw_alignstack))
2883 return false;
2884 LocTy ParenLoc = Lex.getLoc();
2885 if (!EatIfPresent(lltok::lparen))
2886 return error(ParenLoc, "expected '('");
2887 LocTy AlignLoc = Lex.getLoc();
2888 if (parseUInt32(Alignment))
2889 return true;
2890 ParenLoc = Lex.getLoc();
2891 if (!EatIfPresent(lltok::rparen))
2892 return error(ParenLoc, "expected ')'");
2893 if (!isPowerOf2_32(Alignment))
2894 return error(AlignLoc, "stack alignment is not a power of two");
2895 return false;
2896}
2897
2898/// parseIndexList - This parses the index list for an insert/extractvalue
2899/// instruction. This sets AteExtraComma in the case where we eat an extra
2900/// comma at the end of the line and find that it is followed by metadata.
2901/// Clients that don't allow metadata can call the version of this function that
2902/// only takes one argument.
2903///
2904/// parseIndexList
2905/// ::= (',' uint32)+
2906///
2907bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2908 bool &AteExtraComma) {
2909 AteExtraComma = false;
2910
2911 if (Lex.getKind() != lltok::comma)
2912 return tokError("expected ',' as start of index list");
2913
2914 while (EatIfPresent(lltok::comma)) {
2915 if (Lex.getKind() == lltok::MetadataVar) {
2916 if (Indices.empty())
2917 return tokError("expected index");
2918 AteExtraComma = true;
2919 return false;
2920 }
2921 unsigned Idx = 0;
2922 if (parseUInt32(Idx))
2923 return true;
2924 Indices.push_back(Idx);
2925 }
2926
2927 return false;
2928}
2929
2930//===----------------------------------------------------------------------===//
2931// Type Parsing.
2932//===----------------------------------------------------------------------===//
2933
2934/// parseType - parse a type.
2935bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2936 SMLoc TypeLoc = Lex.getLoc();
2937 switch (Lex.getKind()) {
2938 default:
2939 return tokError(Msg);
2940 case lltok::Type:
2941 // Type ::= 'float' | 'void' (etc)
2942 Result = Lex.getTyVal();
2943 Lex.Lex();
2944
2945 // Handle "ptr" opaque pointer type.
2946 //
2947 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2948 if (Result->isPointerTy()) {
2949 unsigned AddrSpace;
2950 if (parseOptionalAddrSpace(AddrSpace))
2951 return true;
2952 Result = PointerType::get(getContext(), AddrSpace);
2953
2954 // Give a nice error for 'ptr*'.
2955 if (Lex.getKind() == lltok::star)
2956 return tokError("ptr* is invalid - use ptr instead");
2957
2958 // Fall through to parsing the type suffixes only if this 'ptr' is a
2959 // function return. Otherwise, return success, implicitly rejecting other
2960 // suffixes.
2961 if (Lex.getKind() != lltok::lparen)
2962 return false;
2963 }
2964 break;
2965 case lltok::kw_target: {
2966 // Type ::= TargetExtType
2967 if (parseTargetExtType(Result))
2968 return true;
2969 break;
2970 }
2971 case lltok::lbrace:
2972 // Type ::= StructType
2973 if (parseAnonStructType(Result, false))
2974 return true;
2975 break;
2976 case lltok::lsquare:
2977 // Type ::= '[' ... ']'
2978 Lex.Lex(); // eat the lsquare.
2979 if (parseArrayVectorType(Result, false))
2980 return true;
2981 break;
2982 case lltok::less: // Either vector or packed struct.
2983 // Type ::= '<' ... '>'
2984 Lex.Lex();
2985 if (Lex.getKind() == lltok::lbrace) {
2986 if (parseAnonStructType(Result, true) ||
2987 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2988 return true;
2989 } else if (parseArrayVectorType(Result, true))
2990 return true;
2991 break;
2992 case lltok::LocalVar: {
2993 // Type ::= %foo
2994 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2995
2996 // If the type hasn't been defined yet, create a forward definition and
2997 // remember where that forward def'n was seen (in case it never is defined).
2998 if (!Entry.first) {
2999 Entry.first = StructType::create(Context, Lex.getStrVal());
3000 Entry.second = Lex.getLoc();
3001 }
3002 Result = Entry.first;
3003 Lex.Lex();
3004 break;
3005 }
3006
3007 case lltok::LocalVarID: {
3008 // Type ::= %4
3009 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3010
3011 // If the type hasn't been defined yet, create a forward definition and
3012 // remember where that forward def'n was seen (in case it never is defined).
3013 if (!Entry.first) {
3014 Entry.first = StructType::create(Context);
3015 Entry.second = Lex.getLoc();
3016 }
3017 Result = Entry.first;
3018 Lex.Lex();
3019 break;
3020 }
3021 }
3022
3023 // parse the type suffixes.
3024 while (true) {
3025 switch (Lex.getKind()) {
3026 // End of type.
3027 default:
3028 if (!AllowVoid && Result->isVoidTy())
3029 return error(TypeLoc, "void type only allowed for function results");
3030 return false;
3031
3032 // Type ::= Type '*'
3033 case lltok::star:
3034 if (Result->isLabelTy())
3035 return tokError("basic block pointers are invalid");
3036 if (Result->isVoidTy())
3037 return tokError("pointers to void are invalid - use i8* instead");
3039 return tokError("pointer to this type is invalid");
3040 Result = PointerType::getUnqual(Context);
3041 Lex.Lex();
3042 break;
3043
3044 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3045 case lltok::kw_addrspace: {
3046 if (Result->isLabelTy())
3047 return tokError("basic block pointers are invalid");
3048 if (Result->isVoidTy())
3049 return tokError("pointers to void are invalid; use i8* instead");
3051 return tokError("pointer to this type is invalid");
3052 unsigned AddrSpace;
3053 if (parseOptionalAddrSpace(AddrSpace) ||
3054 parseToken(lltok::star, "expected '*' in address space"))
3055 return true;
3056
3057 Result = PointerType::get(Context, AddrSpace);
3058 break;
3059 }
3060
3061 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3062 case lltok::lparen:
3063 if (parseFunctionType(Result))
3064 return true;
3065 break;
3066 }
3067 }
3068}
3069
3070/// parseParameterList
3071/// ::= '(' ')'
3072/// ::= '(' Arg (',' Arg)* ')'
3073/// Arg
3074/// ::= Type OptionalAttributes Value OptionalAttributes
3075bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3076 PerFunctionState &PFS, bool IsMustTailCall,
3077 bool InVarArgsFunc) {
3078 if (parseToken(lltok::lparen, "expected '(' in call"))
3079 return true;
3080
3081 while (Lex.getKind() != lltok::rparen) {
3082 // If this isn't the first argument, we need a comma.
3083 if (!ArgList.empty() &&
3084 parseToken(lltok::comma, "expected ',' in argument list"))
3085 return true;
3086
3087 // parse an ellipsis if this is a musttail call in a variadic function.
3088 if (Lex.getKind() == lltok::dotdotdot) {
3089 const char *Msg = "unexpected ellipsis in argument list for ";
3090 if (!IsMustTailCall)
3091 return tokError(Twine(Msg) + "non-musttail call");
3092 if (!InVarArgsFunc)
3093 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3094 Lex.Lex(); // Lex the '...', it is purely for readability.
3095 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3096 }
3097
3098 // parse the argument.
3099 LocTy ArgLoc;
3100 Type *ArgTy = nullptr;
3101 Value *V;
3102 if (parseType(ArgTy, ArgLoc))
3103 return true;
3105 return error(ArgLoc, "invalid type for function argument");
3106
3107 AttrBuilder ArgAttrs(M->getContext());
3108
3109 if (ArgTy->isMetadataTy()) {
3110 if (parseMetadataAsValue(V, PFS))
3111 return true;
3112 } else {
3113 // Otherwise, handle normal operands.
3114 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3115 return true;
3116 }
3117 ArgList.push_back(ParamInfo(
3118 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3119 }
3120
3121 if (IsMustTailCall && InVarArgsFunc)
3122 return tokError("expected '...' at end of argument list for musttail call "
3123 "in varargs function");
3124
3125 Lex.Lex(); // Lex the ')'.
3126 return false;
3127}
3128
3129/// parseRequiredTypeAttr
3130/// ::= attrname(<ty>)
3131bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3132 Attribute::AttrKind AttrKind) {
3133 Type *Ty = nullptr;
3134 if (!EatIfPresent(AttrToken))
3135 return true;
3136 if (!EatIfPresent(lltok::lparen))
3137 return error(Lex.getLoc(), "expected '('");
3138 if (parseType(Ty))
3139 return true;
3140 if (!EatIfPresent(lltok::rparen))
3141 return error(Lex.getLoc(), "expected ')'");
3142
3143 B.addTypeAttr(AttrKind, Ty);
3144 return false;
3145}
3146
3147/// parseRangeAttr
3148/// ::= range(<ty> <n>,<n>)
3149bool LLParser::parseRangeAttr(AttrBuilder &B) {
3150 Lex.Lex();
3151
3152 APInt Lower;
3153 APInt Upper;
3154 Type *Ty = nullptr;
3155 LocTy TyLoc;
3156
3157 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3158 if (Lex.getKind() != lltok::APSInt)
3159 return tokError("expected integer");
3160 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3161 return tokError(
3162 "integer is too large for the bit width of specified type");
3163 Val = Lex.getAPSIntVal().extend(BitWidth);
3164 Lex.Lex();
3165 return false;
3166 };
3167
3168 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3169 return true;
3170 if (!Ty->isIntegerTy())
3171 return error(TyLoc, "the range must have integer type!");
3172
3173 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3174
3175 if (ParseAPSInt(BitWidth, Lower) ||
3176 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3177 return true;
3178 if (Lower == Upper && !Lower.isZero())
3179 return tokError("the range represent the empty set but limits aren't 0!");
3180
3181 if (parseToken(lltok::rparen, "expected ')'"))
3182 return true;
3183
3184 B.addRangeAttr(ConstantRange(Lower, Upper));
3185 return false;
3186}
3187
3188/// parseInitializesAttr
3189/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3190bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3191 Lex.Lex();
3192
3193 auto ParseAPSInt = [&](APInt &Val) {
3194 if (Lex.getKind() != lltok::APSInt)
3195 return tokError("expected integer");
3196 Val = Lex.getAPSIntVal().extend(64);
3197 Lex.Lex();
3198 return false;
3199 };
3200
3201 if (parseToken(lltok::lparen, "expected '('"))
3202 return true;
3203
3205 // Parse each constant range.
3206 do {
3207 APInt Lower, Upper;
3208 if (parseToken(lltok::lparen, "expected '('"))
3209 return true;
3210
3211 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3212 ParseAPSInt(Upper))
3213 return true;
3214
3215 if (Lower == Upper)
3216 return tokError("the range should not represent the full or empty set!");
3217
3218 if (parseToken(lltok::rparen, "expected ')'"))
3219 return true;
3220
3221 RangeList.push_back(ConstantRange(Lower, Upper));
3222 } while (EatIfPresent(lltok::comma));
3223
3224 if (parseToken(lltok::rparen, "expected ')'"))
3225 return true;
3226
3227 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3228 if (!CRLOrNull.has_value())
3229 return tokError("Invalid (unordered or overlapping) range list");
3230 B.addInitializesAttr(*CRLOrNull);
3231 return false;
3232}
3233
3234bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3236 std::optional<CaptureComponents> Ret;
3237
3238 // We use syntax like captures(ret: address, provenance), so the colon
3239 // should not be interpreted as a label terminator.
3240 Lex.setIgnoreColonInIdentifiers(true);
3241 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
3242
3243 Lex.Lex();
3244 if (parseToken(lltok::lparen, "expected '('"))
3245 return true;
3246
3247 CaptureComponents *Current = &Other;
3248 bool SeenComponent = false;
3249 while (true) {
3250 if (EatIfPresent(lltok::kw_ret)) {
3251 if (parseToken(lltok::colon, "expected ':'"))
3252 return true;
3253 if (Ret)
3254 return tokError("duplicate 'ret' location");
3256 Current = &*Ret;
3257 SeenComponent = false;
3258 }
3259
3260 if (EatIfPresent(lltok::kw_none)) {
3261 if (SeenComponent)
3262 return tokError("cannot use 'none' with other component");
3263 *Current = CaptureComponents::None;
3264 } else {
3265 if (SeenComponent && capturesNothing(*Current))
3266 return tokError("cannot use 'none' with other component");
3267
3268 if (EatIfPresent(lltok::kw_address_is_null))
3270 else if (EatIfPresent(lltok::kw_address))
3271 *Current |= CaptureComponents::Address;
3272 else if (EatIfPresent(lltok::kw_provenance))
3274 else if (EatIfPresent(lltok::kw_read_provenance))
3276 else
3277 return tokError("expected one of 'none', 'address', 'address_is_null', "
3278 "'provenance' or 'read_provenance'");
3279 }
3280
3281 SeenComponent = true;
3282 if (EatIfPresent(lltok::rparen))
3283 break;
3284
3285 if (parseToken(lltok::comma, "expected ',' or ')'"))
3286 return true;
3287 }
3288
3289 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3290 return false;
3291}
3292
3293/// parseOptionalOperandBundles
3294/// ::= /*empty*/
3295/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3296///
3297/// OperandBundle
3298/// ::= bundle-tag '(' ')'
3299/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3300///
3301/// bundle-tag ::= String Constant
3302bool LLParser::parseOptionalOperandBundles(
3303 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3304 LocTy BeginLoc = Lex.getLoc();
3305 if (!EatIfPresent(lltok::lsquare))
3306 return false;
3307
3308 while (Lex.getKind() != lltok::rsquare) {
3309 // If this isn't the first operand bundle, we need a comma.
3310 if (!BundleList.empty() &&
3311 parseToken(lltok::comma, "expected ',' in input list"))
3312 return true;
3313
3314 std::string Tag;
3315 if (parseStringConstant(Tag))
3316 return true;
3317
3318 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3319 return true;
3320
3321 std::vector<Value *> Inputs;
3322 while (Lex.getKind() != lltok::rparen) {
3323 // If this isn't the first input, we need a comma.
3324 if (!Inputs.empty() &&
3325 parseToken(lltok::comma, "expected ',' in input list"))
3326 return true;
3327
3328 Type *Ty = nullptr;
3329 Value *Input = nullptr;
3330 if (parseType(Ty))
3331 return true;
3332 if (Ty->isMetadataTy()) {
3333 if (parseMetadataAsValue(Input, PFS))
3334 return true;
3335 } else if (parseValue(Ty, Input, PFS)) {
3336 return true;
3337 }
3338 Inputs.push_back(Input);
3339 }
3340
3341 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3342
3343 Lex.Lex(); // Lex the ')'.
3344 }
3345
3346 if (BundleList.empty())
3347 return error(BeginLoc, "operand bundle set must not be empty");
3348
3349 Lex.Lex(); // Lex the ']'.
3350 return false;
3351}
3352
3353bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3354 unsigned NextID, unsigned ID) {
3355 if (ID < NextID)
3356 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3357 Twine(NextID) + "' or greater");
3358
3359 return false;
3360}
3361
3362/// parseArgumentList - parse the argument list for a function type or function
3363/// prototype.
3364/// ::= '(' ArgTypeListI ')'
3365/// ArgTypeListI
3366/// ::= /*empty*/
3367/// ::= '...'
3368/// ::= ArgTypeList ',' '...'
3369/// ::= ArgType (',' ArgType)*
3370///
3371bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3372 SmallVectorImpl<unsigned> &UnnamedArgNums,
3373 bool &IsVarArg) {
3374 unsigned CurValID = 0;
3375 IsVarArg = false;
3376 assert(Lex.getKind() == lltok::lparen);
3377 Lex.Lex(); // eat the (.
3378
3379 if (Lex.getKind() != lltok::rparen) {
3380 do {
3381 // Handle ... at end of arg list.
3382 if (EatIfPresent(lltok::dotdotdot)) {
3383 IsVarArg = true;
3384 break;
3385 }
3386
3387 // Otherwise must be an argument type.
3388 LocTy TypeLoc = Lex.getLoc();
3389 Type *ArgTy = nullptr;
3390 AttrBuilder Attrs(M->getContext());
3391 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3392 return true;
3393
3394 if (ArgTy->isVoidTy())
3395 return error(TypeLoc, "argument can not have void type");
3396
3397 std::string Name;
3398 if (Lex.getKind() == lltok::LocalVar) {
3399 Name = Lex.getStrVal();
3400 Lex.Lex();
3401 } else {
3402 unsigned ArgID;
3403 if (Lex.getKind() == lltok::LocalVarID) {
3404 ArgID = Lex.getUIntVal();
3405 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3406 return true;
3407 Lex.Lex();
3408 } else {
3409 ArgID = CurValID;
3410 }
3411 UnnamedArgNums.push_back(ArgID);
3412 CurValID = ArgID + 1;
3413 }
3414
3416 return error(TypeLoc, "invalid type for function argument");
3417
3418 ArgList.emplace_back(TypeLoc, ArgTy,
3419 AttributeSet::get(ArgTy->getContext(), Attrs),
3420 std::move(Name));
3421 } while (EatIfPresent(lltok::comma));
3422 }
3423
3424 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3425}
3426
3427/// parseFunctionType
3428/// ::= Type ArgumentList OptionalAttrs
3429bool LLParser::parseFunctionType(Type *&Result) {
3430 assert(Lex.getKind() == lltok::lparen);
3431
3433 return tokError("invalid function return type");
3434
3436 bool IsVarArg;
3437 SmallVector<unsigned> UnnamedArgNums;
3438 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3439 return true;
3440
3441 // Reject names on the arguments lists.
3442 for (const ArgInfo &Arg : ArgList) {
3443 if (!Arg.Name.empty())
3444 return error(Arg.Loc, "argument name invalid in function type");
3445 if (Arg.Attrs.hasAttributes())
3446 return error(Arg.Loc, "argument attributes invalid in function type");
3447 }
3448
3449 SmallVector<Type*, 16> ArgListTy;
3450 for (const ArgInfo &Arg : ArgList)
3451 ArgListTy.push_back(Arg.Ty);
3452
3453 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3454 return false;
3455}
3456
3457/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3458/// other structs.
3459bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3461 if (parseStructBody(Elts))
3462 return true;
3463
3464 Result = StructType::get(Context, Elts, Packed);
3465 return false;
3466}
3467
3468/// parseStructDefinition - parse a struct in a 'type' definition.
3469bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3470 std::pair<Type *, LocTy> &Entry,
3471 Type *&ResultTy) {
3472 // If the type was already defined, diagnose the redefinition.
3473 if (Entry.first && !Entry.second.isValid())
3474 return error(TypeLoc, "redefinition of type");
3475
3476 // If we have opaque, just return without filling in the definition for the
3477 // struct. This counts as a definition as far as the .ll file goes.
3478 if (EatIfPresent(lltok::kw_opaque)) {
3479 // This type is being defined, so clear the location to indicate this.
3480 Entry.second = SMLoc();
3481
3482 // If this type number has never been uttered, create it.
3483 if (!Entry.first)
3484 Entry.first = StructType::create(Context, Name);
3485 ResultTy = Entry.first;
3486 return false;
3487 }
3488
3489 // If the type starts with '<', then it is either a packed struct or a vector.
3490 bool isPacked = EatIfPresent(lltok::less);
3491
3492 // If we don't have a struct, then we have a random type alias, which we
3493 // accept for compatibility with old files. These types are not allowed to be
3494 // forward referenced and not allowed to be recursive.
3495 if (Lex.getKind() != lltok::lbrace) {
3496 if (Entry.first)
3497 return error(TypeLoc, "forward references to non-struct type");
3498
3499 ResultTy = nullptr;
3500 if (isPacked)
3501 return parseArrayVectorType(ResultTy, true);
3502 return parseType(ResultTy);
3503 }
3504
3505 // This type is being defined, so clear the location to indicate this.
3506 Entry.second = SMLoc();
3507
3508 // If this type number has never been uttered, create it.
3509 if (!Entry.first)
3510 Entry.first = StructType::create(Context, Name);
3511
3512 StructType *STy = cast<StructType>(Entry.first);
3513
3515 if (parseStructBody(Body) ||
3516 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3517 return true;
3518
3519 if (auto E = STy->setBodyOrError(Body, isPacked))
3520 return tokError(toString(std::move(E)));
3521
3522 ResultTy = STy;
3523 return false;
3524}
3525
3526/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3527/// StructType
3528/// ::= '{' '}'
3529/// ::= '{' Type (',' Type)* '}'
3530/// ::= '<' '{' '}' '>'
3531/// ::= '<' '{' Type (',' Type)* '}' '>'
3532bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3533 assert(Lex.getKind() == lltok::lbrace);
3534 Lex.Lex(); // Consume the '{'
3535
3536 // Handle the empty struct.
3537 if (EatIfPresent(lltok::rbrace))
3538 return false;
3539
3540 LocTy EltTyLoc = Lex.getLoc();
3541 Type *Ty = nullptr;
3542 if (parseType(Ty))
3543 return true;
3544 Body.push_back(Ty);
3545
3547 return error(EltTyLoc, "invalid element type for struct");
3548
3549 while (EatIfPresent(lltok::comma)) {
3550 EltTyLoc = Lex.getLoc();
3551 if (parseType(Ty))
3552 return true;
3553
3555 return error(EltTyLoc, "invalid element type for struct");
3556
3557 Body.push_back(Ty);
3558 }
3559
3560 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3561}
3562
3563/// parseArrayVectorType - parse an array or vector type, assuming the first
3564/// token has already been consumed.
3565/// Type
3566/// ::= '[' APSINTVAL 'x' Types ']'
3567/// ::= '<' APSINTVAL 'x' Types '>'
3568/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3569bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3570 bool Scalable = false;
3571
3572 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3573 Lex.Lex(); // consume the 'vscale'
3574 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3575 return true;
3576
3577 Scalable = true;
3578 }
3579
3580 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3581 Lex.getAPSIntVal().getBitWidth() > 64)
3582 return tokError("expected number in address space");
3583
3584 LocTy SizeLoc = Lex.getLoc();
3585 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3586 Lex.Lex();
3587
3588 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3589 return true;
3590
3591 LocTy TypeLoc = Lex.getLoc();
3592 Type *EltTy = nullptr;
3593 if (parseType(EltTy))
3594 return true;
3595
3596 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3597 "expected end of sequential type"))
3598 return true;
3599
3600 if (IsVector) {
3601 if (Size == 0)
3602 return error(SizeLoc, "zero element vector is illegal");
3603 if ((unsigned)Size != Size)
3604 return error(SizeLoc, "size too large for vector");
3606 return error(TypeLoc, "invalid vector element type");
3607 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3608 } else {
3610 return error(TypeLoc, "invalid array element type");
3611 Result = ArrayType::get(EltTy, Size);
3612 }
3613 return false;
3614}
3615
3616/// parseTargetExtType - handle target extension type syntax
3617/// TargetExtType
3618/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3619///
3620/// TargetExtTypeParams
3621/// ::= /*empty*/
3622/// ::= ',' Type TargetExtTypeParams
3623///
3624/// TargetExtIntParams
3625/// ::= /*empty*/
3626/// ::= ',' uint32 TargetExtIntParams
3627bool LLParser::parseTargetExtType(Type *&Result) {
3628 Lex.Lex(); // Eat the 'target' keyword.
3629
3630 // Get the mandatory type name.
3631 std::string TypeName;
3632 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3633 parseStringConstant(TypeName))
3634 return true;
3635
3636 // Parse all of the integer and type parameters at the same time; the use of
3637 // SeenInt will allow us to catch cases where type parameters follow integer
3638 // parameters.
3639 SmallVector<Type *> TypeParams;
3640 SmallVector<unsigned> IntParams;
3641 bool SeenInt = false;
3642 while (Lex.getKind() == lltok::comma) {
3643 Lex.Lex(); // Eat the comma.
3644
3645 if (Lex.getKind() == lltok::APSInt) {
3646 SeenInt = true;
3647 unsigned IntVal;
3648 if (parseUInt32(IntVal))
3649 return true;
3650 IntParams.push_back(IntVal);
3651 } else if (SeenInt) {
3652 // The only other kind of parameter we support is type parameters, which
3653 // must precede the integer parameters. This is therefore an error.
3654 return tokError("expected uint32 param");
3655 } else {
3656 Type *TypeParam;
3657 if (parseType(TypeParam, /*AllowVoid=*/true))
3658 return true;
3659 TypeParams.push_back(TypeParam);
3660 }
3661 }
3662
3663 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3664 return true;
3665
3666 auto TTy =
3667 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3668 if (auto E = TTy.takeError())
3669 return tokError(toString(std::move(E)));
3670
3671 Result = *TTy;
3672 return false;
3673}
3674
3675//===----------------------------------------------------------------------===//
3676// Function Semantic Analysis.
3677//===----------------------------------------------------------------------===//
3678
3679LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3680 int functionNumber,
3681 ArrayRef<unsigned> UnnamedArgNums)
3682 : P(p), F(f), FunctionNumber(functionNumber) {
3683
3684 // Insert unnamed arguments into the NumberedVals list.
3685 auto It = UnnamedArgNums.begin();
3686 for (Argument &A : F.args()) {
3687 if (!A.hasName()) {
3688 unsigned ArgNum = *It++;
3689 NumberedVals.add(ArgNum, &A);
3690 }
3691 }
3692}
3693
3694LLParser::PerFunctionState::~PerFunctionState() {
3695 // If there were any forward referenced non-basicblock values, delete them.
3696
3697 for (const auto &P : ForwardRefVals) {
3698 if (isa<BasicBlock>(P.second.first))
3699 continue;
3700 P.second.first->replaceAllUsesWith(
3701 PoisonValue::get(P.second.first->getType()));
3702 P.second.first->deleteValue();
3703 }
3704
3705 for (const auto &P : ForwardRefValIDs) {
3706 if (isa<BasicBlock>(P.second.first))
3707 continue;
3708 P.second.first->replaceAllUsesWith(
3709 PoisonValue::get(P.second.first->getType()));
3710 P.second.first->deleteValue();
3711 }
3712}
3713
3714bool LLParser::PerFunctionState::finishFunction() {
3715 if (!ForwardRefVals.empty())
3716 return P.error(ForwardRefVals.begin()->second.second,
3717 "use of undefined value '%" + ForwardRefVals.begin()->first +
3718 "'");
3719 if (!ForwardRefValIDs.empty())
3720 return P.error(ForwardRefValIDs.begin()->second.second,
3721 "use of undefined value '%" +
3722 Twine(ForwardRefValIDs.begin()->first) + "'");
3723 return false;
3724}
3725
3726/// getVal - Get a value with the specified name or ID, creating a
3727/// forward reference record if needed. This can return null if the value
3728/// exists but does not have the right type.
3729Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3730 LocTy Loc) {
3731 // Look this name up in the normal function symbol table.
3732 Value *Val = F.getValueSymbolTable()->lookup(Name);
3733
3734 // If this is a forward reference for the value, see if we already created a
3735 // forward ref record.
3736 if (!Val) {
3737 auto I = ForwardRefVals.find(Name);
3738 if (I != ForwardRefVals.end())
3739 Val = I->second.first;
3740 }
3741
3742 // If we have the value in the symbol table or fwd-ref table, return it.
3743 if (Val)
3744 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3745
3746 // Don't make placeholders with invalid type.
3747 if (!Ty->isFirstClassType()) {
3748 P.error(Loc, "invalid use of a non-first-class type");
3749 return nullptr;
3750 }
3751
3752 // Otherwise, create a new forward reference for this value and remember it.
3753 Value *FwdVal;
3754 if (Ty->isLabelTy()) {
3755 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3756 } else {
3757 FwdVal = new Argument(Ty, Name);
3758 }
3759 if (FwdVal->getName() != Name) {
3760 P.error(Loc, "name is too long which can result in name collisions, "
3761 "consider making the name shorter or "
3762 "increasing -non-global-value-max-name-size");
3763 return nullptr;
3764 }
3765
3766 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3767 return FwdVal;
3768}
3769
3770Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3771 // Look this name up in the normal function symbol table.
3772 Value *Val = NumberedVals.get(ID);
3773
3774 // If this is a forward reference for the value, see if we already created a
3775 // forward ref record.
3776 if (!Val) {
3777 auto I = ForwardRefValIDs.find(ID);
3778 if (I != ForwardRefValIDs.end())
3779 Val = I->second.first;
3780 }
3781
3782 // If we have the value in the symbol table or fwd-ref table, return it.
3783 if (Val)
3784 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3785
3786 if (!Ty->isFirstClassType()) {
3787 P.error(Loc, "invalid use of a non-first-class type");
3788 return nullptr;
3789 }
3790
3791 // Otherwise, create a new forward reference for this value and remember it.
3792 Value *FwdVal;
3793 if (Ty->isLabelTy()) {
3794 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3795 } else {
3796 FwdVal = new Argument(Ty);
3797 }
3798
3799 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3800 return FwdVal;
3801}
3802
3803/// setInstName - After an instruction is parsed and inserted into its
3804/// basic block, this installs its name.
3805bool LLParser::PerFunctionState::setInstName(int NameID,
3806 const std::string &NameStr,
3807 LocTy NameLoc, Instruction *Inst) {
3808 // If this instruction has void type, it cannot have a name or ID specified.
3809 if (Inst->getType()->isVoidTy()) {
3810 if (NameID != -1 || !NameStr.empty())
3811 return P.error(NameLoc, "instructions returning void cannot have a name");
3812 return false;
3813 }
3814
3815 // If this was a numbered instruction, verify that the instruction is the
3816 // expected value and resolve any forward references.
3817 if (NameStr.empty()) {
3818 // If neither a name nor an ID was specified, just use the next ID.
3819 if (NameID == -1)
3820 NameID = NumberedVals.getNext();
3821
3822 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3823 NameID))
3824 return true;
3825
3826 auto FI = ForwardRefValIDs.find(NameID);
3827 if (FI != ForwardRefValIDs.end()) {
3828 Value *Sentinel = FI->second.first;
3829 if (Sentinel->getType() != Inst->getType())
3830 return P.error(NameLoc, "instruction forward referenced with type '" +
3831 getTypeString(FI->second.first->getType()) +
3832 "'");
3833
3834 Sentinel->replaceAllUsesWith(Inst);
3835 Sentinel->deleteValue();
3836 ForwardRefValIDs.erase(FI);
3837 }
3838
3839 NumberedVals.add(NameID, Inst);
3840 return false;
3841 }
3842
3843 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3844 auto FI = ForwardRefVals.find(NameStr);
3845 if (FI != ForwardRefVals.end()) {
3846 Value *Sentinel = FI->second.first;
3847 if (Sentinel->getType() != Inst->getType())
3848 return P.error(NameLoc, "instruction forward referenced with type '" +
3849 getTypeString(FI->second.first->getType()) +
3850 "'");
3851
3852 Sentinel->replaceAllUsesWith(Inst);
3853 Sentinel->deleteValue();
3854 ForwardRefVals.erase(FI);
3855 }
3856
3857 // Set the name on the instruction.
3858 Inst->setName(NameStr);
3859
3860 if (Inst->getName() != NameStr)
3861 return P.error(NameLoc, "multiple definition of local value named '" +
3862 NameStr + "'");
3863 return false;
3864}
3865
3866/// getBB - Get a basic block with the specified name or ID, creating a
3867/// forward reference record if needed.
3868BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3869 LocTy Loc) {
3871 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3872}
3873
3874BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3876 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3877}
3878
3879/// defineBB - Define the specified basic block, which is either named or
3880/// unnamed. If there is an error, this returns null otherwise it returns
3881/// the block being defined.
3882BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3883 int NameID, LocTy Loc) {
3884 BasicBlock *BB;
3885 if (Name.empty()) {
3886 if (NameID != -1) {
3887 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3888 return nullptr;
3889 } else {
3890 NameID = NumberedVals.getNext();
3891 }
3892 BB = getBB(NameID, Loc);
3893 if (!BB) {
3894 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3895 return nullptr;
3896 }
3897 } else {
3898 BB = getBB(Name, Loc);
3899 if (!BB) {
3900 P.error(Loc, "unable to create block named '" + Name + "'");
3901 return nullptr;
3902 }
3903 }
3904
3905 // Move the block to the end of the function. Forward ref'd blocks are
3906 // inserted wherever they happen to be referenced.
3907 F.splice(F.end(), &F, BB->getIterator());
3908
3909 // Remove the block from forward ref sets.
3910 if (Name.empty()) {
3911 ForwardRefValIDs.erase(NameID);
3912 NumberedVals.add(NameID, BB);
3913 } else {
3914 // BB forward references are already in the function symbol table.
3915 ForwardRefVals.erase(Name);
3916 }
3917
3918 return BB;
3919}
3920
3921//===----------------------------------------------------------------------===//
3922// Constants.
3923//===----------------------------------------------------------------------===//
3924
3925/// parseValID - parse an abstract value that doesn't necessarily have a
3926/// type implied. For example, if we parse "4" we don't know what integer type
3927/// it has. The value will later be combined with its type and checked for
3928/// basic correctness. PFS is used to convert function-local operands of
3929/// metadata (since metadata operands are not just parsed here but also
3930/// converted to values). PFS can be null when we are not parsing metadata
3931/// values inside a function.
3932bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3933 ID.Loc = Lex.getLoc();
3934 switch (Lex.getKind()) {
3935 default:
3936 return tokError("expected value token");
3937 case lltok::GlobalID: // @42
3938 ID.UIntVal = Lex.getUIntVal();
3939 ID.Kind = ValID::t_GlobalID;
3940 break;
3941 case lltok::GlobalVar: // @foo
3942 ID.StrVal = Lex.getStrVal();
3943 ID.Kind = ValID::t_GlobalName;
3944 break;
3945 case lltok::LocalVarID: // %42
3946 ID.UIntVal = Lex.getUIntVal();
3947 ID.Kind = ValID::t_LocalID;
3948 break;
3949 case lltok::LocalVar: // %foo
3950 ID.StrVal = Lex.getStrVal();
3951 ID.Kind = ValID::t_LocalName;
3952 break;
3953 case lltok::APSInt:
3954 ID.APSIntVal = Lex.getAPSIntVal();
3955 ID.Kind = ValID::t_APSInt;
3956 break;
3957 case lltok::APFloat:
3958 ID.APFloatVal = Lex.getAPFloatVal();
3959 ID.Kind = ValID::t_APFloat;
3960 break;
3961 case lltok::kw_true:
3962 ID.ConstantVal = ConstantInt::getTrue(Context);
3963 ID.Kind = ValID::t_Constant;
3964 break;
3965 case lltok::kw_false:
3966 ID.ConstantVal = ConstantInt::getFalse(Context);
3967 ID.Kind = ValID::t_Constant;
3968 break;
3969 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3970 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3971 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3972 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3973 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3974
3975 case lltok::lbrace: {
3976 // ValID ::= '{' ConstVector '}'
3977 Lex.Lex();
3979 if (parseGlobalValueVector(Elts) ||
3980 parseToken(lltok::rbrace, "expected end of struct constant"))
3981 return true;
3982
3983 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3984 ID.UIntVal = Elts.size();
3985 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3986 Elts.size() * sizeof(Elts[0]));
3988 return false;
3989 }
3990 case lltok::less: {
3991 // ValID ::= '<' ConstVector '>' --> Vector.
3992 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3993 Lex.Lex();
3994 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3995
3997 LocTy FirstEltLoc = Lex.getLoc();
3998 if (parseGlobalValueVector(Elts) ||
3999 (isPackedStruct &&
4000 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4001 parseToken(lltok::greater, "expected end of constant"))
4002 return true;
4003
4004 if (isPackedStruct) {
4005 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4006 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4007 Elts.size() * sizeof(Elts[0]));
4008 ID.UIntVal = Elts.size();
4010 return false;
4011 }
4012
4013 if (Elts.empty())
4014 return error(ID.Loc, "constant vector must not be empty");
4015
4016 if (!Elts[0]->getType()->isIntegerTy() &&
4017 !Elts[0]->getType()->isFloatingPointTy() &&
4018 !Elts[0]->getType()->isPointerTy())
4019 return error(
4020 FirstEltLoc,
4021 "vector elements must have integer, pointer or floating point type");
4022
4023 // Verify that all the vector elements have the same type.
4024 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4025 if (Elts[i]->getType() != Elts[0]->getType())
4026 return error(FirstEltLoc, "vector element #" + Twine(i) +
4027 " is not of type '" +
4028 getTypeString(Elts[0]->getType()));
4029
4030 ID.ConstantVal = ConstantVector::get(Elts);
4031 ID.Kind = ValID::t_Constant;
4032 return false;
4033 }
4034 case lltok::lsquare: { // Array Constant
4035 Lex.Lex();
4037 LocTy FirstEltLoc = Lex.getLoc();
4038 if (parseGlobalValueVector(Elts) ||
4039 parseToken(lltok::rsquare, "expected end of array constant"))
4040 return true;
4041
4042 // Handle empty element.
4043 if (Elts.empty()) {
4044 // Use undef instead of an array because it's inconvenient to determine
4045 // the element type at this point, there being no elements to examine.
4046 ID.Kind = ValID::t_EmptyArray;
4047 return false;
4048 }
4049
4050 if (!Elts[0]->getType()->isFirstClassType())
4051 return error(FirstEltLoc, "invalid array element type: " +
4052 getTypeString(Elts[0]->getType()));
4053
4054 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4055
4056 // Verify all elements are correct type!
4057 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4058 if (Elts[i]->getType() != Elts[0]->getType())
4059 return error(FirstEltLoc, "array element #" + Twine(i) +
4060 " is not of type '" +
4061 getTypeString(Elts[0]->getType()));
4062 }
4063
4064 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4065 ID.Kind = ValID::t_Constant;
4066 return false;
4067 }
4068 case lltok::kw_c: // c "foo"
4069 Lex.Lex();
4070 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4071 false);
4072 if (parseToken(lltok::StringConstant, "expected string"))
4073 return true;
4074 ID.Kind = ValID::t_Constant;
4075 return false;
4076
4077 case lltok::kw_asm: {
4078 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4079 // STRINGCONSTANT
4080 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4081 Lex.Lex();
4082 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4083 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4084 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4085 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4086 parseStringConstant(ID.StrVal) ||
4087 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4088 parseToken(lltok::StringConstant, "expected constraint string"))
4089 return true;
4090 ID.StrVal2 = Lex.getStrVal();
4091 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4092 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4093 ID.Kind = ValID::t_InlineAsm;
4094 return false;
4095 }
4096
4098 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4099 Lex.Lex();
4100
4101 ValID Fn, Label;
4102
4103 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4104 parseValID(Fn, PFS) ||
4105 parseToken(lltok::comma,
4106 "expected comma in block address expression") ||
4107 parseValID(Label, PFS) ||
4108 parseToken(lltok::rparen, "expected ')' in block address expression"))
4109 return true;
4110
4112 return error(Fn.Loc, "expected function name in blockaddress");
4113 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4114 return error(Label.Loc, "expected basic block name in blockaddress");
4115
4116 // Try to find the function (but skip it if it's forward-referenced).
4117 GlobalValue *GV = nullptr;
4118 if (Fn.Kind == ValID::t_GlobalID) {
4119 GV = NumberedVals.get(Fn.UIntVal);
4120 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4121 GV = M->getNamedValue(Fn.StrVal);
4122 }
4123 Function *F = nullptr;
4124 if (GV) {
4125 // Confirm that it's actually a function with a definition.
4126 if (!isa<Function>(GV))
4127 return error(Fn.Loc, "expected function name in blockaddress");
4128 F = cast<Function>(GV);
4129 if (F->isDeclaration())
4130 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4131 }
4132
4133 if (!F) {
4134 // Make a global variable as a placeholder for this reference.
4135 GlobalValue *&FwdRef =
4136 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4137 if (!FwdRef) {
4138 unsigned FwdDeclAS;
4139 if (ExpectedTy) {
4140 // If we know the type that the blockaddress is being assigned to,
4141 // we can use the address space of that type.
4142 if (!ExpectedTy->isPointerTy())
4143 return error(ID.Loc,
4144 "type of blockaddress must be a pointer and not '" +
4145 getTypeString(ExpectedTy) + "'");
4146 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4147 } else if (PFS) {
4148 // Otherwise, we default the address space of the current function.
4149 FwdDeclAS = PFS->getFunction().getAddressSpace();
4150 } else {
4151 llvm_unreachable("Unknown address space for blockaddress");
4152 }
4153 FwdRef = new GlobalVariable(
4154 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4155 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4156 }
4157
4158 ID.ConstantVal = FwdRef;
4159 ID.Kind = ValID::t_Constant;
4160 return false;
4161 }
4162
4163 // We found the function; now find the basic block. Don't use PFS, since we
4164 // might be inside a constant expression.
4165 BasicBlock *BB;
4166 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4167 if (Label.Kind == ValID::t_LocalID)
4168 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4169 else
4170 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4171 if (!BB)
4172 return error(Label.Loc, "referenced value is not a basic block");
4173 } else {
4174 if (Label.Kind == ValID::t_LocalID)
4175 return error(Label.Loc, "cannot take address of numeric label after "
4176 "the function is defined");
4178 F->getValueSymbolTable()->lookup(Label.StrVal));
4179 if (!BB)
4180 return error(Label.Loc, "referenced value is not a basic block");
4181 }
4182
4183 ID.ConstantVal = BlockAddress::get(F, BB);
4184 ID.Kind = ValID::t_Constant;
4185 return false;
4186 }
4187
4189 // ValID ::= 'dso_local_equivalent' @foo
4190 Lex.Lex();
4191
4192 ValID Fn;
4193
4194 if (parseValID(Fn, PFS))
4195 return true;
4196
4198 return error(Fn.Loc,
4199 "expected global value name in dso_local_equivalent");
4200
4201 // Try to find the function (but skip it if it's forward-referenced).
4202 GlobalValue *GV = nullptr;
4203 if (Fn.Kind == ValID::t_GlobalID) {
4204 GV = NumberedVals.get(Fn.UIntVal);
4205 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4206 GV = M->getNamedValue(Fn.StrVal);
4207 }
4208
4209 if (!GV) {
4210 // Make a placeholder global variable as a placeholder for this reference.
4211 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4212 ? ForwardRefDSOLocalEquivalentIDs
4213 : ForwardRefDSOLocalEquivalentNames;
4214 GlobalValue *&FwdRef = FwdRefMap[Fn];
4215 if (!FwdRef) {
4216 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4217 GlobalValue::InternalLinkage, nullptr, "",
4219 }
4220
4221 ID.ConstantVal = FwdRef;
4222 ID.Kind = ValID::t_Constant;
4223 return false;
4224 }
4225
4226 if (!GV->getValueType()->isFunctionTy())
4227 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4228 "in dso_local_equivalent");
4229
4230 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4231 ID.Kind = ValID::t_Constant;
4232 return false;
4233 }
4234
4235 case lltok::kw_no_cfi: {
4236 // ValID ::= 'no_cfi' @foo
4237 Lex.Lex();
4238
4239 if (parseValID(ID, PFS))
4240 return true;
4241
4242 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4243 return error(ID.Loc, "expected global value name in no_cfi");
4244
4245 ID.NoCFI = true;
4246 return false;
4247 }
4248 case lltok::kw_ptrauth: {
4249 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4250 // (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4251 Lex.Lex();
4252
4253 Constant *Ptr, *Key;
4254 Constant *Disc = nullptr, *AddrDisc = nullptr;
4255
4256 if (parseToken(lltok::lparen,
4257 "expected '(' in constant ptrauth expression") ||
4258 parseGlobalTypeAndValue(Ptr) ||
4259 parseToken(lltok::comma,
4260 "expected comma in constant ptrauth expression") ||
4261 parseGlobalTypeAndValue(Key))
4262 return true;
4263 // If present, parse the optional disc/addrdisc.
4264 if (EatIfPresent(lltok::comma))
4265 if (parseGlobalTypeAndValue(Disc) ||
4266 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4267 return true;
4268 if (parseToken(lltok::rparen,
4269 "expected ')' in constant ptrauth expression"))
4270 return true;
4271
4272 if (!Ptr->getType()->isPointerTy())
4273 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4274
4275 auto *KeyC = dyn_cast<ConstantInt>(Key);
4276 if (!KeyC || KeyC->getBitWidth() != 32)
4277 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4278
4279 ConstantInt *DiscC = nullptr;
4280 if (Disc) {
4281 DiscC = dyn_cast<ConstantInt>(Disc);
4282 if (!DiscC || DiscC->getBitWidth() != 64)
4283 return error(
4284 ID.Loc,
4285 "constant ptrauth integer discriminator must be i64 constant");
4286 } else {
4287 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4288 }
4289
4290 if (AddrDisc) {
4291 if (!AddrDisc->getType()->isPointerTy())
4292 return error(
4293 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4294 } else {
4295 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4296 }
4297
4298 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4299 ID.Kind = ValID::t_Constant;
4300 return false;
4301 }
4302
4303 case lltok::kw_trunc:
4304 case lltok::kw_bitcast:
4306 case lltok::kw_inttoptr:
4308 case lltok::kw_ptrtoint: {
4309 unsigned Opc = Lex.getUIntVal();
4310 Type *DestTy = nullptr;
4311 Constant *SrcVal;
4312 Lex.Lex();
4313 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4314 parseGlobalTypeAndValue(SrcVal) ||
4315 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4316 parseType(DestTy) ||
4317 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4318 return true;
4319 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4320 return error(ID.Loc, "invalid cast opcode for cast from '" +
4321 getTypeString(SrcVal->getType()) + "' to '" +
4322 getTypeString(DestTy) + "'");
4324 SrcVal, DestTy);
4325 ID.Kind = ValID::t_Constant;
4326 return false;
4327 }
4329 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4331 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4332 case lltok::kw_udiv:
4333 return error(ID.Loc, "udiv constexprs are no longer supported");
4334 case lltok::kw_sdiv:
4335 return error(ID.Loc, "sdiv constexprs are no longer supported");
4336 case lltok::kw_urem:
4337 return error(ID.Loc, "urem constexprs are no longer supported");
4338 case lltok::kw_srem:
4339 return error(ID.Loc, "srem constexprs are no longer supported");
4340 case lltok::kw_fadd:
4341 return error(ID.Loc, "fadd constexprs are no longer supported");
4342 case lltok::kw_fsub:
4343 return error(ID.Loc, "fsub constexprs are no longer supported");
4344 case lltok::kw_fmul:
4345 return error(ID.Loc, "fmul constexprs are no longer supported");
4346 case lltok::kw_fdiv:
4347 return error(ID.Loc, "fdiv constexprs are no longer supported");
4348 case lltok::kw_frem:
4349 return error(ID.Loc, "frem constexprs are no longer supported");
4350 case lltok::kw_and:
4351 return error(ID.Loc, "and constexprs are no longer supported");
4352 case lltok::kw_or:
4353 return error(ID.Loc, "or constexprs are no longer supported");
4354 case lltok::kw_lshr:
4355 return error(ID.Loc, "lshr constexprs are no longer supported");
4356 case lltok::kw_ashr:
4357 return error(ID.Loc, "ashr constexprs are no longer supported");
4358 case lltok::kw_shl:
4359 return error(ID.Loc, "shl constexprs are no longer supported");
4360 case lltok::kw_mul:
4361 return error(ID.Loc, "mul constexprs are no longer supported");
4362 case lltok::kw_fneg:
4363 return error(ID.Loc, "fneg constexprs are no longer supported");
4364 case lltok::kw_select:
4365 return error(ID.Loc, "select constexprs are no longer supported");
4366 case lltok::kw_zext:
4367 return error(ID.Loc, "zext constexprs are no longer supported");
4368 case lltok::kw_sext:
4369 return error(ID.Loc, "sext constexprs are no longer supported");
4370 case lltok::kw_fptrunc:
4371 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4372 case lltok::kw_fpext:
4373 return error(ID.Loc, "fpext constexprs are no longer supported");
4374 case lltok::kw_uitofp:
4375 return error(ID.Loc, "uitofp constexprs are no longer supported");
4376 case lltok::kw_sitofp:
4377 return error(ID.Loc, "sitofp constexprs are no longer supported");
4378 case lltok::kw_fptoui:
4379 return error(ID.Loc, "fptoui constexprs are no longer supported");
4380 case lltok::kw_fptosi:
4381 return error(ID.Loc, "fptosi constexprs are no longer supported");
4382 case lltok::kw_icmp:
4383 return error(ID.Loc, "icmp constexprs are no longer supported");
4384 case lltok::kw_fcmp:
4385 return error(ID.Loc, "fcmp constexprs are no longer supported");
4386
4387 // Binary Operators.
4388 case lltok::kw_add:
4389 case lltok::kw_sub:
4390 case lltok::kw_xor: {
4391 bool NUW = false;
4392 bool NSW = false;
4393 unsigned Opc = Lex.getUIntVal();
4394 Constant *Val0, *Val1;
4395 Lex.Lex();
4396 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4397 Opc == Instruction::Mul) {
4398 if (EatIfPresent(lltok::kw_nuw))
4399 NUW = true;
4400 if (EatIfPresent(lltok::kw_nsw)) {
4401 NSW = true;
4402 if (EatIfPresent(lltok::kw_nuw))
4403 NUW = true;
4404 }
4405 }
4406 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4407 parseGlobalTypeAndValue(Val0) ||
4408 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4409 parseGlobalTypeAndValue(Val1) ||
4410 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4411 return true;
4412 if (Val0->getType() != Val1->getType())
4413 return error(ID.Loc, "operands of constexpr must have same type");
4414 // Check that the type is valid for the operator.
4415 if (!Val0->getType()->isIntOrIntVectorTy())
4416 return error(ID.Loc,
4417 "constexpr requires integer or integer vector operands");
4418 unsigned Flags = 0;
4421 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4422 ID.Kind = ValID::t_Constant;
4423 return false;
4424 }
4425
4426 case lltok::kw_splat: {
4427 Lex.Lex();
4428 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4429 return true;
4430 Constant *C;
4431 if (parseGlobalTypeAndValue(C))
4432 return true;
4433 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4434 return true;
4435
4436 ID.ConstantVal = C;
4438 return false;
4439 }
4440
4445 unsigned Opc = Lex.getUIntVal();
4447 GEPNoWrapFlags NW;
4448 bool HasInRange = false;
4449 APSInt InRangeStart;
4450 APSInt InRangeEnd;
4451 Type *Ty;
4452 Lex.Lex();
4453
4454 if (Opc == Instruction::GetElementPtr) {
4455 while (true) {
4456 if (EatIfPresent(lltok::kw_inbounds))
4458 else if (EatIfPresent(lltok::kw_nusw))
4460 else if (EatIfPresent(lltok::kw_nuw))
4462 else
4463 break;
4464 }
4465
4466 if (EatIfPresent(lltok::kw_inrange)) {
4467 if (parseToken(lltok::lparen, "expected '('"))
4468 return true;
4469 if (Lex.getKind() != lltok::APSInt)
4470 return tokError("expected integer");
4471 InRangeStart = Lex.getAPSIntVal();
4472 Lex.Lex();
4473 if (parseToken(lltok::comma, "expected ','"))
4474 return true;
4475 if (Lex.getKind() != lltok::APSInt)
4476 return tokError("expected integer");
4477 InRangeEnd = Lex.getAPSIntVal();
4478 Lex.Lex();
4479 if (parseToken(lltok::rparen, "expected ')'"))
4480 return true;
4481 HasInRange = true;
4482 }
4483 }
4484
4485 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4486 return true;
4487
4488 if (Opc == Instruction::GetElementPtr) {
4489 if (parseType(Ty) ||
4490 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4491 return true;
4492 }
4493
4494 if (parseGlobalValueVector(Elts) ||
4495 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4496 return true;
4497
4498 if (Opc == Instruction::GetElementPtr) {
4499 if (Elts.size() == 0 ||
4500 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4501 return error(ID.Loc, "base of getelementptr must be a pointer");
4502
4503 Type *BaseType = Elts[0]->getType();
4504 std::optional<ConstantRange> InRange;
4505 if (HasInRange) {
4506 unsigned IndexWidth =
4507 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4508 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4509 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4510 if (InRangeStart.sge(InRangeEnd))
4511 return error(ID.Loc, "expected end to be larger than start");
4512 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4513 }
4514
4515 unsigned GEPWidth =
4516 BaseType->isVectorTy()
4517 ? cast<FixedVectorType>(BaseType)->getNumElements()
4518 : 0;
4519
4520 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4521 for (Constant *Val : Indices) {
4522 Type *ValTy = Val->getType();
4523 if (!ValTy->isIntOrIntVectorTy())
4524 return error(ID.Loc, "getelementptr index must be an integer");
4525 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4526 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4527 if (GEPWidth && (ValNumEl != GEPWidth))
4528 return error(
4529 ID.Loc,
4530 "getelementptr vector index has a wrong number of elements");
4531 // GEPWidth may have been unknown because the base is a scalar,
4532 // but it is known now.
4533 GEPWidth = ValNumEl;
4534 }
4535 }
4536
4537 SmallPtrSet<Type*, 4> Visited;
4538 if (!Indices.empty() && !Ty->isSized(&Visited))
4539 return error(ID.Loc, "base element of getelementptr must be sized");
4540
4542 return error(ID.Loc, "invalid base element for constant getelementptr");
4543
4544 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4545 return error(ID.Loc, "invalid getelementptr indices");
4546
4547 ID.ConstantVal =
4548 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4549 } else if (Opc == Instruction::ShuffleVector) {
4550 if (Elts.size() != 3)
4551 return error(ID.Loc, "expected three operands to shufflevector");
4552 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4553 return error(ID.Loc, "invalid operands to shufflevector");
4554 SmallVector<int, 16> Mask;
4556 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4557 } else if (Opc == Instruction::ExtractElement) {
4558 if (Elts.size() != 2)
4559 return error(ID.Loc, "expected two operands to extractelement");
4560 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4561 return error(ID.Loc, "invalid extractelement operands");
4562 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4563 } else {
4564 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4565 if (Elts.size() != 3)
4566 return error(ID.Loc, "expected three operands to insertelement");
4567 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4568 return error(ID.Loc, "invalid insertelement operands");
4569 ID.ConstantVal =
4570 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4571 }
4572
4573 ID.Kind = ValID::t_Constant;
4574 return false;
4575 }
4576 }
4577
4578 Lex.Lex();
4579 return false;
4580}
4581
4582/// parseGlobalValue - parse a global value with the specified type.
4583bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4584 C = nullptr;
4585 ValID ID;
4586 Value *V = nullptr;
4587 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4588 convertValIDToValue(Ty, ID, V, nullptr);
4589 if (V && !(C = dyn_cast<Constant>(V)))
4590 return error(ID.Loc, "global values must be constants");
4591 return Parsed;
4592}
4593
4594bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4595 Type *Ty = nullptr;
4596 return parseType(Ty) || parseGlobalValue(Ty, V);
4597}
4598
4599bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4600 C = nullptr;
4601
4602 LocTy KwLoc = Lex.getLoc();
4603 if (!EatIfPresent(lltok::kw_comdat))
4604 return false;
4605
4606 if (EatIfPresent(lltok::lparen)) {
4607 if (Lex.getKind() != lltok::ComdatVar)
4608 return tokError("expected comdat variable");
4609 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4610 Lex.Lex();
4611 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4612 return true;
4613 } else {
4614 if (GlobalName.empty())
4615 return tokError("comdat cannot be unnamed");
4616 C = getComdat(std::string(GlobalName), KwLoc);
4617 }
4618
4619 return false;
4620}
4621
4622/// parseGlobalValueVector
4623/// ::= /*empty*/
4624/// ::= TypeAndValue (',' TypeAndValue)*
4625bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4626 // Empty list.
4627 if (Lex.getKind() == lltok::rbrace ||
4628 Lex.getKind() == lltok::rsquare ||
4629 Lex.getKind() == lltok::greater ||
4630 Lex.getKind() == lltok::rparen)
4631 return false;
4632
4633 do {
4634 // Let the caller deal with inrange.
4635 if (Lex.getKind() == lltok::kw_inrange)
4636 return false;
4637
4638 Constant *C;
4639 if (parseGlobalTypeAndValue(C))
4640 return true;
4641 Elts.push_back(C);
4642 } while (EatIfPresent(lltok::comma));
4643
4644 return false;
4645}
4646
4647bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4649 if (parseMDNodeVector(Elts))
4650 return true;
4651
4652 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4653 return false;
4654}
4655
4656/// MDNode:
4657/// ::= !{ ... }
4658/// ::= !7
4659/// ::= !DILocation(...)
4660bool LLParser::parseMDNode(MDNode *&N) {
4661 if (Lex.getKind() == lltok::MetadataVar)
4662 return parseSpecializedMDNode(N);
4663
4664 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4665}
4666
4667bool LLParser::parseMDNodeTail(MDNode *&N) {
4668 // !{ ... }
4669 if (Lex.getKind() == lltok::lbrace)
4670 return parseMDTuple(N);
4671
4672 // !42
4673 return parseMDNodeID(N);
4674}
4675
4676namespace {
4677
4678/// Structure to represent an optional metadata field.
4679template <class FieldTy> struct MDFieldImpl {
4680 typedef MDFieldImpl ImplTy;
4681 FieldTy Val;
4682 bool Seen;
4683
4684 void assign(FieldTy Val) {
4685 Seen = true;
4686 this->Val = std::move(Val);
4687 }
4688
4689 explicit MDFieldImpl(FieldTy Default)
4690 : Val(std::move(Default)), Seen(false) {}
4691};
4692
4693/// Structure to represent an optional metadata field that
4694/// can be of either type (A or B) and encapsulates the
4695/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4696/// to reimplement the specifics for representing each Field.
4697template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4698 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4699 FieldTypeA A;
4700 FieldTypeB B;
4701 bool Seen;
4702
4703 enum {
4704 IsInvalid = 0,
4705 IsTypeA = 1,
4706 IsTypeB = 2
4707 } WhatIs;
4708
4709 void assign(FieldTypeA A) {
4710 Seen = true;
4711 this->A = std::move(A);
4712 WhatIs = IsTypeA;
4713 }
4714
4715 void assign(FieldTypeB B) {
4716 Seen = true;
4717 this->B = std::move(B);
4718 WhatIs = IsTypeB;
4719 }
4720
4721 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4722 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4723 WhatIs(IsInvalid) {}
4724};
4725
4726struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4727 uint64_t Max;
4728
4729 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4730 : ImplTy(Default), Max(Max) {}
4731};
4732
4733struct LineField : public MDUnsignedField {
4734 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4735};
4736
4737struct ColumnField : public MDUnsignedField {
4738 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4739};
4740
4741struct DwarfTagField : public MDUnsignedField {
4742 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4743 DwarfTagField(dwarf::Tag DefaultTag)
4744 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4745};
4746
4747struct DwarfMacinfoTypeField : public MDUnsignedField {
4748 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4749 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4750 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4751};
4752
4753struct DwarfAttEncodingField : public MDUnsignedField {
4754 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4755};
4756
4757struct DwarfVirtualityField : public MDUnsignedField {
4758 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4759};
4760
4761struct DwarfLangField : public MDUnsignedField {
4762 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4763};
4764
4765struct DwarfSourceLangNameField : public MDUnsignedField {
4766 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4767};
4768
4769struct DwarfCCField : public MDUnsignedField {
4770 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4771};
4772
4773struct DwarfEnumKindField : public MDUnsignedField {
4774 DwarfEnumKindField()
4775 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4776 dwarf::DW_APPLE_ENUM_KIND_max) {}
4777};
4778
4779struct EmissionKindField : public MDUnsignedField {
4780 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4781};
4782
4783struct FixedPointKindField : public MDUnsignedField {
4784 FixedPointKindField()
4785 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4786};
4787
4788struct NameTableKindField : public MDUnsignedField {
4789 NameTableKindField()
4790 : MDUnsignedField(
4791 0, (unsigned)
4792 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4793};
4794
4795struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4796 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4797};
4798
4799struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4800 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4801};
4802
4803struct MDAPSIntField : public MDFieldImpl<APSInt> {
4804 MDAPSIntField() : ImplTy(APSInt()) {}
4805};
4806
4807struct MDSignedField : public MDFieldImpl<int64_t> {
4808 int64_t Min = INT64_MIN;
4809 int64_t Max = INT64_MAX;
4810
4811 MDSignedField(int64_t Default = 0)
4812 : ImplTy(Default) {}
4813 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4814 : ImplTy(Default), Min(Min), Max(Max) {}
4815};
4816
4817struct MDBoolField : public MDFieldImpl<bool> {
4818 MDBoolField(bool Default = false) : ImplTy(Default) {}
4819};
4820
4821struct MDField : public MDFieldImpl<Metadata *> {
4822 bool AllowNull;
4823
4824 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4825};
4826
4827struct MDStringField : public MDFieldImpl<MDString *> {
4828 enum class EmptyIs {
4829 Null, //< Allow empty input string, map to nullptr
4830 Empty, //< Allow empty input string, map to an empty MDString
4831 Error, //< Disallow empty string, map to an error
4832 } EmptyIs;
4833 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
4834 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4835};
4836
4837struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4838 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4839};
4840
4841struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4842 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4843};
4844
4845struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4846 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4847 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4848
4849 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4850 bool AllowNull = true)
4851 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4852
4853 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4854 bool isMDField() const { return WhatIs == IsTypeB; }
4855 int64_t getMDSignedValue() const {
4856 assert(isMDSignedField() && "Wrong field type");
4857 return A.Val;
4858 }
4859 Metadata *getMDFieldValue() const {
4860 assert(isMDField() && "Wrong field type");
4861 return B.Val;
4862 }
4863};
4864
4865struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4866 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
4867 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
4868
4869 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
4870 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
4871
4872 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
4873 bool isMDField() const { return WhatIs == IsTypeB; }
4874 uint64_t getMDUnsignedValue() const {
4875 assert(isMDUnsignedField() && "Wrong field type");
4876 return A.Val;
4877 }
4878 Metadata *getMDFieldValue() const {
4879 assert(isMDField() && "Wrong field type");
4880 return B.Val;
4881 }
4882
4883 Metadata *getValueAsMetadata(LLVMContext &Context) const {
4884 if (isMDUnsignedField())
4886 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
4887 if (isMDField())
4888 return getMDFieldValue();
4889 return nullptr;
4890 }
4891};
4892
4893} // end anonymous namespace
4894
4895namespace llvm {
4896
4897template <>
4898bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4899 if (Lex.getKind() != lltok::APSInt)
4900 return tokError("expected integer");
4901
4902 Result.assign(Lex.getAPSIntVal());
4903 Lex.Lex();
4904 return false;
4905}
4906
4907template <>
4908bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4909 MDUnsignedField &Result) {
4910 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4911 return tokError("expected unsigned integer");
4912
4913 auto &U = Lex.getAPSIntVal();
4914 if (U.ugt(Result.Max))
4915 return tokError("value for '" + Name + "' too large, limit is " +
4916 Twine(Result.Max));
4917 Result.assign(U.getZExtValue());
4918 assert(Result.Val <= Result.Max && "Expected value in range");
4919 Lex.Lex();
4920 return false;
4921}
4922
4923template <>
4924bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4925 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4926}
4927template <>
4928bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4929 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4930}
4931
4932template <>
4933bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4934 if (Lex.getKind() == lltok::APSInt)
4935 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4936
4937 if (Lex.getKind() != lltok::DwarfTag)
4938 return tokError("expected DWARF tag");
4939
4940 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4942 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4943 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4944
4945 Result.assign(Tag);
4946 Lex.Lex();
4947 return false;
4948}
4949
4950template <>
4951bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4952 DwarfMacinfoTypeField &Result) {
4953 if (Lex.getKind() == lltok::APSInt)
4954 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4955
4956 if (Lex.getKind() != lltok::DwarfMacinfo)
4957 return tokError("expected DWARF macinfo type");
4958
4959 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4960 if (Macinfo == dwarf::DW_MACINFO_invalid)
4961 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4962 Lex.getStrVal() + "'");
4963 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4964
4965 Result.assign(Macinfo);
4966 Lex.Lex();
4967 return false;
4968}
4969
4970template <>
4971bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4972 DwarfVirtualityField &Result) {
4973 if (Lex.getKind() == lltok::APSInt)
4974 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4975
4976 if (Lex.getKind() != lltok::DwarfVirtuality)
4977 return tokError("expected DWARF virtuality code");
4978
4979 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4980 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4981 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4982 Lex.getStrVal() + "'");
4983 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4984 Result.assign(Virtuality);
4985 Lex.Lex();
4986 return false;
4987}
4988
4989template <>
4990bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4991 DwarfEnumKindField &Result) {
4992 if (Lex.getKind() == lltok::APSInt)
4993 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4994
4995 if (Lex.getKind() != lltok::DwarfEnumKind)
4996 return tokError("expected DWARF enum kind code");
4997
4998 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
4999 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5000 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5001 Lex.getStrVal() + "'");
5002 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5003 Result.assign(EnumKind);
5004 Lex.Lex();
5005 return false;
5006}
5007
5008template <>
5009bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5010 if (Lex.getKind() == lltok::APSInt)
5011 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5012
5013 if (Lex.getKind() != lltok::DwarfLang)
5014 return tokError("expected DWARF language");
5015
5016 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5017 if (!Lang)
5018 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5019 "'");
5020 assert(Lang <= Result.Max && "Expected valid DWARF language");
5021 Result.assign(Lang);
5022 Lex.Lex();
5023 return false;
5024}
5025
5026template <>
5027bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5028 DwarfSourceLangNameField &Result) {
5029 if (Lex.getKind() == lltok::APSInt)
5030 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5031
5032 if (Lex.getKind() != lltok::DwarfSourceLangName)
5033 return tokError("expected DWARF source language name");
5034
5035 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5036 if (!Lang)
5037 return tokError("invalid DWARF source language name" + Twine(" '") +
5038 Lex.getStrVal() + "'");
5039 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5040 Result.assign(Lang);
5041 Lex.Lex();
5042 return false;
5043}
5044
5045template <>
5046bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5047 if (Lex.getKind() == lltok::APSInt)
5048 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5049
5050 if (Lex.getKind() != lltok::DwarfCC)
5051 return tokError("expected DWARF calling convention");
5052
5053 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5054 if (!CC)
5055 return tokError("invalid DWARF calling convention" + Twine(" '") +
5056 Lex.getStrVal() + "'");
5057 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5058 Result.assign(CC);
5059 Lex.Lex();
5060 return false;
5061}
5062
5063template <>
5064bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5065 EmissionKindField &Result) {
5066 if (Lex.getKind() == lltok::APSInt)
5067 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5068
5069 if (Lex.getKind() != lltok::EmissionKind)
5070 return tokError("expected emission kind");
5071
5072 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5073 if (!Kind)
5074 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5075 "'");
5076 assert(*Kind <= Result.Max && "Expected valid emission kind");
5077 Result.assign(*Kind);
5078 Lex.Lex();
5079 return false;
5080}
5081
5082template <>
5083bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5084 FixedPointKindField &Result) {
5085 if (Lex.getKind() == lltok::APSInt)
5086 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5087
5088 if (Lex.getKind() != lltok::FixedPointKind)
5089 return tokError("expected fixed-point kind");
5090
5091 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5092 if (!Kind)
5093 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5094 "'");
5095 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5096 Result.assign(*Kind);
5097 Lex.Lex();
5098 return false;
5099}
5100
5101template <>
5102bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5103 NameTableKindField &Result) {
5104 if (Lex.getKind() == lltok::APSInt)
5105 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5106
5107 if (Lex.getKind() != lltok::NameTableKind)
5108 return tokError("expected nameTable kind");
5109
5110 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5111 if (!Kind)
5112 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5113 "'");
5114 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5115 Result.assign((unsigned)*Kind);
5116 Lex.Lex();
5117 return false;
5118}
5119
5120template <>
5121bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5122 DwarfAttEncodingField &Result) {
5123 if (Lex.getKind() == lltok::APSInt)
5124 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5125
5126 if (Lex.getKind() != lltok::DwarfAttEncoding)
5127 return tokError("expected DWARF type attribute encoding");
5128
5129 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5130 if (!Encoding)
5131 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5132 Lex.getStrVal() + "'");
5133 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5134 Result.assign(Encoding);
5135 Lex.Lex();
5136 return false;
5137}
5138
5139/// DIFlagField
5140/// ::= uint32
5141/// ::= DIFlagVector
5142/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5143template <>
5144bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5145
5146 // parser for a single flag.
5147 auto parseFlag = [&](DINode::DIFlags &Val) {
5148 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5149 uint32_t TempVal = static_cast<uint32_t>(Val);
5150 bool Res = parseUInt32(TempVal);
5151 Val = static_cast<DINode::DIFlags>(TempVal);
5152 return Res;
5153 }
5154
5155 if (Lex.getKind() != lltok::DIFlag)
5156 return tokError("expected debug info flag");
5157
5158 Val = DINode::getFlag(Lex.getStrVal());
5159 if (!Val)
5160 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5161 "'");
5162 Lex.Lex();
5163 return false;
5164 };
5165
5166 // parse the flags and combine them together.
5167 DINode::DIFlags Combined = DINode::FlagZero;
5168 do {
5169 DINode::DIFlags Val;
5170 if (parseFlag(Val))
5171 return true;
5172 Combined |= Val;
5173 } while (EatIfPresent(lltok::bar));
5174
5175 Result.assign(Combined);
5176 return false;
5177}
5178
5179/// DISPFlagField
5180/// ::= uint32
5181/// ::= DISPFlagVector
5182/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5183template <>
5184bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5185
5186 // parser for a single flag.
5187 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5188 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5189 uint32_t TempVal = static_cast<uint32_t>(Val);
5190 bool Res = parseUInt32(TempVal);
5191 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5192 return Res;
5193 }
5194
5195 if (Lex.getKind() != lltok::DISPFlag)
5196 return tokError("expected debug info flag");
5197
5198 Val = DISubprogram::getFlag(Lex.getStrVal());
5199 if (!Val)
5200 return tokError(Twine("invalid subprogram debug info flag '") +
5201 Lex.getStrVal() + "'");
5202 Lex.Lex();
5203 return false;
5204 };
5205
5206 // parse the flags and combine them together.
5207 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5208 do {
5210 if (parseFlag(Val))
5211 return true;
5212 Combined |= Val;
5213 } while (EatIfPresent(lltok::bar));
5214
5215 Result.assign(Combined);
5216 return false;
5217}
5218
5219template <>
5220bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5221 if (Lex.getKind() != lltok::APSInt)
5222 return tokError("expected signed integer");
5223
5224 auto &S = Lex.getAPSIntVal();
5225 if (S < Result.Min)
5226 return tokError("value for '" + Name + "' too small, limit is " +
5227 Twine(Result.Min));
5228 if (S > Result.Max)
5229 return tokError("value for '" + Name + "' too large, limit is " +
5230 Twine(Result.Max));
5231 Result.assign(S.getExtValue());
5232 assert(Result.Val >= Result.Min && "Expected value in range");
5233 assert(Result.Val <= Result.Max && "Expected value in range");
5234 Lex.Lex();
5235 return false;
5236}
5237
5238template <>
5239bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5240 switch (Lex.getKind()) {
5241 default:
5242 return tokError("expected 'true' or 'false'");
5243 case lltok::kw_true:
5244 Result.assign(true);
5245 break;
5246 case lltok::kw_false:
5247 Result.assign(false);
5248 break;
5249 }
5250 Lex.Lex();
5251 return false;
5252}
5253
5254template <>
5255bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5256 if (Lex.getKind() == lltok::kw_null) {
5257 if (!Result.AllowNull)
5258 return tokError("'" + Name + "' cannot be null");
5259 Lex.Lex();
5260 Result.assign(nullptr);
5261 return false;
5262 }
5263
5264 Metadata *MD;
5265 if (parseMetadata(MD, nullptr))
5266 return true;
5267
5268 Result.assign(MD);
5269 return false;
5270}
5271
5272template <>
5273bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5274 MDSignedOrMDField &Result) {
5275 // Try to parse a signed int.
5276 if (Lex.getKind() == lltok::APSInt) {
5277 MDSignedField Res = Result.A;
5278 if (!parseMDField(Loc, Name, Res)) {
5279 Result.assign(Res);
5280 return false;
5281 }
5282 return true;
5283 }
5284
5285 // Otherwise, try to parse as an MDField.
5286 MDField Res = Result.B;
5287 if (!parseMDField(Loc, Name, Res)) {
5288 Result.assign(Res);
5289 return false;
5290 }
5291
5292 return true;
5293}
5294
5295template <>
5296bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5297 MDUnsignedOrMDField &Result) {
5298 // Try to parse an unsigned int.
5299 if (Lex.getKind() == lltok::APSInt) {
5300 MDUnsignedField Res = Result.A;
5301 if (!parseMDField(Loc, Name, Res)) {
5302 Result.assign(Res);
5303 return false;
5304 }
5305 return true;
5306 }
5307
5308 // Otherwise, try to parse as an MDField.
5309 MDField Res = Result.B;
5310 if (!parseMDField(Loc, Name, Res)) {
5311 Result.assign(Res);
5312 return false;
5313 }
5314
5315 return true;
5316}
5317
5318template <>
5319bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5320 LocTy ValueLoc = Lex.getLoc();
5321 std::string S;
5322 if (parseStringConstant(S))
5323 return true;
5324
5325 if (S.empty()) {
5326 switch (Result.EmptyIs) {
5327 case MDStringField::EmptyIs::Null:
5328 Result.assign(nullptr);
5329 return false;
5330 case MDStringField::EmptyIs::Empty:
5331 break;
5332 case MDStringField::EmptyIs::Error:
5333 return error(ValueLoc, "'" + Name + "' cannot be empty");
5334 }
5335 }
5336
5337 Result.assign(MDString::get(Context, S));
5338 return false;
5339}
5340
5341template <>
5342bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5344 if (parseMDNodeVector(MDs))
5345 return true;
5346
5347 Result.assign(std::move(MDs));
5348 return false;
5349}
5350
5351template <>
5352bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5353 ChecksumKindField &Result) {
5354 std::optional<DIFile::ChecksumKind> CSKind =
5355 DIFile::getChecksumKind(Lex.getStrVal());
5356
5357 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5358 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5359 "'");
5360
5361 Result.assign(*CSKind);
5362 Lex.Lex();
5363 return false;
5364}
5365
5366} // end namespace llvm
5367
5368template <class ParserTy>
5369bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5370 do {
5371 if (Lex.getKind() != lltok::LabelStr)
5372 return tokError("expected field label here");
5373
5374 if (ParseField())
5375 return true;
5376 } while (EatIfPresent(lltok::comma));
5377
5378 return false;
5379}
5380
5381template <class ParserTy>
5382bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5383 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5384 Lex.Lex();
5385
5386 if (parseToken(lltok::lparen, "expected '(' here"))
5387 return true;
5388 if (Lex.getKind() != lltok::rparen)
5389 if (parseMDFieldsImplBody(ParseField))
5390 return true;
5391
5392 ClosingLoc = Lex.getLoc();
5393 return parseToken(lltok::rparen, "expected ')' here");
5394}
5395
5396template <class FieldTy>
5397bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5398 if (Result.Seen)
5399 return tokError("field '" + Name + "' cannot be specified more than once");
5400
5401 LocTy Loc = Lex.getLoc();
5402 Lex.Lex();
5403 return parseMDField(Loc, Name, Result);
5404}
5405
5406bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5407 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5408
5409#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5410 if (Lex.getStrVal() == #CLASS) \
5411 return parse##CLASS(N, IsDistinct);
5412#include "llvm/IR/Metadata.def"
5413
5414 return tokError("expected metadata type");
5415}
5416
5417#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5418#define NOP_FIELD(NAME, TYPE, INIT)
5419#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5420 if (!NAME.Seen) \
5421 return error(ClosingLoc, "missing required field '" #NAME "'");
5422#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5423 if (Lex.getStrVal() == #NAME) \
5424 return parseMDField(#NAME, NAME);
5425#define PARSE_MD_FIELDS() \
5426 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5427 do { \
5428 LocTy ClosingLoc; \
5429 if (parseMDFieldsImpl( \
5430 [&]() -> bool { \
5431 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5432 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5433 "'"); \
5434 }, \
5435 ClosingLoc)) \
5436 return true; \
5437 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5438 } while (false)
5439#define GET_OR_DISTINCT(CLASS, ARGS) \
5440 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5441
5442/// parseDILocationFields:
5443/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5444/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5445bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5446#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5447 OPTIONAL(line, LineField, ); \
5448 OPTIONAL(column, ColumnField, ); \
5449 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5450 OPTIONAL(inlinedAt, MDField, ); \
5451 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5452 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5453 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5455#undef VISIT_MD_FIELDS
5456
5457 Result = GET_OR_DISTINCT(
5458 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5459 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5460 return false;
5461}
5462
5463/// parseDIAssignID:
5464/// ::= distinct !DIAssignID()
5465bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5466 if (!IsDistinct)
5467 return tokError("missing 'distinct', required for !DIAssignID()");
5468
5469 Lex.Lex();
5470
5471 // Now eat the parens.
5472 if (parseToken(lltok::lparen, "expected '(' here"))
5473 return true;
5474 if (parseToken(lltok::rparen, "expected ')' here"))
5475 return true;
5476
5478 return false;
5479}
5480
5481/// parseGenericDINode:
5482/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5483bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5484#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5485 REQUIRED(tag, DwarfTagField, ); \
5486 OPTIONAL(header, MDStringField, ); \
5487 OPTIONAL(operands, MDFieldList, );
5489#undef VISIT_MD_FIELDS
5490
5491 Result = GET_OR_DISTINCT(GenericDINode,
5492 (Context, tag.Val, header.Val, operands.Val));
5493 return false;
5494}
5495
5496/// parseDISubrangeType:
5497/// ::= !DISubrangeType(name: "whatever", file: !0,
5498/// line: 7, scope: !1, baseType: !2, size: 32,
5499/// align: 32, flags: 0, lowerBound: !3
5500/// upperBound: !4, stride: !5, bias: !6)
5501bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5502#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5503 OPTIONAL(name, MDStringField, ); \
5504 OPTIONAL(file, MDField, ); \
5505 OPTIONAL(line, LineField, ); \
5506 OPTIONAL(scope, MDField, ); \
5507 OPTIONAL(baseType, MDField, ); \
5508 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5509 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5510 OPTIONAL(flags, DIFlagField, ); \
5511 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5512 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5513 OPTIONAL(stride, MDSignedOrMDField, ); \
5514 OPTIONAL(bias, MDSignedOrMDField, );
5516#undef VISIT_MD_FIELDS
5517
5518 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5519 if (Bound.isMDSignedField())
5521 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5522 if (Bound.isMDField())
5523 return Bound.getMDFieldValue();
5524 return nullptr;
5525 };
5526
5527 Metadata *LowerBound = convToMetadata(lowerBound);
5528 Metadata *UpperBound = convToMetadata(upperBound);
5529 Metadata *Stride = convToMetadata(stride);
5530 Metadata *Bias = convToMetadata(bias);
5531
5533 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5534 size.getValueAsMetadata(Context), align.Val, flags.Val,
5535 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5536
5537 return false;
5538}
5539
5540/// parseDISubrange:
5541/// ::= !DISubrange(count: 30, lowerBound: 2)
5542/// ::= !DISubrange(count: !node, lowerBound: 2)
5543/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5544bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5545#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5546 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5547 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5548 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5549 OPTIONAL(stride, MDSignedOrMDField, );
5551#undef VISIT_MD_FIELDS
5552
5553 Metadata *Count = nullptr;
5554 Metadata *LowerBound = nullptr;
5555 Metadata *UpperBound = nullptr;
5556 Metadata *Stride = nullptr;
5557
5558 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5559 if (Bound.isMDSignedField())
5561 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5562 if (Bound.isMDField())
5563 return Bound.getMDFieldValue();
5564 return nullptr;
5565 };
5566
5567 Count = convToMetadata(count);
5568 LowerBound = convToMetadata(lowerBound);
5569 UpperBound = convToMetadata(upperBound);
5570 Stride = convToMetadata(stride);
5571
5572 Result = GET_OR_DISTINCT(DISubrange,
5573 (Context, Count, LowerBound, UpperBound, Stride));
5574
5575 return false;
5576}
5577
5578/// parseDIGenericSubrange:
5579/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5580/// !node3)
5581bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5582#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5583 OPTIONAL(count, MDSignedOrMDField, ); \
5584 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5585 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5586 OPTIONAL(stride, MDSignedOrMDField, );
5588#undef VISIT_MD_FIELDS
5589
5590 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5591 if (Bound.isMDSignedField())
5592 return DIExpression::get(
5593 Context, {dwarf::DW_OP_consts,
5594 static_cast<uint64_t>(Bound.getMDSignedValue())});
5595 if (Bound.isMDField())
5596 return Bound.getMDFieldValue();
5597 return nullptr;
5598 };
5599
5600 Metadata *Count = ConvToMetadata(count);
5601 Metadata *LowerBound = ConvToMetadata(lowerBound);
5602 Metadata *UpperBound = ConvToMetadata(upperBound);
5603 Metadata *Stride = ConvToMetadata(stride);
5604
5605 Result = GET_OR_DISTINCT(DIGenericSubrange,
5606 (Context, Count, LowerBound, UpperBound, Stride));
5607
5608 return false;
5609}
5610
5611/// parseDIEnumerator:
5612/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5613bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5614#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5615 REQUIRED(name, MDStringField, ); \
5616 REQUIRED(value, MDAPSIntField, ); \
5617 OPTIONAL(isUnsigned, MDBoolField, (false));
5619#undef VISIT_MD_FIELDS
5620
5621 if (isUnsigned.Val && value.Val.isNegative())
5622 return tokError("unsigned enumerator with negative value");
5623
5624 APSInt Value(value.Val);
5625 // Add a leading zero so that unsigned values with the msb set are not
5626 // mistaken for negative values when used for signed enumerators.
5627 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5628 Value = Value.zext(Value.getBitWidth() + 1);
5629
5630 Result =
5631 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5632
5633 return false;
5634}
5635
5636/// parseDIBasicType:
5637/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5638/// encoding: DW_ATE_encoding, flags: 0)
5639bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5640#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5641 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5642 OPTIONAL(name, MDStringField, ); \
5643 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5644 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5645 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5646 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5647 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5648 OPTIONAL(flags, DIFlagField, );
5650#undef VISIT_MD_FIELDS
5651
5653 DIBasicType,
5654 (Context, tag.Val, name.Val, size.getValueAsMetadata(Context), align.Val,
5655 encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5656 return false;
5657}
5658
5659/// parseDIFixedPointType:
5660/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5661/// align: 32, encoding: DW_ATE_signed_fixed,
5662/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5663/// denominator: 8)
5664bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5665#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5666 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5667 OPTIONAL(name, MDStringField, ); \
5668 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5669 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5670 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5671 OPTIONAL(flags, DIFlagField, ); \
5672 OPTIONAL(kind, FixedPointKindField, ); \
5673 OPTIONAL(factor, MDSignedField, ); \
5674 OPTIONAL(numerator, MDAPSIntField, ); \
5675 OPTIONAL(denominator, MDAPSIntField, );
5677#undef VISIT_MD_FIELDS
5678
5679 Result = GET_OR_DISTINCT(DIFixedPointType,
5680 (Context, tag.Val, name.Val,
5681 size.getValueAsMetadata(Context), align.Val,
5682 encoding.Val, flags.Val, kind.Val, factor.Val,
5683 numerator.Val, denominator.Val));
5684 return false;
5685}
5686
5687/// parseDIStringType:
5688/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5689bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5690#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5691 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5692 OPTIONAL(name, MDStringField, ); \
5693 OPTIONAL(stringLength, MDField, ); \
5694 OPTIONAL(stringLengthExpression, MDField, ); \
5695 OPTIONAL(stringLocationExpression, MDField, ); \
5696 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5697 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5698 OPTIONAL(encoding, DwarfAttEncodingField, );
5700#undef VISIT_MD_FIELDS
5701
5703 DIStringType,
5704 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5705 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5706 align.Val, encoding.Val));
5707 return false;
5708}
5709
5710/// parseDIDerivedType:
5711/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5712/// line: 7, scope: !1, baseType: !2, size: 32,
5713/// align: 32, offset: 0, flags: 0, extraData: !3,
5714/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5715/// ptrAuthIsAddressDiscriminated: true,
5716/// ptrAuthExtraDiscriminator: 0x1234,
5717/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5718/// )
5719bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5720#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5721 REQUIRED(tag, DwarfTagField, ); \
5722 OPTIONAL(name, MDStringField, ); \
5723 OPTIONAL(file, MDField, ); \
5724 OPTIONAL(line, LineField, ); \
5725 OPTIONAL(scope, MDField, ); \
5726 REQUIRED(baseType, MDField, ); \
5727 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5728 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5729 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5730 OPTIONAL(flags, DIFlagField, ); \
5731 OPTIONAL(extraData, MDField, ); \
5732 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5733 OPTIONAL(annotations, MDField, ); \
5734 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5735 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5736 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5737 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5738 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5740#undef VISIT_MD_FIELDS
5741
5742 std::optional<unsigned> DWARFAddressSpace;
5743 if (dwarfAddressSpace.Val != UINT32_MAX)
5744 DWARFAddressSpace = dwarfAddressSpace.Val;
5745 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5746 if (ptrAuthKey.Val)
5747 PtrAuthData.emplace(
5748 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5749 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5750 ptrAuthAuthenticatesNullValues.Val);
5751
5753 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5754 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5755 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5756 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5757 return false;
5758}
5759
5760bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5761#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5762 REQUIRED(tag, DwarfTagField, ); \
5763 OPTIONAL(name, MDStringField, ); \
5764 OPTIONAL(file, MDField, ); \
5765 OPTIONAL(line, LineField, ); \
5766 OPTIONAL(scope, MDField, ); \
5767 OPTIONAL(baseType, MDField, ); \
5768 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5769 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5770 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5771 OPTIONAL(flags, DIFlagField, ); \
5772 OPTIONAL(elements, MDField, ); \
5773 OPTIONAL(runtimeLang, DwarfLangField, ); \
5774 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5775 OPTIONAL(vtableHolder, MDField, ); \
5776 OPTIONAL(templateParams, MDField, ); \
5777 OPTIONAL(identifier, MDStringField, ); \
5778 OPTIONAL(discriminator, MDField, ); \
5779 OPTIONAL(dataLocation, MDField, ); \
5780 OPTIONAL(associated, MDField, ); \
5781 OPTIONAL(allocated, MDField, ); \
5782 OPTIONAL(rank, MDSignedOrMDField, ); \
5783 OPTIONAL(annotations, MDField, ); \
5784 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5785 OPTIONAL(specification, MDField, ); \
5786 OPTIONAL(bitStride, MDField, );
5788#undef VISIT_MD_FIELDS
5789
5790 Metadata *Rank = nullptr;
5791 if (rank.isMDSignedField())
5793 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5794 else if (rank.isMDField())
5795 Rank = rank.getMDFieldValue();
5796
5797 std::optional<unsigned> EnumKind;
5798 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5799 EnumKind = enumKind.Val;
5800
5801 // If this has an identifier try to build an ODR type.
5802 if (identifier.Val)
5803 if (auto *CT = DICompositeType::buildODRType(
5804 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5805 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
5806 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5807 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5808 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5809 dataLocation.Val, associated.Val, allocated.Val, Rank,
5810 annotations.Val, bitStride.Val)) {
5811 Result = CT;
5812 return false;
5813 }
5814
5815 // Create a new node, and save it in the context if it belongs in the type
5816 // map.
5818 DICompositeType,
5819 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5820 size.getValueAsMetadata(Context), align.Val,
5821 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5822 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5823 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5824 allocated.Val, Rank, annotations.Val, specification.Val,
5825 num_extra_inhabitants.Val, bitStride.Val));
5826 return false;
5827}
5828
5829bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5831 OPTIONAL(flags, DIFlagField, ); \
5832 OPTIONAL(cc, DwarfCCField, ); \
5833 REQUIRED(types, MDField, );
5835#undef VISIT_MD_FIELDS
5836
5837 Result = GET_OR_DISTINCT(DISubroutineType,
5838 (Context, flags.Val, cc.Val, types.Val));
5839 return false;
5840}
5841
5842/// parseDIFileType:
5843/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5844/// checksumkind: CSK_MD5,
5845/// checksum: "000102030405060708090a0b0c0d0e0f",
5846/// source: "source file contents")
5847bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5848 // The default constructed value for checksumkind is required, but will never
5849 // be used, as the parser checks if the field was actually Seen before using
5850 // the Val.
5851#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5852 REQUIRED(filename, MDStringField, ); \
5853 REQUIRED(directory, MDStringField, ); \
5854 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5855 OPTIONAL(checksum, MDStringField, ); \
5856 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5858#undef VISIT_MD_FIELDS
5859
5860 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5861 if (checksumkind.Seen && checksum.Seen)
5862 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5863 else if (checksumkind.Seen || checksum.Seen)
5864 return tokError("'checksumkind' and 'checksum' must be provided together");
5865
5866 MDString *Source = nullptr;
5867 if (source.Seen)
5868 Source = source.Val;
5870 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5871 return false;
5872}
5873
5874/// parseDICompileUnit:
5875/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5876/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5877/// splitDebugFilename: "abc.debug",
5878/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5879/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5880/// sysroot: "/", sdk: "MacOSX.sdk")
5881bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5882 if (!IsDistinct)
5883 return tokError("missing 'distinct', required for !DICompileUnit");
5884
5885 LocTy Loc = Lex.getLoc();
5886
5887#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5888 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5889 OPTIONAL(language, DwarfLangField, ); \
5890 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
5891 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
5892 OPTIONAL(producer, MDStringField, ); \
5893 OPTIONAL(isOptimized, MDBoolField, ); \
5894 OPTIONAL(flags, MDStringField, ); \
5895 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5896 OPTIONAL(splitDebugFilename, MDStringField, ); \
5897 OPTIONAL(emissionKind, EmissionKindField, ); \
5898 OPTIONAL(enums, MDField, ); \
5899 OPTIONAL(retainedTypes, MDField, ); \
5900 OPTIONAL(globals, MDField, ); \
5901 OPTIONAL(imports, MDField, ); \
5902 OPTIONAL(macros, MDField, ); \
5903 OPTIONAL(dwoId, MDUnsignedField, ); \
5904 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5905 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5906 OPTIONAL(nameTableKind, NameTableKindField, ); \
5907 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5908 OPTIONAL(sysroot, MDStringField, ); \
5909 OPTIONAL(sdk, MDStringField, );
5911#undef VISIT_MD_FIELDS
5912
5913 if (!language.Seen && !sourceLanguageName.Seen)
5914 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
5915 "required for !DICompileUnit");
5916
5917 if (language.Seen && sourceLanguageName.Seen)
5918 return error(Loc, "can only specify one of 'language' and "
5919 "'sourceLanguageName' on !DICompileUnit");
5920
5921 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
5922 return error(Loc, "'sourceLanguageVersion' requires an associated "
5923 "'sourceLanguageName' on !DICompileUnit");
5924
5926 Context,
5927 language.Seen ? DISourceLanguageName(language.Val)
5928 : DISourceLanguageName(sourceLanguageName.Val,
5929 sourceLanguageVersion.Val),
5930 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
5931 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
5932 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
5933 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
5934 sysroot.Val, sdk.Val);
5935 return false;
5936}
5937
5938/// parseDISubprogram:
5939/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5940/// file: !1, line: 7, type: !2, isLocal: false,
5941/// isDefinition: true, scopeLine: 8, containingType: !3,
5942/// virtuality: DW_VIRTUALTIY_pure_virtual,
5943/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5944/// spFlags: 10, isOptimized: false, templateParams: !4,
5945/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5946/// annotations: !8)
5947bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5948 auto Loc = Lex.getLoc();
5949#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5950 OPTIONAL(scope, MDField, ); \
5951 OPTIONAL(name, MDStringField, ); \
5952 OPTIONAL(linkageName, MDStringField, ); \
5953 OPTIONAL(file, MDField, ); \
5954 OPTIONAL(line, LineField, ); \
5955 OPTIONAL(type, MDField, ); \
5956 OPTIONAL(isLocal, MDBoolField, ); \
5957 OPTIONAL(isDefinition, MDBoolField, (true)); \
5958 OPTIONAL(scopeLine, LineField, ); \
5959 OPTIONAL(containingType, MDField, ); \
5960 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5961 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5962 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5963 OPTIONAL(flags, DIFlagField, ); \
5964 OPTIONAL(spFlags, DISPFlagField, ); \
5965 OPTIONAL(isOptimized, MDBoolField, ); \
5966 OPTIONAL(unit, MDField, ); \
5967 OPTIONAL(templateParams, MDField, ); \
5968 OPTIONAL(declaration, MDField, ); \
5969 OPTIONAL(retainedNodes, MDField, ); \
5970 OPTIONAL(thrownTypes, MDField, ); \
5971 OPTIONAL(annotations, MDField, ); \
5972 OPTIONAL(targetFuncName, MDStringField, ); \
5973 OPTIONAL(keyInstructions, MDBoolField, );
5975#undef VISIT_MD_FIELDS
5976
5977 // An explicit spFlags field takes precedence over individual fields in
5978 // older IR versions.
5979 DISubprogram::DISPFlags SPFlags =
5980 spFlags.Seen ? spFlags.Val
5981 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5982 isOptimized.Val, virtuality.Val);
5983 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5984 return error(
5985 Loc,
5986 "missing 'distinct', required for !DISubprogram that is a Definition");
5988 DISubprogram,
5989 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5990 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5991 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5992 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5993 targetFuncName.Val, keyInstructions.Val));
5994 return false;
5995}
5996
5997/// parseDILexicalBlock:
5998/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5999bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6000#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6001 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6002 OPTIONAL(file, MDField, ); \
6003 OPTIONAL(line, LineField, ); \
6004 OPTIONAL(column, ColumnField, );
6006#undef VISIT_MD_FIELDS
6007
6009 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6010 return false;
6011}
6012
6013/// parseDILexicalBlockFile:
6014/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6015bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6016#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6017 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6018 OPTIONAL(file, MDField, ); \
6019 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6021#undef VISIT_MD_FIELDS
6022
6023 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6024 (Context, scope.Val, file.Val, discriminator.Val));
6025 return false;
6026}
6027
6028/// parseDICommonBlock:
6029/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6030bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6031#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6032 REQUIRED(scope, MDField, ); \
6033 OPTIONAL(declaration, MDField, ); \
6034 OPTIONAL(name, MDStringField, ); \
6035 OPTIONAL(file, MDField, ); \
6036 OPTIONAL(line, LineField, );
6038#undef VISIT_MD_FIELDS
6039
6040 Result = GET_OR_DISTINCT(DICommonBlock,
6041 (Context, scope.Val, declaration.Val, name.Val,
6042 file.Val, line.Val));
6043 return false;
6044}
6045
6046/// parseDINamespace:
6047/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6048bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6049#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6050 REQUIRED(scope, MDField, ); \
6051 OPTIONAL(name, MDStringField, ); \
6052 OPTIONAL(exportSymbols, MDBoolField, );
6054#undef VISIT_MD_FIELDS
6055
6056 Result = GET_OR_DISTINCT(DINamespace,
6057 (Context, scope.Val, name.Val, exportSymbols.Val));
6058 return false;
6059}
6060
6061/// parseDIMacro:
6062/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6063/// "SomeValue")
6064bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6065#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6066 REQUIRED(type, DwarfMacinfoTypeField, ); \
6067 OPTIONAL(line, LineField, ); \
6068 REQUIRED(name, MDStringField, ); \
6069 OPTIONAL(value, MDStringField, );
6071#undef VISIT_MD_FIELDS
6072
6073 Result = GET_OR_DISTINCT(DIMacro,
6074 (Context, type.Val, line.Val, name.Val, value.Val));
6075 return false;
6076}
6077
6078/// parseDIMacroFile:
6079/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6080bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6081#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6082 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6083 OPTIONAL(line, LineField, ); \
6084 REQUIRED(file, MDField, ); \
6085 OPTIONAL(nodes, MDField, );
6087#undef VISIT_MD_FIELDS
6088
6089 Result = GET_OR_DISTINCT(DIMacroFile,
6090 (Context, type.Val, line.Val, file.Val, nodes.Val));
6091 return false;
6092}
6093
6094/// parseDIModule:
6095/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6096/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6097/// file: !1, line: 4, isDecl: false)
6098bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6099#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6100 REQUIRED(scope, MDField, ); \
6101 REQUIRED(name, MDStringField, ); \
6102 OPTIONAL(configMacros, MDStringField, ); \
6103 OPTIONAL(includePath, MDStringField, ); \
6104 OPTIONAL(apinotes, MDStringField, ); \
6105 OPTIONAL(file, MDField, ); \
6106 OPTIONAL(line, LineField, ); \
6107 OPTIONAL(isDecl, MDBoolField, );
6109#undef VISIT_MD_FIELDS
6110
6111 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6112 configMacros.Val, includePath.Val,
6113 apinotes.Val, line.Val, isDecl.Val));
6114 return false;
6115}
6116
6117/// parseDITemplateTypeParameter:
6118/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6119bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6120#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6121 OPTIONAL(name, MDStringField, ); \
6122 REQUIRED(type, MDField, ); \
6123 OPTIONAL(defaulted, MDBoolField, );
6125#undef VISIT_MD_FIELDS
6126
6127 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6128 (Context, name.Val, type.Val, defaulted.Val));
6129 return false;
6130}
6131
6132/// parseDITemplateValueParameter:
6133/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6134/// name: "V", type: !1, defaulted: false,
6135/// value: i32 7)
6136bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6138 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6139 OPTIONAL(name, MDStringField, ); \
6140 OPTIONAL(type, MDField, ); \
6141 OPTIONAL(defaulted, MDBoolField, ); \
6142 REQUIRED(value, MDField, );
6143
6145#undef VISIT_MD_FIELDS
6146
6148 DITemplateValueParameter,
6149 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6150 return false;
6151}
6152
6153/// parseDIGlobalVariable:
6154/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6155/// file: !1, line: 7, type: !2, isLocal: false,
6156/// isDefinition: true, templateParams: !3,
6157/// declaration: !4, align: 8)
6158bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6159#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6160 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6161 OPTIONAL(scope, MDField, ); \
6162 OPTIONAL(linkageName, MDStringField, ); \
6163 OPTIONAL(file, MDField, ); \
6164 OPTIONAL(line, LineField, ); \
6165 OPTIONAL(type, MDField, ); \
6166 OPTIONAL(isLocal, MDBoolField, ); \
6167 OPTIONAL(isDefinition, MDBoolField, (true)); \
6168 OPTIONAL(templateParams, MDField, ); \
6169 OPTIONAL(declaration, MDField, ); \
6170 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6171 OPTIONAL(annotations, MDField, );
6173#undef VISIT_MD_FIELDS
6174
6175 Result =
6176 GET_OR_DISTINCT(DIGlobalVariable,
6177 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6178 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6179 declaration.Val, templateParams.Val, align.Val,
6180 annotations.Val));
6181 return false;
6182}
6183
6184/// parseDILocalVariable:
6185/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6186/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6187/// align: 8)
6188/// ::= !DILocalVariable(scope: !0, name: "foo",
6189/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6190/// align: 8)
6191bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6192#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6193 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6194 OPTIONAL(name, MDStringField, ); \
6195 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6196 OPTIONAL(file, MDField, ); \
6197 OPTIONAL(line, LineField, ); \
6198 OPTIONAL(type, MDField, ); \
6199 OPTIONAL(flags, DIFlagField, ); \
6200 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6201 OPTIONAL(annotations, MDField, );
6203#undef VISIT_MD_FIELDS
6204
6205 Result = GET_OR_DISTINCT(DILocalVariable,
6206 (Context, scope.Val, name.Val, file.Val, line.Val,
6207 type.Val, arg.Val, flags.Val, align.Val,
6208 annotations.Val));
6209 return false;
6210}
6211
6212/// parseDILabel:
6213/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6214bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6215#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6216 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6217 REQUIRED(name, MDStringField, ); \
6218 REQUIRED(file, MDField, ); \
6219 REQUIRED(line, LineField, ); \
6220 OPTIONAL(column, ColumnField, ); \
6221 OPTIONAL(isArtificial, MDBoolField, ); \
6222 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6224#undef VISIT_MD_FIELDS
6225
6226 std::optional<unsigned> CoroSuspendIdx =
6227 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6228 : std::nullopt;
6229
6230 Result = GET_OR_DISTINCT(DILabel,
6231 (Context, scope.Val, name.Val, file.Val, line.Val,
6232 column.Val, isArtificial.Val, CoroSuspendIdx));
6233 return false;
6234}
6235
6236/// parseDIExpressionBody:
6237/// ::= (0, 7, -1)
6238bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6239 if (parseToken(lltok::lparen, "expected '(' here"))
6240 return true;
6241
6242 SmallVector<uint64_t, 8> Elements;
6243 if (Lex.getKind() != lltok::rparen)
6244 do {
6245 if (Lex.getKind() == lltok::DwarfOp) {
6246 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6247 Lex.Lex();
6248 Elements.push_back(Op);
6249 continue;
6250 }
6251 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6252 }
6253
6254 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6255 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6256 Lex.Lex();
6257 Elements.push_back(Op);
6258 continue;
6259 }
6260 return tokError(Twine("invalid DWARF attribute encoding '") +
6261 Lex.getStrVal() + "'");
6262 }
6263
6264 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6265 return tokError("expected unsigned integer");
6266
6267 auto &U = Lex.getAPSIntVal();
6268 if (U.ugt(UINT64_MAX))
6269 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6270 Elements.push_back(U.getZExtValue());
6271 Lex.Lex();
6272 } while (EatIfPresent(lltok::comma));
6273
6274 if (parseToken(lltok::rparen, "expected ')' here"))
6275 return true;
6276
6277 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6278 return false;
6279}
6280
6281/// parseDIExpression:
6282/// ::= !DIExpression(0, 7, -1)
6283bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6284 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6285 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6286 Lex.Lex();
6287
6288 return parseDIExpressionBody(Result, IsDistinct);
6289}
6290
6291/// ParseDIArgList:
6292/// ::= !DIArgList(i32 7, i64 %0)
6293bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6294 assert(PFS && "Expected valid function state");
6295 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6296 Lex.Lex();
6297
6298 if (parseToken(lltok::lparen, "expected '(' here"))
6299 return true;
6300
6302 if (Lex.getKind() != lltok::rparen)
6303 do {
6304 Metadata *MD;
6305 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6306 return true;
6307 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6308 } while (EatIfPresent(lltok::comma));
6309
6310 if (parseToken(lltok::rparen, "expected ')' here"))
6311 return true;
6312
6313 MD = DIArgList::get(Context, Args);
6314 return false;
6315}
6316
6317/// parseDIGlobalVariableExpression:
6318/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6319bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6320 bool IsDistinct) {
6321#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6322 REQUIRED(var, MDField, ); \
6323 REQUIRED(expr, MDField, );
6325#undef VISIT_MD_FIELDS
6326
6327 Result =
6328 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6329 return false;
6330}
6331
6332/// parseDIObjCProperty:
6333/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6334/// getter: "getFoo", attributes: 7, type: !2)
6335bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6336#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6337 OPTIONAL(name, MDStringField, ); \
6338 OPTIONAL(file, MDField, ); \
6339 OPTIONAL(line, LineField, ); \
6340 OPTIONAL(setter, MDStringField, ); \
6341 OPTIONAL(getter, MDStringField, ); \
6342 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6343 OPTIONAL(type, MDField, );
6345#undef VISIT_MD_FIELDS
6346
6347 Result = GET_OR_DISTINCT(DIObjCProperty,
6348 (Context, name.Val, file.Val, line.Val, getter.Val,
6349 setter.Val, attributes.Val, type.Val));
6350 return false;
6351}
6352
6353/// parseDIImportedEntity:
6354/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6355/// line: 7, name: "foo", elements: !2)
6356bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6357#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6358 REQUIRED(tag, DwarfTagField, ); \
6359 REQUIRED(scope, MDField, ); \
6360 OPTIONAL(entity, MDField, ); \
6361 OPTIONAL(file, MDField, ); \
6362 OPTIONAL(line, LineField, ); \
6363 OPTIONAL(name, MDStringField, ); \
6364 OPTIONAL(elements, MDField, );
6366#undef VISIT_MD_FIELDS
6367
6368 Result = GET_OR_DISTINCT(DIImportedEntity,
6369 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6370 line.Val, name.Val, elements.Val));
6371 return false;
6372}
6373
6374#undef PARSE_MD_FIELD
6375#undef NOP_FIELD
6376#undef REQUIRE_FIELD
6377#undef DECLARE_FIELD
6378
6379/// parseMetadataAsValue
6380/// ::= metadata i32 %local
6381/// ::= metadata i32 @global
6382/// ::= metadata i32 7
6383/// ::= metadata !0
6384/// ::= metadata !{...}
6385/// ::= metadata !"string"
6386bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6387 // Note: the type 'metadata' has already been parsed.
6388 Metadata *MD;
6389 if (parseMetadata(MD, &PFS))
6390 return true;
6391
6392 V = MetadataAsValue::get(Context, MD);
6393 return false;
6394}
6395
6396/// parseValueAsMetadata
6397/// ::= i32 %local
6398/// ::= i32 @global
6399/// ::= i32 7
6400bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6401 PerFunctionState *PFS) {
6402 Type *Ty;
6403 LocTy Loc;
6404 if (parseType(Ty, TypeMsg, Loc))
6405 return true;
6406 if (Ty->isMetadataTy())
6407 return error(Loc, "invalid metadata-value-metadata roundtrip");
6408
6409 Value *V;
6410 if (parseValue(Ty, V, PFS))
6411 return true;
6412
6413 MD = ValueAsMetadata::get(V);
6414 return false;
6415}
6416
6417/// parseMetadata
6418/// ::= i32 %local
6419/// ::= i32 @global
6420/// ::= i32 7
6421/// ::= !42
6422/// ::= !{...}
6423/// ::= !"string"
6424/// ::= !DILocation(...)
6425bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6426 if (Lex.getKind() == lltok::MetadataVar) {
6427 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6428 // so parsing this requires a Function State.
6429 if (Lex.getStrVal() == "DIArgList") {
6430 Metadata *AL;
6431 if (parseDIArgList(AL, PFS))
6432 return true;
6433 MD = AL;
6434 return false;
6435 }
6436 MDNode *N;
6437 if (parseSpecializedMDNode(N)) {
6438 return true;
6439 }
6440 MD = N;
6441 return false;
6442 }
6443
6444 // ValueAsMetadata:
6445 // <type> <value>
6446 if (Lex.getKind() != lltok::exclaim)
6447 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6448
6449 // '!'.
6450 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6451 Lex.Lex();
6452
6453 // MDString:
6454 // ::= '!' STRINGCONSTANT
6455 if (Lex.getKind() == lltok::StringConstant) {
6456 MDString *S;
6457 if (parseMDString(S))
6458 return true;
6459 MD = S;
6460 return false;
6461 }
6462
6463 // MDNode:
6464 // !{ ... }
6465 // !7
6466 MDNode *N;
6467 if (parseMDNodeTail(N))
6468 return true;
6469 MD = N;
6470 return false;
6471}
6472
6473//===----------------------------------------------------------------------===//
6474// Function Parsing.
6475//===----------------------------------------------------------------------===//
6476
6477bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6478 PerFunctionState *PFS) {
6479 if (Ty->isFunctionTy())
6480 return error(ID.Loc, "functions are not values, refer to them as pointers");
6481
6482 switch (ID.Kind) {
6483 case ValID::t_LocalID:
6484 if (!PFS)
6485 return error(ID.Loc, "invalid use of function-local name");
6486 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6487 return V == nullptr;
6488 case ValID::t_LocalName:
6489 if (!PFS)
6490 return error(ID.Loc, "invalid use of function-local name");
6491 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6492 return V == nullptr;
6493 case ValID::t_InlineAsm: {
6494 if (!ID.FTy)
6495 return error(ID.Loc, "invalid type for inline asm constraint string");
6496 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6497 return error(ID.Loc, toString(std::move(Err)));
6498 V = InlineAsm::get(
6499 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6500 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6501 return false;
6502 }
6504 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6505 if (V && ID.NoCFI)
6507 return V == nullptr;
6508 case ValID::t_GlobalID:
6509 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6510 if (V && ID.NoCFI)
6512 return V == nullptr;
6513 case ValID::t_APSInt:
6514 if (!Ty->isIntegerTy())
6515 return error(ID.Loc, "integer constant must have integer type");
6516 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6517 V = ConstantInt::get(Context, ID.APSIntVal);
6518 return false;
6519 case ValID::t_APFloat:
6520 if (!Ty->isFloatingPointTy() ||
6521 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6522 return error(ID.Loc, "floating point constant invalid for type");
6523
6524 // The lexer has no type info, so builds all half, bfloat, float, and double
6525 // FP constants as double. Fix this here. Long double does not need this.
6526 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6527 // Check for signaling before potentially converting and losing that info.
6528 bool IsSNAN = ID.APFloatVal.isSignaling();
6529 bool Ignored;
6530 if (Ty->isHalfTy())
6532 &Ignored);
6533 else if (Ty->isBFloatTy())
6534 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6535 &Ignored);
6536 else if (Ty->isFloatTy())
6538 &Ignored);
6539 if (IsSNAN) {
6540 // The convert call above may quiet an SNaN, so manufacture another
6541 // SNaN. The bitcast works because the payload (significand) parameter
6542 // is truncated to fit.
6543 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6544 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6545 ID.APFloatVal.isNegative(), &Payload);
6546 }
6547 }
6548 V = ConstantFP::get(Context, ID.APFloatVal);
6549
6550 if (V->getType() != Ty)
6551 return error(ID.Loc, "floating point constant does not have type '" +
6552 getTypeString(Ty) + "'");
6553
6554 return false;
6555 case ValID::t_Null:
6556 if (!Ty->isPointerTy())
6557 return error(ID.Loc, "null must be a pointer type");
6559 return false;
6560 case ValID::t_Undef:
6561 // FIXME: LabelTy should not be a first-class type.
6562 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6563 return error(ID.Loc, "invalid type for undef constant");
6564 V = UndefValue::get(Ty);
6565 return false;
6567 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6568 return error(ID.Loc, "invalid empty array initializer");
6569 V = PoisonValue::get(Ty);
6570 return false;
6571 case ValID::t_Zero:
6572 // FIXME: LabelTy should not be a first-class type.
6573 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6574 return error(ID.Loc, "invalid type for null constant");
6575 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6576 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6577 return error(ID.Loc, "invalid type for null constant");
6579 return false;
6580 case ValID::t_None:
6581 if (!Ty->isTokenTy())
6582 return error(ID.Loc, "invalid type for none constant");
6584 return false;
6585 case ValID::t_Poison:
6586 // FIXME: LabelTy should not be a first-class type.
6587 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6588 return error(ID.Loc, "invalid type for poison constant");
6589 V = PoisonValue::get(Ty);
6590 return false;
6591 case ValID::t_Constant:
6592 if (ID.ConstantVal->getType() != Ty)
6593 return error(ID.Loc, "constant expression type mismatch: got type '" +
6594 getTypeString(ID.ConstantVal->getType()) +
6595 "' but expected '" + getTypeString(Ty) + "'");
6596 V = ID.ConstantVal;
6597 return false;
6599 if (!Ty->isVectorTy())
6600 return error(ID.Loc, "vector constant must have vector type");
6601 if (ID.ConstantVal->getType() != Ty->getScalarType())
6602 return error(ID.Loc, "constant expression type mismatch: got type '" +
6603 getTypeString(ID.ConstantVal->getType()) +
6604 "' but expected '" +
6605 getTypeString(Ty->getScalarType()) + "'");
6606 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6607 ID.ConstantVal);
6608 return false;
6611 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6612 if (ST->getNumElements() != ID.UIntVal)
6613 return error(ID.Loc,
6614 "initializer with struct type has wrong # elements");
6615 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6616 return error(ID.Loc, "packed'ness of initializer and type don't match");
6617
6618 // Verify that the elements are compatible with the structtype.
6619 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6620 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6621 return error(
6622 ID.Loc,
6623 "element " + Twine(i) +
6624 " of struct initializer doesn't match struct element type");
6625
6627 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6628 } else
6629 return error(ID.Loc, "constant expression type mismatch");
6630 return false;
6631 }
6632 llvm_unreachable("Invalid ValID");
6633}
6634
6635bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6636 C = nullptr;
6637 ValID ID;
6638 auto Loc = Lex.getLoc();
6639 if (parseValID(ID, /*PFS=*/nullptr))
6640 return true;
6641 switch (ID.Kind) {
6642 case ValID::t_APSInt:
6643 case ValID::t_APFloat:
6644 case ValID::t_Undef:
6645 case ValID::t_Poison:
6646 case ValID::t_Zero:
6647 case ValID::t_Constant:
6651 Value *V;
6652 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6653 return true;
6654 assert(isa<Constant>(V) && "Expected a constant value");
6655 C = cast<Constant>(V);
6656 return false;
6657 }
6658 case ValID::t_Null:
6660 return false;
6661 default:
6662 return error(Loc, "expected a constant value");
6663 }
6664}
6665
6666bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6667 V = nullptr;
6668 ValID ID;
6669 return parseValID(ID, PFS, Ty) ||
6670 convertValIDToValue(Ty, ID, V, PFS);
6671}
6672
6673bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6674 Type *Ty = nullptr;
6675 return parseType(Ty) || parseValue(Ty, V, PFS);
6676}
6677
6678bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6679 PerFunctionState &PFS) {
6680 Value *V;
6681 Loc = Lex.getLoc();
6682 if (parseTypeAndValue(V, PFS))
6683 return true;
6684 if (!isa<BasicBlock>(V))
6685 return error(Loc, "expected a basic block");
6686 BB = cast<BasicBlock>(V);
6687 return false;
6688}
6689
6691 // Exit early for the common (non-debug-intrinsic) case.
6692 // We can make this the only check when we begin supporting all "llvm.dbg"
6693 // intrinsics in the new debug info format.
6694 if (!Name.starts_with("llvm.dbg."))
6695 return false;
6697 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6698 FnID == Intrinsic::dbg_assign;
6699}
6700
6701/// FunctionHeader
6702/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6703/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6704/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6705/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6706bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6707 unsigned &FunctionNumber,
6708 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6709 // parse the linkage.
6710 LocTy LinkageLoc = Lex.getLoc();
6711 unsigned Linkage;
6712 unsigned Visibility;
6713 unsigned DLLStorageClass;
6714 bool DSOLocal;
6715 AttrBuilder RetAttrs(M->getContext());
6716 unsigned CC;
6717 bool HasLinkage;
6718 Type *RetType = nullptr;
6719 LocTy RetTypeLoc = Lex.getLoc();
6720 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6721 DSOLocal) ||
6722 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6723 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6724 return true;
6725
6726 // Verify that the linkage is ok.
6729 break; // always ok.
6731 if (IsDefine)
6732 return error(LinkageLoc, "invalid linkage for function definition");
6733 break;
6741 if (!IsDefine)
6742 return error(LinkageLoc, "invalid linkage for function declaration");
6743 break;
6746 return error(LinkageLoc, "invalid function linkage type");
6747 }
6748
6749 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6750 return error(LinkageLoc,
6751 "symbol with local linkage must have default visibility");
6752
6753 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6754 return error(LinkageLoc,
6755 "symbol with local linkage cannot have a DLL storage class");
6756
6757 if (!FunctionType::isValidReturnType(RetType))
6758 return error(RetTypeLoc, "invalid function return type");
6759
6760 LocTy NameLoc = Lex.getLoc();
6761
6762 std::string FunctionName;
6763 if (Lex.getKind() == lltok::GlobalVar) {
6764 FunctionName = Lex.getStrVal();
6765 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6766 FunctionNumber = Lex.getUIntVal();
6767 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6768 FunctionNumber))
6769 return true;
6770 } else {
6771 return tokError("expected function name");
6772 }
6773
6774 Lex.Lex();
6775
6776 if (Lex.getKind() != lltok::lparen)
6777 return tokError("expected '(' in function argument list");
6778
6780 bool IsVarArg;
6781 AttrBuilder FuncAttrs(M->getContext());
6782 std::vector<unsigned> FwdRefAttrGrps;
6783 LocTy BuiltinLoc;
6784 std::string Section;
6785 std::string Partition;
6786 MaybeAlign Alignment;
6787 std::string GC;
6789 unsigned AddrSpace = 0;
6790 Constant *Prefix = nullptr;
6791 Constant *Prologue = nullptr;
6792 Constant *PersonalityFn = nullptr;
6793 Comdat *C;
6794
6795 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6796 parseOptionalUnnamedAddr(UnnamedAddr) ||
6797 parseOptionalProgramAddrSpace(AddrSpace) ||
6798 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6799 BuiltinLoc) ||
6800 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6801 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6802 parseOptionalComdat(FunctionName, C) ||
6803 parseOptionalAlignment(Alignment) ||
6804 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6805 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6806 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6807 (EatIfPresent(lltok::kw_personality) &&
6808 parseGlobalTypeAndValue(PersonalityFn)))
6809 return true;
6810
6811 if (FuncAttrs.contains(Attribute::Builtin))
6812 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6813
6814 // If the alignment was parsed as an attribute, move to the alignment field.
6815 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6816 Alignment = A;
6817 FuncAttrs.removeAttribute(Attribute::Alignment);
6818 }
6819
6820 // Okay, if we got here, the function is syntactically valid. Convert types
6821 // and do semantic checks.
6822 std::vector<Type*> ParamTypeList;
6824
6825 for (const ArgInfo &Arg : ArgList) {
6826 ParamTypeList.push_back(Arg.Ty);
6827 Attrs.push_back(Arg.Attrs);
6828 }
6829
6830 AttributeList PAL =
6831 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6832 AttributeSet::get(Context, RetAttrs), Attrs);
6833
6834 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6835 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6836
6837 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6838 PointerType *PFT = PointerType::get(Context, AddrSpace);
6839
6840 Fn = nullptr;
6841 GlobalValue *FwdFn = nullptr;
6842 if (!FunctionName.empty()) {
6843 // If this was a definition of a forward reference, remove the definition
6844 // from the forward reference table and fill in the forward ref.
6845 auto FRVI = ForwardRefVals.find(FunctionName);
6846 if (FRVI != ForwardRefVals.end()) {
6847 FwdFn = FRVI->second.first;
6848 if (FwdFn->getType() != PFT)
6849 return error(FRVI->second.second,
6850 "invalid forward reference to "
6851 "function '" +
6852 FunctionName +
6853 "' with wrong type: "
6854 "expected '" +
6855 getTypeString(PFT) + "' but was '" +
6856 getTypeString(FwdFn->getType()) + "'");
6857 ForwardRefVals.erase(FRVI);
6858 } else if ((Fn = M->getFunction(FunctionName))) {
6859 // Reject redefinitions.
6860 return error(NameLoc,
6861 "invalid redefinition of function '" + FunctionName + "'");
6862 } else if (M->getNamedValue(FunctionName)) {
6863 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6864 }
6865
6866 } else {
6867 // Handle @"", where a name is syntactically specified, but semantically
6868 // missing.
6869 if (FunctionNumber == (unsigned)-1)
6870 FunctionNumber = NumberedVals.getNext();
6871
6872 // If this is a definition of a forward referenced function, make sure the
6873 // types agree.
6874 auto I = ForwardRefValIDs.find(FunctionNumber);
6875 if (I != ForwardRefValIDs.end()) {
6876 FwdFn = I->second.first;
6877 if (FwdFn->getType() != PFT)
6878 return error(NameLoc, "type of definition and forward reference of '@" +
6879 Twine(FunctionNumber) +
6880 "' disagree: "
6881 "expected '" +
6882 getTypeString(PFT) + "' but was '" +
6883 getTypeString(FwdFn->getType()) + "'");
6884 ForwardRefValIDs.erase(I);
6885 }
6886 }
6887
6889 FunctionName, M);
6890
6891 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6892
6893 if (FunctionName.empty())
6894 NumberedVals.add(FunctionNumber, Fn);
6895
6897 maybeSetDSOLocal(DSOLocal, *Fn);
6900 Fn->setCallingConv(CC);
6901 Fn->setAttributes(PAL);
6902 Fn->setUnnamedAddr(UnnamedAddr);
6903 if (Alignment)
6904 Fn->setAlignment(*Alignment);
6905 Fn->setSection(Section);
6906 Fn->setPartition(Partition);
6907 Fn->setComdat(C);
6908 Fn->setPersonalityFn(PersonalityFn);
6909 if (!GC.empty()) Fn->setGC(GC);
6910 Fn->setPrefixData(Prefix);
6911 Fn->setPrologueData(Prologue);
6912 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6913
6914 // Add all of the arguments we parsed to the function.
6915 Function::arg_iterator ArgIt = Fn->arg_begin();
6916 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6917 // If the argument has a name, insert it into the argument symbol table.
6918 if (ArgList[i].Name.empty()) continue;
6919
6920 // Set the name, if it conflicted, it will be auto-renamed.
6921 ArgIt->setName(ArgList[i].Name);
6922
6923 if (ArgIt->getName() != ArgList[i].Name)
6924 return error(ArgList[i].Loc,
6925 "redefinition of argument '%" + ArgList[i].Name + "'");
6926 }
6927
6928 if (FwdFn) {
6929 FwdFn->replaceAllUsesWith(Fn);
6930 FwdFn->eraseFromParent();
6931 }
6932
6933 if (IsDefine)
6934 return false;
6935
6936 // Check the declaration has no block address forward references.
6937 ValID ID;
6938 if (FunctionName.empty()) {
6939 ID.Kind = ValID::t_GlobalID;
6940 ID.UIntVal = FunctionNumber;
6941 } else {
6942 ID.Kind = ValID::t_GlobalName;
6943 ID.StrVal = FunctionName;
6944 }
6945 auto Blocks = ForwardRefBlockAddresses.find(ID);
6946 if (Blocks != ForwardRefBlockAddresses.end())
6947 return error(Blocks->first.Loc,
6948 "cannot take blockaddress inside a declaration");
6949 return false;
6950}
6951
6952bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6953 ValID ID;
6954 if (FunctionNumber == -1) {
6955 ID.Kind = ValID::t_GlobalName;
6956 ID.StrVal = std::string(F.getName());
6957 } else {
6958 ID.Kind = ValID::t_GlobalID;
6959 ID.UIntVal = FunctionNumber;
6960 }
6961
6962 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6963 if (Blocks == P.ForwardRefBlockAddresses.end())
6964 return false;
6965
6966 for (const auto &I : Blocks->second) {
6967 const ValID &BBID = I.first;
6968 GlobalValue *GV = I.second;
6969
6970 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6971 "Expected local id or name");
6972 BasicBlock *BB;
6973 if (BBID.Kind == ValID::t_LocalName)
6974 BB = getBB(BBID.StrVal, BBID.Loc);
6975 else
6976 BB = getBB(BBID.UIntVal, BBID.Loc);
6977 if (!BB)
6978 return P.error(BBID.Loc, "referenced value is not a basic block");
6979
6980 Value *ResolvedVal = BlockAddress::get(&F, BB);
6981 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6982 ResolvedVal);
6983 if (!ResolvedVal)
6984 return true;
6985 GV->replaceAllUsesWith(ResolvedVal);
6986 GV->eraseFromParent();
6987 }
6988
6989 P.ForwardRefBlockAddresses.erase(Blocks);
6990 return false;
6991}
6992
6993/// parseFunctionBody
6994/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6995bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6996 ArrayRef<unsigned> UnnamedArgNums) {
6997 if (Lex.getKind() != lltok::lbrace)
6998 return tokError("expected '{' in function body");
6999 Lex.Lex(); // eat the {.
7000
7001 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7002
7003 // Resolve block addresses and allow basic blocks to be forward-declared
7004 // within this function.
7005 if (PFS.resolveForwardRefBlockAddresses())
7006 return true;
7007 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7008
7009 // We need at least one basic block.
7010 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7011 return tokError("function body requires at least one basic block");
7012
7013 while (Lex.getKind() != lltok::rbrace &&
7014 Lex.getKind() != lltok::kw_uselistorder)
7015 if (parseBasicBlock(PFS))
7016 return true;
7017
7018 while (Lex.getKind() != lltok::rbrace)
7019 if (parseUseListOrder(&PFS))
7020 return true;
7021
7022 // Eat the }.
7023 Lex.Lex();
7024
7025 // Verify function is ok.
7026 return PFS.finishFunction();
7027}
7028
7029/// parseBasicBlock
7030/// ::= (LabelStr|LabelID)? Instruction*
7031bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7032 FileLoc BBStart(Lex.getTokLineColumnPos());
7033
7034 // If this basic block starts out with a name, remember it.
7035 std::string Name;
7036 int NameID = -1;
7037 LocTy NameLoc = Lex.getLoc();
7038 if (Lex.getKind() == lltok::LabelStr) {
7039 Name = Lex.getStrVal();
7040 Lex.Lex();
7041 } else if (Lex.getKind() == lltok::LabelID) {
7042 NameID = Lex.getUIntVal();
7043 Lex.Lex();
7044 }
7045
7046 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7047 if (!BB)
7048 return true;
7049
7050 std::string NameStr;
7051
7052 // Parse the instructions and debug values in this block until we get a
7053 // terminator.
7054 Instruction *Inst;
7055 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7056 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7057 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7058 do {
7059 // Handle debug records first - there should always be an instruction
7060 // following the debug records, i.e. they cannot appear after the block
7061 // terminator.
7062 while (Lex.getKind() == lltok::hash) {
7063 if (SeenOldDbgInfoFormat)
7064 return error(Lex.getLoc(), "debug record should not appear in a module "
7065 "containing debug info intrinsics");
7066 SeenNewDbgInfoFormat = true;
7067 Lex.Lex();
7068
7069 DbgRecord *DR;
7070 if (parseDebugRecord(DR, PFS))
7071 return true;
7072 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7073 }
7074
7075 FileLoc InstStart(Lex.getTokLineColumnPos());
7076 // This instruction may have three possibilities for a name: a) none
7077 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7078 LocTy NameLoc = Lex.getLoc();
7079 int NameID = -1;
7080 NameStr = "";
7081
7082 if (Lex.getKind() == lltok::LocalVarID) {
7083 NameID = Lex.getUIntVal();
7084 Lex.Lex();
7085 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7086 return true;
7087 } else if (Lex.getKind() == lltok::LocalVar) {
7088 NameStr = Lex.getStrVal();
7089 Lex.Lex();
7090 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7091 return true;
7092 }
7093
7094 switch (parseInstruction(Inst, BB, PFS)) {
7095 default:
7096 llvm_unreachable("Unknown parseInstruction result!");
7097 case InstError: return true;
7098 case InstNormal:
7099 Inst->insertInto(BB, BB->end());
7100
7101 // With a normal result, we check to see if the instruction is followed by
7102 // a comma and metadata.
7103 if (EatIfPresent(lltok::comma))
7104 if (parseInstructionMetadata(*Inst))
7105 return true;
7106 break;
7107 case InstExtraComma:
7108 Inst->insertInto(BB, BB->end());
7109
7110 // If the instruction parser ate an extra comma at the end of it, it
7111 // *must* be followed by metadata.
7112 if (parseInstructionMetadata(*Inst))
7113 return true;
7114 break;
7115 }
7116
7117 // Set the name on the instruction.
7118 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7119 return true;
7120
7121 // Attach any preceding debug values to this instruction.
7122 for (DbgRecordPtr &DR : TrailingDbgRecord)
7123 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7124 TrailingDbgRecord.clear();
7125 if (ParserContext) {
7126 ParserContext->addInstructionLocation(
7127 Inst, FileLocRange(InstStart, Lex.getPrevTokEndLineColumnPos()));
7128 }
7129 } while (!Inst->isTerminator());
7130
7131 if (ParserContext)
7132 ParserContext->addBlockLocation(
7133 BB, FileLocRange(BBStart, Lex.getPrevTokEndLineColumnPos()));
7134
7135 assert(TrailingDbgRecord.empty() &&
7136 "All debug values should have been attached to an instruction.");
7137
7138 return false;
7139}
7140
7141/// parseDebugRecord
7142/// ::= #dbg_label '(' MDNode ')'
7143/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7144/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7145bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7146 using RecordKind = DbgRecord::Kind;
7147 using LocType = DbgVariableRecord::LocationType;
7148 LocTy DVRLoc = Lex.getLoc();
7149 if (Lex.getKind() != lltok::DbgRecordType)
7150 return error(DVRLoc, "expected debug record type here");
7151 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7152 .Case("declare", RecordKind::ValueKind)
7153 .Case("value", RecordKind::ValueKind)
7154 .Case("assign", RecordKind::ValueKind)
7155 .Case("label", RecordKind::LabelKind);
7156
7157 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7158 // full DbgVariableRecord processing stage.
7159 if (RecordType == RecordKind::LabelKind) {
7160 Lex.Lex();
7161 if (parseToken(lltok::lparen, "Expected '(' here"))
7162 return true;
7163 MDNode *Label;
7164 if (parseMDNode(Label))
7165 return true;
7166 if (parseToken(lltok::comma, "Expected ',' here"))
7167 return true;
7168 MDNode *DbgLoc;
7169 if (parseMDNode(DbgLoc))
7170 return true;
7171 if (parseToken(lltok::rparen, "Expected ')' here"))
7172 return true;
7174 return false;
7175 }
7176
7177 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7178 .Case("declare", LocType::Declare)
7179 .Case("value", LocType::Value)
7180 .Case("assign", LocType::Assign);
7181
7182 Lex.Lex();
7183 if (parseToken(lltok::lparen, "Expected '(' here"))
7184 return true;
7185
7186 // Parse Value field.
7187 Metadata *ValLocMD;
7188 if (parseMetadata(ValLocMD, &PFS))
7189 return true;
7190 if (parseToken(lltok::comma, "Expected ',' here"))
7191 return true;
7192
7193 // Parse Variable field.
7194 MDNode *Variable;
7195 if (parseMDNode(Variable))
7196 return true;
7197 if (parseToken(lltok::comma, "Expected ',' here"))
7198 return true;
7199
7200 // Parse Expression field.
7201 MDNode *Expression;
7202 if (parseMDNode(Expression))
7203 return true;
7204 if (parseToken(lltok::comma, "Expected ',' here"))
7205 return true;
7206
7207 // Parse additional fields for #dbg_assign.
7208 MDNode *AssignID = nullptr;
7209 Metadata *AddressLocation = nullptr;
7210 MDNode *AddressExpression = nullptr;
7211 if (ValueType == LocType::Assign) {
7212 // Parse DIAssignID.
7213 if (parseMDNode(AssignID))
7214 return true;
7215 if (parseToken(lltok::comma, "Expected ',' here"))
7216 return true;
7217
7218 // Parse address ValueAsMetadata.
7219 if (parseMetadata(AddressLocation, &PFS))
7220 return true;
7221 if (parseToken(lltok::comma, "Expected ',' here"))
7222 return true;
7223
7224 // Parse address DIExpression.
7225 if (parseMDNode(AddressExpression))
7226 return true;
7227 if (parseToken(lltok::comma, "Expected ',' here"))
7228 return true;
7229 }
7230
7231 /// Parse DILocation.
7232 MDNode *DebugLoc;
7233 if (parseMDNode(DebugLoc))
7234 return true;
7235
7236 if (parseToken(lltok::rparen, "Expected ')' here"))
7237 return true;
7239 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7240 AddressExpression, DebugLoc);
7241 return false;
7242}
7243//===----------------------------------------------------------------------===//
7244// Instruction Parsing.
7245//===----------------------------------------------------------------------===//
7246
7247/// parseInstruction - parse one of the many different instructions.
7248///
7249int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7250 PerFunctionState &PFS) {
7251 lltok::Kind Token = Lex.getKind();
7252 if (Token == lltok::Eof)
7253 return tokError("found end of file when expecting more instructions");
7254 LocTy Loc = Lex.getLoc();
7255 unsigned KeywordVal = Lex.getUIntVal();
7256 Lex.Lex(); // Eat the keyword.
7257
7258 switch (Token) {
7259 default:
7260 return error(Loc, "expected instruction opcode");
7261 // Terminator Instructions.
7262 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7263 case lltok::kw_ret:
7264 return parseRet(Inst, BB, PFS);
7265 case lltok::kw_br:
7266 return parseBr(Inst, PFS);
7267 case lltok::kw_switch:
7268 return parseSwitch(Inst, PFS);
7270 return parseIndirectBr(Inst, PFS);
7271 case lltok::kw_invoke:
7272 return parseInvoke(Inst, PFS);
7273 case lltok::kw_resume:
7274 return parseResume(Inst, PFS);
7276 return parseCleanupRet(Inst, PFS);
7277 case lltok::kw_catchret:
7278 return parseCatchRet(Inst, PFS);
7280 return parseCatchSwitch(Inst, PFS);
7281 case lltok::kw_catchpad:
7282 return parseCatchPad(Inst, PFS);
7284 return parseCleanupPad(Inst, PFS);
7285 case lltok::kw_callbr:
7286 return parseCallBr(Inst, PFS);
7287 // Unary Operators.
7288 case lltok::kw_fneg: {
7289 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7290 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7291 if (Res != 0)
7292 return Res;
7293 if (FMF.any())
7294 Inst->setFastMathFlags(FMF);
7295 return false;
7296 }
7297 // Binary Operators.
7298 case lltok::kw_add:
7299 case lltok::kw_sub:
7300 case lltok::kw_mul:
7301 case lltok::kw_shl: {
7302 bool NUW = EatIfPresent(lltok::kw_nuw);
7303 bool NSW = EatIfPresent(lltok::kw_nsw);
7304 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7305
7306 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7307 return true;
7308
7309 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7310 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7311 return false;
7312 }
7313 case lltok::kw_fadd:
7314 case lltok::kw_fsub:
7315 case lltok::kw_fmul:
7316 case lltok::kw_fdiv:
7317 case lltok::kw_frem: {
7318 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7319 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7320 if (Res != 0)
7321 return Res;
7322 if (FMF.any())
7323 Inst->setFastMathFlags(FMF);
7324 return 0;
7325 }
7326
7327 case lltok::kw_sdiv:
7328 case lltok::kw_udiv:
7329 case lltok::kw_lshr:
7330 case lltok::kw_ashr: {
7331 bool Exact = EatIfPresent(lltok::kw_exact);
7332
7333 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7334 return true;
7335 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7336 return false;
7337 }
7338
7339 case lltok::kw_urem:
7340 case lltok::kw_srem:
7341 return parseArithmetic(Inst, PFS, KeywordVal,
7342 /*IsFP*/ false);
7343 case lltok::kw_or: {
7344 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7345 if (parseLogical(Inst, PFS, KeywordVal))
7346 return true;
7347 if (Disjoint)
7348 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7349 return false;
7350 }
7351 case lltok::kw_and:
7352 case lltok::kw_xor:
7353 return parseLogical(Inst, PFS, KeywordVal);
7354 case lltok::kw_icmp: {
7355 bool SameSign = EatIfPresent(lltok::kw_samesign);
7356 if (parseCompare(Inst, PFS, KeywordVal))
7357 return true;
7358 if (SameSign)
7359 cast<ICmpInst>(Inst)->setSameSign();
7360 return false;
7361 }
7362 case lltok::kw_fcmp: {
7363 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7364 int Res = parseCompare(Inst, PFS, KeywordVal);
7365 if (Res != 0)
7366 return Res;
7367 if (FMF.any())
7368 Inst->setFastMathFlags(FMF);
7369 return 0;
7370 }
7371
7372 // Casts.
7373 case lltok::kw_uitofp:
7374 case lltok::kw_zext: {
7375 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7376 bool Res = parseCast(Inst, PFS, KeywordVal);
7377 if (Res != 0)
7378 return Res;
7379 if (NonNeg)
7380 Inst->setNonNeg();
7381 return 0;
7382 }
7383 case lltok::kw_trunc: {
7384 bool NUW = EatIfPresent(lltok::kw_nuw);
7385 bool NSW = EatIfPresent(lltok::kw_nsw);
7386 if (!NUW)
7387 NUW = EatIfPresent(lltok::kw_nuw);
7388 if (parseCast(Inst, PFS, KeywordVal))
7389 return true;
7390 if (NUW)
7391 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7392 if (NSW)
7393 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7394 return false;
7395 }
7396 case lltok::kw_sext:
7397 case lltok::kw_bitcast:
7399 case lltok::kw_sitofp:
7400 case lltok::kw_fptoui:
7401 case lltok::kw_fptosi:
7402 case lltok::kw_inttoptr:
7404 case lltok::kw_ptrtoint:
7405 return parseCast(Inst, PFS, KeywordVal);
7406 case lltok::kw_fptrunc:
7407 case lltok::kw_fpext: {
7408 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7409 if (parseCast(Inst, PFS, KeywordVal))
7410 return true;
7411 if (FMF.any())
7412 Inst->setFastMathFlags(FMF);
7413 return false;
7414 }
7415
7416 // Other.
7417 case lltok::kw_select: {
7418 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7419 int Res = parseSelect(Inst, PFS);
7420 if (Res != 0)
7421 return Res;
7422 if (FMF.any()) {
7423 if (!isa<FPMathOperator>(Inst))
7424 return error(Loc, "fast-math-flags specified for select without "
7425 "floating-point scalar or vector return type");
7426 Inst->setFastMathFlags(FMF);
7427 }
7428 return 0;
7429 }
7430 case lltok::kw_va_arg:
7431 return parseVAArg(Inst, PFS);
7433 return parseExtractElement(Inst, PFS);
7435 return parseInsertElement(Inst, PFS);
7437 return parseShuffleVector(Inst, PFS);
7438 case lltok::kw_phi: {
7439 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7440 int Res = parsePHI(Inst, PFS);
7441 if (Res != 0)
7442 return Res;
7443 if (FMF.any()) {
7444 if (!isa<FPMathOperator>(Inst))
7445 return error(Loc, "fast-math-flags specified for phi without "
7446 "floating-point scalar or vector return type");
7447 Inst->setFastMathFlags(FMF);
7448 }
7449 return 0;
7450 }
7452 return parseLandingPad(Inst, PFS);
7453 case lltok::kw_freeze:
7454 return parseFreeze(Inst, PFS);
7455 // Call.
7456 case lltok::kw_call:
7457 return parseCall(Inst, PFS, CallInst::TCK_None);
7458 case lltok::kw_tail:
7459 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7460 case lltok::kw_musttail:
7461 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7462 case lltok::kw_notail:
7463 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7464 // Memory.
7465 case lltok::kw_alloca:
7466 return parseAlloc(Inst, PFS);
7467 case lltok::kw_load:
7468 return parseLoad(Inst, PFS);
7469 case lltok::kw_store:
7470 return parseStore(Inst, PFS);
7471 case lltok::kw_cmpxchg:
7472 return parseCmpXchg(Inst, PFS);
7474 return parseAtomicRMW(Inst, PFS);
7475 case lltok::kw_fence:
7476 return parseFence(Inst, PFS);
7478 return parseGetElementPtr(Inst, PFS);
7480 return parseExtractValue(Inst, PFS);
7482 return parseInsertValue(Inst, PFS);
7483 }
7484}
7485
7486/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7487bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7488 if (Opc == Instruction::FCmp) {
7489 switch (Lex.getKind()) {
7490 default:
7491 return tokError("expected fcmp predicate (e.g. 'oeq')");
7492 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7493 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7494 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7495 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7496 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7497 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7498 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7499 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7500 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7501 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7502 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7503 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7504 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7505 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7506 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7507 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7508 }
7509 } else {
7510 switch (Lex.getKind()) {
7511 default:
7512 return tokError("expected icmp predicate (e.g. 'eq')");
7513 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7514 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7515 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7516 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7517 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7518 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7519 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7520 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7521 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7522 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7523 }
7524 }
7525 Lex.Lex();
7526 return false;
7527}
7528
7529//===----------------------------------------------------------------------===//
7530// Terminator Instructions.
7531//===----------------------------------------------------------------------===//
7532
7533/// parseRet - parse a return instruction.
7534/// ::= 'ret' void (',' !dbg, !1)*
7535/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7536bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7537 PerFunctionState &PFS) {
7538 SMLoc TypeLoc = Lex.getLoc();
7539 Type *Ty = nullptr;
7540 if (parseType(Ty, true /*void allowed*/))
7541 return true;
7542
7543 Type *ResType = PFS.getFunction().getReturnType();
7544
7545 if (Ty->isVoidTy()) {
7546 if (!ResType->isVoidTy())
7547 return error(TypeLoc, "value doesn't match function result type '" +
7548 getTypeString(ResType) + "'");
7549
7550 Inst = ReturnInst::Create(Context);
7551 return false;
7552 }
7553
7554 Value *RV;
7555 if (parseValue(Ty, RV, PFS))
7556 return true;
7557
7558 if (ResType != RV->getType())
7559 return error(TypeLoc, "value doesn't match function result type '" +
7560 getTypeString(ResType) + "'");
7561
7562 Inst = ReturnInst::Create(Context, RV);
7563 return false;
7564}
7565
7566/// parseBr
7567/// ::= 'br' TypeAndValue
7568/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7569bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7570 LocTy Loc, Loc2;
7571 Value *Op0;
7572 BasicBlock *Op1, *Op2;
7573 if (parseTypeAndValue(Op0, Loc, PFS))
7574 return true;
7575
7576 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7577 Inst = BranchInst::Create(BB);
7578 return false;
7579 }
7580
7581 if (Op0->getType() != Type::getInt1Ty(Context))
7582 return error(Loc, "branch condition must have 'i1' type");
7583
7584 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7585 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7586 parseToken(lltok::comma, "expected ',' after true destination") ||
7587 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7588 return true;
7589
7590 Inst = BranchInst::Create(Op1, Op2, Op0);
7591 return false;
7592}
7593
7594/// parseSwitch
7595/// Instruction
7596/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7597/// JumpTable
7598/// ::= (TypeAndValue ',' TypeAndValue)*
7599bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7600 LocTy CondLoc, BBLoc;
7601 Value *Cond;
7602 BasicBlock *DefaultBB;
7603 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7604 parseToken(lltok::comma, "expected ',' after switch condition") ||
7605 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7606 parseToken(lltok::lsquare, "expected '[' with switch table"))
7607 return true;
7608
7609 if (!Cond->getType()->isIntegerTy())
7610 return error(CondLoc, "switch condition must have integer type");
7611
7612 // parse the jump table pairs.
7613 SmallPtrSet<Value*, 32> SeenCases;
7615 while (Lex.getKind() != lltok::rsquare) {
7616 Value *Constant;
7617 BasicBlock *DestBB;
7618
7619 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7620 parseToken(lltok::comma, "expected ',' after case value") ||
7621 parseTypeAndBasicBlock(DestBB, PFS))
7622 return true;
7623
7624 if (!SeenCases.insert(Constant).second)
7625 return error(CondLoc, "duplicate case value in switch");
7626 if (!isa<ConstantInt>(Constant))
7627 return error(CondLoc, "case value is not a constant integer");
7628
7629 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7630 }
7631
7632 Lex.Lex(); // Eat the ']'.
7633
7634 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7635 for (const auto &[OnVal, Dest] : Table)
7636 SI->addCase(OnVal, Dest);
7637 Inst = SI;
7638 return false;
7639}
7640
7641/// parseIndirectBr
7642/// Instruction
7643/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7644bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7645 LocTy AddrLoc;
7646 Value *Address;
7647 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7648 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7649 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7650 return true;
7651
7652 if (!Address->getType()->isPointerTy())
7653 return error(AddrLoc, "indirectbr address must have pointer type");
7654
7655 // parse the destination list.
7656 SmallVector<BasicBlock*, 16> DestList;
7657
7658 if (Lex.getKind() != lltok::rsquare) {
7659 BasicBlock *DestBB;
7660 if (parseTypeAndBasicBlock(DestBB, PFS))
7661 return true;
7662 DestList.push_back(DestBB);
7663
7664 while (EatIfPresent(lltok::comma)) {
7665 if (parseTypeAndBasicBlock(DestBB, PFS))
7666 return true;
7667 DestList.push_back(DestBB);
7668 }
7669 }
7670
7671 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7672 return true;
7673
7674 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7675 for (BasicBlock *Dest : DestList)
7676 IBI->addDestination(Dest);
7677 Inst = IBI;
7678 return false;
7679}
7680
7681// If RetType is a non-function pointer type, then this is the short syntax
7682// for the call, which means that RetType is just the return type. Infer the
7683// rest of the function argument types from the arguments that are present.
7684bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7685 FunctionType *&FuncTy) {
7686 FuncTy = dyn_cast<FunctionType>(RetType);
7687 if (!FuncTy) {
7688 // Pull out the types of all of the arguments...
7689 SmallVector<Type *, 8> ParamTypes;
7690 ParamTypes.reserve(ArgList.size());
7691 for (const ParamInfo &Arg : ArgList)
7692 ParamTypes.push_back(Arg.V->getType());
7693
7694 if (!FunctionType::isValidReturnType(RetType))
7695 return true;
7696
7697 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7698 }
7699 return false;
7700}
7701
7702/// parseInvoke
7703/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7704/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7705bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7706 LocTy CallLoc = Lex.getLoc();
7707 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7708 std::vector<unsigned> FwdRefAttrGrps;
7709 LocTy NoBuiltinLoc;
7710 unsigned CC;
7711 unsigned InvokeAddrSpace;
7712 Type *RetType = nullptr;
7713 LocTy RetTypeLoc;
7714 ValID CalleeID;
7717
7718 BasicBlock *NormalBB, *UnwindBB;
7719 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7720 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7721 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7722 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7723 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7724 NoBuiltinLoc) ||
7725 parseOptionalOperandBundles(BundleList, PFS) ||
7726 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7727 parseTypeAndBasicBlock(NormalBB, PFS) ||
7728 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7729 parseTypeAndBasicBlock(UnwindBB, PFS))
7730 return true;
7731
7732 // If RetType is a non-function pointer type, then this is the short syntax
7733 // for the call, which means that RetType is just the return type. Infer the
7734 // rest of the function argument types from the arguments that are present.
7735 FunctionType *Ty;
7736 if (resolveFunctionType(RetType, ArgList, Ty))
7737 return error(RetTypeLoc, "Invalid result type for LLVM function");
7738
7739 CalleeID.FTy = Ty;
7740
7741 // Look up the callee.
7742 Value *Callee;
7743 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7744 Callee, &PFS))
7745 return true;
7746
7747 // Set up the Attribute for the function.
7748 SmallVector<Value *, 8> Args;
7750
7751 // Loop through FunctionType's arguments and ensure they are specified
7752 // correctly. Also, gather any parameter attributes.
7753 FunctionType::param_iterator I = Ty->param_begin();
7754 FunctionType::param_iterator E = Ty->param_end();
7755 for (const ParamInfo &Arg : ArgList) {
7756 Type *ExpectedTy = nullptr;
7757 if (I != E) {
7758 ExpectedTy = *I++;
7759 } else if (!Ty->isVarArg()) {
7760 return error(Arg.Loc, "too many arguments specified");
7761 }
7762
7763 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7764 return error(Arg.Loc, "argument is not of expected type '" +
7765 getTypeString(ExpectedTy) + "'");
7766 Args.push_back(Arg.V);
7767 ArgAttrs.push_back(Arg.Attrs);
7768 }
7769
7770 if (I != E)
7771 return error(CallLoc, "not enough parameters specified for call");
7772
7773 // Finish off the Attribute and check them
7774 AttributeList PAL =
7775 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7776 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7777
7778 InvokeInst *II =
7779 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7780 II->setCallingConv(CC);
7781 II->setAttributes(PAL);
7782 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7783 Inst = II;
7784 return false;
7785}
7786
7787/// parseResume
7788/// ::= 'resume' TypeAndValue
7789bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7790 Value *Exn; LocTy ExnLoc;
7791 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7792 return true;
7793
7794 ResumeInst *RI = ResumeInst::Create(Exn);
7795 Inst = RI;
7796 return false;
7797}
7798
7799bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7800 PerFunctionState &PFS) {
7801 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7802 return true;
7803
7804 while (Lex.getKind() != lltok::rsquare) {
7805 // If this isn't the first argument, we need a comma.
7806 if (!Args.empty() &&
7807 parseToken(lltok::comma, "expected ',' in argument list"))
7808 return true;
7809
7810 // parse the argument.
7811 LocTy ArgLoc;
7812 Type *ArgTy = nullptr;
7813 if (parseType(ArgTy, ArgLoc))
7814 return true;
7815
7816 Value *V;
7817 if (ArgTy->isMetadataTy()) {
7818 if (parseMetadataAsValue(V, PFS))
7819 return true;
7820 } else {
7821 if (parseValue(ArgTy, V, PFS))
7822 return true;
7823 }
7824 Args.push_back(V);
7825 }
7826
7827 Lex.Lex(); // Lex the ']'.
7828 return false;
7829}
7830
7831/// parseCleanupRet
7832/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7833bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7834 Value *CleanupPad = nullptr;
7835
7836 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7837 return true;
7838
7839 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7840 return true;
7841
7842 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7843 return true;
7844
7845 BasicBlock *UnwindBB = nullptr;
7846 if (Lex.getKind() == lltok::kw_to) {
7847 Lex.Lex();
7848 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7849 return true;
7850 } else {
7851 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7852 return true;
7853 }
7854 }
7855
7856 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7857 return false;
7858}
7859
7860/// parseCatchRet
7861/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7862bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7863 Value *CatchPad = nullptr;
7864
7865 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7866 return true;
7867
7868 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7869 return true;
7870
7871 BasicBlock *BB;
7872 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7873 parseTypeAndBasicBlock(BB, PFS))
7874 return true;
7875
7876 Inst = CatchReturnInst::Create(CatchPad, BB);
7877 return false;
7878}
7879
7880/// parseCatchSwitch
7881/// ::= 'catchswitch' within Parent
7882bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7883 Value *ParentPad;
7884
7885 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7886 return true;
7887
7888 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7889 Lex.getKind() != lltok::LocalVarID)
7890 return tokError("expected scope value for catchswitch");
7891
7892 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7893 return true;
7894
7895 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7896 return true;
7897
7899 do {
7900 BasicBlock *DestBB;
7901 if (parseTypeAndBasicBlock(DestBB, PFS))
7902 return true;
7903 Table.push_back(DestBB);
7904 } while (EatIfPresent(lltok::comma));
7905
7906 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7907 return true;
7908
7909 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7910 return true;
7911
7912 BasicBlock *UnwindBB = nullptr;
7913 if (EatIfPresent(lltok::kw_to)) {
7914 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7915 return true;
7916 } else {
7917 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7918 return true;
7919 }
7920
7921 auto *CatchSwitch =
7922 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7923 for (BasicBlock *DestBB : Table)
7924 CatchSwitch->addHandler(DestBB);
7925 Inst = CatchSwitch;
7926 return false;
7927}
7928
7929/// parseCatchPad
7930/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7931bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7932 Value *CatchSwitch = nullptr;
7933
7934 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7935 return true;
7936
7937 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7938 return tokError("expected scope value for catchpad");
7939
7940 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7941 return true;
7942
7943 SmallVector<Value *, 8> Args;
7944 if (parseExceptionArgs(Args, PFS))
7945 return true;
7946
7947 Inst = CatchPadInst::Create(CatchSwitch, Args);
7948 return false;
7949}
7950
7951/// parseCleanupPad
7952/// ::= 'cleanuppad' within Parent ParamList
7953bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7954 Value *ParentPad = nullptr;
7955
7956 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7957 return true;
7958
7959 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7960 Lex.getKind() != lltok::LocalVarID)
7961 return tokError("expected scope value for cleanuppad");
7962
7963 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7964 return true;
7965
7966 SmallVector<Value *, 8> Args;
7967 if (parseExceptionArgs(Args, PFS))
7968 return true;
7969
7970 Inst = CleanupPadInst::Create(ParentPad, Args);
7971 return false;
7972}
7973
7974//===----------------------------------------------------------------------===//
7975// Unary Operators.
7976//===----------------------------------------------------------------------===//
7977
7978/// parseUnaryOp
7979/// ::= UnaryOp TypeAndValue ',' Value
7980///
7981/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7982/// operand is allowed.
7983bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7984 unsigned Opc, bool IsFP) {
7985 LocTy Loc; Value *LHS;
7986 if (parseTypeAndValue(LHS, Loc, PFS))
7987 return true;
7988
7989 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7991
7992 if (!Valid)
7993 return error(Loc, "invalid operand type for instruction");
7994
7996 return false;
7997}
7998
7999/// parseCallBr
8000/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8001/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8002/// '[' LabelList ']'
8003bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8004 LocTy CallLoc = Lex.getLoc();
8005 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8006 std::vector<unsigned> FwdRefAttrGrps;
8007 LocTy NoBuiltinLoc;
8008 unsigned CC;
8009 Type *RetType = nullptr;
8010 LocTy RetTypeLoc;
8011 ValID CalleeID;
8014
8015 BasicBlock *DefaultDest;
8016 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8017 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8018 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8019 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8020 NoBuiltinLoc) ||
8021 parseOptionalOperandBundles(BundleList, PFS) ||
8022 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8023 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8024 parseToken(lltok::lsquare, "expected '[' in callbr"))
8025 return true;
8026
8027 // parse the destination list.
8028 SmallVector<BasicBlock *, 16> IndirectDests;
8029
8030 if (Lex.getKind() != lltok::rsquare) {
8031 BasicBlock *DestBB;
8032 if (parseTypeAndBasicBlock(DestBB, PFS))
8033 return true;
8034 IndirectDests.push_back(DestBB);
8035
8036 while (EatIfPresent(lltok::comma)) {
8037 if (parseTypeAndBasicBlock(DestBB, PFS))
8038 return true;
8039 IndirectDests.push_back(DestBB);
8040 }
8041 }
8042
8043 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8044 return true;
8045
8046 // If RetType is a non-function pointer type, then this is the short syntax
8047 // for the call, which means that RetType is just the return type. Infer the
8048 // rest of the function argument types from the arguments that are present.
8049 FunctionType *Ty;
8050 if (resolveFunctionType(RetType, ArgList, Ty))
8051 return error(RetTypeLoc, "Invalid result type for LLVM function");
8052
8053 CalleeID.FTy = Ty;
8054
8055 // Look up the callee.
8056 Value *Callee;
8057 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8058 &PFS))
8059 return true;
8060
8061 // Set up the Attribute for the function.
8062 SmallVector<Value *, 8> Args;
8064
8065 // Loop through FunctionType's arguments and ensure they are specified
8066 // correctly. Also, gather any parameter attributes.
8067 FunctionType::param_iterator I = Ty->param_begin();
8068 FunctionType::param_iterator E = Ty->param_end();
8069 for (const ParamInfo &Arg : ArgList) {
8070 Type *ExpectedTy = nullptr;
8071 if (I != E) {
8072 ExpectedTy = *I++;
8073 } else if (!Ty->isVarArg()) {
8074 return error(Arg.Loc, "too many arguments specified");
8075 }
8076
8077 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8078 return error(Arg.Loc, "argument is not of expected type '" +
8079 getTypeString(ExpectedTy) + "'");
8080 Args.push_back(Arg.V);
8081 ArgAttrs.push_back(Arg.Attrs);
8082 }
8083
8084 if (I != E)
8085 return error(CallLoc, "not enough parameters specified for call");
8086
8087 // Finish off the Attribute and check them
8088 AttributeList PAL =
8089 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8090 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8091
8092 CallBrInst *CBI =
8093 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8094 BundleList);
8095 CBI->setCallingConv(CC);
8096 CBI->setAttributes(PAL);
8097 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8098 Inst = CBI;
8099 return false;
8100}
8101
8102//===----------------------------------------------------------------------===//
8103// Binary Operators.
8104//===----------------------------------------------------------------------===//
8105
8106/// parseArithmetic
8107/// ::= ArithmeticOps TypeAndValue ',' Value
8108///
8109/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8110/// operand is allowed.
8111bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8112 unsigned Opc, bool IsFP) {
8113 LocTy Loc; Value *LHS, *RHS;
8114 if (parseTypeAndValue(LHS, Loc, PFS) ||
8115 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8116 parseValue(LHS->getType(), RHS, PFS))
8117 return true;
8118
8119 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8121
8122 if (!Valid)
8123 return error(Loc, "invalid operand type for instruction");
8124
8126 return false;
8127}
8128
8129/// parseLogical
8130/// ::= ArithmeticOps TypeAndValue ',' Value {
8131bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8132 unsigned Opc) {
8133 LocTy Loc; Value *LHS, *RHS;
8134 if (parseTypeAndValue(LHS, Loc, PFS) ||
8135 parseToken(lltok::comma, "expected ',' in logical operation") ||
8136 parseValue(LHS->getType(), RHS, PFS))
8137 return true;
8138
8139 if (!LHS->getType()->isIntOrIntVectorTy())
8140 return error(Loc,
8141 "instruction requires integer or integer vector operands");
8142
8144 return false;
8145}
8146
8147/// parseCompare
8148/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8149/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8150bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8151 unsigned Opc) {
8152 // parse the integer/fp comparison predicate.
8153 LocTy Loc;
8154 unsigned Pred;
8155 Value *LHS, *RHS;
8156 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8157 parseToken(lltok::comma, "expected ',' after compare value") ||
8158 parseValue(LHS->getType(), RHS, PFS))
8159 return true;
8160
8161 if (Opc == Instruction::FCmp) {
8162 if (!LHS->getType()->isFPOrFPVectorTy())
8163 return error(Loc, "fcmp requires floating point operands");
8164 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8165 } else {
8166 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8167 if (!LHS->getType()->isIntOrIntVectorTy() &&
8169 return error(Loc, "icmp requires integer operands");
8170 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8171 }
8172 return false;
8173}
8174
8175//===----------------------------------------------------------------------===//
8176// Other Instructions.
8177//===----------------------------------------------------------------------===//
8178
8179/// parseCast
8180/// ::= CastOpc TypeAndValue 'to' Type
8181bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8182 unsigned Opc) {
8183 LocTy Loc;
8184 Value *Op;
8185 Type *DestTy = nullptr;
8186 if (parseTypeAndValue(Op, Loc, PFS) ||
8187 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8188 parseType(DestTy))
8189 return true;
8190
8192 return error(Loc, "invalid cast opcode for cast from '" +
8193 getTypeString(Op->getType()) + "' to '" +
8194 getTypeString(DestTy) + "'");
8195 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8196 return false;
8197}
8198
8199/// parseSelect
8200/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8201bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8202 LocTy Loc;
8203 Value *Op0, *Op1, *Op2;
8204 if (parseTypeAndValue(Op0, Loc, PFS) ||
8205 parseToken(lltok::comma, "expected ',' after select condition") ||
8206 parseTypeAndValue(Op1, PFS) ||
8207 parseToken(lltok::comma, "expected ',' after select value") ||
8208 parseTypeAndValue(Op2, PFS))
8209 return true;
8210
8211 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8212 return error(Loc, Reason);
8213
8214 Inst = SelectInst::Create(Op0, Op1, Op2);
8215 return false;
8216}
8217
8218/// parseVAArg
8219/// ::= 'va_arg' TypeAndValue ',' Type
8220bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8221 Value *Op;
8222 Type *EltTy = nullptr;
8223 LocTy TypeLoc;
8224 if (parseTypeAndValue(Op, PFS) ||
8225 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8226 parseType(EltTy, TypeLoc))
8227 return true;
8228
8229 if (!EltTy->isFirstClassType())
8230 return error(TypeLoc, "va_arg requires operand with first class type");
8231
8232 Inst = new VAArgInst(Op, EltTy);
8233 return false;
8234}
8235
8236/// parseExtractElement
8237/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8238bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8239 LocTy Loc;
8240 Value *Op0, *Op1;
8241 if (parseTypeAndValue(Op0, Loc, PFS) ||
8242 parseToken(lltok::comma, "expected ',' after extract value") ||
8243 parseTypeAndValue(Op1, PFS))
8244 return true;
8245
8247 return error(Loc, "invalid extractelement operands");
8248
8249 Inst = ExtractElementInst::Create(Op0, Op1);
8250 return false;
8251}
8252
8253/// parseInsertElement
8254/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8255bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8256 LocTy Loc;
8257 Value *Op0, *Op1, *Op2;
8258 if (parseTypeAndValue(Op0, Loc, PFS) ||
8259 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8260 parseTypeAndValue(Op1, PFS) ||
8261 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8262 parseTypeAndValue(Op2, PFS))
8263 return true;
8264
8265 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8266 return error(Loc, "invalid insertelement operands");
8267
8268 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8269 return false;
8270}
8271
8272/// parseShuffleVector
8273/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8274bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8275 LocTy Loc;
8276 Value *Op0, *Op1, *Op2;
8277 if (parseTypeAndValue(Op0, Loc, PFS) ||
8278 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8279 parseTypeAndValue(Op1, PFS) ||
8280 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8281 parseTypeAndValue(Op2, PFS))
8282 return true;
8283
8284 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8285 return error(Loc, "invalid shufflevector operands");
8286
8287 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8288 return false;
8289}
8290
8291/// parsePHI
8292/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8293int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8294 Type *Ty = nullptr; LocTy TypeLoc;
8295 Value *Op0, *Op1;
8296
8297 if (parseType(Ty, TypeLoc))
8298 return true;
8299
8300 if (!Ty->isFirstClassType())
8301 return error(TypeLoc, "phi node must have first class type");
8302
8303 bool First = true;
8304 bool AteExtraComma = false;
8306
8307 while (true) {
8308 if (First) {
8309 if (Lex.getKind() != lltok::lsquare)
8310 break;
8311 First = false;
8312 } else if (!EatIfPresent(lltok::comma))
8313 break;
8314
8315 if (Lex.getKind() == lltok::MetadataVar) {
8316 AteExtraComma = true;
8317 break;
8318 }
8319
8320 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8321 parseValue(Ty, Op0, PFS) ||
8322 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8323 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8324 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8325 return true;
8326
8327 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8328 }
8329
8330 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8331 for (const auto &[Val, BB] : PHIVals)
8332 PN->addIncoming(Val, BB);
8333 Inst = PN;
8334 return AteExtraComma ? InstExtraComma : InstNormal;
8335}
8336
8337/// parseLandingPad
8338/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8339/// Clause
8340/// ::= 'catch' TypeAndValue
8341/// ::= 'filter'
8342/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8343bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8344 Type *Ty = nullptr; LocTy TyLoc;
8345
8346 if (parseType(Ty, TyLoc))
8347 return true;
8348
8349 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8350 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8351
8352 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8354 if (EatIfPresent(lltok::kw_catch))
8356 else if (EatIfPresent(lltok::kw_filter))
8358 else
8359 return tokError("expected 'catch' or 'filter' clause type");
8360
8361 Value *V;
8362 LocTy VLoc;
8363 if (parseTypeAndValue(V, VLoc, PFS))
8364 return true;
8365
8366 // A 'catch' type expects a non-array constant. A filter clause expects an
8367 // array constant.
8368 if (CT == LandingPadInst::Catch) {
8369 if (isa<ArrayType>(V->getType()))
8370 return error(VLoc, "'catch' clause has an invalid type");
8371 } else {
8372 if (!isa<ArrayType>(V->getType()))
8373 return error(VLoc, "'filter' clause has an invalid type");
8374 }
8375
8377 if (!CV)
8378 return error(VLoc, "clause argument must be a constant");
8379 LP->addClause(CV);
8380 }
8381
8382 Inst = LP.release();
8383 return false;
8384}
8385
8386/// parseFreeze
8387/// ::= 'freeze' Type Value
8388bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8389 LocTy Loc;
8390 Value *Op;
8391 if (parseTypeAndValue(Op, Loc, PFS))
8392 return true;
8393
8394 Inst = new FreezeInst(Op);
8395 return false;
8396}
8397
8398/// parseCall
8399/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8400/// OptionalAttrs Type Value ParameterList OptionalAttrs
8401/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8402/// OptionalAttrs Type Value ParameterList OptionalAttrs
8403/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8404/// OptionalAttrs Type Value ParameterList OptionalAttrs
8405/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8406/// OptionalAttrs Type Value ParameterList OptionalAttrs
8407bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8409 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8410 std::vector<unsigned> FwdRefAttrGrps;
8411 LocTy BuiltinLoc;
8412 unsigned CallAddrSpace;
8413 unsigned CC;
8414 Type *RetType = nullptr;
8415 LocTy RetTypeLoc;
8416 ValID CalleeID;
8419 LocTy CallLoc = Lex.getLoc();
8420
8421 if (TCK != CallInst::TCK_None &&
8422 parseToken(lltok::kw_call,
8423 "expected 'tail call', 'musttail call', or 'notail call'"))
8424 return true;
8425
8426 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8427
8428 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8429 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8430 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8431 parseValID(CalleeID, &PFS) ||
8432 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8433 PFS.getFunction().isVarArg()) ||
8434 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8435 parseOptionalOperandBundles(BundleList, PFS))
8436 return true;
8437
8438 // If RetType is a non-function pointer type, then this is the short syntax
8439 // for the call, which means that RetType is just the return type. Infer the
8440 // rest of the function argument types from the arguments that are present.
8441 FunctionType *Ty;
8442 if (resolveFunctionType(RetType, ArgList, Ty))
8443 return error(RetTypeLoc, "Invalid result type for LLVM function");
8444
8445 CalleeID.FTy = Ty;
8446
8447 // Look up the callee.
8448 Value *Callee;
8449 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8450 Callee, &PFS))
8451 return true;
8452
8453 // Set up the Attribute for the function.
8455
8456 SmallVector<Value*, 8> Args;
8457
8458 // Loop through FunctionType's arguments and ensure they are specified
8459 // correctly. Also, gather any parameter attributes.
8460 FunctionType::param_iterator I = Ty->param_begin();
8461 FunctionType::param_iterator E = Ty->param_end();
8462 for (const ParamInfo &Arg : ArgList) {
8463 Type *ExpectedTy = nullptr;
8464 if (I != E) {
8465 ExpectedTy = *I++;
8466 } else if (!Ty->isVarArg()) {
8467 return error(Arg.Loc, "too many arguments specified");
8468 }
8469
8470 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8471 return error(Arg.Loc, "argument is not of expected type '" +
8472 getTypeString(ExpectedTy) + "'");
8473 Args.push_back(Arg.V);
8474 Attrs.push_back(Arg.Attrs);
8475 }
8476
8477 if (I != E)
8478 return error(CallLoc, "not enough parameters specified for call");
8479
8480 // Finish off the Attribute and check them
8481 AttributeList PAL =
8482 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8483 AttributeSet::get(Context, RetAttrs), Attrs);
8484
8485 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8486 CI->setTailCallKind(TCK);
8487 CI->setCallingConv(CC);
8488 if (FMF.any()) {
8489 if (!isa<FPMathOperator>(CI)) {
8490 CI->deleteValue();
8491 return error(CallLoc, "fast-math-flags specified for call without "
8492 "floating-point scalar or vector return type");
8493 }
8494 CI->setFastMathFlags(FMF);
8495 }
8496
8497 if (CalleeID.Kind == ValID::t_GlobalName &&
8498 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8499 if (SeenNewDbgInfoFormat) {
8500 CI->deleteValue();
8501 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8502 "using non-intrinsic debug info");
8503 }
8504 SeenOldDbgInfoFormat = true;
8505 }
8506 CI->setAttributes(PAL);
8507 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8508 Inst = CI;
8509 return false;
8510}
8511
8512//===----------------------------------------------------------------------===//
8513// Memory Instructions.
8514//===----------------------------------------------------------------------===//
8515
8516/// parseAlloc
8517/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8518/// (',' 'align' i32)? (',', 'addrspace(n))?
8519int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8520 Value *Size = nullptr;
8521 LocTy SizeLoc, TyLoc, ASLoc;
8522 MaybeAlign Alignment;
8523 unsigned AddrSpace = 0;
8524 Type *Ty = nullptr;
8525
8526 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8527 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8528
8529 if (parseType(Ty, TyLoc))
8530 return true;
8531
8533 return error(TyLoc, "invalid type for alloca");
8534
8535 bool AteExtraComma = false;
8536 if (EatIfPresent(lltok::comma)) {
8537 if (Lex.getKind() == lltok::kw_align) {
8538 if (parseOptionalAlignment(Alignment))
8539 return true;
8540 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8541 return true;
8542 } else if (Lex.getKind() == lltok::kw_addrspace) {
8543 ASLoc = Lex.getLoc();
8544 if (parseOptionalAddrSpace(AddrSpace))
8545 return true;
8546 } else if (Lex.getKind() == lltok::MetadataVar) {
8547 AteExtraComma = true;
8548 } else {
8549 if (parseTypeAndValue(Size, SizeLoc, PFS))
8550 return true;
8551 if (EatIfPresent(lltok::comma)) {
8552 if (Lex.getKind() == lltok::kw_align) {
8553 if (parseOptionalAlignment(Alignment))
8554 return true;
8555 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8556 return true;
8557 } else if (Lex.getKind() == lltok::kw_addrspace) {
8558 ASLoc = Lex.getLoc();
8559 if (parseOptionalAddrSpace(AddrSpace))
8560 return true;
8561 } else if (Lex.getKind() == lltok::MetadataVar) {
8562 AteExtraComma = true;
8563 }
8564 }
8565 }
8566 }
8567
8568 if (Size && !Size->getType()->isIntegerTy())
8569 return error(SizeLoc, "element count must have integer type");
8570
8571 SmallPtrSet<Type *, 4> Visited;
8572 if (!Alignment && !Ty->isSized(&Visited))
8573 return error(TyLoc, "Cannot allocate unsized type");
8574 if (!Alignment)
8575 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8576 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8577 AI->setUsedWithInAlloca(IsInAlloca);
8578 AI->setSwiftError(IsSwiftError);
8579 Inst = AI;
8580 return AteExtraComma ? InstExtraComma : InstNormal;
8581}
8582
8583/// parseLoad
8584/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8585/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8586/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8587int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8588 Value *Val; LocTy Loc;
8589 MaybeAlign Alignment;
8590 bool AteExtraComma = false;
8591 bool isAtomic = false;
8594
8595 if (Lex.getKind() == lltok::kw_atomic) {
8596 isAtomic = true;
8597 Lex.Lex();
8598 }
8599
8600 bool isVolatile = false;
8601 if (Lex.getKind() == lltok::kw_volatile) {
8602 isVolatile = true;
8603 Lex.Lex();
8604 }
8605
8606 Type *Ty;
8607 LocTy ExplicitTypeLoc = Lex.getLoc();
8608 if (parseType(Ty) ||
8609 parseToken(lltok::comma, "expected comma after load's type") ||
8610 parseTypeAndValue(Val, Loc, PFS) ||
8611 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8612 parseOptionalCommaAlign(Alignment, AteExtraComma))
8613 return true;
8614
8615 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8616 return error(Loc, "load operand must be a pointer to a first class type");
8617 if (isAtomic && !Alignment)
8618 return error(Loc, "atomic load must have explicit non-zero alignment");
8619 if (Ordering == AtomicOrdering::Release ||
8621 return error(Loc, "atomic load cannot use Release ordering");
8622
8623 SmallPtrSet<Type *, 4> Visited;
8624 if (!Alignment && !Ty->isSized(&Visited))
8625 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8626 if (!Alignment)
8627 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8628 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8629 return AteExtraComma ? InstExtraComma : InstNormal;
8630}
8631
8632/// parseStore
8633
8634/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8635/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8636/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8637int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8638 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8639 MaybeAlign Alignment;
8640 bool AteExtraComma = false;
8641 bool isAtomic = false;
8644
8645 if (Lex.getKind() == lltok::kw_atomic) {
8646 isAtomic = true;
8647 Lex.Lex();
8648 }
8649
8650 bool isVolatile = false;
8651 if (Lex.getKind() == lltok::kw_volatile) {
8652 isVolatile = true;
8653 Lex.Lex();
8654 }
8655
8656 if (parseTypeAndValue(Val, Loc, PFS) ||
8657 parseToken(lltok::comma, "expected ',' after store operand") ||
8658 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8659 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8660 parseOptionalCommaAlign(Alignment, AteExtraComma))
8661 return true;
8662
8663 if (!Ptr->getType()->isPointerTy())
8664 return error(PtrLoc, "store operand must be a pointer");
8665 if (!Val->getType()->isFirstClassType())
8666 return error(Loc, "store operand must be a first class value");
8667 if (isAtomic && !Alignment)
8668 return error(Loc, "atomic store must have explicit non-zero alignment");
8669 if (Ordering == AtomicOrdering::Acquire ||
8671 return error(Loc, "atomic store cannot use Acquire ordering");
8672 SmallPtrSet<Type *, 4> Visited;
8673 if (!Alignment && !Val->getType()->isSized(&Visited))
8674 return error(Loc, "storing unsized types is not allowed");
8675 if (!Alignment)
8676 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8677
8678 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8679 return AteExtraComma ? InstExtraComma : InstNormal;
8680}
8681
8682/// parseCmpXchg
8683/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8684/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8685/// 'Align'?
8686int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8687 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8688 bool AteExtraComma = false;
8689 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8690 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8692 bool isVolatile = false;
8693 bool isWeak = false;
8694 MaybeAlign Alignment;
8695
8696 if (EatIfPresent(lltok::kw_weak))
8697 isWeak = true;
8698
8699 if (EatIfPresent(lltok::kw_volatile))
8700 isVolatile = true;
8701
8702 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8703 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8704 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8705 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8706 parseTypeAndValue(New, NewLoc, PFS) ||
8707 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8708 parseOrdering(FailureOrdering) ||
8709 parseOptionalCommaAlign(Alignment, AteExtraComma))
8710 return true;
8711
8712 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8713 return tokError("invalid cmpxchg success ordering");
8714 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8715 return tokError("invalid cmpxchg failure ordering");
8716 if (!Ptr->getType()->isPointerTy())
8717 return error(PtrLoc, "cmpxchg operand must be a pointer");
8718 if (Cmp->getType() != New->getType())
8719 return error(NewLoc, "compare value and new value type do not match");
8720 if (!New->getType()->isFirstClassType())
8721 return error(NewLoc, "cmpxchg operand must be a first class value");
8722
8723 const Align DefaultAlignment(
8724 PFS.getFunction().getDataLayout().getTypeStoreSize(
8725 Cmp->getType()));
8726
8727 AtomicCmpXchgInst *CXI =
8728 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8729 SuccessOrdering, FailureOrdering, SSID);
8730 CXI->setVolatile(isVolatile);
8731 CXI->setWeak(isWeak);
8732
8733 Inst = CXI;
8734 return AteExtraComma ? InstExtraComma : InstNormal;
8735}
8736
8737/// parseAtomicRMW
8738/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8739/// 'singlethread'? AtomicOrdering
8740int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8741 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8742 bool AteExtraComma = false;
8745 bool isVolatile = false;
8746 bool IsFP = false;
8748 MaybeAlign Alignment;
8749
8750 if (EatIfPresent(lltok::kw_volatile))
8751 isVolatile = true;
8752
8753 switch (Lex.getKind()) {
8754 default:
8755 return tokError("expected binary operation in atomicrmw");
8769 break;
8772 break;
8775 break;
8776 case lltok::kw_usub_sat:
8778 break;
8779 case lltok::kw_fadd:
8781 IsFP = true;
8782 break;
8783 case lltok::kw_fsub:
8785 IsFP = true;
8786 break;
8787 case lltok::kw_fmax:
8789 IsFP = true;
8790 break;
8791 case lltok::kw_fmin:
8793 IsFP = true;
8794 break;
8795 case lltok::kw_fmaximum:
8797 IsFP = true;
8798 break;
8799 case lltok::kw_fminimum:
8801 IsFP = true;
8802 break;
8803 }
8804 Lex.Lex(); // Eat the operation.
8805
8806 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8807 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8808 parseTypeAndValue(Val, ValLoc, PFS) ||
8809 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8810 parseOptionalCommaAlign(Alignment, AteExtraComma))
8811 return true;
8812
8813 if (Ordering == AtomicOrdering::Unordered)
8814 return tokError("atomicrmw cannot be unordered");
8815 if (!Ptr->getType()->isPointerTy())
8816 return error(PtrLoc, "atomicrmw operand must be a pointer");
8817 if (Val->getType()->isScalableTy())
8818 return error(ValLoc, "atomicrmw operand may not be scalable");
8819
8821 if (!Val->getType()->isIntegerTy() &&
8822 !Val->getType()->isFloatingPointTy() &&
8823 !Val->getType()->isPointerTy()) {
8824 return error(
8825 ValLoc,
8827 " operand must be an integer, floating point, or pointer type");
8828 }
8829 } else if (IsFP) {
8830 if (!Val->getType()->isFPOrFPVectorTy()) {
8831 return error(ValLoc, "atomicrmw " +
8833 " operand must be a floating point type");
8834 }
8835 } else {
8836 if (!Val->getType()->isIntegerTy()) {
8837 return error(ValLoc, "atomicrmw " +
8839 " operand must be an integer");
8840 }
8841 }
8842
8843 unsigned Size =
8844 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8845 Val->getType());
8846 if (Size < 8 || (Size & (Size - 1)))
8847 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8848 " integer");
8849 const Align DefaultAlignment(
8850 PFS.getFunction().getDataLayout().getTypeStoreSize(
8851 Val->getType()));
8852 AtomicRMWInst *RMWI =
8853 new AtomicRMWInst(Operation, Ptr, Val,
8854 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8855 RMWI->setVolatile(isVolatile);
8856 Inst = RMWI;
8857 return AteExtraComma ? InstExtraComma : InstNormal;
8858}
8859
8860/// parseFence
8861/// ::= 'fence' 'singlethread'? AtomicOrdering
8862int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8865 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8866 return true;
8867
8868 if (Ordering == AtomicOrdering::Unordered)
8869 return tokError("fence cannot be unordered");
8870 if (Ordering == AtomicOrdering::Monotonic)
8871 return tokError("fence cannot be monotonic");
8872
8873 Inst = new FenceInst(Context, Ordering, SSID);
8874 return InstNormal;
8875}
8876
8877/// parseGetElementPtr
8878/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8879int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8880 Value *Ptr = nullptr;
8881 Value *Val = nullptr;
8882 LocTy Loc, EltLoc;
8883 GEPNoWrapFlags NW;
8884
8885 while (true) {
8886 if (EatIfPresent(lltok::kw_inbounds))
8888 else if (EatIfPresent(lltok::kw_nusw))
8890 else if (EatIfPresent(lltok::kw_nuw))
8892 else
8893 break;
8894 }
8895
8896 Type *Ty = nullptr;
8897 if (parseType(Ty) ||
8898 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8899 parseTypeAndValue(Ptr, Loc, PFS))
8900 return true;
8901
8902 Type *BaseType = Ptr->getType();
8903 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8904 if (!BasePointerType)
8905 return error(Loc, "base of getelementptr must be a pointer");
8906
8907 SmallVector<Value*, 16> Indices;
8908 bool AteExtraComma = false;
8909 // GEP returns a vector of pointers if at least one of parameters is a vector.
8910 // All vector parameters should have the same vector width.
8911 ElementCount GEPWidth = BaseType->isVectorTy()
8912 ? cast<VectorType>(BaseType)->getElementCount()
8914
8915 while (EatIfPresent(lltok::comma)) {
8916 if (Lex.getKind() == lltok::MetadataVar) {
8917 AteExtraComma = true;
8918 break;
8919 }
8920 if (parseTypeAndValue(Val, EltLoc, PFS))
8921 return true;
8922 if (!Val->getType()->isIntOrIntVectorTy())
8923 return error(EltLoc, "getelementptr index must be an integer");
8924
8925 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8926 ElementCount ValNumEl = ValVTy->getElementCount();
8927 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8928 return error(
8929 EltLoc,
8930 "getelementptr vector index has a wrong number of elements");
8931 GEPWidth = ValNumEl;
8932 }
8933 Indices.push_back(Val);
8934 }
8935
8936 SmallPtrSet<Type*, 4> Visited;
8937 if (!Indices.empty() && !Ty->isSized(&Visited))
8938 return error(Loc, "base element of getelementptr must be sized");
8939
8940 auto *STy = dyn_cast<StructType>(Ty);
8941 if (STy && STy->isScalableTy())
8942 return error(Loc, "getelementptr cannot target structure that contains "
8943 "scalable vector type");
8944
8945 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8946 return error(Loc, "invalid getelementptr indices");
8947 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8948 Inst = GEP;
8949 GEP->setNoWrapFlags(NW);
8950 return AteExtraComma ? InstExtraComma : InstNormal;
8951}
8952
8953/// parseExtractValue
8954/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8955int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8956 Value *Val; LocTy Loc;
8957 SmallVector<unsigned, 4> Indices;
8958 bool AteExtraComma;
8959 if (parseTypeAndValue(Val, Loc, PFS) ||
8960 parseIndexList(Indices, AteExtraComma))
8961 return true;
8962
8963 if (!Val->getType()->isAggregateType())
8964 return error(Loc, "extractvalue operand must be aggregate type");
8965
8966 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8967 return error(Loc, "invalid indices for extractvalue");
8968 Inst = ExtractValueInst::Create(Val, Indices);
8969 return AteExtraComma ? InstExtraComma : InstNormal;
8970}
8971
8972/// parseInsertValue
8973/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8974int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8975 Value *Val0, *Val1; LocTy Loc0, Loc1;
8976 SmallVector<unsigned, 4> Indices;
8977 bool AteExtraComma;
8978 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8979 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8980 parseTypeAndValue(Val1, Loc1, PFS) ||
8981 parseIndexList(Indices, AteExtraComma))
8982 return true;
8983
8984 if (!Val0->getType()->isAggregateType())
8985 return error(Loc0, "insertvalue operand must be aggregate type");
8986
8987 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8988 if (!IndexedType)
8989 return error(Loc0, "invalid indices for insertvalue");
8990 if (IndexedType != Val1->getType())
8991 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8992 getTypeString(Val1->getType()) + "' instead of '" +
8993 getTypeString(IndexedType) + "'");
8994 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8995 return AteExtraComma ? InstExtraComma : InstNormal;
8996}
8997
8998//===----------------------------------------------------------------------===//
8999// Embedded metadata.
9000//===----------------------------------------------------------------------===//
9001
9002/// parseMDNodeVector
9003/// ::= { Element (',' Element)* }
9004/// Element
9005/// ::= 'null' | Metadata
9006bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9007 if (parseToken(lltok::lbrace, "expected '{' here"))
9008 return true;
9009
9010 // Check for an empty list.
9011 if (EatIfPresent(lltok::rbrace))
9012 return false;
9013
9014 do {
9015 if (EatIfPresent(lltok::kw_null)) {
9016 Elts.push_back(nullptr);
9017 continue;
9018 }
9019
9020 Metadata *MD;
9021 if (parseMetadata(MD, nullptr))
9022 return true;
9023 Elts.push_back(MD);
9024 } while (EatIfPresent(lltok::comma));
9025
9026 return parseToken(lltok::rbrace, "expected end of metadata node");
9027}
9028
9029//===----------------------------------------------------------------------===//
9030// Use-list order directives.
9031//===----------------------------------------------------------------------===//
9032bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9033 SMLoc Loc) {
9034 if (!V->hasUseList())
9035 return false;
9036 if (V->use_empty())
9037 return error(Loc, "value has no uses");
9038
9039 unsigned NumUses = 0;
9040 SmallDenseMap<const Use *, unsigned, 16> Order;
9041 for (const Use &U : V->uses()) {
9042 if (++NumUses > Indexes.size())
9043 break;
9044 Order[&U] = Indexes[NumUses - 1];
9045 }
9046 if (NumUses < 2)
9047 return error(Loc, "value only has one use");
9048 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9049 return error(Loc,
9050 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9051
9052 V->sortUseList([&](const Use &L, const Use &R) {
9053 return Order.lookup(&L) < Order.lookup(&R);
9054 });
9055 return false;
9056}
9057
9058/// parseUseListOrderIndexes
9059/// ::= '{' uint32 (',' uint32)+ '}'
9060bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9061 SMLoc Loc = Lex.getLoc();
9062 if (parseToken(lltok::lbrace, "expected '{' here"))
9063 return true;
9064 if (Lex.getKind() == lltok::rbrace)
9065 return tokError("expected non-empty list of uselistorder indexes");
9066
9067 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9068 // indexes should be distinct numbers in the range [0, size-1], and should
9069 // not be in order.
9070 unsigned Offset = 0;
9071 unsigned Max = 0;
9072 bool IsOrdered = true;
9073 assert(Indexes.empty() && "Expected empty order vector");
9074 do {
9075 unsigned Index;
9076 if (parseUInt32(Index))
9077 return true;
9078
9079 // Update consistency checks.
9080 Offset += Index - Indexes.size();
9081 Max = std::max(Max, Index);
9082 IsOrdered &= Index == Indexes.size();
9083
9084 Indexes.push_back(Index);
9085 } while (EatIfPresent(lltok::comma));
9086
9087 if (parseToken(lltok::rbrace, "expected '}' here"))
9088 return true;
9089
9090 if (Indexes.size() < 2)
9091 return error(Loc, "expected >= 2 uselistorder indexes");
9092 if (Offset != 0 || Max >= Indexes.size())
9093 return error(Loc,
9094 "expected distinct uselistorder indexes in range [0, size)");
9095 if (IsOrdered)
9096 return error(Loc, "expected uselistorder indexes to change the order");
9097
9098 return false;
9099}
9100
9101/// parseUseListOrder
9102/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9103bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9104 SMLoc Loc = Lex.getLoc();
9105 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9106 return true;
9107
9108 Value *V;
9109 SmallVector<unsigned, 16> Indexes;
9110 if (parseTypeAndValue(V, PFS) ||
9111 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9112 parseUseListOrderIndexes(Indexes))
9113 return true;
9114
9115 return sortUseListOrder(V, Indexes, Loc);
9116}
9117
9118/// parseUseListOrderBB
9119/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9120bool LLParser::parseUseListOrderBB() {
9121 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9122 SMLoc Loc = Lex.getLoc();
9123 Lex.Lex();
9124
9125 ValID Fn, Label;
9126 SmallVector<unsigned, 16> Indexes;
9127 if (parseValID(Fn, /*PFS=*/nullptr) ||
9128 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9129 parseValID(Label, /*PFS=*/nullptr) ||
9130 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9131 parseUseListOrderIndexes(Indexes))
9132 return true;
9133
9134 // Check the function.
9135 GlobalValue *GV;
9136 if (Fn.Kind == ValID::t_GlobalName)
9137 GV = M->getNamedValue(Fn.StrVal);
9138 else if (Fn.Kind == ValID::t_GlobalID)
9139 GV = NumberedVals.get(Fn.UIntVal);
9140 else
9141 return error(Fn.Loc, "expected function name in uselistorder_bb");
9142 if (!GV)
9143 return error(Fn.Loc,
9144 "invalid function forward reference in uselistorder_bb");
9145 auto *F = dyn_cast<Function>(GV);
9146 if (!F)
9147 return error(Fn.Loc, "expected function name in uselistorder_bb");
9148 if (F->isDeclaration())
9149 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9150
9151 // Check the basic block.
9152 if (Label.Kind == ValID::t_LocalID)
9153 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9154 if (Label.Kind != ValID::t_LocalName)
9155 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9156 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9157 if (!V)
9158 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9159 if (!isa<BasicBlock>(V))
9160 return error(Label.Loc, "expected basic block in uselistorder_bb");
9161
9162 return sortUseListOrder(V, Indexes, Loc);
9163}
9164
9165/// ModuleEntry
9166/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9167/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9168bool LLParser::parseModuleEntry(unsigned ID) {
9169 assert(Lex.getKind() == lltok::kw_module);
9170 Lex.Lex();
9171
9172 std::string Path;
9173 if (parseToken(lltok::colon, "expected ':' here") ||
9174 parseToken(lltok::lparen, "expected '(' here") ||
9175 parseToken(lltok::kw_path, "expected 'path' here") ||
9176 parseToken(lltok::colon, "expected ':' here") ||
9177 parseStringConstant(Path) ||
9178 parseToken(lltok::comma, "expected ',' here") ||
9179 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9180 parseToken(lltok::colon, "expected ':' here") ||
9181 parseToken(lltok::lparen, "expected '(' here"))
9182 return true;
9183
9184 ModuleHash Hash;
9185 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9186 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9187 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9188 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9189 parseUInt32(Hash[4]))
9190 return true;
9191
9192 if (parseToken(lltok::rparen, "expected ')' here") ||
9193 parseToken(lltok::rparen, "expected ')' here"))
9194 return true;
9195
9196 auto ModuleEntry = Index->addModule(Path, Hash);
9197 ModuleIdMap[ID] = ModuleEntry->first();
9198
9199 return false;
9200}
9201
9202/// TypeIdEntry
9203/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9204bool LLParser::parseTypeIdEntry(unsigned ID) {
9205 assert(Lex.getKind() == lltok::kw_typeid);
9206 Lex.Lex();
9207
9208 std::string Name;
9209 if (parseToken(lltok::colon, "expected ':' here") ||
9210 parseToken(lltok::lparen, "expected '(' here") ||
9211 parseToken(lltok::kw_name, "expected 'name' here") ||
9212 parseToken(lltok::colon, "expected ':' here") ||
9213 parseStringConstant(Name))
9214 return true;
9215
9216 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9217 if (parseToken(lltok::comma, "expected ',' here") ||
9218 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9219 return true;
9220
9221 // Check if this ID was forward referenced, and if so, update the
9222 // corresponding GUIDs.
9223 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9224 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9225 for (auto TIDRef : FwdRefTIDs->second) {
9226 assert(!*TIDRef.first &&
9227 "Forward referenced type id GUID expected to be 0");
9228 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9229 }
9230 ForwardRefTypeIds.erase(FwdRefTIDs);
9231 }
9232
9233 return false;
9234}
9235
9236/// TypeIdSummary
9237/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9238bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9239 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9240 parseToken(lltok::colon, "expected ':' here") ||
9241 parseToken(lltok::lparen, "expected '(' here") ||
9242 parseTypeTestResolution(TIS.TTRes))
9243 return true;
9244
9245 if (EatIfPresent(lltok::comma)) {
9246 // Expect optional wpdResolutions field
9247 if (parseOptionalWpdResolutions(TIS.WPDRes))
9248 return true;
9249 }
9250
9251 if (parseToken(lltok::rparen, "expected ')' here"))
9252 return true;
9253
9254 return false;
9255}
9256
9258 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9259
9260/// TypeIdCompatibleVtableEntry
9261/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9262/// TypeIdCompatibleVtableInfo
9263/// ')'
9264bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9266 Lex.Lex();
9267
9268 std::string Name;
9269 if (parseToken(lltok::colon, "expected ':' here") ||
9270 parseToken(lltok::lparen, "expected '(' here") ||
9271 parseToken(lltok::kw_name, "expected 'name' here") ||
9272 parseToken(lltok::colon, "expected ':' here") ||
9273 parseStringConstant(Name))
9274 return true;
9275
9277 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9278 if (parseToken(lltok::comma, "expected ',' here") ||
9279 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9280 parseToken(lltok::colon, "expected ':' here") ||
9281 parseToken(lltok::lparen, "expected '(' here"))
9282 return true;
9283
9284 IdToIndexMapType IdToIndexMap;
9285 // parse each call edge
9286 do {
9288 if (parseToken(lltok::lparen, "expected '(' here") ||
9289 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9290 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9291 parseToken(lltok::comma, "expected ',' here"))
9292 return true;
9293
9294 LocTy Loc = Lex.getLoc();
9295 unsigned GVId;
9296 ValueInfo VI;
9297 if (parseGVReference(VI, GVId))
9298 return true;
9299
9300 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9301 // forward reference. We will save the location of the ValueInfo needing an
9302 // update, but can only do so once the std::vector is finalized.
9303 if (VI == EmptyVI)
9304 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9305 TI.push_back({Offset, VI});
9306
9307 if (parseToken(lltok::rparen, "expected ')' in call"))
9308 return true;
9309 } while (EatIfPresent(lltok::comma));
9310
9311 // Now that the TI vector is finalized, it is safe to save the locations
9312 // of any forward GV references that need updating later.
9313 for (auto I : IdToIndexMap) {
9314 auto &Infos = ForwardRefValueInfos[I.first];
9315 for (auto P : I.second) {
9316 assert(TI[P.first].VTableVI == EmptyVI &&
9317 "Forward referenced ValueInfo expected to be empty");
9318 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9319 }
9320 }
9321
9322 if (parseToken(lltok::rparen, "expected ')' here") ||
9323 parseToken(lltok::rparen, "expected ')' here"))
9324 return true;
9325
9326 // Check if this ID was forward referenced, and if so, update the
9327 // corresponding GUIDs.
9328 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9329 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9330 for (auto TIDRef : FwdRefTIDs->second) {
9331 assert(!*TIDRef.first &&
9332 "Forward referenced type id GUID expected to be 0");
9333 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9334 }
9335 ForwardRefTypeIds.erase(FwdRefTIDs);
9336 }
9337
9338 return false;
9339}
9340
9341/// TypeTestResolution
9342/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9343/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9344/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9345/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9346/// [',' 'inlinesBits' ':' UInt64]? ')'
9347bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9348 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9349 parseToken(lltok::colon, "expected ':' here") ||
9350 parseToken(lltok::lparen, "expected '(' here") ||
9351 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9352 parseToken(lltok::colon, "expected ':' here"))
9353 return true;
9354
9355 switch (Lex.getKind()) {
9356 case lltok::kw_unknown:
9358 break;
9359 case lltok::kw_unsat:
9361 break;
9364 break;
9365 case lltok::kw_inline:
9367 break;
9368 case lltok::kw_single:
9370 break;
9371 case lltok::kw_allOnes:
9373 break;
9374 default:
9375 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9376 }
9377 Lex.Lex();
9378
9379 if (parseToken(lltok::comma, "expected ',' here") ||
9380 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9381 parseToken(lltok::colon, "expected ':' here") ||
9382 parseUInt32(TTRes.SizeM1BitWidth))
9383 return true;
9384
9385 // parse optional fields
9386 while (EatIfPresent(lltok::comma)) {
9387 switch (Lex.getKind()) {
9389 Lex.Lex();
9390 if (parseToken(lltok::colon, "expected ':'") ||
9391 parseUInt64(TTRes.AlignLog2))
9392 return true;
9393 break;
9394 case lltok::kw_sizeM1:
9395 Lex.Lex();
9396 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9397 return true;
9398 break;
9399 case lltok::kw_bitMask: {
9400 unsigned Val;
9401 Lex.Lex();
9402 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9403 return true;
9404 assert(Val <= 0xff);
9405 TTRes.BitMask = (uint8_t)Val;
9406 break;
9407 }
9409 Lex.Lex();
9410 if (parseToken(lltok::colon, "expected ':'") ||
9411 parseUInt64(TTRes.InlineBits))
9412 return true;
9413 break;
9414 default:
9415 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9416 }
9417 }
9418
9419 if (parseToken(lltok::rparen, "expected ')' here"))
9420 return true;
9421
9422 return false;
9423}
9424
9425/// OptionalWpdResolutions
9426/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9427/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9428bool LLParser::parseOptionalWpdResolutions(
9429 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9430 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9431 parseToken(lltok::colon, "expected ':' here") ||
9432 parseToken(lltok::lparen, "expected '(' here"))
9433 return true;
9434
9435 do {
9436 uint64_t Offset;
9437 WholeProgramDevirtResolution WPDRes;
9438 if (parseToken(lltok::lparen, "expected '(' here") ||
9439 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9440 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9441 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9442 parseToken(lltok::rparen, "expected ')' here"))
9443 return true;
9444 WPDResMap[Offset] = WPDRes;
9445 } while (EatIfPresent(lltok::comma));
9446
9447 if (parseToken(lltok::rparen, "expected ')' here"))
9448 return true;
9449
9450 return false;
9451}
9452
9453/// WpdRes
9454/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9455/// [',' OptionalResByArg]? ')'
9456/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9457/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9458/// [',' OptionalResByArg]? ')'
9459/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9460/// [',' OptionalResByArg]? ')'
9461bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9462 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9463 parseToken(lltok::colon, "expected ':' here") ||
9464 parseToken(lltok::lparen, "expected '(' here") ||
9465 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9466 parseToken(lltok::colon, "expected ':' here"))
9467 return true;
9468
9469 switch (Lex.getKind()) {
9470 case lltok::kw_indir:
9472 break;
9475 break;
9478 break;
9479 default:
9480 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9481 }
9482 Lex.Lex();
9483
9484 // parse optional fields
9485 while (EatIfPresent(lltok::comma)) {
9486 switch (Lex.getKind()) {
9488 Lex.Lex();
9489 if (parseToken(lltok::colon, "expected ':' here") ||
9490 parseStringConstant(WPDRes.SingleImplName))
9491 return true;
9492 break;
9493 case lltok::kw_resByArg:
9494 if (parseOptionalResByArg(WPDRes.ResByArg))
9495 return true;
9496 break;
9497 default:
9498 return error(Lex.getLoc(),
9499 "expected optional WholeProgramDevirtResolution field");
9500 }
9501 }
9502
9503 if (parseToken(lltok::rparen, "expected ')' here"))
9504 return true;
9505
9506 return false;
9507}
9508
9509/// OptionalResByArg
9510/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9511/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9512/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9513/// 'virtualConstProp' )
9514/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9515/// [',' 'bit' ':' UInt32]? ')'
9516bool LLParser::parseOptionalResByArg(
9517 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9518 &ResByArg) {
9519 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9520 parseToken(lltok::colon, "expected ':' here") ||
9521 parseToken(lltok::lparen, "expected '(' here"))
9522 return true;
9523
9524 do {
9525 std::vector<uint64_t> Args;
9526 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9527 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9528 parseToken(lltok::colon, "expected ':' here") ||
9529 parseToken(lltok::lparen, "expected '(' here") ||
9530 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9531 parseToken(lltok::colon, "expected ':' here"))
9532 return true;
9533
9534 WholeProgramDevirtResolution::ByArg ByArg;
9535 switch (Lex.getKind()) {
9536 case lltok::kw_indir:
9538 break;
9541 break;
9544 break;
9547 break;
9548 default:
9549 return error(Lex.getLoc(),
9550 "unexpected WholeProgramDevirtResolution::ByArg kind");
9551 }
9552 Lex.Lex();
9553
9554 // parse optional fields
9555 while (EatIfPresent(lltok::comma)) {
9556 switch (Lex.getKind()) {
9557 case lltok::kw_info:
9558 Lex.Lex();
9559 if (parseToken(lltok::colon, "expected ':' here") ||
9560 parseUInt64(ByArg.Info))
9561 return true;
9562 break;
9563 case lltok::kw_byte:
9564 Lex.Lex();
9565 if (parseToken(lltok::colon, "expected ':' here") ||
9566 parseUInt32(ByArg.Byte))
9567 return true;
9568 break;
9569 case lltok::kw_bit:
9570 Lex.Lex();
9571 if (parseToken(lltok::colon, "expected ':' here") ||
9572 parseUInt32(ByArg.Bit))
9573 return true;
9574 break;
9575 default:
9576 return error(Lex.getLoc(),
9577 "expected optional whole program devirt field");
9578 }
9579 }
9580
9581 if (parseToken(lltok::rparen, "expected ')' here"))
9582 return true;
9583
9584 ResByArg[Args] = ByArg;
9585 } while (EatIfPresent(lltok::comma));
9586
9587 if (parseToken(lltok::rparen, "expected ')' here"))
9588 return true;
9589
9590 return false;
9591}
9592
9593/// OptionalResByArg
9594/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9595bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9596 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9597 parseToken(lltok::colon, "expected ':' here") ||
9598 parseToken(lltok::lparen, "expected '(' here"))
9599 return true;
9600
9601 do {
9602 uint64_t Val;
9603 if (parseUInt64(Val))
9604 return true;
9605 Args.push_back(Val);
9606 } while (EatIfPresent(lltok::comma));
9607
9608 if (parseToken(lltok::rparen, "expected ')' here"))
9609 return true;
9610
9611 return false;
9612}
9613
9614static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9615
9616static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9617 bool ReadOnly = Fwd->isReadOnly();
9618 bool WriteOnly = Fwd->isWriteOnly();
9619 assert(!(ReadOnly && WriteOnly));
9620 *Fwd = Resolved;
9621 if (ReadOnly)
9622 Fwd->setReadOnly();
9623 if (WriteOnly)
9624 Fwd->setWriteOnly();
9625}
9626
9627/// Stores the given Name/GUID and associated summary into the Index.
9628/// Also updates any forward references to the associated entry ID.
9629bool LLParser::addGlobalValueToIndex(
9630 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9631 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9632 // First create the ValueInfo utilizing the Name or GUID.
9633 ValueInfo VI;
9634 if (GUID != 0) {
9635 assert(Name.empty());
9636 VI = Index->getOrInsertValueInfo(GUID);
9637 } else {
9638 assert(!Name.empty());
9639 if (M) {
9640 auto *GV = M->getNamedValue(Name);
9641 if (!GV)
9642 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9643
9644 VI = Index->getOrInsertValueInfo(GV);
9645 } else {
9646 assert(
9647 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9648 "Need a source_filename to compute GUID for local");
9650 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9651 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9652 }
9653 }
9654
9655 // Resolve forward references from calls/refs
9656 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9657 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9658 for (auto VIRef : FwdRefVIs->second) {
9659 assert(VIRef.first->getRef() == FwdVIRef &&
9660 "Forward referenced ValueInfo expected to be empty");
9661 resolveFwdRef(VIRef.first, VI);
9662 }
9663 ForwardRefValueInfos.erase(FwdRefVIs);
9664 }
9665
9666 // Resolve forward references from aliases
9667 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9668 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9669 for (auto AliaseeRef : FwdRefAliasees->second) {
9670 assert(!AliaseeRef.first->hasAliasee() &&
9671 "Forward referencing alias already has aliasee");
9672 assert(Summary && "Aliasee must be a definition");
9673 AliaseeRef.first->setAliasee(VI, Summary.get());
9674 }
9675 ForwardRefAliasees.erase(FwdRefAliasees);
9676 }
9677
9678 // Add the summary if one was provided.
9679 if (Summary)
9680 Index->addGlobalValueSummary(VI, std::move(Summary));
9681
9682 // Save the associated ValueInfo for use in later references by ID.
9683 if (ID == NumberedValueInfos.size())
9684 NumberedValueInfos.push_back(VI);
9685 else {
9686 // Handle non-continuous numbers (to make test simplification easier).
9687 if (ID > NumberedValueInfos.size())
9688 NumberedValueInfos.resize(ID + 1);
9689 NumberedValueInfos[ID] = VI;
9690 }
9691
9692 return false;
9693}
9694
9695/// parseSummaryIndexFlags
9696/// ::= 'flags' ':' UInt64
9697bool LLParser::parseSummaryIndexFlags() {
9698 assert(Lex.getKind() == lltok::kw_flags);
9699 Lex.Lex();
9700
9701 if (parseToken(lltok::colon, "expected ':' here"))
9702 return true;
9703 uint64_t Flags;
9704 if (parseUInt64(Flags))
9705 return true;
9706 if (Index)
9707 Index->setFlags(Flags);
9708 return false;
9709}
9710
9711/// parseBlockCount
9712/// ::= 'blockcount' ':' UInt64
9713bool LLParser::parseBlockCount() {
9714 assert(Lex.getKind() == lltok::kw_blockcount);
9715 Lex.Lex();
9716
9717 if (parseToken(lltok::colon, "expected ':' here"))
9718 return true;
9719 uint64_t BlockCount;
9720 if (parseUInt64(BlockCount))
9721 return true;
9722 if (Index)
9723 Index->setBlockCount(BlockCount);
9724 return false;
9725}
9726
9727/// parseGVEntry
9728/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9729/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9730/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9731bool LLParser::parseGVEntry(unsigned ID) {
9732 assert(Lex.getKind() == lltok::kw_gv);
9733 Lex.Lex();
9734
9735 if (parseToken(lltok::colon, "expected ':' here") ||
9736 parseToken(lltok::lparen, "expected '(' here"))
9737 return true;
9738
9739 LocTy Loc = Lex.getLoc();
9740 std::string Name;
9742 switch (Lex.getKind()) {
9743 case lltok::kw_name:
9744 Lex.Lex();
9745 if (parseToken(lltok::colon, "expected ':' here") ||
9746 parseStringConstant(Name))
9747 return true;
9748 // Can't create GUID/ValueInfo until we have the linkage.
9749 break;
9750 case lltok::kw_guid:
9751 Lex.Lex();
9752 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9753 return true;
9754 break;
9755 default:
9756 return error(Lex.getLoc(), "expected name or guid tag");
9757 }
9758
9759 if (!EatIfPresent(lltok::comma)) {
9760 // No summaries. Wrap up.
9761 if (parseToken(lltok::rparen, "expected ')' here"))
9762 return true;
9763 // This was created for a call to an external or indirect target.
9764 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9765 // created for indirect calls with VP. A Name with no GUID came from
9766 // an external definition. We pass ExternalLinkage since that is only
9767 // used when the GUID must be computed from Name, and in that case
9768 // the symbol must have external linkage.
9769 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9770 nullptr, Loc);
9771 }
9772
9773 // Have a list of summaries
9774 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9775 parseToken(lltok::colon, "expected ':' here") ||
9776 parseToken(lltok::lparen, "expected '(' here"))
9777 return true;
9778 do {
9779 switch (Lex.getKind()) {
9780 case lltok::kw_function:
9781 if (parseFunctionSummary(Name, GUID, ID))
9782 return true;
9783 break;
9784 case lltok::kw_variable:
9785 if (parseVariableSummary(Name, GUID, ID))
9786 return true;
9787 break;
9788 case lltok::kw_alias:
9789 if (parseAliasSummary(Name, GUID, ID))
9790 return true;
9791 break;
9792 default:
9793 return error(Lex.getLoc(), "expected summary type");
9794 }
9795 } while (EatIfPresent(lltok::comma));
9796
9797 if (parseToken(lltok::rparen, "expected ')' here") ||
9798 parseToken(lltok::rparen, "expected ')' here"))
9799 return true;
9800
9801 return false;
9802}
9803
9804/// FunctionSummary
9805/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9806/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9807/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9808/// [',' OptionalRefs]? ')'
9809bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9810 unsigned ID) {
9811 LocTy Loc = Lex.getLoc();
9812 assert(Lex.getKind() == lltok::kw_function);
9813 Lex.Lex();
9814
9815 StringRef ModulePath;
9816 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9818 /*NotEligibleToImport=*/false,
9819 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9821 unsigned InstCount;
9823 FunctionSummary::TypeIdInfo TypeIdInfo;
9824 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9826 std::vector<CallsiteInfo> Callsites;
9827 std::vector<AllocInfo> Allocs;
9828 // Default is all-zeros (conservative values).
9829 FunctionSummary::FFlags FFlags = {};
9830 if (parseToken(lltok::colon, "expected ':' here") ||
9831 parseToken(lltok::lparen, "expected '(' here") ||
9832 parseModuleReference(ModulePath) ||
9833 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9834 parseToken(lltok::comma, "expected ',' here") ||
9835 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9836 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9837 return true;
9838
9839 // parse optional fields
9840 while (EatIfPresent(lltok::comma)) {
9841 switch (Lex.getKind()) {
9843 if (parseOptionalFFlags(FFlags))
9844 return true;
9845 break;
9846 case lltok::kw_calls:
9847 if (parseOptionalCalls(Calls))
9848 return true;
9849 break;
9851 if (parseOptionalTypeIdInfo(TypeIdInfo))
9852 return true;
9853 break;
9854 case lltok::kw_refs:
9855 if (parseOptionalRefs(Refs))
9856 return true;
9857 break;
9858 case lltok::kw_params:
9859 if (parseOptionalParamAccesses(ParamAccesses))
9860 return true;
9861 break;
9862 case lltok::kw_allocs:
9863 if (parseOptionalAllocs(Allocs))
9864 return true;
9865 break;
9867 if (parseOptionalCallsites(Callsites))
9868 return true;
9869 break;
9870 default:
9871 return error(Lex.getLoc(), "expected optional function summary field");
9872 }
9873 }
9874
9875 if (parseToken(lltok::rparen, "expected ')' here"))
9876 return true;
9877
9878 auto FS = std::make_unique<FunctionSummary>(
9879 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9880 std::move(TypeIdInfo.TypeTests),
9881 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9882 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9883 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9884 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9885 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9886
9887 FS->setModulePath(ModulePath);
9888
9889 return addGlobalValueToIndex(Name, GUID,
9891 std::move(FS), Loc);
9892}
9893
9894/// VariableSummary
9895/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9896/// [',' OptionalRefs]? ')'
9897bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9898 unsigned ID) {
9899 LocTy Loc = Lex.getLoc();
9900 assert(Lex.getKind() == lltok::kw_variable);
9901 Lex.Lex();
9902
9903 StringRef ModulePath;
9904 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9906 /*NotEligibleToImport=*/false,
9907 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9909 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9910 /* WriteOnly */ false,
9911 /* Constant */ false,
9914 VTableFuncList VTableFuncs;
9915 if (parseToken(lltok::colon, "expected ':' here") ||
9916 parseToken(lltok::lparen, "expected '(' here") ||
9917 parseModuleReference(ModulePath) ||
9918 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9919 parseToken(lltok::comma, "expected ',' here") ||
9920 parseGVarFlags(GVarFlags))
9921 return true;
9922
9923 // parse optional fields
9924 while (EatIfPresent(lltok::comma)) {
9925 switch (Lex.getKind()) {
9927 if (parseOptionalVTableFuncs(VTableFuncs))
9928 return true;
9929 break;
9930 case lltok::kw_refs:
9931 if (parseOptionalRefs(Refs))
9932 return true;
9933 break;
9934 default:
9935 return error(Lex.getLoc(), "expected optional variable summary field");
9936 }
9937 }
9938
9939 if (parseToken(lltok::rparen, "expected ')' here"))
9940 return true;
9941
9942 auto GS =
9943 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9944
9945 GS->setModulePath(ModulePath);
9946 GS->setVTableFuncs(std::move(VTableFuncs));
9947
9948 return addGlobalValueToIndex(Name, GUID,
9950 std::move(GS), Loc);
9951}
9952
9953/// AliasSummary
9954/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9955/// 'aliasee' ':' GVReference ')'
9956bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9957 unsigned ID) {
9958 assert(Lex.getKind() == lltok::kw_alias);
9959 LocTy Loc = Lex.getLoc();
9960 Lex.Lex();
9961
9962 StringRef ModulePath;
9963 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9965 /*NotEligibleToImport=*/false,
9966 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9968 if (parseToken(lltok::colon, "expected ':' here") ||
9969 parseToken(lltok::lparen, "expected '(' here") ||
9970 parseModuleReference(ModulePath) ||
9971 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9972 parseToken(lltok::comma, "expected ',' here") ||
9973 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9974 parseToken(lltok::colon, "expected ':' here"))
9975 return true;
9976
9977 ValueInfo AliaseeVI;
9978 unsigned GVId;
9979 if (parseGVReference(AliaseeVI, GVId))
9980 return true;
9981
9982 if (parseToken(lltok::rparen, "expected ')' here"))
9983 return true;
9984
9985 auto AS = std::make_unique<AliasSummary>(GVFlags);
9986
9987 AS->setModulePath(ModulePath);
9988
9989 // Record forward reference if the aliasee is not parsed yet.
9990 if (AliaseeVI.getRef() == FwdVIRef) {
9991 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9992 } else {
9993 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9994 assert(Summary && "Aliasee must be a definition");
9995 AS->setAliasee(AliaseeVI, Summary);
9996 }
9997
9998 return addGlobalValueToIndex(Name, GUID,
10000 std::move(AS), Loc);
10001}
10002
10003/// Flag
10004/// ::= [0|1]
10005bool LLParser::parseFlag(unsigned &Val) {
10006 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10007 return tokError("expected integer");
10008 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10009 Lex.Lex();
10010 return false;
10011}
10012
10013/// OptionalFFlags
10014/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10015/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10016/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10017/// [',' 'noInline' ':' Flag]? ')'
10018/// [',' 'alwaysInline' ':' Flag]? ')'
10019/// [',' 'noUnwind' ':' Flag]? ')'
10020/// [',' 'mayThrow' ':' Flag]? ')'
10021/// [',' 'hasUnknownCall' ':' Flag]? ')'
10022/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10023
10024bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10025 assert(Lex.getKind() == lltok::kw_funcFlags);
10026 Lex.Lex();
10027
10028 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10029 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10030 return true;
10031
10032 do {
10033 unsigned Val = 0;
10034 switch (Lex.getKind()) {
10035 case lltok::kw_readNone:
10036 Lex.Lex();
10037 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10038 return true;
10039 FFlags.ReadNone = Val;
10040 break;
10041 case lltok::kw_readOnly:
10042 Lex.Lex();
10043 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10044 return true;
10045 FFlags.ReadOnly = Val;
10046 break;
10048 Lex.Lex();
10049 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10050 return true;
10051 FFlags.NoRecurse = Val;
10052 break;
10054 Lex.Lex();
10055 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10056 return true;
10057 FFlags.ReturnDoesNotAlias = Val;
10058 break;
10059 case lltok::kw_noInline:
10060 Lex.Lex();
10061 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10062 return true;
10063 FFlags.NoInline = Val;
10064 break;
10066 Lex.Lex();
10067 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10068 return true;
10069 FFlags.AlwaysInline = Val;
10070 break;
10071 case lltok::kw_noUnwind:
10072 Lex.Lex();
10073 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10074 return true;
10075 FFlags.NoUnwind = Val;
10076 break;
10077 case lltok::kw_mayThrow:
10078 Lex.Lex();
10079 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10080 return true;
10081 FFlags.MayThrow = Val;
10082 break;
10084 Lex.Lex();
10085 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10086 return true;
10087 FFlags.HasUnknownCall = Val;
10088 break;
10090 Lex.Lex();
10091 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10092 return true;
10093 FFlags.MustBeUnreachable = Val;
10094 break;
10095 default:
10096 return error(Lex.getLoc(), "expected function flag type");
10097 }
10098 } while (EatIfPresent(lltok::comma));
10099
10100 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10101 return true;
10102
10103 return false;
10104}
10105
10106/// OptionalCalls
10107/// := 'calls' ':' '(' Call [',' Call]* ')'
10108/// Call ::= '(' 'callee' ':' GVReference
10109/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10110/// [ ',' 'tail' ]? ')'
10111bool LLParser::parseOptionalCalls(
10112 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10113 assert(Lex.getKind() == lltok::kw_calls);
10114 Lex.Lex();
10115
10116 if (parseToken(lltok::colon, "expected ':' in calls") ||
10117 parseToken(lltok::lparen, "expected '(' in calls"))
10118 return true;
10119
10120 IdToIndexMapType IdToIndexMap;
10121 // parse each call edge
10122 do {
10123 ValueInfo VI;
10124 if (parseToken(lltok::lparen, "expected '(' in call") ||
10125 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10126 parseToken(lltok::colon, "expected ':'"))
10127 return true;
10128
10129 LocTy Loc = Lex.getLoc();
10130 unsigned GVId;
10131 if (parseGVReference(VI, GVId))
10132 return true;
10133
10135 unsigned RelBF = 0;
10136 unsigned HasTailCall = false;
10137
10138 // parse optional fields
10139 while (EatIfPresent(lltok::comma)) {
10140 switch (Lex.getKind()) {
10141 case lltok::kw_hotness:
10142 Lex.Lex();
10143 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10144 return true;
10145 break;
10146 case lltok::kw_relbf:
10147 Lex.Lex();
10148 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10149 return true;
10150 break;
10151 case lltok::kw_tail:
10152 Lex.Lex();
10153 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10154 return true;
10155 break;
10156 default:
10157 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10158 }
10159 }
10160 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
10161 return tokError("Expected only one of hotness or relbf");
10162 // Keep track of the Call array index needing a forward reference.
10163 // We will save the location of the ValueInfo needing an update, but
10164 // can only do so once the std::vector is finalized.
10165 if (VI.getRef() == FwdVIRef)
10166 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10167 Calls.push_back(
10168 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
10169
10170 if (parseToken(lltok::rparen, "expected ')' in call"))
10171 return true;
10172 } while (EatIfPresent(lltok::comma));
10173
10174 // Now that the Calls vector is finalized, it is safe to save the locations
10175 // of any forward GV references that need updating later.
10176 for (auto I : IdToIndexMap) {
10177 auto &Infos = ForwardRefValueInfos[I.first];
10178 for (auto P : I.second) {
10179 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10180 "Forward referenced ValueInfo expected to be empty");
10181 Infos.emplace_back(&Calls[P.first].first, P.second);
10182 }
10183 }
10184
10185 if (parseToken(lltok::rparen, "expected ')' in calls"))
10186 return true;
10187
10188 return false;
10189}
10190
10191/// Hotness
10192/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10193bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10194 switch (Lex.getKind()) {
10195 case lltok::kw_unknown:
10197 break;
10198 case lltok::kw_cold:
10200 break;
10201 case lltok::kw_none:
10203 break;
10204 case lltok::kw_hot:
10206 break;
10207 case lltok::kw_critical:
10209 break;
10210 default:
10211 return error(Lex.getLoc(), "invalid call edge hotness");
10212 }
10213 Lex.Lex();
10214 return false;
10215}
10216
10217/// OptionalVTableFuncs
10218/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10219/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10220bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10221 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10222 Lex.Lex();
10223
10224 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10225 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10226 return true;
10227
10228 IdToIndexMapType IdToIndexMap;
10229 // parse each virtual function pair
10230 do {
10231 ValueInfo VI;
10232 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10233 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10234 parseToken(lltok::colon, "expected ':'"))
10235 return true;
10236
10237 LocTy Loc = Lex.getLoc();
10238 unsigned GVId;
10239 if (parseGVReference(VI, GVId))
10240 return true;
10241
10242 uint64_t Offset;
10243 if (parseToken(lltok::comma, "expected comma") ||
10244 parseToken(lltok::kw_offset, "expected offset") ||
10245 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10246 return true;
10247
10248 // Keep track of the VTableFuncs array index needing a forward reference.
10249 // We will save the location of the ValueInfo needing an update, but
10250 // can only do so once the std::vector is finalized.
10251 if (VI == EmptyVI)
10252 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10253 VTableFuncs.push_back({VI, Offset});
10254
10255 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10256 return true;
10257 } while (EatIfPresent(lltok::comma));
10258
10259 // Now that the VTableFuncs vector is finalized, it is safe to save the
10260 // locations of any forward GV references that need updating later.
10261 for (auto I : IdToIndexMap) {
10262 auto &Infos = ForwardRefValueInfos[I.first];
10263 for (auto P : I.second) {
10264 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10265 "Forward referenced ValueInfo expected to be empty");
10266 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10267 }
10268 }
10269
10270 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10271 return true;
10272
10273 return false;
10274}
10275
10276/// ParamNo := 'param' ':' UInt64
10277bool LLParser::parseParamNo(uint64_t &ParamNo) {
10278 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10279 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10280 return true;
10281 return false;
10282}
10283
10284/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10285bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10286 APSInt Lower;
10287 APSInt Upper;
10288 auto ParseAPSInt = [&](APSInt &Val) {
10289 if (Lex.getKind() != lltok::APSInt)
10290 return tokError("expected integer");
10291 Val = Lex.getAPSIntVal();
10292 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10293 Val.setIsSigned(true);
10294 Lex.Lex();
10295 return false;
10296 };
10297 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10298 parseToken(lltok::colon, "expected ':' here") ||
10299 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10300 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10301 parseToken(lltok::rsquare, "expected ']' here"))
10302 return true;
10303
10304 ++Upper;
10305 Range =
10306 (Lower == Upper && !Lower.isMaxValue())
10307 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10308 : ConstantRange(Lower, Upper);
10309
10310 return false;
10311}
10312
10313/// ParamAccessCall
10314/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10315bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10316 IdLocListType &IdLocList) {
10317 if (parseToken(lltok::lparen, "expected '(' here") ||
10318 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10319 parseToken(lltok::colon, "expected ':' here"))
10320 return true;
10321
10322 unsigned GVId;
10323 ValueInfo VI;
10324 LocTy Loc = Lex.getLoc();
10325 if (parseGVReference(VI, GVId))
10326 return true;
10327
10328 Call.Callee = VI;
10329 IdLocList.emplace_back(GVId, Loc);
10330
10331 if (parseToken(lltok::comma, "expected ',' here") ||
10332 parseParamNo(Call.ParamNo) ||
10333 parseToken(lltok::comma, "expected ',' here") ||
10334 parseParamAccessOffset(Call.Offsets))
10335 return true;
10336
10337 if (parseToken(lltok::rparen, "expected ')' here"))
10338 return true;
10339
10340 return false;
10341}
10342
10343/// ParamAccess
10344/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10345/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10346bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10347 IdLocListType &IdLocList) {
10348 if (parseToken(lltok::lparen, "expected '(' here") ||
10349 parseParamNo(Param.ParamNo) ||
10350 parseToken(lltok::comma, "expected ',' here") ||
10351 parseParamAccessOffset(Param.Use))
10352 return true;
10353
10354 if (EatIfPresent(lltok::comma)) {
10355 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10356 parseToken(lltok::colon, "expected ':' here") ||
10357 parseToken(lltok::lparen, "expected '(' here"))
10358 return true;
10359 do {
10360 FunctionSummary::ParamAccess::Call Call;
10361 if (parseParamAccessCall(Call, IdLocList))
10362 return true;
10363 Param.Calls.push_back(Call);
10364 } while (EatIfPresent(lltok::comma));
10365
10366 if (parseToken(lltok::rparen, "expected ')' here"))
10367 return true;
10368 }
10369
10370 if (parseToken(lltok::rparen, "expected ')' here"))
10371 return true;
10372
10373 return false;
10374}
10375
10376/// OptionalParamAccesses
10377/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10378bool LLParser::parseOptionalParamAccesses(
10379 std::vector<FunctionSummary::ParamAccess> &Params) {
10380 assert(Lex.getKind() == lltok::kw_params);
10381 Lex.Lex();
10382
10383 if (parseToken(lltok::colon, "expected ':' here") ||
10384 parseToken(lltok::lparen, "expected '(' here"))
10385 return true;
10386
10387 IdLocListType VContexts;
10388 size_t CallsNum = 0;
10389 do {
10390 FunctionSummary::ParamAccess ParamAccess;
10391 if (parseParamAccess(ParamAccess, VContexts))
10392 return true;
10393 CallsNum += ParamAccess.Calls.size();
10394 assert(VContexts.size() == CallsNum);
10395 (void)CallsNum;
10396 Params.emplace_back(std::move(ParamAccess));
10397 } while (EatIfPresent(lltok::comma));
10398
10399 if (parseToken(lltok::rparen, "expected ')' here"))
10400 return true;
10401
10402 // Now that the Params is finalized, it is safe to save the locations
10403 // of any forward GV references that need updating later.
10404 IdLocListType::const_iterator ItContext = VContexts.begin();
10405 for (auto &PA : Params) {
10406 for (auto &C : PA.Calls) {
10407 if (C.Callee.getRef() == FwdVIRef)
10408 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10409 ItContext->second);
10410 ++ItContext;
10411 }
10412 }
10413 assert(ItContext == VContexts.end());
10414
10415 return false;
10416}
10417
10418/// OptionalRefs
10419/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10420bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10421 assert(Lex.getKind() == lltok::kw_refs);
10422 Lex.Lex();
10423
10424 if (parseToken(lltok::colon, "expected ':' in refs") ||
10425 parseToken(lltok::lparen, "expected '(' in refs"))
10426 return true;
10427
10428 struct ValueContext {
10429 ValueInfo VI;
10430 unsigned GVId;
10431 LocTy Loc;
10432 };
10433 std::vector<ValueContext> VContexts;
10434 // parse each ref edge
10435 do {
10436 ValueContext VC;
10437 VC.Loc = Lex.getLoc();
10438 if (parseGVReference(VC.VI, VC.GVId))
10439 return true;
10440 VContexts.push_back(VC);
10441 } while (EatIfPresent(lltok::comma));
10442
10443 // Sort value contexts so that ones with writeonly
10444 // and readonly ValueInfo are at the end of VContexts vector.
10445 // See FunctionSummary::specialRefCounts()
10446 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10447 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10448 });
10449
10450 IdToIndexMapType IdToIndexMap;
10451 for (auto &VC : VContexts) {
10452 // Keep track of the Refs array index needing a forward reference.
10453 // We will save the location of the ValueInfo needing an update, but
10454 // can only do so once the std::vector is finalized.
10455 if (VC.VI.getRef() == FwdVIRef)
10456 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10457 Refs.push_back(VC.VI);
10458 }
10459
10460 // Now that the Refs vector is finalized, it is safe to save the locations
10461 // of any forward GV references that need updating later.
10462 for (auto I : IdToIndexMap) {
10463 auto &Infos = ForwardRefValueInfos[I.first];
10464 for (auto P : I.second) {
10465 assert(Refs[P.first].getRef() == FwdVIRef &&
10466 "Forward referenced ValueInfo expected to be empty");
10467 Infos.emplace_back(&Refs[P.first], P.second);
10468 }
10469 }
10470
10471 if (parseToken(lltok::rparen, "expected ')' in refs"))
10472 return true;
10473
10474 return false;
10475}
10476
10477/// OptionalTypeIdInfo
10478/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10479/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10480/// [',' TypeCheckedLoadConstVCalls]? ')'
10481bool LLParser::parseOptionalTypeIdInfo(
10482 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10483 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10484 Lex.Lex();
10485
10486 if (parseToken(lltok::colon, "expected ':' here") ||
10487 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10488 return true;
10489
10490 do {
10491 switch (Lex.getKind()) {
10493 if (parseTypeTests(TypeIdInfo.TypeTests))
10494 return true;
10495 break;
10497 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10498 TypeIdInfo.TypeTestAssumeVCalls))
10499 return true;
10500 break;
10502 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10503 TypeIdInfo.TypeCheckedLoadVCalls))
10504 return true;
10505 break;
10507 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10508 TypeIdInfo.TypeTestAssumeConstVCalls))
10509 return true;
10510 break;
10512 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10513 TypeIdInfo.TypeCheckedLoadConstVCalls))
10514 return true;
10515 break;
10516 default:
10517 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10518 }
10519 } while (EatIfPresent(lltok::comma));
10520
10521 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10522 return true;
10523
10524 return false;
10525}
10526
10527/// TypeTests
10528/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10529/// [',' (SummaryID | UInt64)]* ')'
10530bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10531 assert(Lex.getKind() == lltok::kw_typeTests);
10532 Lex.Lex();
10533
10534 if (parseToken(lltok::colon, "expected ':' here") ||
10535 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10536 return true;
10537
10538 IdToIndexMapType IdToIndexMap;
10539 do {
10541 if (Lex.getKind() == lltok::SummaryID) {
10542 unsigned ID = Lex.getUIntVal();
10543 LocTy Loc = Lex.getLoc();
10544 // Keep track of the TypeTests array index needing a forward reference.
10545 // We will save the location of the GUID needing an update, but
10546 // can only do so once the std::vector is finalized.
10547 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10548 Lex.Lex();
10549 } else if (parseUInt64(GUID))
10550 return true;
10551 TypeTests.push_back(GUID);
10552 } while (EatIfPresent(lltok::comma));
10553
10554 // Now that the TypeTests vector is finalized, it is safe to save the
10555 // locations of any forward GV references that need updating later.
10556 for (auto I : IdToIndexMap) {
10557 auto &Ids = ForwardRefTypeIds[I.first];
10558 for (auto P : I.second) {
10559 assert(TypeTests[P.first] == 0 &&
10560 "Forward referenced type id GUID expected to be 0");
10561 Ids.emplace_back(&TypeTests[P.first], P.second);
10562 }
10563 }
10564
10565 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10566 return true;
10567
10568 return false;
10569}
10570
10571/// VFuncIdList
10572/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10573bool LLParser::parseVFuncIdList(
10574 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10575 assert(Lex.getKind() == Kind);
10576 Lex.Lex();
10577
10578 if (parseToken(lltok::colon, "expected ':' here") ||
10579 parseToken(lltok::lparen, "expected '(' here"))
10580 return true;
10581
10582 IdToIndexMapType IdToIndexMap;
10583 do {
10584 FunctionSummary::VFuncId VFuncId;
10585 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10586 return true;
10587 VFuncIdList.push_back(VFuncId);
10588 } while (EatIfPresent(lltok::comma));
10589
10590 if (parseToken(lltok::rparen, "expected ')' here"))
10591 return true;
10592
10593 // Now that the VFuncIdList vector is finalized, it is safe to save the
10594 // locations of any forward GV references that need updating later.
10595 for (auto I : IdToIndexMap) {
10596 auto &Ids = ForwardRefTypeIds[I.first];
10597 for (auto P : I.second) {
10598 assert(VFuncIdList[P.first].GUID == 0 &&
10599 "Forward referenced type id GUID expected to be 0");
10600 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10601 }
10602 }
10603
10604 return false;
10605}
10606
10607/// ConstVCallList
10608/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10609bool LLParser::parseConstVCallList(
10610 lltok::Kind Kind,
10611 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10612 assert(Lex.getKind() == Kind);
10613 Lex.Lex();
10614
10615 if (parseToken(lltok::colon, "expected ':' here") ||
10616 parseToken(lltok::lparen, "expected '(' here"))
10617 return true;
10618
10619 IdToIndexMapType IdToIndexMap;
10620 do {
10621 FunctionSummary::ConstVCall ConstVCall;
10622 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10623 return true;
10624 ConstVCallList.push_back(ConstVCall);
10625 } while (EatIfPresent(lltok::comma));
10626
10627 if (parseToken(lltok::rparen, "expected ')' here"))
10628 return true;
10629
10630 // Now that the ConstVCallList vector is finalized, it is safe to save the
10631 // locations of any forward GV references that need updating later.
10632 for (auto I : IdToIndexMap) {
10633 auto &Ids = ForwardRefTypeIds[I.first];
10634 for (auto P : I.second) {
10635 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10636 "Forward referenced type id GUID expected to be 0");
10637 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10638 }
10639 }
10640
10641 return false;
10642}
10643
10644/// ConstVCall
10645/// ::= '(' VFuncId ',' Args ')'
10646bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10647 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10648 if (parseToken(lltok::lparen, "expected '(' here") ||
10649 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10650 return true;
10651
10652 if (EatIfPresent(lltok::comma))
10653 if (parseArgs(ConstVCall.Args))
10654 return true;
10655
10656 if (parseToken(lltok::rparen, "expected ')' here"))
10657 return true;
10658
10659 return false;
10660}
10661
10662/// VFuncId
10663/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10664/// 'offset' ':' UInt64 ')'
10665bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10666 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10667 assert(Lex.getKind() == lltok::kw_vFuncId);
10668 Lex.Lex();
10669
10670 if (parseToken(lltok::colon, "expected ':' here") ||
10671 parseToken(lltok::lparen, "expected '(' here"))
10672 return true;
10673
10674 if (Lex.getKind() == lltok::SummaryID) {
10675 VFuncId.GUID = 0;
10676 unsigned ID = Lex.getUIntVal();
10677 LocTy Loc = Lex.getLoc();
10678 // Keep track of the array index needing a forward reference.
10679 // We will save the location of the GUID needing an update, but
10680 // can only do so once the caller's std::vector is finalized.
10681 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10682 Lex.Lex();
10683 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10684 parseToken(lltok::colon, "expected ':' here") ||
10685 parseUInt64(VFuncId.GUID))
10686 return true;
10687
10688 if (parseToken(lltok::comma, "expected ',' here") ||
10689 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10690 parseToken(lltok::colon, "expected ':' here") ||
10691 parseUInt64(VFuncId.Offset) ||
10692 parseToken(lltok::rparen, "expected ')' here"))
10693 return true;
10694
10695 return false;
10696}
10697
10698/// GVFlags
10699/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10700/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10701/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10702/// 'canAutoHide' ':' Flag ',' ')'
10703bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10704 assert(Lex.getKind() == lltok::kw_flags);
10705 Lex.Lex();
10706
10707 if (parseToken(lltok::colon, "expected ':' here") ||
10708 parseToken(lltok::lparen, "expected '(' here"))
10709 return true;
10710
10711 do {
10712 unsigned Flag = 0;
10713 switch (Lex.getKind()) {
10714 case lltok::kw_linkage:
10715 Lex.Lex();
10716 if (parseToken(lltok::colon, "expected ':'"))
10717 return true;
10718 bool HasLinkage;
10719 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10720 assert(HasLinkage && "Linkage not optional in summary entry");
10721 Lex.Lex();
10722 break;
10724 Lex.Lex();
10725 if (parseToken(lltok::colon, "expected ':'"))
10726 return true;
10727 parseOptionalVisibility(Flag);
10728 GVFlags.Visibility = Flag;
10729 break;
10731 Lex.Lex();
10732 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10733 return true;
10734 GVFlags.NotEligibleToImport = Flag;
10735 break;
10736 case lltok::kw_live:
10737 Lex.Lex();
10738 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10739 return true;
10740 GVFlags.Live = Flag;
10741 break;
10742 case lltok::kw_dsoLocal:
10743 Lex.Lex();
10744 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10745 return true;
10746 GVFlags.DSOLocal = Flag;
10747 break;
10749 Lex.Lex();
10750 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10751 return true;
10752 GVFlags.CanAutoHide = Flag;
10753 break;
10755 Lex.Lex();
10756 if (parseToken(lltok::colon, "expected ':'"))
10757 return true;
10759 if (parseOptionalImportType(Lex.getKind(), IK))
10760 return true;
10761 GVFlags.ImportType = static_cast<unsigned>(IK);
10762 Lex.Lex();
10763 break;
10764 default:
10765 return error(Lex.getLoc(), "expected gv flag type");
10766 }
10767 } while (EatIfPresent(lltok::comma));
10768
10769 if (parseToken(lltok::rparen, "expected ')' here"))
10770 return true;
10771
10772 return false;
10773}
10774
10775/// GVarFlags
10776/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10777/// ',' 'writeonly' ':' Flag
10778/// ',' 'constant' ':' Flag ')'
10779bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10780 assert(Lex.getKind() == lltok::kw_varFlags);
10781 Lex.Lex();
10782
10783 if (parseToken(lltok::colon, "expected ':' here") ||
10784 parseToken(lltok::lparen, "expected '(' here"))
10785 return true;
10786
10787 auto ParseRest = [this](unsigned int &Val) {
10788 Lex.Lex();
10789 if (parseToken(lltok::colon, "expected ':'"))
10790 return true;
10791 return parseFlag(Val);
10792 };
10793
10794 do {
10795 unsigned Flag = 0;
10796 switch (Lex.getKind()) {
10797 case lltok::kw_readonly:
10798 if (ParseRest(Flag))
10799 return true;
10800 GVarFlags.MaybeReadOnly = Flag;
10801 break;
10802 case lltok::kw_writeonly:
10803 if (ParseRest(Flag))
10804 return true;
10805 GVarFlags.MaybeWriteOnly = Flag;
10806 break;
10807 case lltok::kw_constant:
10808 if (ParseRest(Flag))
10809 return true;
10810 GVarFlags.Constant = Flag;
10811 break;
10813 if (ParseRest(Flag))
10814 return true;
10815 GVarFlags.VCallVisibility = Flag;
10816 break;
10817 default:
10818 return error(Lex.getLoc(), "expected gvar flag type");
10819 }
10820 } while (EatIfPresent(lltok::comma));
10821 return parseToken(lltok::rparen, "expected ')' here");
10822}
10823
10824/// ModuleReference
10825/// ::= 'module' ':' UInt
10826bool LLParser::parseModuleReference(StringRef &ModulePath) {
10827 // parse module id.
10828 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10829 parseToken(lltok::colon, "expected ':' here") ||
10830 parseToken(lltok::SummaryID, "expected module ID"))
10831 return true;
10832
10833 unsigned ModuleID = Lex.getUIntVal();
10834 auto I = ModuleIdMap.find(ModuleID);
10835 // We should have already parsed all module IDs
10836 assert(I != ModuleIdMap.end());
10837 ModulePath = I->second;
10838 return false;
10839}
10840
10841/// GVReference
10842/// ::= SummaryID
10843bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10844 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10845 if (!ReadOnly)
10846 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10847 if (parseToken(lltok::SummaryID, "expected GV ID"))
10848 return true;
10849
10850 GVId = Lex.getUIntVal();
10851 // Check if we already have a VI for this GV
10852 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10853 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10854 VI = NumberedValueInfos[GVId];
10855 } else
10856 // We will create a forward reference to the stored location.
10857 VI = ValueInfo(false, FwdVIRef);
10858
10859 if (ReadOnly)
10860 VI.setReadOnly();
10861 if (WriteOnly)
10862 VI.setWriteOnly();
10863 return false;
10864}
10865
10866/// OptionalAllocs
10867/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10868/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10869/// ',' MemProfs ')'
10870/// Version ::= UInt32
10871bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10872 assert(Lex.getKind() == lltok::kw_allocs);
10873 Lex.Lex();
10874
10875 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10876 parseToken(lltok::lparen, "expected '(' in allocs"))
10877 return true;
10878
10879 // parse each alloc
10880 do {
10881 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10882 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10883 parseToken(lltok::colon, "expected ':'") ||
10884 parseToken(lltok::lparen, "expected '(' in versions"))
10885 return true;
10886
10887 SmallVector<uint8_t> Versions;
10888 do {
10889 uint8_t V = 0;
10890 if (parseAllocType(V))
10891 return true;
10892 Versions.push_back(V);
10893 } while (EatIfPresent(lltok::comma));
10894
10895 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10896 parseToken(lltok::comma, "expected ',' in alloc"))
10897 return true;
10898
10899 std::vector<MIBInfo> MIBs;
10900 if (parseMemProfs(MIBs))
10901 return true;
10902
10903 Allocs.push_back({Versions, MIBs});
10904
10905 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10906 return true;
10907 } while (EatIfPresent(lltok::comma));
10908
10909 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10910 return true;
10911
10912 return false;
10913}
10914
10915/// MemProfs
10916/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10917/// MemProf ::= '(' 'type' ':' AllocType
10918/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10919/// StackId ::= UInt64
10920bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10921 assert(Lex.getKind() == lltok::kw_memProf);
10922 Lex.Lex();
10923
10924 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10925 parseToken(lltok::lparen, "expected '(' in memprof"))
10926 return true;
10927
10928 // parse each MIB
10929 do {
10930 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10931 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10932 parseToken(lltok::colon, "expected ':'"))
10933 return true;
10934
10935 uint8_t AllocType;
10936 if (parseAllocType(AllocType))
10937 return true;
10938
10939 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10940 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10941 parseToken(lltok::colon, "expected ':'") ||
10942 parseToken(lltok::lparen, "expected '(' in stackIds"))
10943 return true;
10944
10945 SmallVector<unsigned> StackIdIndices;
10946 // Combined index alloc records may not have a stack id list.
10947 if (Lex.getKind() != lltok::rparen) {
10948 do {
10949 uint64_t StackId = 0;
10950 if (parseUInt64(StackId))
10951 return true;
10952 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10953 } while (EatIfPresent(lltok::comma));
10954 }
10955
10956 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10957 return true;
10958
10959 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10960
10961 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10962 return true;
10963 } while (EatIfPresent(lltok::comma));
10964
10965 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10966 return true;
10967
10968 return false;
10969}
10970
10971/// AllocType
10972/// := ('none'|'notcold'|'cold'|'hot')
10973bool LLParser::parseAllocType(uint8_t &AllocType) {
10974 switch (Lex.getKind()) {
10975 case lltok::kw_none:
10977 break;
10978 case lltok::kw_notcold:
10980 break;
10981 case lltok::kw_cold:
10983 break;
10984 case lltok::kw_hot:
10985 AllocType = (uint8_t)AllocationType::Hot;
10986 break;
10987 default:
10988 return error(Lex.getLoc(), "invalid alloc type");
10989 }
10990 Lex.Lex();
10991 return false;
10992}
10993
10994/// OptionalCallsites
10995/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10996/// Callsite ::= '(' 'callee' ':' GVReference
10997/// ',' 'clones' ':' '(' Version [',' Version]* ')'
10998/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10999/// Version ::= UInt32
11000/// StackId ::= UInt64
11001bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11002 assert(Lex.getKind() == lltok::kw_callsites);
11003 Lex.Lex();
11004
11005 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11006 parseToken(lltok::lparen, "expected '(' in callsites"))
11007 return true;
11008
11009 IdToIndexMapType IdToIndexMap;
11010 // parse each callsite
11011 do {
11012 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11013 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11014 parseToken(lltok::colon, "expected ':'"))
11015 return true;
11016
11017 ValueInfo VI;
11018 unsigned GVId = 0;
11019 LocTy Loc = Lex.getLoc();
11020 if (!EatIfPresent(lltok::kw_null)) {
11021 if (parseGVReference(VI, GVId))
11022 return true;
11023 }
11024
11025 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11026 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11027 parseToken(lltok::colon, "expected ':'") ||
11028 parseToken(lltok::lparen, "expected '(' in clones"))
11029 return true;
11030
11031 SmallVector<unsigned> Clones;
11032 do {
11033 unsigned V = 0;
11034 if (parseUInt32(V))
11035 return true;
11036 Clones.push_back(V);
11037 } while (EatIfPresent(lltok::comma));
11038
11039 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11040 parseToken(lltok::comma, "expected ',' in callsite") ||
11041 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11042 parseToken(lltok::colon, "expected ':'") ||
11043 parseToken(lltok::lparen, "expected '(' in stackIds"))
11044 return true;
11045
11046 SmallVector<unsigned> StackIdIndices;
11047 // Synthesized callsite records will not have a stack id list.
11048 if (Lex.getKind() != lltok::rparen) {
11049 do {
11050 uint64_t StackId = 0;
11051 if (parseUInt64(StackId))
11052 return true;
11053 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11054 } while (EatIfPresent(lltok::comma));
11055 }
11056
11057 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11058 return true;
11059
11060 // Keep track of the Callsites array index needing a forward reference.
11061 // We will save the location of the ValueInfo needing an update, but
11062 // can only do so once the SmallVector is finalized.
11063 if (VI.getRef() == FwdVIRef)
11064 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11065 Callsites.push_back({VI, Clones, StackIdIndices});
11066
11067 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11068 return true;
11069 } while (EatIfPresent(lltok::comma));
11070
11071 // Now that the Callsites vector is finalized, it is safe to save the
11072 // locations of any forward GV references that need updating later.
11073 for (auto I : IdToIndexMap) {
11074 auto &Infos = ForwardRefValueInfos[I.first];
11075 for (auto P : I.second) {
11076 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11077 "Forward referenced ValueInfo expected to be empty");
11078 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11079 }
11080 }
11081
11082 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11083 return true;
11084
11085 return false;
11086}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:244
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:151
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:67
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static 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:1237
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:120
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:143
iterator begin() const
Definition ArrayRef.h:131
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:766
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:107
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:88
@ None
No attributes have been set.
Definition Attributes.h:90
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:367
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static 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:310
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool any() const
Definition FMF.h:56
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition Type.cpp:404
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:399
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:836
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:448
arg_iterator arg_begin()
Definition Function.h:866
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1038
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:274
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:598
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition Globals.cpp:655
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:245
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:93
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:251
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:228
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:524
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:566
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h: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:125
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:193
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:141
static MemoryEffectsBase writeOnly()
Definition ModRef.h:130
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:158
static MemoryEffectsBase none()
Definition ModRef.h:120
static MemoryEffectsBase unknown()
Definition ModRef.h:115
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:183
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:876
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h: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:414
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:620
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:704
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition Type.cpp:539
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:441
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:914
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:288
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:62
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:250
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:295
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:198
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:294
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:258
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:503
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
static constexpr uint64_t MaximumAlignment
Definition Value.h:830
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:598
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:631
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:703
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:765
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:220
MacinfoRecordType
Definition Dwarf.h:815
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:821
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:153
@ kw_riscv_vls_cc
Definition LLToken.h:189
@ kw_cxx_fast_tlscc
Definition LLToken.h:172
@ kw_extractvalue
Definition LLToken.h:364
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:499
@ kw_arm_apcscc
Definition LLToken.h:145
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:140
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:151
@ kw_provenance
Definition LLToken.h:220
@ kw_mustBeUnreachable
Definition LLToken.h:410
@ kw_internal
Definition LLToken.h:54
@ kw_no_sanitize_hwaddress
Definition LLToken.h:478
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:449
@ kw_canAutoHide
Definition LLToken.h:394
@ kw_alwaysInline
Definition LLToken.h:406
@ kw_insertelement
Definition LLToken.h:361
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:192
@ kw_inaccessiblememonly
Definition LLToken.h:213
@ kw_amdgpu_gfx
Definition LLToken.h:183
@ kw_getelementptr
Definition LLToken.h:358
@ kw_m68k_rtdcc
Definition LLToken.h:186
@ kw_preserve_nonecc
Definition LLToken.h:167
@ kw_x86_fastcallcc
Definition LLToken.h:141
@ kw_visibility
Definition LLToken.h:390
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:191
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:452
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:139
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:429
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:149
@ kw_amdgpu_kernel
Definition LLToken.h:182
@ kw_uselistorder
Definition LLToken.h:377
@ kw_blockcount
Definition LLToken.h:388
@ kw_notEligibleToImport
Definition LLToken.h:391
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:143
@ kw_ptx_device
Definition LLToken.h:157
@ kw_personality
Definition LLToken.h:333
@ DwarfEnumKind
Definition LLToken.h:512
@ kw_declaration
Definition LLToken.h:397
@ DwarfAttEncoding
Definition LLToken.h:498
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:158
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:409
@ kw_x86_intrcc
Definition LLToken.h:169
@ kw_addrspacecast
Definition LLToken.h:328
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:496
@ kw_x86_thiscallcc
Definition LLToken.h:142
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:190
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:378
@ NameTableKind
Definition LLToken.h:504
@ kw_inlineBits
Definition LLToken.h:447
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:212
@ kw_blockaddress
Definition LLToken.h:366
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:184
@ kw_landingpad
Definition LLToken.h:332
@ kw_aarch64_vector_pcs
Definition LLToken.h:148
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:428
@ FixedPointKind
Definition LLToken.h:505
@ kw_ptx_kernel
Definition LLToken.h:156
@ kw_extractelement
Definition LLToken.h:360
@ kw_branchFunnel
Definition LLToken.h:453
@ kw_typeidCompatibleVTable
Definition LLToken.h:434
@ kw_vTableFuncs
Definition LLToken.h:420
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:427
@ kw_no_sanitize_address
Definition LLToken.h:475
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:214
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:481
@ DwarfSourceLangName
Definition LLToken.h:501
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:181
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:346
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:146
@ kw_read_provenance
Definition LLToken.h:221
@ kw_cleanuppad
Definition LLToken.h:349
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:454
@ kw_swifttailcc
Definition LLToken.h:164
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:426
@ kw_attributes
Definition LLToken.h:195
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:457
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:443
@ kw_nodeduplicate
Definition LLToken.h:250
@ kw_avr_signalcc
Definition LLToken.h:155
@ kw_exactmatch
Definition LLToken.h:248
@ kw_unreachable
Definition LLToken.h:344
@ kw_intel_ocl_bicc
Definition LLToken.h:138
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:404
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:150
@ kw_preserve_allcc
Definition LLToken.h:166
@ kw_importType
Definition LLToken.h:395
@ kw_cleanupret
Definition LLToken.h:345
@ kw_shufflevector
Definition LLToken.h:362
@ kw_riscv_vector_cc
Definition LLToken.h:188
@ kw_avr_intrcc
Definition LLToken.h:154
@ kw_definition
Definition LLToken.h:396
@ kw_virtualConstProp
Definition LLToken.h:459
@ kw_vcall_visibility
Definition LLToken.h:448
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:208
@ kw_preserve_mostcc
Definition LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:147
@ kw_typeTestRes
Definition LLToken.h:436
@ kw_x86_regcallcc
Definition LLToken.h:144
@ kw_typeIdInfo
Definition LLToken.h:424
@ kw_amdgpu_cs_chain
Definition LLToken.h:180
@ kw_dso_local_equivalent
Definition LLToken.h:367
@ kw_x86_64_sysvcc
Definition LLToken.h:160
@ DbgRecordType
Definition LLToken.h:511
@ kw_address_is_null
Definition LLToken.h:219
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:152
@ kw_uniqueRetVal
Definition LLToken.h:458
@ kw_insertvalue
Definition LLToken.h:365
@ kw_indirectbr
Definition LLToken.h:341
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:577
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1655
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h: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:296
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:148
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:151
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:150
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h: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:305
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h: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
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h: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:315
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:33
std::map< unsigned, Type * > Types
Definition SlotMapping.h:37
StringMap< Type * > NamedTypes
Definition SlotMapping.h:36
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:35
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:34
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h: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.