LLVM 23.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/AutoUpgrade.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Comdat.h"
30#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalIFunc.h"
36#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
63 "allow-incomplete-ir", cl::init(false), cl::Hidden,
65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
67
68static std::string getTypeString(Type *T) {
69 std::string Result;
70 raw_string_ostream Tmp(Result);
71 Tmp << *T;
72 return Tmp.str();
73}
74
75/// Run: module ::= toplevelentity*
76bool LLParser::Run(bool UpgradeDebugInfo,
77 DataLayoutCallbackTy DataLayoutCallback) {
78 // Prime the lexer.
79 Lex.Lex();
80
81 if (Context.shouldDiscardValueNames())
82 return error(
83 Lex.getLoc(),
84 "Can't read textual IR with a Context that discards named Values");
85
86 if (M) {
87 if (parseTargetDefinitions(DataLayoutCallback))
88 return true;
89 }
90
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
92 validateEndOfIndex();
93}
94
96 const SlotMapping *Slots) {
97 restoreParsingState(Slots);
98 Lex.Lex();
99
100 Type *Ty = nullptr;
101 if (parseType(Ty) || parseConstantValue(Ty, C))
102 return true;
103 if (Lex.getKind() != lltok::Eof)
104 return error(Lex.getLoc(), "expected end of string");
105 return false;
106}
107
109 const SlotMapping *Slots) {
110 restoreParsingState(Slots);
111 Lex.Lex();
112
113 Read = 0;
114 SMLoc Start = Lex.getLoc();
115 Ty = nullptr;
116 if (parseType(Ty))
117 return true;
118 SMLoc End = Lex.getLoc();
119 Read = End.getPointer() - Start.getPointer();
120
121 return false;
122}
123
125 const SlotMapping *Slots) {
126 restoreParsingState(Slots);
127 Lex.Lex();
128
129 Read = 0;
130 SMLoc Start = Lex.getLoc();
131 Result = nullptr;
132 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
133 SMLoc End = Lex.getLoc();
134 Read = End.getPointer() - Start.getPointer();
135
136 return Status;
137}
138
139void LLParser::restoreParsingState(const SlotMapping *Slots) {
140 if (!Slots)
141 return;
142 NumberedVals = Slots->GlobalValues;
143 NumberedMetadata = Slots->MetadataNodes;
144 for (const auto &I : Slots->NamedTypes)
145 NamedTypes.insert(
146 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
147 for (const auto &I : Slots->Types)
148 NumberedTypes.insert(
149 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
150}
151
153 // White-list intrinsics that are safe to drop.
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
156 return;
157
159 for (Value *V : II->args())
160 if (auto *MV = dyn_cast<MetadataAsValue>(V))
161 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
162 if (MD->isTemporary())
163 MVs.push_back(MV);
164
165 if (!MVs.empty()) {
166 assert(II->use_empty() && "Cannot have uses");
167 II->eraseFromParent();
168
169 // Also remove no longer used MetadataAsValue wrappers.
170 for (MetadataAsValue *MV : MVs)
171 if (MV->use_empty())
172 delete MV;
173 }
174}
175
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
178 for (Function &F : *M) {
179 F.eraseMetadataIf(Pred);
180 for (Instruction &I : make_early_inc_range(instructions(F))) {
181 I.eraseMetadataIf(Pred);
182
183 if (auto *II = dyn_cast<IntrinsicInst>(&I))
185 }
186 }
187
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
190
191 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
192 // Check whether there is only a single use left, which would be in our
193 // own NumberedMetadata.
194 if (Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(ID);
196 ForwardRefMDNodes.erase(ID);
197 }
198 }
199}
200
201/// validateEndOfModule - Do final validity and basic correctness checks at the
202/// end of the module.
203bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
204 if (!M)
205 return false;
206
207 // We should have already returned an error if we observed both intrinsics and
208 // records in this IR.
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
211
212 // Handle any function attribute group forward references.
213 for (const auto &RAG : ForwardRefAttrGroups) {
214 Value *V = RAG.first;
215 const std::vector<unsigned> &Attrs = RAG.second;
216 AttrBuilder B(Context);
217
218 for (const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(Attr);
220 if (R != NumberedAttrBuilders.end())
221 B.merge(R->second);
222 }
223
224 if (Function *Fn = dyn_cast<Function>(V)) {
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(Context);
228
229 FnAttrs.merge(B);
230
231 // If the alignment was parsed as an attribute, move to the alignment
232 // field.
233 if (MaybeAlign A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*A);
235 FnAttrs.removeAttribute(Attribute::Alignment);
236 }
237
238 AS = AS.addFnAttributes(Context, FnAttrs);
239 Fn->setAttributes(AS);
240 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(Context);
244 FnAttrs.merge(B);
245 AS = AS.addFnAttributes(Context, FnAttrs);
246 CI->setAttributes(AS);
247 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
248 AttributeList AS = II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(Context);
251 FnAttrs.merge(B);
252 AS = AS.addFnAttributes(Context, FnAttrs);
253 II->setAttributes(AS);
254 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(Context);
258 FnAttrs.merge(B);
259 AS = AS.addFnAttributes(Context, FnAttrs);
260 CBI->setAttributes(AS);
261 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
262 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
263 Attrs.merge(B);
264 GV->setAttributes(AttributeSet::get(Context,Attrs));
265 } else {
266 llvm_unreachable("invalid object with forward attribute group reference");
267 }
268 }
269
270 // If there are entries in ForwardRefBlockAddresses at this point, the
271 // function was never defined.
272 if (!ForwardRefBlockAddresses.empty())
273 return error(ForwardRefBlockAddresses.begin()->first.Loc,
274 "expected function name in blockaddress");
275
276 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV = nullptr;
279 if (GVRef.Kind == ValID::t_GlobalName) {
280 GV = M->getNamedValue(GVRef.StrVal);
281 } else {
282 GV = NumberedVals.get(GVRef.UIntVal);
283 }
284
285 if (!GV)
286 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
287 "' referenced by dso_local_equivalent");
288
289 if (!GV->getValueType()->isFunctionTy())
290 return error(GVRef.Loc,
291 "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
293
294 auto *Equiv = DSOLocalEquivalent::get(GV);
295 FwdRef->replaceAllUsesWith(Equiv);
296 FwdRef->eraseFromParent();
297 return false;
298 };
299
300 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
301 // point, they are references after the function was defined. Resolve those
302 // now.
303 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 return true;
306 }
307 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
309 return true;
310 }
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
313
314 for (const auto &NT : NumberedTypes)
315 if (NT.second.second.isValid())
316 return error(NT.second.second,
317 "use of undefined type '%" + Twine(NT.first) + "'");
318
319 for (const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(TypeInfo.second,
322 "use of undefined type named '" + Name + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 // Automatically create declarations for intrinsics. Intrinsics can only
333 // be called directly, so the call function type directly determines the
334 // declaration function type.
335 //
336 // Additionally, automatically add the required mangling suffix to the
337 // intrinsic name. This means that we may replace a single forward
338 // declaration with multiple functions here.
339 for (Use &U : make_early_inc_range(Info.first->uses())) {
340 auto *CB = dyn_cast<CallBase>(U.getUser());
341 if (!CB || !CB->isCallee(&U))
342 return error(Info.second, "intrinsic can only be used as callee");
343
344 SmallVector<Type *> OverloadTys;
345 if (IID != Intrinsic::not_intrinsic &&
346 Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
347 OverloadTys)) {
348 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
349 } else {
350 // Try to upgrade the intrinsic.
351 Function *TmpF = Function::Create(CB->getFunctionType(),
353 Function *NewF = nullptr;
354 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
355 if (IID == Intrinsic::not_intrinsic)
356 return error(Info.second, "unknown intrinsic '" + Name + "'");
357 return error(Info.second, "invalid intrinsic signature");
358 }
359
360 U.set(TmpF);
361 UpgradeIntrinsicCall(CB, NewF);
362 if (TmpF->use_empty())
363 TmpF->eraseFromParent();
364 }
365 }
366
367 Info.first->eraseFromParent();
368 ForwardRefVals.erase(Name);
369 continue;
370 }
371
372 // If incomplete IR is allowed, also add declarations for
373 // non-intrinsics.
375 continue;
376
377 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
378 FunctionType *FTy = nullptr;
379 for (Use &U : V->uses()) {
380 auto *CB = dyn_cast<CallBase>(U.getUser());
381 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
382 return nullptr;
383 FTy = CB->getFunctionType();
384 }
385 return FTy;
386 };
387
388 // First check whether this global is only used in calls with the same
389 // type, in which case we'll insert a function. Otherwise, fall back to
390 // using a dummy i8 type.
391 Type *Ty = GetCommonFunctionType(Info.first);
392 if (!Ty)
393 Ty = Type::getInt8Ty(Context);
394
395 GlobalValue *GV;
396 if (auto *FTy = dyn_cast<FunctionType>(Ty))
398 else
399 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
401 /*Initializer*/ nullptr, Name);
402 Info.first->replaceAllUsesWith(GV);
403 Info.first->eraseFromParent();
404 ForwardRefVals.erase(Name);
405 }
406
407 if (!ForwardRefVals.empty())
408 return error(ForwardRefVals.begin()->second.second,
409 "use of undefined value '@" + ForwardRefVals.begin()->first +
410 "'");
411
412 if (!ForwardRefValIDs.empty())
413 return error(ForwardRefValIDs.begin()->second.second,
414 "use of undefined value '@" +
415 Twine(ForwardRefValIDs.begin()->first) + "'");
416
417 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
418 dropUnknownMetadataReferences();
419
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) + "'");
424
425 // Resolve metadata cycles.
426 for (auto &N : NumberedMetadata) {
427 if (N.second && !N.second->isResolved())
428 N.second->resolveCycles();
429 }
430
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 std::optional<uint64_t> Bytes;
1611 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1612 return true;
1613 assert(Bytes.has_value());
1614 B.addDereferenceableAttr(Bytes.value());
1615 return false;
1616 }
1617 case Attribute::DeadOnReturn: {
1618 std::optional<uint64_t> Bytes;
1619 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1620 /*ErrorNoBytes=*/false))
1621 return true;
1622 if (Bytes.has_value()) {
1623 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1624 } else {
1625 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1626 }
1627 return false;
1628 }
1629 case Attribute::DereferenceableOrNull: {
1630 std::optional<uint64_t> Bytes;
1631 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1632 return true;
1633 assert(Bytes.has_value());
1634 B.addDereferenceableOrNullAttr(Bytes.value());
1635 return false;
1636 }
1637 case Attribute::UWTable: {
1639 if (parseOptionalUWTableKind(Kind))
1640 return true;
1641 B.addUWTableAttr(Kind);
1642 return false;
1643 }
1644 case Attribute::AllocKind: {
1646 if (parseAllocKind(Kind))
1647 return true;
1648 B.addAllocKindAttr(Kind);
1649 return false;
1650 }
1651 case Attribute::Memory: {
1652 std::optional<MemoryEffects> ME = parseMemoryAttr();
1653 if (!ME)
1654 return true;
1655 B.addMemoryAttr(*ME);
1656 return false;
1657 }
1658 case Attribute::NoFPClass: {
1659 if (FPClassTest NoFPClass =
1660 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1661 B.addNoFPClassAttr(NoFPClass);
1662 return false;
1663 }
1664
1665 return true;
1666 }
1667 case Attribute::Range:
1668 return parseRangeAttr(B);
1669 case Attribute::Initializes:
1670 return parseInitializesAttr(B);
1671 case Attribute::Captures:
1672 return parseCapturesAttr(B);
1673 default:
1674 B.addAttribute(Attr);
1675 Lex.Lex();
1676 return false;
1677 }
1678}
1679
1681 switch (Kind) {
1682 case lltok::kw_readnone:
1683 ME &= MemoryEffects::none();
1684 return true;
1685 case lltok::kw_readonly:
1687 return true;
1688 case lltok::kw_writeonly:
1690 return true;
1693 return true;
1696 return true;
1699 return true;
1700 default:
1701 return false;
1702 }
1703}
1704
1705/// parseFnAttributeValuePairs
1706/// ::= <attr> | <attr> '=' <value>
1707bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1708 std::vector<unsigned> &FwdRefAttrGrps,
1709 bool InAttrGrp, LocTy &BuiltinLoc) {
1710 bool HaveError = false;
1711
1712 B.clear();
1713
1715 while (true) {
1716 lltok::Kind Token = Lex.getKind();
1717 if (Token == lltok::rbrace)
1718 break; // Finished.
1719
1720 if (Token == lltok::StringConstant) {
1721 if (parseStringAttribute(B))
1722 return true;
1723 continue;
1724 }
1725
1726 if (Token == lltok::AttrGrpID) {
1727 // Allow a function to reference an attribute group:
1728 //
1729 // define void @foo() #1 { ... }
1730 if (InAttrGrp) {
1731 HaveError |= error(
1732 Lex.getLoc(),
1733 "cannot have an attribute group reference in an attribute group");
1734 } else {
1735 // Save the reference to the attribute group. We'll fill it in later.
1736 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1737 }
1738 Lex.Lex();
1739 continue;
1740 }
1741
1742 SMLoc Loc = Lex.getLoc();
1743 if (Token == lltok::kw_builtin)
1744 BuiltinLoc = Loc;
1745
1746 if (upgradeMemoryAttr(ME, Token)) {
1747 Lex.Lex();
1748 continue;
1749 }
1750
1752 if (Attr == Attribute::None) {
1753 if (!InAttrGrp)
1754 break;
1755 return error(Lex.getLoc(), "unterminated attribute group");
1756 }
1757
1758 if (parseEnumAttribute(Attr, B, InAttrGrp))
1759 return true;
1760
1761 // As a hack, we allow function alignment to be initially parsed as an
1762 // attribute on a function declaration/definition or added to an attribute
1763 // group and later moved to the alignment field.
1764 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1765 HaveError |= error(Loc, "this attribute does not apply to functions");
1766 }
1767
1768 if (ME != MemoryEffects::unknown())
1769 B.addMemoryAttr(ME);
1770 return HaveError;
1771}
1772
1773//===----------------------------------------------------------------------===//
1774// GlobalValue Reference/Resolution Routines.
1775//===----------------------------------------------------------------------===//
1776
1778 // The used global type does not matter. We will later RAUW it with a
1779 // global/function of the correct type.
1780 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1783 PTy->getAddressSpace());
1784}
1785
1786Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1787 Value *Val) {
1788 Type *ValTy = Val->getType();
1789 if (ValTy == Ty)
1790 return Val;
1791 if (Ty->isLabelTy())
1792 error(Loc, "'" + Name + "' is not a basic block");
1793 else
1794 error(Loc, "'" + Name + "' defined with type '" +
1795 getTypeString(Val->getType()) + "' but expected '" +
1796 getTypeString(Ty) + "'");
1797 return nullptr;
1798}
1799
1800/// getGlobalVal - Get a value with the specified name or ID, creating a
1801/// forward reference record if needed. This can return null if the value
1802/// exists but does not have the right type.
1803GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1804 LocTy Loc) {
1806 if (!PTy) {
1807 error(Loc, "global variable reference must have pointer type");
1808 return nullptr;
1809 }
1810
1811 // Look this name up in the normal function symbol table.
1812 GlobalValue *Val =
1813 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1814
1815 // If this is a forward reference for the value, see if we already created a
1816 // forward ref record.
1817 if (!Val) {
1818 auto I = ForwardRefVals.find(Name);
1819 if (I != ForwardRefVals.end())
1820 Val = I->second.first;
1821 }
1822
1823 // If we have the value in the symbol table or fwd-ref table, return it.
1824 if (Val)
1826 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1827
1828 // Otherwise, create a new forward reference for this value and remember it.
1829 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1830 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1831 return FwdVal;
1832}
1833
1834GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1836 if (!PTy) {
1837 error(Loc, "global variable reference must have pointer type");
1838 return nullptr;
1839 }
1840
1841 GlobalValue *Val = NumberedVals.get(ID);
1842
1843 // If this is a forward reference for the value, see if we already created a
1844 // forward ref record.
1845 if (!Val) {
1846 auto I = ForwardRefValIDs.find(ID);
1847 if (I != ForwardRefValIDs.end())
1848 Val = I->second.first;
1849 }
1850
1851 // If we have the value in the symbol table or fwd-ref table, return it.
1852 if (Val)
1854 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1855
1856 // Otherwise, create a new forward reference for this value and remember it.
1857 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1858 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1859 return FwdVal;
1860}
1861
1862//===----------------------------------------------------------------------===//
1863// Comdat Reference/Resolution Routines.
1864//===----------------------------------------------------------------------===//
1865
1866Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1867 // Look this name up in the comdat symbol table.
1868 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1869 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1870 if (I != ComdatSymTab.end())
1871 return &I->second;
1872
1873 // Otherwise, create a new forward reference for this value and remember it.
1874 Comdat *C = M->getOrInsertComdat(Name);
1875 ForwardRefComdats[Name] = Loc;
1876 return C;
1877}
1878
1879//===----------------------------------------------------------------------===//
1880// Helper Routines.
1881//===----------------------------------------------------------------------===//
1882
1883/// parseToken - If the current token has the specified kind, eat it and return
1884/// success. Otherwise, emit the specified error and return failure.
1885bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1886 if (Lex.getKind() != T)
1887 return tokError(ErrMsg);
1888 Lex.Lex();
1889 return false;
1890}
1891
1892/// parseStringConstant
1893/// ::= StringConstant
1894bool LLParser::parseStringConstant(std::string &Result) {
1895 if (Lex.getKind() != lltok::StringConstant)
1896 return tokError("expected string constant");
1897 Result = Lex.getStrVal();
1898 Lex.Lex();
1899 return false;
1900}
1901
1902/// parseUInt32
1903/// ::= uint32
1904bool LLParser::parseUInt32(uint32_t &Val) {
1905 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1906 return tokError("expected integer");
1907 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1908 if (Val64 != unsigned(Val64))
1909 return tokError("expected 32-bit integer (too large)");
1910 Val = Val64;
1911 Lex.Lex();
1912 return false;
1913}
1914
1915/// parseUInt64
1916/// ::= uint64
1917bool LLParser::parseUInt64(uint64_t &Val) {
1918 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1919 return tokError("expected integer");
1920 Val = Lex.getAPSIntVal().getLimitedValue();
1921 Lex.Lex();
1922 return false;
1923}
1924
1925/// parseTLSModel
1926/// := 'localdynamic'
1927/// := 'initialexec'
1928/// := 'localexec'
1929bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1930 switch (Lex.getKind()) {
1931 default:
1932 return tokError("expected localdynamic, initialexec or localexec");
1935 break;
1938 break;
1941 break;
1942 }
1943
1944 Lex.Lex();
1945 return false;
1946}
1947
1948/// parseOptionalThreadLocal
1949/// := /*empty*/
1950/// := 'thread_local'
1951/// := 'thread_local' '(' tlsmodel ')'
1952bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1954 if (!EatIfPresent(lltok::kw_thread_local))
1955 return false;
1956
1958 if (Lex.getKind() == lltok::lparen) {
1959 Lex.Lex();
1960 return parseTLSModel(TLM) ||
1961 parseToken(lltok::rparen, "expected ')' after thread local model");
1962 }
1963 return false;
1964}
1965
1966/// parseOptionalAddrSpace
1967/// := /*empty*/
1968/// := 'addrspace' '(' uint32 ')'
1969bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1970 AddrSpace = DefaultAS;
1971 if (!EatIfPresent(lltok::kw_addrspace))
1972 return false;
1973
1974 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1975 if (Lex.getKind() == lltok::StringConstant) {
1976 const std::string &AddrSpaceStr = Lex.getStrVal();
1977 if (AddrSpaceStr == "A") {
1978 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1979 } else if (AddrSpaceStr == "G") {
1980 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1981 } else if (AddrSpaceStr == "P") {
1982 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1983 } else if (std::optional<unsigned> AS =
1984 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
1985 AddrSpace = *AS;
1986 } else {
1987 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1988 }
1989 Lex.Lex();
1990 return false;
1991 }
1992 if (Lex.getKind() != lltok::APSInt)
1993 return tokError("expected integer or string constant");
1994 SMLoc Loc = Lex.getLoc();
1995 if (parseUInt32(AddrSpace))
1996 return true;
1997 if (!isUInt<24>(AddrSpace))
1998 return error(Loc, "invalid address space, must be a 24-bit integer");
1999 return false;
2000 };
2001
2002 return parseToken(lltok::lparen, "expected '(' in address space") ||
2003 ParseAddrspaceValue(AddrSpace) ||
2004 parseToken(lltok::rparen, "expected ')' in address space");
2005}
2006
2007/// parseStringAttribute
2008/// := StringConstant
2009/// := StringConstant '=' StringConstant
2010bool LLParser::parseStringAttribute(AttrBuilder &B) {
2011 std::string Attr = Lex.getStrVal();
2012 Lex.Lex();
2013 std::string Val;
2014 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2015 return true;
2016 B.addAttribute(Attr, Val);
2017 return false;
2018}
2019
2020/// Parse a potentially empty list of parameter or return attributes.
2021bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2022 bool HaveError = false;
2023
2024 B.clear();
2025
2026 while (true) {
2027 lltok::Kind Token = Lex.getKind();
2028 if (Token == lltok::StringConstant) {
2029 if (parseStringAttribute(B))
2030 return true;
2031 continue;
2032 }
2033
2034 if (Token == lltok::kw_nocapture) {
2035 Lex.Lex();
2036 B.addCapturesAttr(CaptureInfo::none());
2037 continue;
2038 }
2039
2040 SMLoc Loc = Lex.getLoc();
2042 if (Attr == Attribute::None)
2043 return HaveError;
2044
2045 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2046 return true;
2047
2048 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2049 HaveError |= error(Loc, "this attribute does not apply to parameters");
2050 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2051 HaveError |= error(Loc, "this attribute does not apply to return values");
2052 }
2053}
2054
2055static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2056 HasLinkage = true;
2057 switch (Kind) {
2058 default:
2059 HasLinkage = false;
2061 case lltok::kw_private:
2063 case lltok::kw_internal:
2065 case lltok::kw_weak:
2067 case lltok::kw_weak_odr:
2069 case lltok::kw_linkonce:
2077 case lltok::kw_common:
2081 case lltok::kw_external:
2083 }
2084}
2085
2086/// parseOptionalLinkage
2087/// ::= /*empty*/
2088/// ::= 'private'
2089/// ::= 'internal'
2090/// ::= 'weak'
2091/// ::= 'weak_odr'
2092/// ::= 'linkonce'
2093/// ::= 'linkonce_odr'
2094/// ::= 'available_externally'
2095/// ::= 'appending'
2096/// ::= 'common'
2097/// ::= 'extern_weak'
2098/// ::= 'external'
2099bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2100 unsigned &Visibility,
2101 unsigned &DLLStorageClass, bool &DSOLocal) {
2102 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2103 if (HasLinkage)
2104 Lex.Lex();
2105 parseOptionalDSOLocal(DSOLocal);
2106 parseOptionalVisibility(Visibility);
2107 parseOptionalDLLStorageClass(DLLStorageClass);
2108
2109 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2110 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2111 }
2112
2113 return false;
2114}
2115
2116void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2117 switch (Lex.getKind()) {
2118 default:
2119 DSOLocal = false;
2120 break;
2122 DSOLocal = true;
2123 Lex.Lex();
2124 break;
2126 DSOLocal = false;
2127 Lex.Lex();
2128 break;
2129 }
2130}
2131
2132/// parseOptionalVisibility
2133/// ::= /*empty*/
2134/// ::= 'default'
2135/// ::= 'hidden'
2136/// ::= 'protected'
2137///
2138void LLParser::parseOptionalVisibility(unsigned &Res) {
2139 switch (Lex.getKind()) {
2140 default:
2142 return;
2143 case lltok::kw_default:
2145 break;
2146 case lltok::kw_hidden:
2148 break;
2151 break;
2152 }
2153 Lex.Lex();
2154}
2155
2156bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2158 switch (Kind) {
2159 default:
2160 return tokError("unknown import kind. Expect definition or declaration.");
2163 return false;
2166 return false;
2167 }
2168}
2169
2170/// parseOptionalDLLStorageClass
2171/// ::= /*empty*/
2172/// ::= 'dllimport'
2173/// ::= 'dllexport'
2174///
2175void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2176 switch (Lex.getKind()) {
2177 default:
2179 return;
2182 break;
2185 break;
2186 }
2187 Lex.Lex();
2188}
2189
2190/// parseOptionalCallingConv
2191/// ::= /*empty*/
2192/// ::= 'ccc'
2193/// ::= 'fastcc'
2194/// ::= 'intel_ocl_bicc'
2195/// ::= 'coldcc'
2196/// ::= 'cfguard_checkcc'
2197/// ::= 'x86_stdcallcc'
2198/// ::= 'x86_fastcallcc'
2199/// ::= 'x86_thiscallcc'
2200/// ::= 'x86_vectorcallcc'
2201/// ::= 'arm_apcscc'
2202/// ::= 'arm_aapcscc'
2203/// ::= 'arm_aapcs_vfpcc'
2204/// ::= 'aarch64_vector_pcs'
2205/// ::= 'aarch64_sve_vector_pcs'
2206/// ::= 'aarch64_sme_preservemost_from_x0'
2207/// ::= 'aarch64_sme_preservemost_from_x1'
2208/// ::= 'aarch64_sme_preservemost_from_x2'
2209/// ::= 'msp430_intrcc'
2210/// ::= 'avr_intrcc'
2211/// ::= 'avr_signalcc'
2212/// ::= 'ptx_kernel'
2213/// ::= 'ptx_device'
2214/// ::= 'spir_func'
2215/// ::= 'spir_kernel'
2216/// ::= 'x86_64_sysvcc'
2217/// ::= 'win64cc'
2218/// ::= 'anyregcc'
2219/// ::= 'preserve_mostcc'
2220/// ::= 'preserve_allcc'
2221/// ::= 'preserve_nonecc'
2222/// ::= 'ghccc'
2223/// ::= 'swiftcc'
2224/// ::= 'swifttailcc'
2225/// ::= 'x86_intrcc'
2226/// ::= 'hhvmcc'
2227/// ::= 'hhvm_ccc'
2228/// ::= 'cxx_fast_tlscc'
2229/// ::= 'amdgpu_vs'
2230/// ::= 'amdgpu_ls'
2231/// ::= 'amdgpu_hs'
2232/// ::= 'amdgpu_es'
2233/// ::= 'amdgpu_gs'
2234/// ::= 'amdgpu_ps'
2235/// ::= 'amdgpu_cs'
2236/// ::= 'amdgpu_cs_chain'
2237/// ::= 'amdgpu_cs_chain_preserve'
2238/// ::= 'amdgpu_kernel'
2239/// ::= 'tailcc'
2240/// ::= 'm68k_rtdcc'
2241/// ::= 'graalcc'
2242/// ::= 'riscv_vector_cc'
2243/// ::= 'riscv_vls_cc'
2244/// ::= 'cc' UINT
2245///
2246bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2247 switch (Lex.getKind()) {
2248 default: CC = CallingConv::C; return false;
2249 case lltok::kw_ccc: CC = CallingConv::C; break;
2250 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2251 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2264 break;
2267 break;
2270 break;
2273 break;
2283 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2284 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2288 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2289 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2292 case lltok::kw_hhvmcc:
2294 break;
2295 case lltok::kw_hhvm_ccc:
2297 break;
2309 break;
2312 break;
2316 break;
2317 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2319 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2322 break;
2324 // Default ABI_VLEN
2326 Lex.Lex();
2327 if (!EatIfPresent(lltok::lparen))
2328 break;
2329 uint32_t ABIVlen;
2330 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2331 return true;
2332 switch (ABIVlen) {
2333 default:
2334 return tokError("unknown RISC-V ABI VLEN");
2335#define CC_VLS_CASE(ABIVlen) \
2336 case ABIVlen: \
2337 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2338 break;
2339 CC_VLS_CASE(32)
2340 CC_VLS_CASE(64)
2341 CC_VLS_CASE(128)
2342 CC_VLS_CASE(256)
2343 CC_VLS_CASE(512)
2344 CC_VLS_CASE(1024)
2345 CC_VLS_CASE(2048)
2346 CC_VLS_CASE(4096)
2347 CC_VLS_CASE(8192)
2348 CC_VLS_CASE(16384)
2349 CC_VLS_CASE(32768)
2350 CC_VLS_CASE(65536)
2351#undef CC_VLS_CASE
2352 }
2353 return false;
2356 break;
2359 break;
2362 break;
2363 case lltok::kw_cc: {
2364 Lex.Lex();
2365 return parseUInt32(CC);
2366 }
2367 }
2368
2369 Lex.Lex();
2370 return false;
2371}
2372
2373/// parseMetadataAttachment
2374/// ::= !dbg !42
2375bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2376 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2377
2378 std::string Name = Lex.getStrVal();
2379 Kind = M->getMDKindID(Name);
2380 Lex.Lex();
2381
2382 return parseMDNode(MD);
2383}
2384
2385/// parseInstructionMetadata
2386/// ::= !dbg !42 (',' !dbg !57)*
2387bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2388 do {
2389 if (Lex.getKind() != lltok::MetadataVar)
2390 return tokError("expected metadata after comma");
2391
2392 unsigned MDK;
2393 MDNode *N;
2394 if (parseMetadataAttachment(MDK, N))
2395 return true;
2396
2397 if (MDK == LLVMContext::MD_DIAssignID)
2398 TempDIAssignIDAttachments[N].push_back(&Inst);
2399 else
2400 Inst.setMetadata(MDK, N);
2401
2402 if (MDK == LLVMContext::MD_tbaa)
2403 InstsWithTBAATag.push_back(&Inst);
2404
2405 // If this is the end of the list, we're done.
2406 } while (EatIfPresent(lltok::comma));
2407 return false;
2408}
2409
2410/// parseGlobalObjectMetadataAttachment
2411/// ::= !dbg !57
2412bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2413 unsigned MDK;
2414 MDNode *N;
2415 if (parseMetadataAttachment(MDK, N))
2416 return true;
2417
2418 GO.addMetadata(MDK, *N);
2419 return false;
2420}
2421
2422/// parseOptionalFunctionMetadata
2423/// ::= (!dbg !57)*
2424bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2425 while (Lex.getKind() == lltok::MetadataVar)
2426 if (parseGlobalObjectMetadataAttachment(F))
2427 return true;
2428 return false;
2429}
2430
2431/// parseOptionalAlignment
2432/// ::= /* empty */
2433/// ::= 'align' 4
2434bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2435 Alignment = std::nullopt;
2436 if (!EatIfPresent(lltok::kw_align))
2437 return false;
2438 LocTy AlignLoc = Lex.getLoc();
2439 uint64_t Value = 0;
2440
2441 LocTy ParenLoc = Lex.getLoc();
2442 bool HaveParens = false;
2443 if (AllowParens) {
2444 if (EatIfPresent(lltok::lparen))
2445 HaveParens = true;
2446 }
2447
2448 if (parseUInt64(Value))
2449 return true;
2450
2451 if (HaveParens && !EatIfPresent(lltok::rparen))
2452 return error(ParenLoc, "expected ')'");
2453
2454 if (!isPowerOf2_64(Value))
2455 return error(AlignLoc, "alignment is not a power of two");
2457 return error(AlignLoc, "huge alignments are not supported yet");
2458 Alignment = Align(Value);
2459 return false;
2460}
2461
2462/// parseOptionalCodeModel
2463/// ::= /* empty */
2464/// ::= 'code_model' "large"
2465bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2466 Lex.Lex();
2467 auto StrVal = Lex.getStrVal();
2468 auto ErrMsg = "expected global code model string";
2469 if (StrVal == "tiny")
2470 model = CodeModel::Tiny;
2471 else if (StrVal == "small")
2472 model = CodeModel::Small;
2473 else if (StrVal == "kernel")
2474 model = CodeModel::Kernel;
2475 else if (StrVal == "medium")
2476 model = CodeModel::Medium;
2477 else if (StrVal == "large")
2478 model = CodeModel::Large;
2479 else
2480 return tokError(ErrMsg);
2481 if (parseToken(lltok::StringConstant, ErrMsg))
2482 return true;
2483 return false;
2484}
2485
2486/// parseOptionalAttrBytes
2487/// ::= /* empty */
2488/// ::= AttrKind '(' 4 ')'
2489///
2490/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2491/// 'dead_on_return'
2492bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2493 std::optional<uint64_t> &Bytes,
2494 bool ErrorNoBytes) {
2495 assert((AttrKind == lltok::kw_dereferenceable ||
2496 AttrKind == lltok::kw_dereferenceable_or_null ||
2497 AttrKind == lltok::kw_dead_on_return) &&
2498 "contract!");
2499
2500 Bytes = 0;
2501 if (!EatIfPresent(AttrKind))
2502 return false;
2503 LocTy ParenLoc = Lex.getLoc();
2504 if (!EatIfPresent(lltok::lparen)) {
2505 if (ErrorNoBytes)
2506 return error(ParenLoc, "expected '('");
2507 Bytes = std::nullopt;
2508 return false;
2509 }
2510 LocTy DerefLoc = Lex.getLoc();
2511 if (parseUInt64(Bytes.value()))
2512 return true;
2513 ParenLoc = Lex.getLoc();
2514 if (!EatIfPresent(lltok::rparen))
2515 return error(ParenLoc, "expected ')'");
2516 if (!Bytes.value())
2517 return error(DerefLoc, "byte count specified must be non-zero");
2518 return false;
2519}
2520
2521bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2522 Lex.Lex();
2524 if (!EatIfPresent(lltok::lparen))
2525 return false;
2526 LocTy KindLoc = Lex.getLoc();
2527 if (Lex.getKind() == lltok::kw_sync)
2529 else if (Lex.getKind() == lltok::kw_async)
2531 else
2532 return error(KindLoc, "expected unwind table kind");
2533 Lex.Lex();
2534 return parseToken(lltok::rparen, "expected ')'");
2535}
2536
2537bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2538 Lex.Lex();
2539 LocTy ParenLoc = Lex.getLoc();
2540 if (!EatIfPresent(lltok::lparen))
2541 return error(ParenLoc, "expected '('");
2542 LocTy KindLoc = Lex.getLoc();
2543 std::string Arg;
2544 if (parseStringConstant(Arg))
2545 return error(KindLoc, "expected allockind value");
2546 for (StringRef A : llvm::split(Arg, ",")) {
2547 if (A == "alloc") {
2549 } else if (A == "realloc") {
2551 } else if (A == "free") {
2553 } else if (A == "uninitialized") {
2555 } else if (A == "zeroed") {
2557 } else if (A == "aligned") {
2559 } else {
2560 return error(KindLoc, Twine("unknown allockind ") + A);
2561 }
2562 }
2563 ParenLoc = Lex.getLoc();
2564 if (!EatIfPresent(lltok::rparen))
2565 return error(ParenLoc, "expected ')'");
2566 if (Kind == AllocFnKind::Unknown)
2567 return error(KindLoc, "expected allockind value");
2568 return false;
2569}
2570
2571static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2572 switch (Tok) {
2573 case lltok::kw_argmem:
2574 return IRMemLocation::ArgMem;
2577 case lltok::kw_errnomem:
2583 default:
2584 return std::nullopt;
2585 }
2586}
2587
2588static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2589 switch (Tok) {
2590 case lltok::kw_none:
2591 return ModRefInfo::NoModRef;
2592 case lltok::kw_read:
2593 return ModRefInfo::Ref;
2594 case lltok::kw_write:
2595 return ModRefInfo::Mod;
2597 return ModRefInfo::ModRef;
2598 default:
2599 return std::nullopt;
2600 }
2601}
2602
2603std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2605
2606 // We use syntax like memory(argmem: read), so the colon should not be
2607 // interpreted as a label terminator.
2608 Lex.setIgnoreColonInIdentifiers(true);
2609 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2610
2611 Lex.Lex();
2612 if (!EatIfPresent(lltok::lparen)) {
2613 tokError("expected '('");
2614 return std::nullopt;
2615 }
2616
2617 bool SeenLoc = false;
2618 do {
2619 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2620 if (Loc) {
2621 Lex.Lex();
2622 if (!EatIfPresent(lltok::colon)) {
2623 tokError("expected ':' after location");
2624 return std::nullopt;
2625 }
2626 }
2627
2628 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2629 if (!MR) {
2630 if (!Loc)
2631 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2632 "or access kind (none, read, write, readwrite)");
2633 else
2634 tokError("expected access kind (none, read, write, readwrite)");
2635 return std::nullopt;
2636 }
2637
2638 Lex.Lex();
2639 if (Loc) {
2640 SeenLoc = true;
2641 ME = ME.getWithModRef(*Loc, *MR);
2642 } else {
2643 if (SeenLoc) {
2644 tokError("default access kind must be specified first");
2645 return std::nullopt;
2646 }
2647 ME = MemoryEffects(*MR);
2648 }
2649
2650 if (EatIfPresent(lltok::rparen))
2651 return ME;
2652 } while (EatIfPresent(lltok::comma));
2653
2654 tokError("unterminated memory attribute");
2655 return std::nullopt;
2656}
2657
2658static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2659 switch (Tok) {
2660 case lltok::kw_all:
2661 return fcAllFlags;
2662 case lltok::kw_nan:
2663 return fcNan;
2664 case lltok::kw_snan:
2665 return fcSNan;
2666 case lltok::kw_qnan:
2667 return fcQNan;
2668 case lltok::kw_inf:
2669 return fcInf;
2670 case lltok::kw_ninf:
2671 return fcNegInf;
2672 case lltok::kw_pinf:
2673 return fcPosInf;
2674 case lltok::kw_norm:
2675 return fcNormal;
2676 case lltok::kw_nnorm:
2677 return fcNegNormal;
2678 case lltok::kw_pnorm:
2679 return fcPosNormal;
2680 case lltok::kw_sub:
2681 return fcSubnormal;
2682 case lltok::kw_nsub:
2683 return fcNegSubnormal;
2684 case lltok::kw_psub:
2685 return fcPosSubnormal;
2686 case lltok::kw_zero:
2687 return fcZero;
2688 case lltok::kw_nzero:
2689 return fcNegZero;
2690 case lltok::kw_pzero:
2691 return fcPosZero;
2692 default:
2693 return 0;
2694 }
2695}
2696
2697unsigned LLParser::parseNoFPClassAttr() {
2698 unsigned Mask = fcNone;
2699
2700 Lex.Lex();
2701 if (!EatIfPresent(lltok::lparen)) {
2702 tokError("expected '('");
2703 return 0;
2704 }
2705
2706 do {
2707 uint64_t Value = 0;
2708 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2709 if (TestMask != 0) {
2710 Mask |= TestMask;
2711 // TODO: Disallow overlapping masks to avoid copy paste errors
2712 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2713 !parseUInt64(Value)) {
2714 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2715 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2716 return 0;
2717 }
2718
2719 if (!EatIfPresent(lltok::rparen)) {
2720 error(Lex.getLoc(), "expected ')'");
2721 return 0;
2722 }
2723
2724 return Value;
2725 } else {
2726 error(Lex.getLoc(), "expected nofpclass test mask");
2727 return 0;
2728 }
2729
2730 Lex.Lex();
2731 if (EatIfPresent(lltok::rparen))
2732 return Mask;
2733 } while (1);
2734
2735 llvm_unreachable("unterminated nofpclass attribute");
2736}
2737
2738/// parseOptionalCommaAlign
2739/// ::=
2740/// ::= ',' align 4
2741///
2742/// This returns with AteExtraComma set to true if it ate an excess comma at the
2743/// end.
2744bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2745 bool &AteExtraComma) {
2746 AteExtraComma = false;
2747 while (EatIfPresent(lltok::comma)) {
2748 // Metadata at the end is an early exit.
2749 if (Lex.getKind() == lltok::MetadataVar) {
2750 AteExtraComma = true;
2751 return false;
2752 }
2753
2754 if (Lex.getKind() != lltok::kw_align)
2755 return error(Lex.getLoc(), "expected metadata or 'align'");
2756
2757 if (parseOptionalAlignment(Alignment))
2758 return true;
2759 }
2760
2761 return false;
2762}
2763
2764/// parseOptionalCommaAddrSpace
2765/// ::=
2766/// ::= ',' addrspace(1)
2767///
2768/// This returns with AteExtraComma set to true if it ate an excess comma at the
2769/// end.
2770bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2771 bool &AteExtraComma) {
2772 AteExtraComma = false;
2773 while (EatIfPresent(lltok::comma)) {
2774 // Metadata at the end is an early exit.
2775 if (Lex.getKind() == lltok::MetadataVar) {
2776 AteExtraComma = true;
2777 return false;
2778 }
2779
2780 Loc = Lex.getLoc();
2781 if (Lex.getKind() != lltok::kw_addrspace)
2782 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2783
2784 if (parseOptionalAddrSpace(AddrSpace))
2785 return true;
2786 }
2787
2788 return false;
2789}
2790
2791bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2792 std::optional<unsigned> &HowManyArg) {
2793 Lex.Lex();
2794
2795 auto StartParen = Lex.getLoc();
2796 if (!EatIfPresent(lltok::lparen))
2797 return error(StartParen, "expected '('");
2798
2799 if (parseUInt32(BaseSizeArg))
2800 return true;
2801
2802 if (EatIfPresent(lltok::comma)) {
2803 auto HowManyAt = Lex.getLoc();
2804 unsigned HowMany;
2805 if (parseUInt32(HowMany))
2806 return true;
2807 if (HowMany == BaseSizeArg)
2808 return error(HowManyAt,
2809 "'allocsize' indices can't refer to the same parameter");
2810 HowManyArg = HowMany;
2811 } else
2812 HowManyArg = std::nullopt;
2813
2814 auto EndParen = Lex.getLoc();
2815 if (!EatIfPresent(lltok::rparen))
2816 return error(EndParen, "expected ')'");
2817 return false;
2818}
2819
2820bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2821 unsigned &MaxValue) {
2822 Lex.Lex();
2823
2824 auto StartParen = Lex.getLoc();
2825 if (!EatIfPresent(lltok::lparen))
2826 return error(StartParen, "expected '('");
2827
2828 if (parseUInt32(MinValue))
2829 return true;
2830
2831 if (EatIfPresent(lltok::comma)) {
2832 if (parseUInt32(MaxValue))
2833 return true;
2834 } else
2835 MaxValue = MinValue;
2836
2837 auto EndParen = Lex.getLoc();
2838 if (!EatIfPresent(lltok::rparen))
2839 return error(EndParen, "expected ')'");
2840 return false;
2841}
2842
2843/// parseScopeAndOrdering
2844/// if isAtomic: ::= SyncScope? AtomicOrdering
2845/// else: ::=
2846///
2847/// This sets Scope and Ordering to the parsed values.
2848bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2849 AtomicOrdering &Ordering) {
2850 if (!IsAtomic)
2851 return false;
2852
2853 return parseScope(SSID) || parseOrdering(Ordering);
2854}
2855
2856/// parseScope
2857/// ::= syncscope("singlethread" | "<target scope>")?
2858///
2859/// This sets synchronization scope ID to the ID of the parsed value.
2860bool LLParser::parseScope(SyncScope::ID &SSID) {
2861 SSID = SyncScope::System;
2862 if (EatIfPresent(lltok::kw_syncscope)) {
2863 auto StartParenAt = Lex.getLoc();
2864 if (!EatIfPresent(lltok::lparen))
2865 return error(StartParenAt, "Expected '(' in syncscope");
2866
2867 std::string SSN;
2868 auto SSNAt = Lex.getLoc();
2869 if (parseStringConstant(SSN))
2870 return error(SSNAt, "Expected synchronization scope name");
2871
2872 auto EndParenAt = Lex.getLoc();
2873 if (!EatIfPresent(lltok::rparen))
2874 return error(EndParenAt, "Expected ')' in syncscope");
2875
2876 SSID = Context.getOrInsertSyncScopeID(SSN);
2877 }
2878
2879 return false;
2880}
2881
2882/// parseOrdering
2883/// ::= AtomicOrdering
2884///
2885/// This sets Ordering to the parsed value.
2886bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2887 switch (Lex.getKind()) {
2888 default:
2889 return tokError("Expected ordering on atomic instruction");
2892 // Not specified yet:
2893 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2897 case lltok::kw_seq_cst:
2899 break;
2900 }
2901 Lex.Lex();
2902 return false;
2903}
2904
2905/// parseOptionalStackAlignment
2906/// ::= /* empty */
2907/// ::= 'alignstack' '(' 4 ')'
2908bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2909 Alignment = 0;
2910 if (!EatIfPresent(lltok::kw_alignstack))
2911 return false;
2912 LocTy ParenLoc = Lex.getLoc();
2913 if (!EatIfPresent(lltok::lparen))
2914 return error(ParenLoc, "expected '('");
2915 LocTy AlignLoc = Lex.getLoc();
2916 if (parseUInt32(Alignment))
2917 return true;
2918 ParenLoc = Lex.getLoc();
2919 if (!EatIfPresent(lltok::rparen))
2920 return error(ParenLoc, "expected ')'");
2921 if (!isPowerOf2_32(Alignment))
2922 return error(AlignLoc, "stack alignment is not a power of two");
2923 return false;
2924}
2925
2926/// parseIndexList - This parses the index list for an insert/extractvalue
2927/// instruction. This sets AteExtraComma in the case where we eat an extra
2928/// comma at the end of the line and find that it is followed by metadata.
2929/// Clients that don't allow metadata can call the version of this function that
2930/// only takes one argument.
2931///
2932/// parseIndexList
2933/// ::= (',' uint32)+
2934///
2935bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2936 bool &AteExtraComma) {
2937 AteExtraComma = false;
2938
2939 if (Lex.getKind() != lltok::comma)
2940 return tokError("expected ',' as start of index list");
2941
2942 while (EatIfPresent(lltok::comma)) {
2943 if (Lex.getKind() == lltok::MetadataVar) {
2944 if (Indices.empty())
2945 return tokError("expected index");
2946 AteExtraComma = true;
2947 return false;
2948 }
2949 unsigned Idx = 0;
2950 if (parseUInt32(Idx))
2951 return true;
2952 Indices.push_back(Idx);
2953 }
2954
2955 return false;
2956}
2957
2958//===----------------------------------------------------------------------===//
2959// Type Parsing.
2960//===----------------------------------------------------------------------===//
2961
2962/// parseType - parse a type.
2963bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2964 SMLoc TypeLoc = Lex.getLoc();
2965 switch (Lex.getKind()) {
2966 default:
2967 return tokError(Msg);
2968 case lltok::Type:
2969 // Type ::= 'float' | 'void' (etc)
2970 Result = Lex.getTyVal();
2971 Lex.Lex();
2972
2973 // Handle "ptr" opaque pointer type.
2974 //
2975 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2976 if (Result->isPointerTy()) {
2977 unsigned AddrSpace;
2978 if (parseOptionalAddrSpace(AddrSpace))
2979 return true;
2980 Result = PointerType::get(getContext(), AddrSpace);
2981
2982 // Give a nice error for 'ptr*'.
2983 if (Lex.getKind() == lltok::star)
2984 return tokError("ptr* is invalid - use ptr instead");
2985
2986 // Fall through to parsing the type suffixes only if this 'ptr' is a
2987 // function return. Otherwise, return success, implicitly rejecting other
2988 // suffixes.
2989 if (Lex.getKind() != lltok::lparen)
2990 return false;
2991 }
2992 break;
2993 case lltok::kw_target: {
2994 // Type ::= TargetExtType
2995 if (parseTargetExtType(Result))
2996 return true;
2997 break;
2998 }
2999 case lltok::lbrace:
3000 // Type ::= StructType
3001 if (parseAnonStructType(Result, false))
3002 return true;
3003 break;
3004 case lltok::lsquare:
3005 // Type ::= '[' ... ']'
3006 Lex.Lex(); // eat the lsquare.
3007 if (parseArrayVectorType(Result, false))
3008 return true;
3009 break;
3010 case lltok::less: // Either vector or packed struct.
3011 // Type ::= '<' ... '>'
3012 Lex.Lex();
3013 if (Lex.getKind() == lltok::lbrace) {
3014 if (parseAnonStructType(Result, true) ||
3015 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3016 return true;
3017 } else if (parseArrayVectorType(Result, true))
3018 return true;
3019 break;
3020 case lltok::LocalVar: {
3021 // Type ::= %foo
3022 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3023
3024 // If the type hasn't been defined yet, create a forward definition and
3025 // remember where that forward def'n was seen (in case it never is defined).
3026 if (!Entry.first) {
3027 Entry.first = StructType::create(Context, Lex.getStrVal());
3028 Entry.second = Lex.getLoc();
3029 }
3030 Result = Entry.first;
3031 Lex.Lex();
3032 break;
3033 }
3034
3035 case lltok::LocalVarID: {
3036 // Type ::= %4
3037 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3038
3039 // If the type hasn't been defined yet, create a forward definition and
3040 // remember where that forward def'n was seen (in case it never is defined).
3041 if (!Entry.first) {
3042 Entry.first = StructType::create(Context);
3043 Entry.second = Lex.getLoc();
3044 }
3045 Result = Entry.first;
3046 Lex.Lex();
3047 break;
3048 }
3049 }
3050
3051 // parse the type suffixes.
3052 while (true) {
3053 switch (Lex.getKind()) {
3054 // End of type.
3055 default:
3056 if (!AllowVoid && Result->isVoidTy())
3057 return error(TypeLoc, "void type only allowed for function results");
3058 return false;
3059
3060 // Type ::= Type '*'
3061 case lltok::star:
3062 if (Result->isLabelTy())
3063 return tokError("basic block pointers are invalid");
3064 if (Result->isVoidTy())
3065 return tokError("pointers to void are invalid - use i8* instead");
3067 return tokError("pointer to this type is invalid");
3068 Result = PointerType::getUnqual(Context);
3069 Lex.Lex();
3070 break;
3071
3072 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3073 case lltok::kw_addrspace: {
3074 if (Result->isLabelTy())
3075 return tokError("basic block pointers are invalid");
3076 if (Result->isVoidTy())
3077 return tokError("pointers to void are invalid; use i8* instead");
3079 return tokError("pointer to this type is invalid");
3080 unsigned AddrSpace;
3081 if (parseOptionalAddrSpace(AddrSpace) ||
3082 parseToken(lltok::star, "expected '*' in address space"))
3083 return true;
3084
3085 Result = PointerType::get(Context, AddrSpace);
3086 break;
3087 }
3088
3089 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3090 case lltok::lparen:
3091 if (parseFunctionType(Result))
3092 return true;
3093 break;
3094 }
3095 }
3096}
3097
3098/// parseParameterList
3099/// ::= '(' ')'
3100/// ::= '(' Arg (',' Arg)* ')'
3101/// Arg
3102/// ::= Type OptionalAttributes Value OptionalAttributes
3103bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3104 PerFunctionState &PFS, bool IsMustTailCall,
3105 bool InVarArgsFunc) {
3106 if (parseToken(lltok::lparen, "expected '(' in call"))
3107 return true;
3108
3109 while (Lex.getKind() != lltok::rparen) {
3110 // If this isn't the first argument, we need a comma.
3111 if (!ArgList.empty() &&
3112 parseToken(lltok::comma, "expected ',' in argument list"))
3113 return true;
3114
3115 // parse an ellipsis if this is a musttail call in a variadic function.
3116 if (Lex.getKind() == lltok::dotdotdot) {
3117 const char *Msg = "unexpected ellipsis in argument list for ";
3118 if (!IsMustTailCall)
3119 return tokError(Twine(Msg) + "non-musttail call");
3120 if (!InVarArgsFunc)
3121 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3122 Lex.Lex(); // Lex the '...', it is purely for readability.
3123 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3124 }
3125
3126 // parse the argument.
3127 LocTy ArgLoc;
3128 Type *ArgTy = nullptr;
3129 Value *V;
3130 if (parseType(ArgTy, ArgLoc))
3131 return true;
3133 return error(ArgLoc, "invalid type for function argument");
3134
3135 AttrBuilder ArgAttrs(M->getContext());
3136
3137 if (ArgTy->isMetadataTy()) {
3138 if (parseMetadataAsValue(V, PFS))
3139 return true;
3140 } else {
3141 // Otherwise, handle normal operands.
3142 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3143 return true;
3144 }
3145 ArgList.push_back(ParamInfo(
3146 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3147 }
3148
3149 if (IsMustTailCall && InVarArgsFunc)
3150 return tokError("expected '...' at end of argument list for musttail call "
3151 "in varargs function");
3152
3153 Lex.Lex(); // Lex the ')'.
3154 return false;
3155}
3156
3157/// parseRequiredTypeAttr
3158/// ::= attrname(<ty>)
3159bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3160 Attribute::AttrKind AttrKind) {
3161 Type *Ty = nullptr;
3162 if (!EatIfPresent(AttrToken))
3163 return true;
3164 if (!EatIfPresent(lltok::lparen))
3165 return error(Lex.getLoc(), "expected '('");
3166 if (parseType(Ty))
3167 return true;
3168 if (!EatIfPresent(lltok::rparen))
3169 return error(Lex.getLoc(), "expected ')'");
3170
3171 B.addTypeAttr(AttrKind, Ty);
3172 return false;
3173}
3174
3175/// parseRangeAttr
3176/// ::= range(<ty> <n>,<n>)
3177bool LLParser::parseRangeAttr(AttrBuilder &B) {
3178 Lex.Lex();
3179
3180 APInt Lower;
3181 APInt Upper;
3182 Type *Ty = nullptr;
3183 LocTy TyLoc;
3184
3185 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3186 if (Lex.getKind() != lltok::APSInt)
3187 return tokError("expected integer");
3188 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3189 return tokError(
3190 "integer is too large for the bit width of specified type");
3191 Val = Lex.getAPSIntVal().extend(BitWidth);
3192 Lex.Lex();
3193 return false;
3194 };
3195
3196 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3197 return true;
3198 if (!Ty->isIntegerTy())
3199 return error(TyLoc, "the range must have integer type!");
3200
3201 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3202
3203 if (ParseAPSInt(BitWidth, Lower) ||
3204 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3205 return true;
3206 if (Lower == Upper && !Lower.isZero())
3207 return tokError("the range represent the empty set but limits aren't 0!");
3208
3209 if (parseToken(lltok::rparen, "expected ')'"))
3210 return true;
3211
3212 B.addRangeAttr(ConstantRange(Lower, Upper));
3213 return false;
3214}
3215
3216/// parseInitializesAttr
3217/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3218bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3219 Lex.Lex();
3220
3221 auto ParseAPSInt = [&](APInt &Val) {
3222 if (Lex.getKind() != lltok::APSInt)
3223 return tokError("expected integer");
3224 Val = Lex.getAPSIntVal().extend(64);
3225 Lex.Lex();
3226 return false;
3227 };
3228
3229 if (parseToken(lltok::lparen, "expected '('"))
3230 return true;
3231
3233 // Parse each constant range.
3234 do {
3235 APInt Lower, Upper;
3236 if (parseToken(lltok::lparen, "expected '('"))
3237 return true;
3238
3239 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3240 ParseAPSInt(Upper))
3241 return true;
3242
3243 if (Lower == Upper)
3244 return tokError("the range should not represent the full or empty set!");
3245
3246 if (parseToken(lltok::rparen, "expected ')'"))
3247 return true;
3248
3249 RangeList.push_back(ConstantRange(Lower, Upper));
3250 } while (EatIfPresent(lltok::comma));
3251
3252 if (parseToken(lltok::rparen, "expected ')'"))
3253 return true;
3254
3255 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3256 if (!CRLOrNull.has_value())
3257 return tokError("Invalid (unordered or overlapping) range list");
3258 B.addInitializesAttr(*CRLOrNull);
3259 return false;
3260}
3261
3262bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3264 std::optional<CaptureComponents> Ret;
3265
3266 // We use syntax like captures(ret: address, provenance), so the colon
3267 // should not be interpreted as a label terminator.
3268 Lex.setIgnoreColonInIdentifiers(true);
3269 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3270
3271 Lex.Lex();
3272 if (parseToken(lltok::lparen, "expected '('"))
3273 return true;
3274
3275 CaptureComponents *Current = &Other;
3276 bool SeenComponent = false;
3277 while (true) {
3278 if (EatIfPresent(lltok::kw_ret)) {
3279 if (parseToken(lltok::colon, "expected ':'"))
3280 return true;
3281 if (Ret)
3282 return tokError("duplicate 'ret' location");
3284 Current = &*Ret;
3285 SeenComponent = false;
3286 }
3287
3288 if (EatIfPresent(lltok::kw_none)) {
3289 if (SeenComponent)
3290 return tokError("cannot use 'none' with other component");
3291 *Current = CaptureComponents::None;
3292 } else {
3293 if (SeenComponent && capturesNothing(*Current))
3294 return tokError("cannot use 'none' with other component");
3295
3296 if (EatIfPresent(lltok::kw_address_is_null))
3298 else if (EatIfPresent(lltok::kw_address))
3299 *Current |= CaptureComponents::Address;
3300 else if (EatIfPresent(lltok::kw_provenance))
3302 else if (EatIfPresent(lltok::kw_read_provenance))
3304 else
3305 return tokError("expected one of 'none', 'address', 'address_is_null', "
3306 "'provenance' or 'read_provenance'");
3307 }
3308
3309 SeenComponent = true;
3310 if (EatIfPresent(lltok::rparen))
3311 break;
3312
3313 if (parseToken(lltok::comma, "expected ',' or ')'"))
3314 return true;
3315 }
3316
3317 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3318 return false;
3319}
3320
3321/// parseOptionalOperandBundles
3322/// ::= /*empty*/
3323/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3324///
3325/// OperandBundle
3326/// ::= bundle-tag '(' ')'
3327/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3328///
3329/// bundle-tag ::= String Constant
3330bool LLParser::parseOptionalOperandBundles(
3331 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3332 LocTy BeginLoc = Lex.getLoc();
3333 if (!EatIfPresent(lltok::lsquare))
3334 return false;
3335
3336 while (Lex.getKind() != lltok::rsquare) {
3337 // If this isn't the first operand bundle, we need a comma.
3338 if (!BundleList.empty() &&
3339 parseToken(lltok::comma, "expected ',' in input list"))
3340 return true;
3341
3342 std::string Tag;
3343 if (parseStringConstant(Tag))
3344 return true;
3345
3346 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3347 return true;
3348
3349 std::vector<Value *> Inputs;
3350 while (Lex.getKind() != lltok::rparen) {
3351 // If this isn't the first input, we need a comma.
3352 if (!Inputs.empty() &&
3353 parseToken(lltok::comma, "expected ',' in input list"))
3354 return true;
3355
3356 Type *Ty = nullptr;
3357 Value *Input = nullptr;
3358 if (parseType(Ty))
3359 return true;
3360 if (Ty->isMetadataTy()) {
3361 if (parseMetadataAsValue(Input, PFS))
3362 return true;
3363 } else if (parseValue(Ty, Input, PFS)) {
3364 return true;
3365 }
3366 Inputs.push_back(Input);
3367 }
3368
3369 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3370
3371 Lex.Lex(); // Lex the ')'.
3372 }
3373
3374 if (BundleList.empty())
3375 return error(BeginLoc, "operand bundle set must not be empty");
3376
3377 Lex.Lex(); // Lex the ']'.
3378 return false;
3379}
3380
3381bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3382 unsigned NextID, unsigned ID) {
3383 if (ID < NextID)
3384 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3385 Twine(NextID) + "' or greater");
3386
3387 return false;
3388}
3389
3390/// parseArgumentList - parse the argument list for a function type or function
3391/// prototype.
3392/// ::= '(' ArgTypeListI ')'
3393/// ArgTypeListI
3394/// ::= /*empty*/
3395/// ::= '...'
3396/// ::= ArgTypeList ',' '...'
3397/// ::= ArgType (',' ArgType)*
3398///
3399bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3400 SmallVectorImpl<unsigned> &UnnamedArgNums,
3401 bool &IsVarArg) {
3402 unsigned CurValID = 0;
3403 IsVarArg = false;
3404 assert(Lex.getKind() == lltok::lparen);
3405 Lex.Lex(); // eat the (.
3406
3407 if (Lex.getKind() != lltok::rparen) {
3408 do {
3409 // Handle ... at end of arg list.
3410 if (EatIfPresent(lltok::dotdotdot)) {
3411 IsVarArg = true;
3412 break;
3413 }
3414
3415 // Otherwise must be an argument type.
3416 LocTy TypeLoc = Lex.getLoc();
3417 Type *ArgTy = nullptr;
3418 AttrBuilder Attrs(M->getContext());
3419 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3420 return true;
3421
3422 if (ArgTy->isVoidTy())
3423 return error(TypeLoc, "argument can not have void type");
3424
3425 std::string Name;
3426 if (Lex.getKind() == lltok::LocalVar) {
3427 Name = Lex.getStrVal();
3428 Lex.Lex();
3429 } else {
3430 unsigned ArgID;
3431 if (Lex.getKind() == lltok::LocalVarID) {
3432 ArgID = Lex.getUIntVal();
3433 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3434 return true;
3435 Lex.Lex();
3436 } else {
3437 ArgID = CurValID;
3438 }
3439 UnnamedArgNums.push_back(ArgID);
3440 CurValID = ArgID + 1;
3441 }
3442
3444 return error(TypeLoc, "invalid type for function argument");
3445
3446 ArgList.emplace_back(TypeLoc, ArgTy,
3447 AttributeSet::get(ArgTy->getContext(), Attrs),
3448 std::move(Name));
3449 } while (EatIfPresent(lltok::comma));
3450 }
3451
3452 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3453}
3454
3455/// parseFunctionType
3456/// ::= Type ArgumentList OptionalAttrs
3457bool LLParser::parseFunctionType(Type *&Result) {
3458 assert(Lex.getKind() == lltok::lparen);
3459
3461 return tokError("invalid function return type");
3462
3464 bool IsVarArg;
3465 SmallVector<unsigned> UnnamedArgNums;
3466 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3467 return true;
3468
3469 // Reject names on the arguments lists.
3470 for (const ArgInfo &Arg : ArgList) {
3471 if (!Arg.Name.empty())
3472 return error(Arg.Loc, "argument name invalid in function type");
3473 if (Arg.Attrs.hasAttributes())
3474 return error(Arg.Loc, "argument attributes invalid in function type");
3475 }
3476
3477 SmallVector<Type*, 16> ArgListTy;
3478 for (const ArgInfo &Arg : ArgList)
3479 ArgListTy.push_back(Arg.Ty);
3480
3481 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3482 return false;
3483}
3484
3485/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3486/// other structs.
3487bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3489 if (parseStructBody(Elts))
3490 return true;
3491
3492 Result = StructType::get(Context, Elts, Packed);
3493 return false;
3494}
3495
3496/// parseStructDefinition - parse a struct in a 'type' definition.
3497bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3498 std::pair<Type *, LocTy> &Entry,
3499 Type *&ResultTy) {
3500 // If the type was already defined, diagnose the redefinition.
3501 if (Entry.first && !Entry.second.isValid())
3502 return error(TypeLoc, "redefinition of type");
3503
3504 // If we have opaque, just return without filling in the definition for the
3505 // struct. This counts as a definition as far as the .ll file goes.
3506 if (EatIfPresent(lltok::kw_opaque)) {
3507 // This type is being defined, so clear the location to indicate this.
3508 Entry.second = SMLoc();
3509
3510 // If this type number has never been uttered, create it.
3511 if (!Entry.first)
3512 Entry.first = StructType::create(Context, Name);
3513 ResultTy = Entry.first;
3514 return false;
3515 }
3516
3517 // If the type starts with '<', then it is either a packed struct or a vector.
3518 bool isPacked = EatIfPresent(lltok::less);
3519
3520 // If we don't have a struct, then we have a random type alias, which we
3521 // accept for compatibility with old files. These types are not allowed to be
3522 // forward referenced and not allowed to be recursive.
3523 if (Lex.getKind() != lltok::lbrace) {
3524 if (Entry.first)
3525 return error(TypeLoc, "forward references to non-struct type");
3526
3527 ResultTy = nullptr;
3528 if (isPacked)
3529 return parseArrayVectorType(ResultTy, true);
3530 return parseType(ResultTy);
3531 }
3532
3533 // This type is being defined, so clear the location to indicate this.
3534 Entry.second = SMLoc();
3535
3536 // If this type number has never been uttered, create it.
3537 if (!Entry.first)
3538 Entry.first = StructType::create(Context, Name);
3539
3540 StructType *STy = cast<StructType>(Entry.first);
3541
3543 if (parseStructBody(Body) ||
3544 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3545 return true;
3546
3547 if (auto E = STy->setBodyOrError(Body, isPacked))
3548 return tokError(toString(std::move(E)));
3549
3550 ResultTy = STy;
3551 return false;
3552}
3553
3554/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3555/// StructType
3556/// ::= '{' '}'
3557/// ::= '{' Type (',' Type)* '}'
3558/// ::= '<' '{' '}' '>'
3559/// ::= '<' '{' Type (',' Type)* '}' '>'
3560bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3561 assert(Lex.getKind() == lltok::lbrace);
3562 Lex.Lex(); // Consume the '{'
3563
3564 // Handle the empty struct.
3565 if (EatIfPresent(lltok::rbrace))
3566 return false;
3567
3568 LocTy EltTyLoc = Lex.getLoc();
3569 Type *Ty = nullptr;
3570 if (parseType(Ty))
3571 return true;
3572 Body.push_back(Ty);
3573
3575 return error(EltTyLoc, "invalid element type for struct");
3576
3577 while (EatIfPresent(lltok::comma)) {
3578 EltTyLoc = Lex.getLoc();
3579 if (parseType(Ty))
3580 return true;
3581
3583 return error(EltTyLoc, "invalid element type for struct");
3584
3585 Body.push_back(Ty);
3586 }
3587
3588 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3589}
3590
3591/// parseArrayVectorType - parse an array or vector type, assuming the first
3592/// token has already been consumed.
3593/// Type
3594/// ::= '[' APSINTVAL 'x' Types ']'
3595/// ::= '<' APSINTVAL 'x' Types '>'
3596/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3597bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3598 bool Scalable = false;
3599
3600 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3601 Lex.Lex(); // consume the 'vscale'
3602 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3603 return true;
3604
3605 Scalable = true;
3606 }
3607
3608 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3609 Lex.getAPSIntVal().getBitWidth() > 64)
3610 return tokError("expected number in address space");
3611
3612 LocTy SizeLoc = Lex.getLoc();
3613 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3614 Lex.Lex();
3615
3616 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3617 return true;
3618
3619 LocTy TypeLoc = Lex.getLoc();
3620 Type *EltTy = nullptr;
3621 if (parseType(EltTy))
3622 return true;
3623
3624 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3625 "expected end of sequential type"))
3626 return true;
3627
3628 if (IsVector) {
3629 if (Size == 0)
3630 return error(SizeLoc, "zero element vector is illegal");
3631 if ((unsigned)Size != Size)
3632 return error(SizeLoc, "size too large for vector");
3634 return error(TypeLoc, "invalid vector element type");
3635 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3636 } else {
3638 return error(TypeLoc, "invalid array element type");
3639 Result = ArrayType::get(EltTy, Size);
3640 }
3641 return false;
3642}
3643
3644/// parseTargetExtType - handle target extension type syntax
3645/// TargetExtType
3646/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3647///
3648/// TargetExtTypeParams
3649/// ::= /*empty*/
3650/// ::= ',' Type TargetExtTypeParams
3651///
3652/// TargetExtIntParams
3653/// ::= /*empty*/
3654/// ::= ',' uint32 TargetExtIntParams
3655bool LLParser::parseTargetExtType(Type *&Result) {
3656 Lex.Lex(); // Eat the 'target' keyword.
3657
3658 // Get the mandatory type name.
3659 std::string TypeName;
3660 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3661 parseStringConstant(TypeName))
3662 return true;
3663
3664 // Parse all of the integer and type parameters at the same time; the use of
3665 // SeenInt will allow us to catch cases where type parameters follow integer
3666 // parameters.
3667 SmallVector<Type *> TypeParams;
3668 SmallVector<unsigned> IntParams;
3669 bool SeenInt = false;
3670 while (Lex.getKind() == lltok::comma) {
3671 Lex.Lex(); // Eat the comma.
3672
3673 if (Lex.getKind() == lltok::APSInt) {
3674 SeenInt = true;
3675 unsigned IntVal;
3676 if (parseUInt32(IntVal))
3677 return true;
3678 IntParams.push_back(IntVal);
3679 } else if (SeenInt) {
3680 // The only other kind of parameter we support is type parameters, which
3681 // must precede the integer parameters. This is therefore an error.
3682 return tokError("expected uint32 param");
3683 } else {
3684 Type *TypeParam;
3685 if (parseType(TypeParam, /*AllowVoid=*/true))
3686 return true;
3687 TypeParams.push_back(TypeParam);
3688 }
3689 }
3690
3691 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3692 return true;
3693
3694 auto TTy =
3695 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3696 if (auto E = TTy.takeError())
3697 return tokError(toString(std::move(E)));
3698
3699 Result = *TTy;
3700 return false;
3701}
3702
3703//===----------------------------------------------------------------------===//
3704// Function Semantic Analysis.
3705//===----------------------------------------------------------------------===//
3706
3707LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3708 int functionNumber,
3709 ArrayRef<unsigned> UnnamedArgNums)
3710 : P(p), F(f), FunctionNumber(functionNumber) {
3711
3712 // Insert unnamed arguments into the NumberedVals list.
3713 auto It = UnnamedArgNums.begin();
3714 for (Argument &A : F.args()) {
3715 if (!A.hasName()) {
3716 unsigned ArgNum = *It++;
3717 NumberedVals.add(ArgNum, &A);
3718 }
3719 }
3720}
3721
3722LLParser::PerFunctionState::~PerFunctionState() {
3723 // If there were any forward referenced non-basicblock values, delete them.
3724
3725 for (const auto &P : ForwardRefVals) {
3726 if (isa<BasicBlock>(P.second.first))
3727 continue;
3728 P.second.first->replaceAllUsesWith(
3729 PoisonValue::get(P.second.first->getType()));
3730 P.second.first->deleteValue();
3731 }
3732
3733 for (const auto &P : ForwardRefValIDs) {
3734 if (isa<BasicBlock>(P.second.first))
3735 continue;
3736 P.second.first->replaceAllUsesWith(
3737 PoisonValue::get(P.second.first->getType()));
3738 P.second.first->deleteValue();
3739 }
3740}
3741
3742bool LLParser::PerFunctionState::finishFunction() {
3743 if (!ForwardRefVals.empty())
3744 return P.error(ForwardRefVals.begin()->second.second,
3745 "use of undefined value '%" + ForwardRefVals.begin()->first +
3746 "'");
3747 if (!ForwardRefValIDs.empty())
3748 return P.error(ForwardRefValIDs.begin()->second.second,
3749 "use of undefined value '%" +
3750 Twine(ForwardRefValIDs.begin()->first) + "'");
3751 return false;
3752}
3753
3754/// getVal - Get a value with the specified name or ID, creating a
3755/// forward reference record if needed. This can return null if the value
3756/// exists but does not have the right type.
3757Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3758 LocTy Loc) {
3759 // Look this name up in the normal function symbol table.
3760 Value *Val = F.getValueSymbolTable()->lookup(Name);
3761
3762 // If this is a forward reference for the value, see if we already created a
3763 // forward ref record.
3764 if (!Val) {
3765 auto I = ForwardRefVals.find(Name);
3766 if (I != ForwardRefVals.end())
3767 Val = I->second.first;
3768 }
3769
3770 // If we have the value in the symbol table or fwd-ref table, return it.
3771 if (Val)
3772 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3773
3774 // Don't make placeholders with invalid type.
3775 if (!Ty->isFirstClassType()) {
3776 P.error(Loc, "invalid use of a non-first-class type");
3777 return nullptr;
3778 }
3779
3780 // Otherwise, create a new forward reference for this value and remember it.
3781 Value *FwdVal;
3782 if (Ty->isLabelTy()) {
3783 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3784 } else {
3785 FwdVal = new Argument(Ty, Name);
3786 }
3787 if (FwdVal->getName() != Name) {
3788 P.error(Loc, "name is too long which can result in name collisions, "
3789 "consider making the name shorter or "
3790 "increasing -non-global-value-max-name-size");
3791 return nullptr;
3792 }
3793
3794 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3795 return FwdVal;
3796}
3797
3798Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3799 // Look this name up in the normal function symbol table.
3800 Value *Val = NumberedVals.get(ID);
3801
3802 // If this is a forward reference for the value, see if we already created a
3803 // forward ref record.
3804 if (!Val) {
3805 auto I = ForwardRefValIDs.find(ID);
3806 if (I != ForwardRefValIDs.end())
3807 Val = I->second.first;
3808 }
3809
3810 // If we have the value in the symbol table or fwd-ref table, return it.
3811 if (Val)
3812 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3813
3814 if (!Ty->isFirstClassType()) {
3815 P.error(Loc, "invalid use of a non-first-class type");
3816 return nullptr;
3817 }
3818
3819 // Otherwise, create a new forward reference for this value and remember it.
3820 Value *FwdVal;
3821 if (Ty->isLabelTy()) {
3822 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3823 } else {
3824 FwdVal = new Argument(Ty);
3825 }
3826
3827 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3828 return FwdVal;
3829}
3830
3831/// setInstName - After an instruction is parsed and inserted into its
3832/// basic block, this installs its name.
3833bool LLParser::PerFunctionState::setInstName(int NameID,
3834 const std::string &NameStr,
3835 LocTy NameLoc, Instruction *Inst) {
3836 // If this instruction has void type, it cannot have a name or ID specified.
3837 if (Inst->getType()->isVoidTy()) {
3838 if (NameID != -1 || !NameStr.empty())
3839 return P.error(NameLoc, "instructions returning void cannot have a name");
3840 return false;
3841 }
3842
3843 // If this was a numbered instruction, verify that the instruction is the
3844 // expected value and resolve any forward references.
3845 if (NameStr.empty()) {
3846 // If neither a name nor an ID was specified, just use the next ID.
3847 if (NameID == -1)
3848 NameID = NumberedVals.getNext();
3849
3850 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3851 NameID))
3852 return true;
3853
3854 auto FI = ForwardRefValIDs.find(NameID);
3855 if (FI != ForwardRefValIDs.end()) {
3856 Value *Sentinel = FI->second.first;
3857 if (Sentinel->getType() != Inst->getType())
3858 return P.error(NameLoc, "instruction forward referenced with type '" +
3859 getTypeString(FI->second.first->getType()) +
3860 "'");
3861
3862 Sentinel->replaceAllUsesWith(Inst);
3863 Sentinel->deleteValue();
3864 ForwardRefValIDs.erase(FI);
3865 }
3866
3867 NumberedVals.add(NameID, Inst);
3868 return false;
3869 }
3870
3871 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3872 auto FI = ForwardRefVals.find(NameStr);
3873 if (FI != ForwardRefVals.end()) {
3874 Value *Sentinel = FI->second.first;
3875 if (Sentinel->getType() != Inst->getType())
3876 return P.error(NameLoc, "instruction forward referenced with type '" +
3877 getTypeString(FI->second.first->getType()) +
3878 "'");
3879
3880 Sentinel->replaceAllUsesWith(Inst);
3881 Sentinel->deleteValue();
3882 ForwardRefVals.erase(FI);
3883 }
3884
3885 // Set the name on the instruction.
3886 Inst->setName(NameStr);
3887
3888 if (Inst->getName() != NameStr)
3889 return P.error(NameLoc, "multiple definition of local value named '" +
3890 NameStr + "'");
3891 return false;
3892}
3893
3894/// getBB - Get a basic block with the specified name or ID, creating a
3895/// forward reference record if needed.
3896BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3897 LocTy Loc) {
3899 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3900}
3901
3902BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3904 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3905}
3906
3907/// defineBB - Define the specified basic block, which is either named or
3908/// unnamed. If there is an error, this returns null otherwise it returns
3909/// the block being defined.
3910BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3911 int NameID, LocTy Loc) {
3912 BasicBlock *BB;
3913 if (Name.empty()) {
3914 if (NameID != -1) {
3915 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3916 return nullptr;
3917 } else {
3918 NameID = NumberedVals.getNext();
3919 }
3920 BB = getBB(NameID, Loc);
3921 if (!BB) {
3922 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3923 return nullptr;
3924 }
3925 } else {
3926 BB = getBB(Name, Loc);
3927 if (!BB) {
3928 P.error(Loc, "unable to create block named '" + Name + "'");
3929 return nullptr;
3930 }
3931 }
3932
3933 // Move the block to the end of the function. Forward ref'd blocks are
3934 // inserted wherever they happen to be referenced.
3935 F.splice(F.end(), &F, BB->getIterator());
3936
3937 // Remove the block from forward ref sets.
3938 if (Name.empty()) {
3939 ForwardRefValIDs.erase(NameID);
3940 NumberedVals.add(NameID, BB);
3941 } else {
3942 // BB forward references are already in the function symbol table.
3943 ForwardRefVals.erase(Name);
3944 }
3945
3946 return BB;
3947}
3948
3949//===----------------------------------------------------------------------===//
3950// Constants.
3951//===----------------------------------------------------------------------===//
3952
3953/// parseValID - parse an abstract value that doesn't necessarily have a
3954/// type implied. For example, if we parse "4" we don't know what integer type
3955/// it has. The value will later be combined with its type and checked for
3956/// basic correctness. PFS is used to convert function-local operands of
3957/// metadata (since metadata operands are not just parsed here but also
3958/// converted to values). PFS can be null when we are not parsing metadata
3959/// values inside a function.
3960bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3961 ID.Loc = Lex.getLoc();
3962 switch (Lex.getKind()) {
3963 default:
3964 return tokError("expected value token");
3965 case lltok::GlobalID: // @42
3966 ID.UIntVal = Lex.getUIntVal();
3967 ID.Kind = ValID::t_GlobalID;
3968 break;
3969 case lltok::GlobalVar: // @foo
3970 ID.StrVal = Lex.getStrVal();
3971 ID.Kind = ValID::t_GlobalName;
3972 break;
3973 case lltok::LocalVarID: // %42
3974 ID.UIntVal = Lex.getUIntVal();
3975 ID.Kind = ValID::t_LocalID;
3976 break;
3977 case lltok::LocalVar: // %foo
3978 ID.StrVal = Lex.getStrVal();
3979 ID.Kind = ValID::t_LocalName;
3980 break;
3981 case lltok::APSInt:
3982 ID.APSIntVal = Lex.getAPSIntVal();
3983 ID.Kind = ValID::t_APSInt;
3984 break;
3985 case lltok::APFloat:
3986 ID.APFloatVal = Lex.getAPFloatVal();
3987 ID.Kind = ValID::t_APFloat;
3988 break;
3989 case lltok::kw_true:
3990 ID.ConstantVal = ConstantInt::getTrue(Context);
3991 ID.Kind = ValID::t_Constant;
3992 break;
3993 case lltok::kw_false:
3994 ID.ConstantVal = ConstantInt::getFalse(Context);
3995 ID.Kind = ValID::t_Constant;
3996 break;
3997 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3998 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3999 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4000 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4001 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4002
4003 case lltok::lbrace: {
4004 // ValID ::= '{' ConstVector '}'
4005 Lex.Lex();
4007 if (parseGlobalValueVector(Elts) ||
4008 parseToken(lltok::rbrace, "expected end of struct constant"))
4009 return true;
4010
4011 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4012 ID.UIntVal = Elts.size();
4013 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4014 Elts.size() * sizeof(Elts[0]));
4016 return false;
4017 }
4018 case lltok::less: {
4019 // ValID ::= '<' ConstVector '>' --> Vector.
4020 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4021 Lex.Lex();
4022 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4023
4025 LocTy FirstEltLoc = Lex.getLoc();
4026 if (parseGlobalValueVector(Elts) ||
4027 (isPackedStruct &&
4028 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4029 parseToken(lltok::greater, "expected end of constant"))
4030 return true;
4031
4032 if (isPackedStruct) {
4033 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4034 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4035 Elts.size() * sizeof(Elts[0]));
4036 ID.UIntVal = Elts.size();
4038 return false;
4039 }
4040
4041 if (Elts.empty())
4042 return error(ID.Loc, "constant vector must not be empty");
4043
4044 if (!Elts[0]->getType()->isIntegerTy() &&
4045 !Elts[0]->getType()->isFloatingPointTy() &&
4046 !Elts[0]->getType()->isPointerTy())
4047 return error(
4048 FirstEltLoc,
4049 "vector elements must have integer, pointer or floating point type");
4050
4051 // Verify that all the vector elements have the same type.
4052 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4053 if (Elts[i]->getType() != Elts[0]->getType())
4054 return error(FirstEltLoc, "vector element #" + Twine(i) +
4055 " is not of type '" +
4056 getTypeString(Elts[0]->getType()));
4057
4058 ID.ConstantVal = ConstantVector::get(Elts);
4059 ID.Kind = ValID::t_Constant;
4060 return false;
4061 }
4062 case lltok::lsquare: { // Array Constant
4063 Lex.Lex();
4065 LocTy FirstEltLoc = Lex.getLoc();
4066 if (parseGlobalValueVector(Elts) ||
4067 parseToken(lltok::rsquare, "expected end of array constant"))
4068 return true;
4069
4070 // Handle empty element.
4071 if (Elts.empty()) {
4072 // Use undef instead of an array because it's inconvenient to determine
4073 // the element type at this point, there being no elements to examine.
4074 ID.Kind = ValID::t_EmptyArray;
4075 return false;
4076 }
4077
4078 if (!Elts[0]->getType()->isFirstClassType())
4079 return error(FirstEltLoc, "invalid array element type: " +
4080 getTypeString(Elts[0]->getType()));
4081
4082 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4083
4084 // Verify all elements are correct type!
4085 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4086 if (Elts[i]->getType() != Elts[0]->getType())
4087 return error(FirstEltLoc, "array element #" + Twine(i) +
4088 " is not of type '" +
4089 getTypeString(Elts[0]->getType()));
4090 }
4091
4092 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4093 ID.Kind = ValID::t_Constant;
4094 return false;
4095 }
4096 case lltok::kw_c: // c "foo"
4097 Lex.Lex();
4098 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4099 false);
4100 if (parseToken(lltok::StringConstant, "expected string"))
4101 return true;
4102 ID.Kind = ValID::t_Constant;
4103 return false;
4104
4105 case lltok::kw_asm: {
4106 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4107 // STRINGCONSTANT
4108 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4109 Lex.Lex();
4110 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4111 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4112 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4113 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4114 parseStringConstant(ID.StrVal) ||
4115 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4116 parseToken(lltok::StringConstant, "expected constraint string"))
4117 return true;
4118 ID.StrVal2 = Lex.getStrVal();
4119 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4120 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4121 ID.Kind = ValID::t_InlineAsm;
4122 return false;
4123 }
4124
4126 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4127 Lex.Lex();
4128
4129 ValID Fn, Label;
4130
4131 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4132 parseValID(Fn, PFS) ||
4133 parseToken(lltok::comma,
4134 "expected comma in block address expression") ||
4135 parseValID(Label, PFS) ||
4136 parseToken(lltok::rparen, "expected ')' in block address expression"))
4137 return true;
4138
4140 return error(Fn.Loc, "expected function name in blockaddress");
4141 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4142 return error(Label.Loc, "expected basic block name in blockaddress");
4143
4144 // Try to find the function (but skip it if it's forward-referenced).
4145 GlobalValue *GV = nullptr;
4146 if (Fn.Kind == ValID::t_GlobalID) {
4147 GV = NumberedVals.get(Fn.UIntVal);
4148 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4149 GV = M->getNamedValue(Fn.StrVal);
4150 }
4151 Function *F = nullptr;
4152 if (GV) {
4153 // Confirm that it's actually a function with a definition.
4154 if (!isa<Function>(GV))
4155 return error(Fn.Loc, "expected function name in blockaddress");
4156 F = cast<Function>(GV);
4157 if (F->isDeclaration())
4158 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4159 }
4160
4161 if (!F) {
4162 // Make a global variable as a placeholder for this reference.
4163 GlobalValue *&FwdRef =
4164 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4165 if (!FwdRef) {
4166 unsigned FwdDeclAS;
4167 if (ExpectedTy) {
4168 // If we know the type that the blockaddress is being assigned to,
4169 // we can use the address space of that type.
4170 if (!ExpectedTy->isPointerTy())
4171 return error(ID.Loc,
4172 "type of blockaddress must be a pointer and not '" +
4173 getTypeString(ExpectedTy) + "'");
4174 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4175 } else if (PFS) {
4176 // Otherwise, we default the address space of the current function.
4177 FwdDeclAS = PFS->getFunction().getAddressSpace();
4178 } else {
4179 llvm_unreachable("Unknown address space for blockaddress");
4180 }
4181 FwdRef = new GlobalVariable(
4182 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4183 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4184 }
4185
4186 ID.ConstantVal = FwdRef;
4187 ID.Kind = ValID::t_Constant;
4188 return false;
4189 }
4190
4191 // We found the function; now find the basic block. Don't use PFS, since we
4192 // might be inside a constant expression.
4193 BasicBlock *BB;
4194 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4195 if (Label.Kind == ValID::t_LocalID)
4196 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4197 else
4198 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4199 if (!BB)
4200 return error(Label.Loc, "referenced value is not a basic block");
4201 } else {
4202 if (Label.Kind == ValID::t_LocalID)
4203 return error(Label.Loc, "cannot take address of numeric label after "
4204 "the function is defined");
4206 F->getValueSymbolTable()->lookup(Label.StrVal));
4207 if (!BB)
4208 return error(Label.Loc, "referenced value is not a basic block");
4209 }
4210
4211 ID.ConstantVal = BlockAddress::get(F, BB);
4212 ID.Kind = ValID::t_Constant;
4213 return false;
4214 }
4215
4217 // ValID ::= 'dso_local_equivalent' @foo
4218 Lex.Lex();
4219
4220 ValID Fn;
4221
4222 if (parseValID(Fn, PFS))
4223 return true;
4224
4226 return error(Fn.Loc,
4227 "expected global value name in dso_local_equivalent");
4228
4229 // Try to find the function (but skip it if it's forward-referenced).
4230 GlobalValue *GV = nullptr;
4231 if (Fn.Kind == ValID::t_GlobalID) {
4232 GV = NumberedVals.get(Fn.UIntVal);
4233 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4234 GV = M->getNamedValue(Fn.StrVal);
4235 }
4236
4237 if (!GV) {
4238 // Make a placeholder global variable as a placeholder for this reference.
4239 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4240 ? ForwardRefDSOLocalEquivalentIDs
4241 : ForwardRefDSOLocalEquivalentNames;
4242 GlobalValue *&FwdRef = FwdRefMap[Fn];
4243 if (!FwdRef) {
4244 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4245 GlobalValue::InternalLinkage, nullptr, "",
4247 }
4248
4249 ID.ConstantVal = FwdRef;
4250 ID.Kind = ValID::t_Constant;
4251 return false;
4252 }
4253
4254 if (!GV->getValueType()->isFunctionTy())
4255 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4256 "in dso_local_equivalent");
4257
4258 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4259 ID.Kind = ValID::t_Constant;
4260 return false;
4261 }
4262
4263 case lltok::kw_no_cfi: {
4264 // ValID ::= 'no_cfi' @foo
4265 Lex.Lex();
4266
4267 if (parseValID(ID, PFS))
4268 return true;
4269
4270 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4271 return error(ID.Loc, "expected global value name in no_cfi");
4272
4273 ID.NoCFI = true;
4274 return false;
4275 }
4276 case lltok::kw_ptrauth: {
4277 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4278 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4279 // )? )? ')'
4280 Lex.Lex();
4281
4282 Constant *Ptr, *Key;
4283 Constant *Disc = nullptr, *AddrDisc = nullptr,
4284 *DeactivationSymbol = nullptr;
4285
4286 if (parseToken(lltok::lparen,
4287 "expected '(' in constant ptrauth expression") ||
4288 parseGlobalTypeAndValue(Ptr) ||
4289 parseToken(lltok::comma,
4290 "expected comma in constant ptrauth expression") ||
4291 parseGlobalTypeAndValue(Key))
4292 return true;
4293 // If present, parse the optional disc/addrdisc/ds.
4294 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4295 return true;
4296 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4297 return true;
4298 if (EatIfPresent(lltok::comma) &&
4299 parseGlobalTypeAndValue(DeactivationSymbol))
4300 return true;
4301 if (parseToken(lltok::rparen,
4302 "expected ')' in constant ptrauth expression"))
4303 return true;
4304
4305 if (!Ptr->getType()->isPointerTy())
4306 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4307
4308 auto *KeyC = dyn_cast<ConstantInt>(Key);
4309 if (!KeyC || KeyC->getBitWidth() != 32)
4310 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4311
4312 ConstantInt *DiscC = nullptr;
4313 if (Disc) {
4314 DiscC = dyn_cast<ConstantInt>(Disc);
4315 if (!DiscC || DiscC->getBitWidth() != 64)
4316 return error(
4317 ID.Loc,
4318 "constant ptrauth integer discriminator must be i64 constant");
4319 } else {
4320 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4321 }
4322
4323 if (AddrDisc) {
4324 if (!AddrDisc->getType()->isPointerTy())
4325 return error(
4326 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4327 } else {
4328 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4329 }
4330
4331 if (!DeactivationSymbol)
4332 DeactivationSymbol =
4334 if (!DeactivationSymbol->getType()->isPointerTy())
4335 return error(ID.Loc,
4336 "constant ptrauth deactivation symbol must be a pointer");
4337
4338 ID.ConstantVal =
4339 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4340 ID.Kind = ValID::t_Constant;
4341 return false;
4342 }
4343
4344 case lltok::kw_trunc:
4345 case lltok::kw_bitcast:
4347 case lltok::kw_inttoptr:
4349 case lltok::kw_ptrtoint: {
4350 unsigned Opc = Lex.getUIntVal();
4351 Type *DestTy = nullptr;
4352 Constant *SrcVal;
4353 Lex.Lex();
4354 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4355 parseGlobalTypeAndValue(SrcVal) ||
4356 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4357 parseType(DestTy) ||
4358 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4359 return true;
4360 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4361 return error(ID.Loc, "invalid cast opcode for cast from '" +
4362 getTypeString(SrcVal->getType()) + "' to '" +
4363 getTypeString(DestTy) + "'");
4365 SrcVal, DestTy);
4366 ID.Kind = ValID::t_Constant;
4367 return false;
4368 }
4370 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4372 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4373 case lltok::kw_udiv:
4374 return error(ID.Loc, "udiv constexprs are no longer supported");
4375 case lltok::kw_sdiv:
4376 return error(ID.Loc, "sdiv constexprs are no longer supported");
4377 case lltok::kw_urem:
4378 return error(ID.Loc, "urem constexprs are no longer supported");
4379 case lltok::kw_srem:
4380 return error(ID.Loc, "srem constexprs are no longer supported");
4381 case lltok::kw_fadd:
4382 return error(ID.Loc, "fadd constexprs are no longer supported");
4383 case lltok::kw_fsub:
4384 return error(ID.Loc, "fsub constexprs are no longer supported");
4385 case lltok::kw_fmul:
4386 return error(ID.Loc, "fmul constexprs are no longer supported");
4387 case lltok::kw_fdiv:
4388 return error(ID.Loc, "fdiv constexprs are no longer supported");
4389 case lltok::kw_frem:
4390 return error(ID.Loc, "frem constexprs are no longer supported");
4391 case lltok::kw_and:
4392 return error(ID.Loc, "and constexprs are no longer supported");
4393 case lltok::kw_or:
4394 return error(ID.Loc, "or constexprs are no longer supported");
4395 case lltok::kw_lshr:
4396 return error(ID.Loc, "lshr constexprs are no longer supported");
4397 case lltok::kw_ashr:
4398 return error(ID.Loc, "ashr constexprs are no longer supported");
4399 case lltok::kw_shl:
4400 return error(ID.Loc, "shl constexprs are no longer supported");
4401 case lltok::kw_mul:
4402 return error(ID.Loc, "mul constexprs are no longer supported");
4403 case lltok::kw_fneg:
4404 return error(ID.Loc, "fneg constexprs are no longer supported");
4405 case lltok::kw_select:
4406 return error(ID.Loc, "select constexprs are no longer supported");
4407 case lltok::kw_zext:
4408 return error(ID.Loc, "zext constexprs are no longer supported");
4409 case lltok::kw_sext:
4410 return error(ID.Loc, "sext constexprs are no longer supported");
4411 case lltok::kw_fptrunc:
4412 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4413 case lltok::kw_fpext:
4414 return error(ID.Loc, "fpext constexprs are no longer supported");
4415 case lltok::kw_uitofp:
4416 return error(ID.Loc, "uitofp constexprs are no longer supported");
4417 case lltok::kw_sitofp:
4418 return error(ID.Loc, "sitofp constexprs are no longer supported");
4419 case lltok::kw_fptoui:
4420 return error(ID.Loc, "fptoui constexprs are no longer supported");
4421 case lltok::kw_fptosi:
4422 return error(ID.Loc, "fptosi constexprs are no longer supported");
4423 case lltok::kw_icmp:
4424 return error(ID.Loc, "icmp constexprs are no longer supported");
4425 case lltok::kw_fcmp:
4426 return error(ID.Loc, "fcmp constexprs are no longer supported");
4427
4428 // Binary Operators.
4429 case lltok::kw_add:
4430 case lltok::kw_sub:
4431 case lltok::kw_xor: {
4432 bool NUW = false;
4433 bool NSW = false;
4434 unsigned Opc = Lex.getUIntVal();
4435 Constant *Val0, *Val1;
4436 Lex.Lex();
4437 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4438 Opc == Instruction::Mul) {
4439 if (EatIfPresent(lltok::kw_nuw))
4440 NUW = true;
4441 if (EatIfPresent(lltok::kw_nsw)) {
4442 NSW = true;
4443 if (EatIfPresent(lltok::kw_nuw))
4444 NUW = true;
4445 }
4446 }
4447 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4448 parseGlobalTypeAndValue(Val0) ||
4449 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4450 parseGlobalTypeAndValue(Val1) ||
4451 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4452 return true;
4453 if (Val0->getType() != Val1->getType())
4454 return error(ID.Loc, "operands of constexpr must have same type");
4455 // Check that the type is valid for the operator.
4456 if (!Val0->getType()->isIntOrIntVectorTy())
4457 return error(ID.Loc,
4458 "constexpr requires integer or integer vector operands");
4459 unsigned Flags = 0;
4462 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4463 ID.Kind = ValID::t_Constant;
4464 return false;
4465 }
4466
4467 case lltok::kw_splat: {
4468 Lex.Lex();
4469 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4470 return true;
4471 Constant *C;
4472 if (parseGlobalTypeAndValue(C))
4473 return true;
4474 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4475 return true;
4476
4477 ID.ConstantVal = C;
4479 return false;
4480 }
4481
4486 unsigned Opc = Lex.getUIntVal();
4488 GEPNoWrapFlags NW;
4489 bool HasInRange = false;
4490 APSInt InRangeStart;
4491 APSInt InRangeEnd;
4492 Type *Ty;
4493 Lex.Lex();
4494
4495 if (Opc == Instruction::GetElementPtr) {
4496 while (true) {
4497 if (EatIfPresent(lltok::kw_inbounds))
4499 else if (EatIfPresent(lltok::kw_nusw))
4501 else if (EatIfPresent(lltok::kw_nuw))
4503 else
4504 break;
4505 }
4506
4507 if (EatIfPresent(lltok::kw_inrange)) {
4508 if (parseToken(lltok::lparen, "expected '('"))
4509 return true;
4510 if (Lex.getKind() != lltok::APSInt)
4511 return tokError("expected integer");
4512 InRangeStart = Lex.getAPSIntVal();
4513 Lex.Lex();
4514 if (parseToken(lltok::comma, "expected ','"))
4515 return true;
4516 if (Lex.getKind() != lltok::APSInt)
4517 return tokError("expected integer");
4518 InRangeEnd = Lex.getAPSIntVal();
4519 Lex.Lex();
4520 if (parseToken(lltok::rparen, "expected ')'"))
4521 return true;
4522 HasInRange = true;
4523 }
4524 }
4525
4526 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4527 return true;
4528
4529 if (Opc == Instruction::GetElementPtr) {
4530 if (parseType(Ty) ||
4531 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4532 return true;
4533 }
4534
4535 if (parseGlobalValueVector(Elts) ||
4536 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4537 return true;
4538
4539 if (Opc == Instruction::GetElementPtr) {
4540 if (Elts.size() == 0 ||
4541 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4542 return error(ID.Loc, "base of getelementptr must be a pointer");
4543
4544 Type *BaseType = Elts[0]->getType();
4545 std::optional<ConstantRange> InRange;
4546 if (HasInRange) {
4547 unsigned IndexWidth =
4548 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4549 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4550 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4551 if (InRangeStart.sge(InRangeEnd))
4552 return error(ID.Loc, "expected end to be larger than start");
4553 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4554 }
4555
4556 unsigned GEPWidth =
4557 BaseType->isVectorTy()
4558 ? cast<FixedVectorType>(BaseType)->getNumElements()
4559 : 0;
4560
4561 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4562 for (Constant *Val : Indices) {
4563 Type *ValTy = Val->getType();
4564 if (!ValTy->isIntOrIntVectorTy())
4565 return error(ID.Loc, "getelementptr index must be an integer");
4566 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4567 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4568 if (GEPWidth && (ValNumEl != GEPWidth))
4569 return error(
4570 ID.Loc,
4571 "getelementptr vector index has a wrong number of elements");
4572 // GEPWidth may have been unknown because the base is a scalar,
4573 // but it is known now.
4574 GEPWidth = ValNumEl;
4575 }
4576 }
4577
4578 SmallPtrSet<Type*, 4> Visited;
4579 if (!Indices.empty() && !Ty->isSized(&Visited))
4580 return error(ID.Loc, "base element of getelementptr must be sized");
4581
4583 return error(ID.Loc, "invalid base element for constant getelementptr");
4584
4585 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4586 return error(ID.Loc, "invalid getelementptr indices");
4587
4588 ID.ConstantVal =
4589 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4590 } else if (Opc == Instruction::ShuffleVector) {
4591 if (Elts.size() != 3)
4592 return error(ID.Loc, "expected three operands to shufflevector");
4593 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4594 return error(ID.Loc, "invalid operands to shufflevector");
4595 SmallVector<int, 16> Mask;
4597 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4598 } else if (Opc == Instruction::ExtractElement) {
4599 if (Elts.size() != 2)
4600 return error(ID.Loc, "expected two operands to extractelement");
4601 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4602 return error(ID.Loc, "invalid extractelement operands");
4603 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4604 } else {
4605 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4606 if (Elts.size() != 3)
4607 return error(ID.Loc, "expected three operands to insertelement");
4608 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4609 return error(ID.Loc, "invalid insertelement operands");
4610 ID.ConstantVal =
4611 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4612 }
4613
4614 ID.Kind = ValID::t_Constant;
4615 return false;
4616 }
4617 }
4618
4619 Lex.Lex();
4620 return false;
4621}
4622
4623/// parseGlobalValue - parse a global value with the specified type.
4624bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4625 C = nullptr;
4626 ValID ID;
4627 Value *V = nullptr;
4628 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4629 convertValIDToValue(Ty, ID, V, nullptr);
4630 if (V && !(C = dyn_cast<Constant>(V)))
4631 return error(ID.Loc, "global values must be constants");
4632 return Parsed;
4633}
4634
4635bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4636 Type *Ty = nullptr;
4637 return parseType(Ty) || parseGlobalValue(Ty, V);
4638}
4639
4640bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4641 C = nullptr;
4642
4643 LocTy KwLoc = Lex.getLoc();
4644 if (!EatIfPresent(lltok::kw_comdat))
4645 return false;
4646
4647 if (EatIfPresent(lltok::lparen)) {
4648 if (Lex.getKind() != lltok::ComdatVar)
4649 return tokError("expected comdat variable");
4650 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4651 Lex.Lex();
4652 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4653 return true;
4654 } else {
4655 if (GlobalName.empty())
4656 return tokError("comdat cannot be unnamed");
4657 C = getComdat(std::string(GlobalName), KwLoc);
4658 }
4659
4660 return false;
4661}
4662
4663/// parseGlobalValueVector
4664/// ::= /*empty*/
4665/// ::= TypeAndValue (',' TypeAndValue)*
4666bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4667 // Empty list.
4668 if (Lex.getKind() == lltok::rbrace ||
4669 Lex.getKind() == lltok::rsquare ||
4670 Lex.getKind() == lltok::greater ||
4671 Lex.getKind() == lltok::rparen)
4672 return false;
4673
4674 do {
4675 // Let the caller deal with inrange.
4676 if (Lex.getKind() == lltok::kw_inrange)
4677 return false;
4678
4679 Constant *C;
4680 if (parseGlobalTypeAndValue(C))
4681 return true;
4682 Elts.push_back(C);
4683 } while (EatIfPresent(lltok::comma));
4684
4685 return false;
4686}
4687
4688bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4690 if (parseMDNodeVector(Elts))
4691 return true;
4692
4693 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4694 return false;
4695}
4696
4697/// MDNode:
4698/// ::= !{ ... }
4699/// ::= !7
4700/// ::= !DILocation(...)
4701bool LLParser::parseMDNode(MDNode *&N) {
4702 if (Lex.getKind() == lltok::MetadataVar)
4703 return parseSpecializedMDNode(N);
4704
4705 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4706}
4707
4708bool LLParser::parseMDNodeTail(MDNode *&N) {
4709 // !{ ... }
4710 if (Lex.getKind() == lltok::lbrace)
4711 return parseMDTuple(N);
4712
4713 // !42
4714 return parseMDNodeID(N);
4715}
4716
4717namespace {
4718
4719/// Structure to represent an optional metadata field.
4720template <class FieldTy> struct MDFieldImpl {
4721 typedef MDFieldImpl ImplTy;
4722 FieldTy Val;
4723 bool Seen;
4724
4725 void assign(FieldTy Val) {
4726 Seen = true;
4727 this->Val = std::move(Val);
4728 }
4729
4730 explicit MDFieldImpl(FieldTy Default)
4731 : Val(std::move(Default)), Seen(false) {}
4732};
4733
4734/// Structure to represent an optional metadata field that
4735/// can be of either type (A or B) and encapsulates the
4736/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4737/// to reimplement the specifics for representing each Field.
4738template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4739 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4740 FieldTypeA A;
4741 FieldTypeB B;
4742 bool Seen;
4743
4744 enum {
4745 IsInvalid = 0,
4746 IsTypeA = 1,
4747 IsTypeB = 2
4748 } WhatIs;
4749
4750 void assign(FieldTypeA A) {
4751 Seen = true;
4752 this->A = std::move(A);
4753 WhatIs = IsTypeA;
4754 }
4755
4756 void assign(FieldTypeB B) {
4757 Seen = true;
4758 this->B = std::move(B);
4759 WhatIs = IsTypeB;
4760 }
4761
4762 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4763 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4764 WhatIs(IsInvalid) {}
4765};
4766
4767struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4768 uint64_t Max;
4769
4770 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4771 : ImplTy(Default), Max(Max) {}
4772};
4773
4774struct LineField : public MDUnsignedField {
4775 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4776};
4777
4778struct ColumnField : public MDUnsignedField {
4779 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4780};
4781
4782struct DwarfTagField : public MDUnsignedField {
4783 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4784 DwarfTagField(dwarf::Tag DefaultTag)
4785 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4786};
4787
4788struct DwarfMacinfoTypeField : public MDUnsignedField {
4789 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4790 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4791 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4792};
4793
4794struct DwarfAttEncodingField : public MDUnsignedField {
4795 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4796};
4797
4798struct DwarfVirtualityField : public MDUnsignedField {
4799 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4800};
4801
4802struct DwarfLangField : public MDUnsignedField {
4803 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4804};
4805
4806struct DwarfSourceLangNameField : public MDUnsignedField {
4807 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4808};
4809
4810struct DwarfCCField : public MDUnsignedField {
4811 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4812};
4813
4814struct DwarfEnumKindField : public MDUnsignedField {
4815 DwarfEnumKindField()
4816 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4817 dwarf::DW_APPLE_ENUM_KIND_max) {}
4818};
4819
4820struct EmissionKindField : public MDUnsignedField {
4821 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4822};
4823
4824struct FixedPointKindField : public MDUnsignedField {
4825 FixedPointKindField()
4826 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4827};
4828
4829struct NameTableKindField : public MDUnsignedField {
4830 NameTableKindField()
4831 : MDUnsignedField(
4832 0, (unsigned)
4833 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4834};
4835
4836struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4837 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4838};
4839
4840struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4841 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4842};
4843
4844struct MDAPSIntField : public MDFieldImpl<APSInt> {
4845 MDAPSIntField() : ImplTy(APSInt()) {}
4846};
4847
4848struct MDSignedField : public MDFieldImpl<int64_t> {
4849 int64_t Min = INT64_MIN;
4850 int64_t Max = INT64_MAX;
4851
4852 MDSignedField(int64_t Default = 0)
4853 : ImplTy(Default) {}
4854 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4855 : ImplTy(Default), Min(Min), Max(Max) {}
4856};
4857
4858struct MDBoolField : public MDFieldImpl<bool> {
4859 MDBoolField(bool Default = false) : ImplTy(Default) {}
4860};
4861
4862struct MDField : public MDFieldImpl<Metadata *> {
4863 bool AllowNull;
4864
4865 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4866};
4867
4868struct MDStringField : public MDFieldImpl<MDString *> {
4869 enum class EmptyIs {
4870 Null, //< Allow empty input string, map to nullptr
4871 Empty, //< Allow empty input string, map to an empty MDString
4872 Error, //< Disallow empty string, map to an error
4873 } EmptyIs;
4874 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
4875 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4876};
4877
4878struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4879 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4880};
4881
4882struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4883 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4884};
4885
4886struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4887 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4888 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4889
4890 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4891 bool AllowNull = true)
4892 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4893
4894 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4895 bool isMDField() const { return WhatIs == IsTypeB; }
4896 int64_t getMDSignedValue() const {
4897 assert(isMDSignedField() && "Wrong field type");
4898 return A.Val;
4899 }
4900 Metadata *getMDFieldValue() const {
4901 assert(isMDField() && "Wrong field type");
4902 return B.Val;
4903 }
4904};
4905
4906struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4907 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
4908 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
4909
4910 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
4911 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
4912
4913 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
4914 bool isMDField() const { return WhatIs == IsTypeB; }
4915 uint64_t getMDUnsignedValue() const {
4916 assert(isMDUnsignedField() && "Wrong field type");
4917 return A.Val;
4918 }
4919 Metadata *getMDFieldValue() const {
4920 assert(isMDField() && "Wrong field type");
4921 return B.Val;
4922 }
4923
4924 Metadata *getValueAsMetadata(LLVMContext &Context) const {
4925 if (isMDUnsignedField())
4927 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
4928 if (isMDField())
4929 return getMDFieldValue();
4930 return nullptr;
4931 }
4932};
4933
4934} // end anonymous namespace
4935
4936namespace llvm {
4937
4938template <>
4939bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4940 if (Lex.getKind() != lltok::APSInt)
4941 return tokError("expected integer");
4942
4943 Result.assign(Lex.getAPSIntVal());
4944 Lex.Lex();
4945 return false;
4946}
4947
4948template <>
4949bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4950 MDUnsignedField &Result) {
4951 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4952 return tokError("expected unsigned integer");
4953
4954 auto &U = Lex.getAPSIntVal();
4955 if (U.ugt(Result.Max))
4956 return tokError("value for '" + Name + "' too large, limit is " +
4957 Twine(Result.Max));
4958 Result.assign(U.getZExtValue());
4959 assert(Result.Val <= Result.Max && "Expected value in range");
4960 Lex.Lex();
4961 return false;
4962}
4963
4964template <>
4965bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4966 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4967}
4968template <>
4969bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4970 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4971}
4972
4973template <>
4974bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4975 if (Lex.getKind() == lltok::APSInt)
4976 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4977
4978 if (Lex.getKind() != lltok::DwarfTag)
4979 return tokError("expected DWARF tag");
4980
4981 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4983 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4984 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4985
4986 Result.assign(Tag);
4987 Lex.Lex();
4988 return false;
4989}
4990
4991template <>
4992bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4993 DwarfMacinfoTypeField &Result) {
4994 if (Lex.getKind() == lltok::APSInt)
4995 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4996
4997 if (Lex.getKind() != lltok::DwarfMacinfo)
4998 return tokError("expected DWARF macinfo type");
4999
5000 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5001 if (Macinfo == dwarf::DW_MACINFO_invalid)
5002 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5003 Lex.getStrVal() + "'");
5004 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5005
5006 Result.assign(Macinfo);
5007 Lex.Lex();
5008 return false;
5009}
5010
5011template <>
5012bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5013 DwarfVirtualityField &Result) {
5014 if (Lex.getKind() == lltok::APSInt)
5015 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5016
5017 if (Lex.getKind() != lltok::DwarfVirtuality)
5018 return tokError("expected DWARF virtuality code");
5019
5020 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5021 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5022 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5023 Lex.getStrVal() + "'");
5024 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5025 Result.assign(Virtuality);
5026 Lex.Lex();
5027 return false;
5028}
5029
5030template <>
5031bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5032 DwarfEnumKindField &Result) {
5033 if (Lex.getKind() == lltok::APSInt)
5034 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5035
5036 if (Lex.getKind() != lltok::DwarfEnumKind)
5037 return tokError("expected DWARF enum kind code");
5038
5039 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5040 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5041 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5042 Lex.getStrVal() + "'");
5043 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5044 Result.assign(EnumKind);
5045 Lex.Lex();
5046 return false;
5047}
5048
5049template <>
5050bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5051 if (Lex.getKind() == lltok::APSInt)
5052 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5053
5054 if (Lex.getKind() != lltok::DwarfLang)
5055 return tokError("expected DWARF language");
5056
5057 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5058 if (!Lang)
5059 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5060 "'");
5061 assert(Lang <= Result.Max && "Expected valid DWARF language");
5062 Result.assign(Lang);
5063 Lex.Lex();
5064 return false;
5065}
5066
5067template <>
5068bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5069 DwarfSourceLangNameField &Result) {
5070 if (Lex.getKind() == lltok::APSInt)
5071 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5072
5073 if (Lex.getKind() != lltok::DwarfSourceLangName)
5074 return tokError("expected DWARF source language name");
5075
5076 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5077 if (!Lang)
5078 return tokError("invalid DWARF source language name" + Twine(" '") +
5079 Lex.getStrVal() + "'");
5080 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5081 Result.assign(Lang);
5082 Lex.Lex();
5083 return false;
5084}
5085
5086template <>
5087bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5088 if (Lex.getKind() == lltok::APSInt)
5089 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5090
5091 if (Lex.getKind() != lltok::DwarfCC)
5092 return tokError("expected DWARF calling convention");
5093
5094 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5095 if (!CC)
5096 return tokError("invalid DWARF calling convention" + Twine(" '") +
5097 Lex.getStrVal() + "'");
5098 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5099 Result.assign(CC);
5100 Lex.Lex();
5101 return false;
5102}
5103
5104template <>
5105bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5106 EmissionKindField &Result) {
5107 if (Lex.getKind() == lltok::APSInt)
5108 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5109
5110 if (Lex.getKind() != lltok::EmissionKind)
5111 return tokError("expected emission kind");
5112
5113 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5114 if (!Kind)
5115 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5116 "'");
5117 assert(*Kind <= Result.Max && "Expected valid emission kind");
5118 Result.assign(*Kind);
5119 Lex.Lex();
5120 return false;
5121}
5122
5123template <>
5124bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5125 FixedPointKindField &Result) {
5126 if (Lex.getKind() == lltok::APSInt)
5127 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5128
5129 if (Lex.getKind() != lltok::FixedPointKind)
5130 return tokError("expected fixed-point kind");
5131
5132 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5133 if (!Kind)
5134 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5135 "'");
5136 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5137 Result.assign(*Kind);
5138 Lex.Lex();
5139 return false;
5140}
5141
5142template <>
5143bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5144 NameTableKindField &Result) {
5145 if (Lex.getKind() == lltok::APSInt)
5146 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5147
5148 if (Lex.getKind() != lltok::NameTableKind)
5149 return tokError("expected nameTable kind");
5150
5151 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5152 if (!Kind)
5153 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5154 "'");
5155 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5156 Result.assign((unsigned)*Kind);
5157 Lex.Lex();
5158 return false;
5159}
5160
5161template <>
5162bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5163 DwarfAttEncodingField &Result) {
5164 if (Lex.getKind() == lltok::APSInt)
5165 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5166
5167 if (Lex.getKind() != lltok::DwarfAttEncoding)
5168 return tokError("expected DWARF type attribute encoding");
5169
5170 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5171 if (!Encoding)
5172 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5173 Lex.getStrVal() + "'");
5174 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5175 Result.assign(Encoding);
5176 Lex.Lex();
5177 return false;
5178}
5179
5180/// DIFlagField
5181/// ::= uint32
5182/// ::= DIFlagVector
5183/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5184template <>
5185bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5186
5187 // parser for a single flag.
5188 auto parseFlag = [&](DINode::DIFlags &Val) {
5189 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5190 uint32_t TempVal = static_cast<uint32_t>(Val);
5191 bool Res = parseUInt32(TempVal);
5192 Val = static_cast<DINode::DIFlags>(TempVal);
5193 return Res;
5194 }
5195
5196 if (Lex.getKind() != lltok::DIFlag)
5197 return tokError("expected debug info flag");
5198
5199 Val = DINode::getFlag(Lex.getStrVal());
5200 if (!Val)
5201 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5202 "'");
5203 Lex.Lex();
5204 return false;
5205 };
5206
5207 // parse the flags and combine them together.
5208 DINode::DIFlags Combined = DINode::FlagZero;
5209 do {
5210 DINode::DIFlags Val;
5211 if (parseFlag(Val))
5212 return true;
5213 Combined |= Val;
5214 } while (EatIfPresent(lltok::bar));
5215
5216 Result.assign(Combined);
5217 return false;
5218}
5219
5220/// DISPFlagField
5221/// ::= uint32
5222/// ::= DISPFlagVector
5223/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5224template <>
5225bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5226
5227 // parser for a single flag.
5228 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5229 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5230 uint32_t TempVal = static_cast<uint32_t>(Val);
5231 bool Res = parseUInt32(TempVal);
5232 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5233 return Res;
5234 }
5235
5236 if (Lex.getKind() != lltok::DISPFlag)
5237 return tokError("expected debug info flag");
5238
5239 Val = DISubprogram::getFlag(Lex.getStrVal());
5240 if (!Val)
5241 return tokError(Twine("invalid subprogram debug info flag '") +
5242 Lex.getStrVal() + "'");
5243 Lex.Lex();
5244 return false;
5245 };
5246
5247 // parse the flags and combine them together.
5248 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5249 do {
5251 if (parseFlag(Val))
5252 return true;
5253 Combined |= Val;
5254 } while (EatIfPresent(lltok::bar));
5255
5256 Result.assign(Combined);
5257 return false;
5258}
5259
5260template <>
5261bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5262 if (Lex.getKind() != lltok::APSInt)
5263 return tokError("expected signed integer");
5264
5265 auto &S = Lex.getAPSIntVal();
5266 if (S < Result.Min)
5267 return tokError("value for '" + Name + "' too small, limit is " +
5268 Twine(Result.Min));
5269 if (S > Result.Max)
5270 return tokError("value for '" + Name + "' too large, limit is " +
5271 Twine(Result.Max));
5272 Result.assign(S.getExtValue());
5273 assert(Result.Val >= Result.Min && "Expected value in range");
5274 assert(Result.Val <= Result.Max && "Expected value in range");
5275 Lex.Lex();
5276 return false;
5277}
5278
5279template <>
5280bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5281 switch (Lex.getKind()) {
5282 default:
5283 return tokError("expected 'true' or 'false'");
5284 case lltok::kw_true:
5285 Result.assign(true);
5286 break;
5287 case lltok::kw_false:
5288 Result.assign(false);
5289 break;
5290 }
5291 Lex.Lex();
5292 return false;
5293}
5294
5295template <>
5296bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5297 if (Lex.getKind() == lltok::kw_null) {
5298 if (!Result.AllowNull)
5299 return tokError("'" + Name + "' cannot be null");
5300 Lex.Lex();
5301 Result.assign(nullptr);
5302 return false;
5303 }
5304
5305 Metadata *MD;
5306 if (parseMetadata(MD, nullptr))
5307 return true;
5308
5309 Result.assign(MD);
5310 return false;
5311}
5312
5313template <>
5314bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5315 MDSignedOrMDField &Result) {
5316 // Try to parse a signed int.
5317 if (Lex.getKind() == lltok::APSInt) {
5318 MDSignedField Res = Result.A;
5319 if (!parseMDField(Loc, Name, Res)) {
5320 Result.assign(Res);
5321 return false;
5322 }
5323 return true;
5324 }
5325
5326 // Otherwise, try to parse as an MDField.
5327 MDField Res = Result.B;
5328 if (!parseMDField(Loc, Name, Res)) {
5329 Result.assign(Res);
5330 return false;
5331 }
5332
5333 return true;
5334}
5335
5336template <>
5337bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5338 MDUnsignedOrMDField &Result) {
5339 // Try to parse an unsigned int.
5340 if (Lex.getKind() == lltok::APSInt) {
5341 MDUnsignedField Res = Result.A;
5342 if (!parseMDField(Loc, Name, Res)) {
5343 Result.assign(Res);
5344 return false;
5345 }
5346 return true;
5347 }
5348
5349 // Otherwise, try to parse as an MDField.
5350 MDField Res = Result.B;
5351 if (!parseMDField(Loc, Name, Res)) {
5352 Result.assign(Res);
5353 return false;
5354 }
5355
5356 return true;
5357}
5358
5359template <>
5360bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5361 LocTy ValueLoc = Lex.getLoc();
5362 std::string S;
5363 if (parseStringConstant(S))
5364 return true;
5365
5366 if (S.empty()) {
5367 switch (Result.EmptyIs) {
5368 case MDStringField::EmptyIs::Null:
5369 Result.assign(nullptr);
5370 return false;
5371 case MDStringField::EmptyIs::Empty:
5372 break;
5373 case MDStringField::EmptyIs::Error:
5374 return error(ValueLoc, "'" + Name + "' cannot be empty");
5375 }
5376 }
5377
5378 Result.assign(MDString::get(Context, S));
5379 return false;
5380}
5381
5382template <>
5383bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5385 if (parseMDNodeVector(MDs))
5386 return true;
5387
5388 Result.assign(std::move(MDs));
5389 return false;
5390}
5391
5392template <>
5393bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5394 ChecksumKindField &Result) {
5395 std::optional<DIFile::ChecksumKind> CSKind =
5396 DIFile::getChecksumKind(Lex.getStrVal());
5397
5398 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5399 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5400 "'");
5401
5402 Result.assign(*CSKind);
5403 Lex.Lex();
5404 return false;
5405}
5406
5407} // end namespace llvm
5408
5409template <class ParserTy>
5410bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5411 do {
5412 if (Lex.getKind() != lltok::LabelStr)
5413 return tokError("expected field label here");
5414
5415 if (ParseField())
5416 return true;
5417 } while (EatIfPresent(lltok::comma));
5418
5419 return false;
5420}
5421
5422template <class ParserTy>
5423bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5424 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5425 Lex.Lex();
5426
5427 if (parseToken(lltok::lparen, "expected '(' here"))
5428 return true;
5429 if (Lex.getKind() != lltok::rparen)
5430 if (parseMDFieldsImplBody(ParseField))
5431 return true;
5432
5433 ClosingLoc = Lex.getLoc();
5434 return parseToken(lltok::rparen, "expected ')' here");
5435}
5436
5437template <class FieldTy>
5438bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5439 if (Result.Seen)
5440 return tokError("field '" + Name + "' cannot be specified more than once");
5441
5442 LocTy Loc = Lex.getLoc();
5443 Lex.Lex();
5444 return parseMDField(Loc, Name, Result);
5445}
5446
5447bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5448 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5449
5450#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5451 if (Lex.getStrVal() == #CLASS) \
5452 return parse##CLASS(N, IsDistinct);
5453#include "llvm/IR/Metadata.def"
5454
5455 return tokError("expected metadata type");
5456}
5457
5458#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5459#define NOP_FIELD(NAME, TYPE, INIT)
5460#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5461 if (!NAME.Seen) \
5462 return error(ClosingLoc, "missing required field '" #NAME "'");
5463#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5464 if (Lex.getStrVal() == #NAME) \
5465 return parseMDField(#NAME, NAME);
5466#define PARSE_MD_FIELDS() \
5467 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5468 do { \
5469 LocTy ClosingLoc; \
5470 if (parseMDFieldsImpl( \
5471 [&]() -> bool { \
5472 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5473 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5474 "'"); \
5475 }, \
5476 ClosingLoc)) \
5477 return true; \
5478 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5479 } while (false)
5480#define GET_OR_DISTINCT(CLASS, ARGS) \
5481 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5482
5483/// parseDILocationFields:
5484/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5485/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5486bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5487#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5488 OPTIONAL(line, LineField, ); \
5489 OPTIONAL(column, ColumnField, ); \
5490 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5491 OPTIONAL(inlinedAt, MDField, ); \
5492 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5493 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5494 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5496#undef VISIT_MD_FIELDS
5497
5498 Result = GET_OR_DISTINCT(
5499 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5500 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5501 return false;
5502}
5503
5504/// parseDIAssignID:
5505/// ::= distinct !DIAssignID()
5506bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5507 if (!IsDistinct)
5508 return tokError("missing 'distinct', required for !DIAssignID()");
5509
5510 Lex.Lex();
5511
5512 // Now eat the parens.
5513 if (parseToken(lltok::lparen, "expected '(' here"))
5514 return true;
5515 if (parseToken(lltok::rparen, "expected ')' here"))
5516 return true;
5517
5519 return false;
5520}
5521
5522/// parseGenericDINode:
5523/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5524bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5525#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5526 REQUIRED(tag, DwarfTagField, ); \
5527 OPTIONAL(header, MDStringField, ); \
5528 OPTIONAL(operands, MDFieldList, );
5530#undef VISIT_MD_FIELDS
5531
5532 Result = GET_OR_DISTINCT(GenericDINode,
5533 (Context, tag.Val, header.Val, operands.Val));
5534 return false;
5535}
5536
5537/// parseDISubrangeType:
5538/// ::= !DISubrangeType(name: "whatever", file: !0,
5539/// line: 7, scope: !1, baseType: !2, size: 32,
5540/// align: 32, flags: 0, lowerBound: !3
5541/// upperBound: !4, stride: !5, bias: !6)
5542bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5543#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5544 OPTIONAL(name, MDStringField, ); \
5545 OPTIONAL(file, MDField, ); \
5546 OPTIONAL(line, LineField, ); \
5547 OPTIONAL(scope, MDField, ); \
5548 OPTIONAL(baseType, MDField, ); \
5549 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5550 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5551 OPTIONAL(flags, DIFlagField, ); \
5552 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5553 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5554 OPTIONAL(stride, MDSignedOrMDField, ); \
5555 OPTIONAL(bias, MDSignedOrMDField, );
5557#undef VISIT_MD_FIELDS
5558
5559 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5560 if (Bound.isMDSignedField())
5562 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5563 if (Bound.isMDField())
5564 return Bound.getMDFieldValue();
5565 return nullptr;
5566 };
5567
5568 Metadata *LowerBound = convToMetadata(lowerBound);
5569 Metadata *UpperBound = convToMetadata(upperBound);
5570 Metadata *Stride = convToMetadata(stride);
5571 Metadata *Bias = convToMetadata(bias);
5572
5574 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5575 size.getValueAsMetadata(Context), align.Val, flags.Val,
5576 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5577
5578 return false;
5579}
5580
5581/// parseDISubrange:
5582/// ::= !DISubrange(count: 30, lowerBound: 2)
5583/// ::= !DISubrange(count: !node, lowerBound: 2)
5584/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5585bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5586#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5587 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5588 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5589 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5590 OPTIONAL(stride, MDSignedOrMDField, );
5592#undef VISIT_MD_FIELDS
5593
5594 Metadata *Count = nullptr;
5595 Metadata *LowerBound = nullptr;
5596 Metadata *UpperBound = nullptr;
5597 Metadata *Stride = nullptr;
5598
5599 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5600 if (Bound.isMDSignedField())
5602 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5603 if (Bound.isMDField())
5604 return Bound.getMDFieldValue();
5605 return nullptr;
5606 };
5607
5608 Count = convToMetadata(count);
5609 LowerBound = convToMetadata(lowerBound);
5610 UpperBound = convToMetadata(upperBound);
5611 Stride = convToMetadata(stride);
5612
5613 Result = GET_OR_DISTINCT(DISubrange,
5614 (Context, Count, LowerBound, UpperBound, Stride));
5615
5616 return false;
5617}
5618
5619/// parseDIGenericSubrange:
5620/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5621/// !node3)
5622bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5623#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5624 OPTIONAL(count, MDSignedOrMDField, ); \
5625 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5626 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5627 OPTIONAL(stride, MDSignedOrMDField, );
5629#undef VISIT_MD_FIELDS
5630
5631 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5632 if (Bound.isMDSignedField())
5633 return DIExpression::get(
5634 Context, {dwarf::DW_OP_consts,
5635 static_cast<uint64_t>(Bound.getMDSignedValue())});
5636 if (Bound.isMDField())
5637 return Bound.getMDFieldValue();
5638 return nullptr;
5639 };
5640
5641 Metadata *Count = ConvToMetadata(count);
5642 Metadata *LowerBound = ConvToMetadata(lowerBound);
5643 Metadata *UpperBound = ConvToMetadata(upperBound);
5644 Metadata *Stride = ConvToMetadata(stride);
5645
5646 Result = GET_OR_DISTINCT(DIGenericSubrange,
5647 (Context, Count, LowerBound, UpperBound, Stride));
5648
5649 return false;
5650}
5651
5652/// parseDIEnumerator:
5653/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5654bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5655#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5656 REQUIRED(name, MDStringField, ); \
5657 REQUIRED(value, MDAPSIntField, ); \
5658 OPTIONAL(isUnsigned, MDBoolField, (false));
5660#undef VISIT_MD_FIELDS
5661
5662 if (isUnsigned.Val && value.Val.isNegative())
5663 return tokError("unsigned enumerator with negative value");
5664
5665 APSInt Value(value.Val);
5666 // Add a leading zero so that unsigned values with the msb set are not
5667 // mistaken for negative values when used for signed enumerators.
5668 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5669 Value = Value.zext(Value.getBitWidth() + 1);
5670
5671 Result =
5672 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5673
5674 return false;
5675}
5676
5677/// parseDIBasicType:
5678/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5679/// encoding: DW_ATE_encoding, flags: 0)
5680bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5681#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5682 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5683 OPTIONAL(name, MDStringField, ); \
5684 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5685 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5686 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5687 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5688 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5689 OPTIONAL(flags, DIFlagField, );
5691#undef VISIT_MD_FIELDS
5692
5694 DIBasicType,
5695 (Context, tag.Val, name.Val, size.getValueAsMetadata(Context), align.Val,
5696 encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5697 return false;
5698}
5699
5700/// parseDIFixedPointType:
5701/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5702/// align: 32, encoding: DW_ATE_signed_fixed,
5703/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5704/// denominator: 8)
5705bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5706#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5707 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5708 OPTIONAL(name, MDStringField, ); \
5709 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5710 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5711 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5712 OPTIONAL(flags, DIFlagField, ); \
5713 OPTIONAL(kind, FixedPointKindField, ); \
5714 OPTIONAL(factor, MDSignedField, ); \
5715 OPTIONAL(numerator, MDAPSIntField, ); \
5716 OPTIONAL(denominator, MDAPSIntField, );
5718#undef VISIT_MD_FIELDS
5719
5720 Result = GET_OR_DISTINCT(DIFixedPointType,
5721 (Context, tag.Val, name.Val,
5722 size.getValueAsMetadata(Context), align.Val,
5723 encoding.Val, flags.Val, kind.Val, factor.Val,
5724 numerator.Val, denominator.Val));
5725 return false;
5726}
5727
5728/// parseDIStringType:
5729/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5730bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5731#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5732 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5733 OPTIONAL(name, MDStringField, ); \
5734 OPTIONAL(stringLength, MDField, ); \
5735 OPTIONAL(stringLengthExpression, MDField, ); \
5736 OPTIONAL(stringLocationExpression, MDField, ); \
5737 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5738 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5739 OPTIONAL(encoding, DwarfAttEncodingField, );
5741#undef VISIT_MD_FIELDS
5742
5744 DIStringType,
5745 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5746 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5747 align.Val, encoding.Val));
5748 return false;
5749}
5750
5751/// parseDIDerivedType:
5752/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5753/// line: 7, scope: !1, baseType: !2, size: 32,
5754/// align: 32, offset: 0, flags: 0, extraData: !3,
5755/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5756/// ptrAuthIsAddressDiscriminated: true,
5757/// ptrAuthExtraDiscriminator: 0x1234,
5758/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5759/// )
5760bool LLParser::parseDIDerivedType(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 REQUIRED(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(extraData, MDField, ); \
5773 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5774 OPTIONAL(annotations, MDField, ); \
5775 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5776 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5777 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5778 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5779 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5781#undef VISIT_MD_FIELDS
5782
5783 std::optional<unsigned> DWARFAddressSpace;
5784 if (dwarfAddressSpace.Val != UINT32_MAX)
5785 DWARFAddressSpace = dwarfAddressSpace.Val;
5786 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5787 if (ptrAuthKey.Val)
5788 PtrAuthData.emplace(
5789 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5790 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5791 ptrAuthAuthenticatesNullValues.Val);
5792
5794 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5795 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5796 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5797 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5798 return false;
5799}
5800
5801bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5802#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5803 REQUIRED(tag, DwarfTagField, ); \
5804 OPTIONAL(name, MDStringField, ); \
5805 OPTIONAL(file, MDField, ); \
5806 OPTIONAL(line, LineField, ); \
5807 OPTIONAL(scope, MDField, ); \
5808 OPTIONAL(baseType, MDField, ); \
5809 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5810 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5811 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5812 OPTIONAL(flags, DIFlagField, ); \
5813 OPTIONAL(elements, MDField, ); \
5814 OPTIONAL(runtimeLang, DwarfLangField, ); \
5815 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5816 OPTIONAL(vtableHolder, MDField, ); \
5817 OPTIONAL(templateParams, MDField, ); \
5818 OPTIONAL(identifier, MDStringField, ); \
5819 OPTIONAL(discriminator, MDField, ); \
5820 OPTIONAL(dataLocation, MDField, ); \
5821 OPTIONAL(associated, MDField, ); \
5822 OPTIONAL(allocated, MDField, ); \
5823 OPTIONAL(rank, MDSignedOrMDField, ); \
5824 OPTIONAL(annotations, MDField, ); \
5825 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5826 OPTIONAL(specification, MDField, ); \
5827 OPTIONAL(bitStride, MDField, );
5829#undef VISIT_MD_FIELDS
5830
5831 Metadata *Rank = nullptr;
5832 if (rank.isMDSignedField())
5834 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5835 else if (rank.isMDField())
5836 Rank = rank.getMDFieldValue();
5837
5838 std::optional<unsigned> EnumKind;
5839 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5840 EnumKind = enumKind.Val;
5841
5842 // If this has an identifier try to build an ODR type.
5843 if (identifier.Val)
5844 if (auto *CT = DICompositeType::buildODRType(
5845 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5846 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
5847 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5848 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5849 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5850 dataLocation.Val, associated.Val, allocated.Val, Rank,
5851 annotations.Val, bitStride.Val)) {
5852 Result = CT;
5853 return false;
5854 }
5855
5856 // Create a new node, and save it in the context if it belongs in the type
5857 // map.
5859 DICompositeType,
5860 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5861 size.getValueAsMetadata(Context), align.Val,
5862 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5863 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5864 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5865 allocated.Val, Rank, annotations.Val, specification.Val,
5866 num_extra_inhabitants.Val, bitStride.Val));
5867 return false;
5868}
5869
5870bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5871#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5872 OPTIONAL(flags, DIFlagField, ); \
5873 OPTIONAL(cc, DwarfCCField, ); \
5874 REQUIRED(types, MDField, );
5876#undef VISIT_MD_FIELDS
5877
5878 Result = GET_OR_DISTINCT(DISubroutineType,
5879 (Context, flags.Val, cc.Val, types.Val));
5880 return false;
5881}
5882
5883/// parseDIFileType:
5884/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5885/// checksumkind: CSK_MD5,
5886/// checksum: "000102030405060708090a0b0c0d0e0f",
5887/// source: "source file contents")
5888bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5889 // The default constructed value for checksumkind is required, but will never
5890 // be used, as the parser checks if the field was actually Seen before using
5891 // the Val.
5892#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5893 REQUIRED(filename, MDStringField, ); \
5894 REQUIRED(directory, MDStringField, ); \
5895 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5896 OPTIONAL(checksum, MDStringField, ); \
5897 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5899#undef VISIT_MD_FIELDS
5900
5901 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5902 if (checksumkind.Seen && checksum.Seen)
5903 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5904 else if (checksumkind.Seen || checksum.Seen)
5905 return tokError("'checksumkind' and 'checksum' must be provided together");
5906
5907 MDString *Source = nullptr;
5908 if (source.Seen)
5909 Source = source.Val;
5911 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5912 return false;
5913}
5914
5915/// parseDICompileUnit:
5916/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5917/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5918/// splitDebugFilename: "abc.debug",
5919/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5920/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5921/// sysroot: "/", sdk: "MacOSX.sdk")
5922bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5923 if (!IsDistinct)
5924 return tokError("missing 'distinct', required for !DICompileUnit");
5925
5926 LocTy Loc = Lex.getLoc();
5927
5928#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5929 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5930 OPTIONAL(language, DwarfLangField, ); \
5931 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
5932 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
5933 OPTIONAL(producer, MDStringField, ); \
5934 OPTIONAL(isOptimized, MDBoolField, ); \
5935 OPTIONAL(flags, MDStringField, ); \
5936 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5937 OPTIONAL(splitDebugFilename, MDStringField, ); \
5938 OPTIONAL(emissionKind, EmissionKindField, ); \
5939 OPTIONAL(enums, MDField, ); \
5940 OPTIONAL(retainedTypes, MDField, ); \
5941 OPTIONAL(globals, MDField, ); \
5942 OPTIONAL(imports, MDField, ); \
5943 OPTIONAL(macros, MDField, ); \
5944 OPTIONAL(dwoId, MDUnsignedField, ); \
5945 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5946 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5947 OPTIONAL(nameTableKind, NameTableKindField, ); \
5948 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5949 OPTIONAL(sysroot, MDStringField, ); \
5950 OPTIONAL(sdk, MDStringField, );
5952#undef VISIT_MD_FIELDS
5953
5954 if (!language.Seen && !sourceLanguageName.Seen)
5955 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
5956 "required for !DICompileUnit");
5957
5958 if (language.Seen && sourceLanguageName.Seen)
5959 return error(Loc, "can only specify one of 'language' and "
5960 "'sourceLanguageName' on !DICompileUnit");
5961
5962 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
5963 return error(Loc, "'sourceLanguageVersion' requires an associated "
5964 "'sourceLanguageName' on !DICompileUnit");
5965
5967 Context,
5968 language.Seen ? DISourceLanguageName(language.Val)
5969 : DISourceLanguageName(sourceLanguageName.Val,
5970 sourceLanguageVersion.Val),
5971 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
5972 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
5973 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
5974 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
5975 sysroot.Val, sdk.Val);
5976 return false;
5977}
5978
5979/// parseDISubprogram:
5980/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5981/// file: !1, line: 7, type: !2, isLocal: false,
5982/// isDefinition: true, scopeLine: 8, containingType: !3,
5983/// virtuality: DW_VIRTUALTIY_pure_virtual,
5984/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5985/// spFlags: 10, isOptimized: false, templateParams: !4,
5986/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5987/// annotations: !8)
5988bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5989 auto Loc = Lex.getLoc();
5990#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5991 OPTIONAL(scope, MDField, ); \
5992 OPTIONAL(name, MDStringField, ); \
5993 OPTIONAL(linkageName, MDStringField, ); \
5994 OPTIONAL(file, MDField, ); \
5995 OPTIONAL(line, LineField, ); \
5996 OPTIONAL(type, MDField, ); \
5997 OPTIONAL(isLocal, MDBoolField, ); \
5998 OPTIONAL(isDefinition, MDBoolField, (true)); \
5999 OPTIONAL(scopeLine, LineField, ); \
6000 OPTIONAL(containingType, MDField, ); \
6001 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6002 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6003 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6004 OPTIONAL(flags, DIFlagField, ); \
6005 OPTIONAL(spFlags, DISPFlagField, ); \
6006 OPTIONAL(isOptimized, MDBoolField, ); \
6007 OPTIONAL(unit, MDField, ); \
6008 OPTIONAL(templateParams, MDField, ); \
6009 OPTIONAL(declaration, MDField, ); \
6010 OPTIONAL(retainedNodes, MDField, ); \
6011 OPTIONAL(thrownTypes, MDField, ); \
6012 OPTIONAL(annotations, MDField, ); \
6013 OPTIONAL(targetFuncName, MDStringField, ); \
6014 OPTIONAL(keyInstructions, MDBoolField, );
6016#undef VISIT_MD_FIELDS
6017
6018 // An explicit spFlags field takes precedence over individual fields in
6019 // older IR versions.
6020 DISubprogram::DISPFlags SPFlags =
6021 spFlags.Seen ? spFlags.Val
6022 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6023 isOptimized.Val, virtuality.Val);
6024 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6025 return error(
6026 Loc,
6027 "missing 'distinct', required for !DISubprogram that is a Definition");
6029 DISubprogram,
6030 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6031 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6032 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6033 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6034 targetFuncName.Val, keyInstructions.Val));
6035 return false;
6036}
6037
6038/// parseDILexicalBlock:
6039/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6040bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6041#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6042 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6043 OPTIONAL(file, MDField, ); \
6044 OPTIONAL(line, LineField, ); \
6045 OPTIONAL(column, ColumnField, );
6047#undef VISIT_MD_FIELDS
6048
6050 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6051 return false;
6052}
6053
6054/// parseDILexicalBlockFile:
6055/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6056bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6057#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6058 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6059 OPTIONAL(file, MDField, ); \
6060 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6062#undef VISIT_MD_FIELDS
6063
6064 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6065 (Context, scope.Val, file.Val, discriminator.Val));
6066 return false;
6067}
6068
6069/// parseDICommonBlock:
6070/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6071bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6072#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6073 REQUIRED(scope, MDField, ); \
6074 OPTIONAL(declaration, MDField, ); \
6075 OPTIONAL(name, MDStringField, ); \
6076 OPTIONAL(file, MDField, ); \
6077 OPTIONAL(line, LineField, );
6079#undef VISIT_MD_FIELDS
6080
6081 Result = GET_OR_DISTINCT(DICommonBlock,
6082 (Context, scope.Val, declaration.Val, name.Val,
6083 file.Val, line.Val));
6084 return false;
6085}
6086
6087/// parseDINamespace:
6088/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6089bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6090#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6091 REQUIRED(scope, MDField, ); \
6092 OPTIONAL(name, MDStringField, ); \
6093 OPTIONAL(exportSymbols, MDBoolField, );
6095#undef VISIT_MD_FIELDS
6096
6097 Result = GET_OR_DISTINCT(DINamespace,
6098 (Context, scope.Val, name.Val, exportSymbols.Val));
6099 return false;
6100}
6101
6102/// parseDIMacro:
6103/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6104/// "SomeValue")
6105bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6106#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6107 REQUIRED(type, DwarfMacinfoTypeField, ); \
6108 OPTIONAL(line, LineField, ); \
6109 REQUIRED(name, MDStringField, ); \
6110 OPTIONAL(value, MDStringField, );
6112#undef VISIT_MD_FIELDS
6113
6114 Result = GET_OR_DISTINCT(DIMacro,
6115 (Context, type.Val, line.Val, name.Val, value.Val));
6116 return false;
6117}
6118
6119/// parseDIMacroFile:
6120/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6121bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6122#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6123 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6124 OPTIONAL(line, LineField, ); \
6125 REQUIRED(file, MDField, ); \
6126 OPTIONAL(nodes, MDField, );
6128#undef VISIT_MD_FIELDS
6129
6130 Result = GET_OR_DISTINCT(DIMacroFile,
6131 (Context, type.Val, line.Val, file.Val, nodes.Val));
6132 return false;
6133}
6134
6135/// parseDIModule:
6136/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6137/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6138/// file: !1, line: 4, isDecl: false)
6139bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6140#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6141 REQUIRED(scope, MDField, ); \
6142 REQUIRED(name, MDStringField, ); \
6143 OPTIONAL(configMacros, MDStringField, ); \
6144 OPTIONAL(includePath, MDStringField, ); \
6145 OPTIONAL(apinotes, MDStringField, ); \
6146 OPTIONAL(file, MDField, ); \
6147 OPTIONAL(line, LineField, ); \
6148 OPTIONAL(isDecl, MDBoolField, );
6150#undef VISIT_MD_FIELDS
6151
6152 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6153 configMacros.Val, includePath.Val,
6154 apinotes.Val, line.Val, isDecl.Val));
6155 return false;
6156}
6157
6158/// parseDITemplateTypeParameter:
6159/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6160bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6161#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6162 OPTIONAL(name, MDStringField, ); \
6163 REQUIRED(type, MDField, ); \
6164 OPTIONAL(defaulted, MDBoolField, );
6166#undef VISIT_MD_FIELDS
6167
6168 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6169 (Context, name.Val, type.Val, defaulted.Val));
6170 return false;
6171}
6172
6173/// parseDITemplateValueParameter:
6174/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6175/// name: "V", type: !1, defaulted: false,
6176/// value: i32 7)
6177bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6178#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6179 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6180 OPTIONAL(name, MDStringField, ); \
6181 OPTIONAL(type, MDField, ); \
6182 OPTIONAL(defaulted, MDBoolField, ); \
6183 REQUIRED(value, MDField, );
6184
6186#undef VISIT_MD_FIELDS
6187
6189 DITemplateValueParameter,
6190 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6191 return false;
6192}
6193
6194/// parseDIGlobalVariable:
6195/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6196/// file: !1, line: 7, type: !2, isLocal: false,
6197/// isDefinition: true, templateParams: !3,
6198/// declaration: !4, align: 8)
6199bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6200#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6201 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6202 OPTIONAL(scope, MDField, ); \
6203 OPTIONAL(linkageName, MDStringField, ); \
6204 OPTIONAL(file, MDField, ); \
6205 OPTIONAL(line, LineField, ); \
6206 OPTIONAL(type, MDField, ); \
6207 OPTIONAL(isLocal, MDBoolField, ); \
6208 OPTIONAL(isDefinition, MDBoolField, (true)); \
6209 OPTIONAL(templateParams, MDField, ); \
6210 OPTIONAL(declaration, MDField, ); \
6211 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6212 OPTIONAL(annotations, MDField, );
6214#undef VISIT_MD_FIELDS
6215
6216 Result =
6217 GET_OR_DISTINCT(DIGlobalVariable,
6218 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6219 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6220 declaration.Val, templateParams.Val, align.Val,
6221 annotations.Val));
6222 return false;
6223}
6224
6225/// parseDILocalVariable:
6226/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6227/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6228/// align: 8)
6229/// ::= !DILocalVariable(scope: !0, name: "foo",
6230/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6231/// align: 8)
6232bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6233#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6234 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6235 OPTIONAL(name, MDStringField, ); \
6236 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6237 OPTIONAL(file, MDField, ); \
6238 OPTIONAL(line, LineField, ); \
6239 OPTIONAL(type, MDField, ); \
6240 OPTIONAL(flags, DIFlagField, ); \
6241 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6242 OPTIONAL(annotations, MDField, );
6244#undef VISIT_MD_FIELDS
6245
6246 Result = GET_OR_DISTINCT(DILocalVariable,
6247 (Context, scope.Val, name.Val, file.Val, line.Val,
6248 type.Val, arg.Val, flags.Val, align.Val,
6249 annotations.Val));
6250 return false;
6251}
6252
6253/// parseDILabel:
6254/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6255bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6256#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6257 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6258 REQUIRED(name, MDStringField, ); \
6259 REQUIRED(file, MDField, ); \
6260 REQUIRED(line, LineField, ); \
6261 OPTIONAL(column, ColumnField, ); \
6262 OPTIONAL(isArtificial, MDBoolField, ); \
6263 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6265#undef VISIT_MD_FIELDS
6266
6267 std::optional<unsigned> CoroSuspendIdx =
6268 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6269 : std::nullopt;
6270
6271 Result = GET_OR_DISTINCT(DILabel,
6272 (Context, scope.Val, name.Val, file.Val, line.Val,
6273 column.Val, isArtificial.Val, CoroSuspendIdx));
6274 return false;
6275}
6276
6277/// parseDIExpressionBody:
6278/// ::= (0, 7, -1)
6279bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6280 if (parseToken(lltok::lparen, "expected '(' here"))
6281 return true;
6282
6283 SmallVector<uint64_t, 8> Elements;
6284 if (Lex.getKind() != lltok::rparen)
6285 do {
6286 if (Lex.getKind() == lltok::DwarfOp) {
6287 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6288 Lex.Lex();
6289 Elements.push_back(Op);
6290 continue;
6291 }
6292 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6293 }
6294
6295 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6296 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6297 Lex.Lex();
6298 Elements.push_back(Op);
6299 continue;
6300 }
6301 return tokError(Twine("invalid DWARF attribute encoding '") +
6302 Lex.getStrVal() + "'");
6303 }
6304
6305 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6306 return tokError("expected unsigned integer");
6307
6308 auto &U = Lex.getAPSIntVal();
6309 if (U.ugt(UINT64_MAX))
6310 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6311 Elements.push_back(U.getZExtValue());
6312 Lex.Lex();
6313 } while (EatIfPresent(lltok::comma));
6314
6315 if (parseToken(lltok::rparen, "expected ')' here"))
6316 return true;
6317
6318 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6319 return false;
6320}
6321
6322/// parseDIExpression:
6323/// ::= !DIExpression(0, 7, -1)
6324bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6325 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6326 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6327 Lex.Lex();
6328
6329 return parseDIExpressionBody(Result, IsDistinct);
6330}
6331
6332/// ParseDIArgList:
6333/// ::= !DIArgList(i32 7, i64 %0)
6334bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6335 assert(PFS && "Expected valid function state");
6336 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6337 Lex.Lex();
6338
6339 if (parseToken(lltok::lparen, "expected '(' here"))
6340 return true;
6341
6343 if (Lex.getKind() != lltok::rparen)
6344 do {
6345 Metadata *MD;
6346 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6347 return true;
6348 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6349 } while (EatIfPresent(lltok::comma));
6350
6351 if (parseToken(lltok::rparen, "expected ')' here"))
6352 return true;
6353
6354 MD = DIArgList::get(Context, Args);
6355 return false;
6356}
6357
6358/// parseDIGlobalVariableExpression:
6359/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6360bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6361 bool IsDistinct) {
6362#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6363 REQUIRED(var, MDField, ); \
6364 REQUIRED(expr, MDField, );
6366#undef VISIT_MD_FIELDS
6367
6368 Result =
6369 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6370 return false;
6371}
6372
6373/// parseDIObjCProperty:
6374/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6375/// getter: "getFoo", attributes: 7, type: !2)
6376bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6377#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6378 OPTIONAL(name, MDStringField, ); \
6379 OPTIONAL(file, MDField, ); \
6380 OPTIONAL(line, LineField, ); \
6381 OPTIONAL(setter, MDStringField, ); \
6382 OPTIONAL(getter, MDStringField, ); \
6383 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6384 OPTIONAL(type, MDField, );
6386#undef VISIT_MD_FIELDS
6387
6388 Result = GET_OR_DISTINCT(DIObjCProperty,
6389 (Context, name.Val, file.Val, line.Val, getter.Val,
6390 setter.Val, attributes.Val, type.Val));
6391 return false;
6392}
6393
6394/// parseDIImportedEntity:
6395/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6396/// line: 7, name: "foo", elements: !2)
6397bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6398#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6399 REQUIRED(tag, DwarfTagField, ); \
6400 REQUIRED(scope, MDField, ); \
6401 OPTIONAL(entity, MDField, ); \
6402 OPTIONAL(file, MDField, ); \
6403 OPTIONAL(line, LineField, ); \
6404 OPTIONAL(name, MDStringField, ); \
6405 OPTIONAL(elements, MDField, );
6407#undef VISIT_MD_FIELDS
6408
6409 Result = GET_OR_DISTINCT(DIImportedEntity,
6410 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6411 line.Val, name.Val, elements.Val));
6412 return false;
6413}
6414
6415#undef PARSE_MD_FIELD
6416#undef NOP_FIELD
6417#undef REQUIRE_FIELD
6418#undef DECLARE_FIELD
6419
6420/// parseMetadataAsValue
6421/// ::= metadata i32 %local
6422/// ::= metadata i32 @global
6423/// ::= metadata i32 7
6424/// ::= metadata !0
6425/// ::= metadata !{...}
6426/// ::= metadata !"string"
6427bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6428 // Note: the type 'metadata' has already been parsed.
6429 Metadata *MD;
6430 if (parseMetadata(MD, &PFS))
6431 return true;
6432
6433 V = MetadataAsValue::get(Context, MD);
6434 return false;
6435}
6436
6437/// parseValueAsMetadata
6438/// ::= i32 %local
6439/// ::= i32 @global
6440/// ::= i32 7
6441bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6442 PerFunctionState *PFS) {
6443 Type *Ty;
6444 LocTy Loc;
6445 if (parseType(Ty, TypeMsg, Loc))
6446 return true;
6447 if (Ty->isMetadataTy())
6448 return error(Loc, "invalid metadata-value-metadata roundtrip");
6449
6450 Value *V;
6451 if (parseValue(Ty, V, PFS))
6452 return true;
6453
6454 MD = ValueAsMetadata::get(V);
6455 return false;
6456}
6457
6458/// parseMetadata
6459/// ::= i32 %local
6460/// ::= i32 @global
6461/// ::= i32 7
6462/// ::= !42
6463/// ::= !{...}
6464/// ::= !"string"
6465/// ::= !DILocation(...)
6466bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6467 if (Lex.getKind() == lltok::MetadataVar) {
6468 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6469 // so parsing this requires a Function State.
6470 if (Lex.getStrVal() == "DIArgList") {
6471 Metadata *AL;
6472 if (parseDIArgList(AL, PFS))
6473 return true;
6474 MD = AL;
6475 return false;
6476 }
6477 MDNode *N;
6478 if (parseSpecializedMDNode(N)) {
6479 return true;
6480 }
6481 MD = N;
6482 return false;
6483 }
6484
6485 // ValueAsMetadata:
6486 // <type> <value>
6487 if (Lex.getKind() != lltok::exclaim)
6488 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6489
6490 // '!'.
6491 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6492 Lex.Lex();
6493
6494 // MDString:
6495 // ::= '!' STRINGCONSTANT
6496 if (Lex.getKind() == lltok::StringConstant) {
6497 MDString *S;
6498 if (parseMDString(S))
6499 return true;
6500 MD = S;
6501 return false;
6502 }
6503
6504 // MDNode:
6505 // !{ ... }
6506 // !7
6507 MDNode *N;
6508 if (parseMDNodeTail(N))
6509 return true;
6510 MD = N;
6511 return false;
6512}
6513
6514//===----------------------------------------------------------------------===//
6515// Function Parsing.
6516//===----------------------------------------------------------------------===//
6517
6518bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6519 PerFunctionState *PFS) {
6520 if (Ty->isFunctionTy())
6521 return error(ID.Loc, "functions are not values, refer to them as pointers");
6522
6523 switch (ID.Kind) {
6524 case ValID::t_LocalID:
6525 if (!PFS)
6526 return error(ID.Loc, "invalid use of function-local name");
6527 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6528 return V == nullptr;
6529 case ValID::t_LocalName:
6530 if (!PFS)
6531 return error(ID.Loc, "invalid use of function-local name");
6532 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6533 return V == nullptr;
6534 case ValID::t_InlineAsm: {
6535 if (!ID.FTy)
6536 return error(ID.Loc, "invalid type for inline asm constraint string");
6537 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6538 return error(ID.Loc, toString(std::move(Err)));
6539 V = InlineAsm::get(
6540 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6541 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6542 return false;
6543 }
6545 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6546 if (V && ID.NoCFI)
6548 return V == nullptr;
6549 case ValID::t_GlobalID:
6550 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6551 if (V && ID.NoCFI)
6553 return V == nullptr;
6554 case ValID::t_APSInt:
6555 if (!Ty->isIntegerTy())
6556 return error(ID.Loc, "integer constant must have integer type");
6557 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6558 V = ConstantInt::get(Context, ID.APSIntVal);
6559 return false;
6560 case ValID::t_APFloat:
6561 if (!Ty->isFloatingPointTy() ||
6562 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6563 return error(ID.Loc, "floating point constant invalid for type");
6564
6565 // The lexer has no type info, so builds all half, bfloat, float, and double
6566 // FP constants as double. Fix this here. Long double does not need this.
6567 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6568 // Check for signaling before potentially converting and losing that info.
6569 bool IsSNAN = ID.APFloatVal.isSignaling();
6570 bool Ignored;
6571 if (Ty->isHalfTy())
6573 &Ignored);
6574 else if (Ty->isBFloatTy())
6575 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6576 &Ignored);
6577 else if (Ty->isFloatTy())
6579 &Ignored);
6580 if (IsSNAN) {
6581 // The convert call above may quiet an SNaN, so manufacture another
6582 // SNaN. The bitcast works because the payload (significand) parameter
6583 // is truncated to fit.
6584 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6585 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6586 ID.APFloatVal.isNegative(), &Payload);
6587 }
6588 }
6589 V = ConstantFP::get(Context, ID.APFloatVal);
6590
6591 if (V->getType() != Ty)
6592 return error(ID.Loc, "floating point constant does not have type '" +
6593 getTypeString(Ty) + "'");
6594
6595 return false;
6596 case ValID::t_Null:
6597 if (!Ty->isPointerTy())
6598 return error(ID.Loc, "null must be a pointer type");
6600 return false;
6601 case ValID::t_Undef:
6602 // FIXME: LabelTy should not be a first-class type.
6603 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6604 return error(ID.Loc, "invalid type for undef constant");
6605 V = UndefValue::get(Ty);
6606 return false;
6608 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6609 return error(ID.Loc, "invalid empty array initializer");
6610 V = PoisonValue::get(Ty);
6611 return false;
6612 case ValID::t_Zero:
6613 // FIXME: LabelTy should not be a first-class type.
6614 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6615 return error(ID.Loc, "invalid type for null constant");
6616 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6617 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6618 return error(ID.Loc, "invalid type for null constant");
6620 return false;
6621 case ValID::t_None:
6622 if (!Ty->isTokenTy())
6623 return error(ID.Loc, "invalid type for none constant");
6625 return false;
6626 case ValID::t_Poison:
6627 // FIXME: LabelTy should not be a first-class type.
6628 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6629 return error(ID.Loc, "invalid type for poison constant");
6630 V = PoisonValue::get(Ty);
6631 return false;
6632 case ValID::t_Constant:
6633 if (ID.ConstantVal->getType() != Ty)
6634 return error(ID.Loc, "constant expression type mismatch: got type '" +
6635 getTypeString(ID.ConstantVal->getType()) +
6636 "' but expected '" + getTypeString(Ty) + "'");
6637 V = ID.ConstantVal;
6638 return false;
6640 if (!Ty->isVectorTy())
6641 return error(ID.Loc, "vector constant must have vector type");
6642 if (ID.ConstantVal->getType() != Ty->getScalarType())
6643 return error(ID.Loc, "constant expression type mismatch: got type '" +
6644 getTypeString(ID.ConstantVal->getType()) +
6645 "' but expected '" +
6646 getTypeString(Ty->getScalarType()) + "'");
6647 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6648 ID.ConstantVal);
6649 return false;
6652 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6653 if (ST->getNumElements() != ID.UIntVal)
6654 return error(ID.Loc,
6655 "initializer with struct type has wrong # elements");
6656 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6657 return error(ID.Loc, "packed'ness of initializer and type don't match");
6658
6659 // Verify that the elements are compatible with the structtype.
6660 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6661 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6662 return error(
6663 ID.Loc,
6664 "element " + Twine(i) +
6665 " of struct initializer doesn't match struct element type");
6666
6668 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6669 } else
6670 return error(ID.Loc, "constant expression type mismatch");
6671 return false;
6672 }
6673 llvm_unreachable("Invalid ValID");
6674}
6675
6676bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6677 C = nullptr;
6678 ValID ID;
6679 auto Loc = Lex.getLoc();
6680 if (parseValID(ID, /*PFS=*/nullptr))
6681 return true;
6682 switch (ID.Kind) {
6683 case ValID::t_APSInt:
6684 case ValID::t_APFloat:
6685 case ValID::t_Undef:
6686 case ValID::t_Poison:
6687 case ValID::t_Zero:
6688 case ValID::t_Constant:
6692 Value *V;
6693 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6694 return true;
6695 assert(isa<Constant>(V) && "Expected a constant value");
6696 C = cast<Constant>(V);
6697 return false;
6698 }
6699 case ValID::t_Null:
6701 return false;
6702 default:
6703 return error(Loc, "expected a constant value");
6704 }
6705}
6706
6707bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6708 V = nullptr;
6709 ValID ID;
6710 return parseValID(ID, PFS, Ty) ||
6711 convertValIDToValue(Ty, ID, V, PFS);
6712}
6713
6714bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6715 Type *Ty = nullptr;
6716 return parseType(Ty) || parseValue(Ty, V, PFS);
6717}
6718
6719bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6720 PerFunctionState &PFS) {
6721 Value *V;
6722 Loc = Lex.getLoc();
6723 if (parseTypeAndValue(V, PFS))
6724 return true;
6725 if (!isa<BasicBlock>(V))
6726 return error(Loc, "expected a basic block");
6727 BB = cast<BasicBlock>(V);
6728 return false;
6729}
6730
6732 // Exit early for the common (non-debug-intrinsic) case.
6733 // We can make this the only check when we begin supporting all "llvm.dbg"
6734 // intrinsics in the new debug info format.
6735 if (!Name.starts_with("llvm.dbg."))
6736 return false;
6738 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6739 FnID == Intrinsic::dbg_assign;
6740}
6741
6742/// FunctionHeader
6743/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6744/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6745/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6746/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6747bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6748 unsigned &FunctionNumber,
6749 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6750 // parse the linkage.
6751 LocTy LinkageLoc = Lex.getLoc();
6752 unsigned Linkage;
6753 unsigned Visibility;
6754 unsigned DLLStorageClass;
6755 bool DSOLocal;
6756 AttrBuilder RetAttrs(M->getContext());
6757 unsigned CC;
6758 bool HasLinkage;
6759 Type *RetType = nullptr;
6760 LocTy RetTypeLoc = Lex.getLoc();
6761 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6762 DSOLocal) ||
6763 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6764 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6765 return true;
6766
6767 // Verify that the linkage is ok.
6770 break; // always ok.
6772 if (IsDefine)
6773 return error(LinkageLoc, "invalid linkage for function definition");
6774 break;
6782 if (!IsDefine)
6783 return error(LinkageLoc, "invalid linkage for function declaration");
6784 break;
6787 return error(LinkageLoc, "invalid function linkage type");
6788 }
6789
6790 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6791 return error(LinkageLoc,
6792 "symbol with local linkage must have default visibility");
6793
6794 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6795 return error(LinkageLoc,
6796 "symbol with local linkage cannot have a DLL storage class");
6797
6798 if (!FunctionType::isValidReturnType(RetType))
6799 return error(RetTypeLoc, "invalid function return type");
6800
6801 LocTy NameLoc = Lex.getLoc();
6802
6803 std::string FunctionName;
6804 if (Lex.getKind() == lltok::GlobalVar) {
6805 FunctionName = Lex.getStrVal();
6806 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6807 FunctionNumber = Lex.getUIntVal();
6808 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6809 FunctionNumber))
6810 return true;
6811 } else {
6812 return tokError("expected function name");
6813 }
6814
6815 Lex.Lex();
6816
6817 if (Lex.getKind() != lltok::lparen)
6818 return tokError("expected '(' in function argument list");
6819
6821 bool IsVarArg;
6822 AttrBuilder FuncAttrs(M->getContext());
6823 std::vector<unsigned> FwdRefAttrGrps;
6824 LocTy BuiltinLoc;
6825 std::string Section;
6826 std::string Partition;
6827 MaybeAlign Alignment;
6828 std::string GC;
6830 unsigned AddrSpace = 0;
6831 Constant *Prefix = nullptr;
6832 Constant *Prologue = nullptr;
6833 Constant *PersonalityFn = nullptr;
6834 Comdat *C;
6835
6836 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6837 parseOptionalUnnamedAddr(UnnamedAddr) ||
6838 parseOptionalProgramAddrSpace(AddrSpace) ||
6839 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6840 BuiltinLoc) ||
6841 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6842 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6843 parseOptionalComdat(FunctionName, C) ||
6844 parseOptionalAlignment(Alignment) ||
6845 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6846 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6847 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6848 (EatIfPresent(lltok::kw_personality) &&
6849 parseGlobalTypeAndValue(PersonalityFn)))
6850 return true;
6851
6852 if (FuncAttrs.contains(Attribute::Builtin))
6853 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6854
6855 // If the alignment was parsed as an attribute, move to the alignment field.
6856 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6857 Alignment = A;
6858 FuncAttrs.removeAttribute(Attribute::Alignment);
6859 }
6860
6861 // Okay, if we got here, the function is syntactically valid. Convert types
6862 // and do semantic checks.
6863 std::vector<Type*> ParamTypeList;
6865
6866 for (const ArgInfo &Arg : ArgList) {
6867 ParamTypeList.push_back(Arg.Ty);
6868 Attrs.push_back(Arg.Attrs);
6869 }
6870
6871 AttributeList PAL =
6872 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6873 AttributeSet::get(Context, RetAttrs), Attrs);
6874
6875 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6876 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6877
6878 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6879 PointerType *PFT = PointerType::get(Context, AddrSpace);
6880
6881 Fn = nullptr;
6882 GlobalValue *FwdFn = nullptr;
6883 if (!FunctionName.empty()) {
6884 // If this was a definition of a forward reference, remove the definition
6885 // from the forward reference table and fill in the forward ref.
6886 auto FRVI = ForwardRefVals.find(FunctionName);
6887 if (FRVI != ForwardRefVals.end()) {
6888 FwdFn = FRVI->second.first;
6889 if (FwdFn->getType() != PFT)
6890 return error(FRVI->second.second,
6891 "invalid forward reference to "
6892 "function '" +
6893 FunctionName +
6894 "' with wrong type: "
6895 "expected '" +
6896 getTypeString(PFT) + "' but was '" +
6897 getTypeString(FwdFn->getType()) + "'");
6898 ForwardRefVals.erase(FRVI);
6899 } else if ((Fn = M->getFunction(FunctionName))) {
6900 // Reject redefinitions.
6901 return error(NameLoc,
6902 "invalid redefinition of function '" + FunctionName + "'");
6903 } else if (M->getNamedValue(FunctionName)) {
6904 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6905 }
6906
6907 } else {
6908 // Handle @"", where a name is syntactically specified, but semantically
6909 // missing.
6910 if (FunctionNumber == (unsigned)-1)
6911 FunctionNumber = NumberedVals.getNext();
6912
6913 // If this is a definition of a forward referenced function, make sure the
6914 // types agree.
6915 auto I = ForwardRefValIDs.find(FunctionNumber);
6916 if (I != ForwardRefValIDs.end()) {
6917 FwdFn = I->second.first;
6918 if (FwdFn->getType() != PFT)
6919 return error(NameLoc, "type of definition and forward reference of '@" +
6920 Twine(FunctionNumber) +
6921 "' disagree: "
6922 "expected '" +
6923 getTypeString(PFT) + "' but was '" +
6924 getTypeString(FwdFn->getType()) + "'");
6925 ForwardRefValIDs.erase(I);
6926 }
6927 }
6928
6930 FunctionName, M);
6931
6932 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6933
6934 if (FunctionName.empty())
6935 NumberedVals.add(FunctionNumber, Fn);
6936
6938 maybeSetDSOLocal(DSOLocal, *Fn);
6941 Fn->setCallingConv(CC);
6942 Fn->setAttributes(PAL);
6943 Fn->setUnnamedAddr(UnnamedAddr);
6944 if (Alignment)
6945 Fn->setAlignment(*Alignment);
6946 Fn->setSection(Section);
6947 Fn->setPartition(Partition);
6948 Fn->setComdat(C);
6949 Fn->setPersonalityFn(PersonalityFn);
6950 if (!GC.empty()) Fn->setGC(GC);
6951 Fn->setPrefixData(Prefix);
6952 Fn->setPrologueData(Prologue);
6953 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6954
6955 // Add all of the arguments we parsed to the function.
6956 Function::arg_iterator ArgIt = Fn->arg_begin();
6957 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6958 // If the argument has a name, insert it into the argument symbol table.
6959 if (ArgList[i].Name.empty()) continue;
6960
6961 // Set the name, if it conflicted, it will be auto-renamed.
6962 ArgIt->setName(ArgList[i].Name);
6963
6964 if (ArgIt->getName() != ArgList[i].Name)
6965 return error(ArgList[i].Loc,
6966 "redefinition of argument '%" + ArgList[i].Name + "'");
6967 }
6968
6969 if (FwdFn) {
6970 FwdFn->replaceAllUsesWith(Fn);
6971 FwdFn->eraseFromParent();
6972 }
6973
6974 if (IsDefine)
6975 return false;
6976
6977 // Check the declaration has no block address forward references.
6978 ValID ID;
6979 if (FunctionName.empty()) {
6980 ID.Kind = ValID::t_GlobalID;
6981 ID.UIntVal = FunctionNumber;
6982 } else {
6983 ID.Kind = ValID::t_GlobalName;
6984 ID.StrVal = FunctionName;
6985 }
6986 auto Blocks = ForwardRefBlockAddresses.find(ID);
6987 if (Blocks != ForwardRefBlockAddresses.end())
6988 return error(Blocks->first.Loc,
6989 "cannot take blockaddress inside a declaration");
6990 return false;
6991}
6992
6993bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6994 ValID ID;
6995 if (FunctionNumber == -1) {
6996 ID.Kind = ValID::t_GlobalName;
6997 ID.StrVal = std::string(F.getName());
6998 } else {
6999 ID.Kind = ValID::t_GlobalID;
7000 ID.UIntVal = FunctionNumber;
7001 }
7002
7003 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7004 if (Blocks == P.ForwardRefBlockAddresses.end())
7005 return false;
7006
7007 for (const auto &I : Blocks->second) {
7008 const ValID &BBID = I.first;
7009 GlobalValue *GV = I.second;
7010
7011 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7012 "Expected local id or name");
7013 BasicBlock *BB;
7014 if (BBID.Kind == ValID::t_LocalName)
7015 BB = getBB(BBID.StrVal, BBID.Loc);
7016 else
7017 BB = getBB(BBID.UIntVal, BBID.Loc);
7018 if (!BB)
7019 return P.error(BBID.Loc, "referenced value is not a basic block");
7020
7021 Value *ResolvedVal = BlockAddress::get(&F, BB);
7022 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7023 ResolvedVal);
7024 if (!ResolvedVal)
7025 return true;
7026 GV->replaceAllUsesWith(ResolvedVal);
7027 GV->eraseFromParent();
7028 }
7029
7030 P.ForwardRefBlockAddresses.erase(Blocks);
7031 return false;
7032}
7033
7034/// parseFunctionBody
7035/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7036bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7037 ArrayRef<unsigned> UnnamedArgNums) {
7038 if (Lex.getKind() != lltok::lbrace)
7039 return tokError("expected '{' in function body");
7040 Lex.Lex(); // eat the {.
7041
7042 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7043
7044 // Resolve block addresses and allow basic blocks to be forward-declared
7045 // within this function.
7046 if (PFS.resolveForwardRefBlockAddresses())
7047 return true;
7048 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7049
7050 // We need at least one basic block.
7051 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7052 return tokError("function body requires at least one basic block");
7053
7054 while (Lex.getKind() != lltok::rbrace &&
7055 Lex.getKind() != lltok::kw_uselistorder)
7056 if (parseBasicBlock(PFS))
7057 return true;
7058
7059 while (Lex.getKind() != lltok::rbrace)
7060 if (parseUseListOrder(&PFS))
7061 return true;
7062
7063 // Eat the }.
7064 Lex.Lex();
7065
7066 // Verify function is ok.
7067 return PFS.finishFunction();
7068}
7069
7070/// parseBasicBlock
7071/// ::= (LabelStr|LabelID)? Instruction*
7072bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7073 FileLoc BBStart(Lex.getTokLineColumnPos());
7074
7075 // If this basic block starts out with a name, remember it.
7076 std::string Name;
7077 int NameID = -1;
7078 LocTy NameLoc = Lex.getLoc();
7079 if (Lex.getKind() == lltok::LabelStr) {
7080 Name = Lex.getStrVal();
7081 Lex.Lex();
7082 } else if (Lex.getKind() == lltok::LabelID) {
7083 NameID = Lex.getUIntVal();
7084 Lex.Lex();
7085 }
7086
7087 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7088 if (!BB)
7089 return true;
7090
7091 std::string NameStr;
7092
7093 // Parse the instructions and debug values in this block until we get a
7094 // terminator.
7095 Instruction *Inst;
7096 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7097 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7098 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7099 do {
7100 // Handle debug records first - there should always be an instruction
7101 // following the debug records, i.e. they cannot appear after the block
7102 // terminator.
7103 while (Lex.getKind() == lltok::hash) {
7104 if (SeenOldDbgInfoFormat)
7105 return error(Lex.getLoc(), "debug record should not appear in a module "
7106 "containing debug info intrinsics");
7107 SeenNewDbgInfoFormat = true;
7108 Lex.Lex();
7109
7110 DbgRecord *DR;
7111 if (parseDebugRecord(DR, PFS))
7112 return true;
7113 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7114 }
7115
7116 FileLoc InstStart(Lex.getTokLineColumnPos());
7117 // This instruction may have three possibilities for a name: a) none
7118 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7119 LocTy NameLoc = Lex.getLoc();
7120 int NameID = -1;
7121 NameStr = "";
7122
7123 if (Lex.getKind() == lltok::LocalVarID) {
7124 NameID = Lex.getUIntVal();
7125 Lex.Lex();
7126 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7127 return true;
7128 } else if (Lex.getKind() == lltok::LocalVar) {
7129 NameStr = Lex.getStrVal();
7130 Lex.Lex();
7131 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7132 return true;
7133 }
7134
7135 switch (parseInstruction(Inst, BB, PFS)) {
7136 default:
7137 llvm_unreachable("Unknown parseInstruction result!");
7138 case InstError: return true;
7139 case InstNormal:
7140 Inst->insertInto(BB, BB->end());
7141
7142 // With a normal result, we check to see if the instruction is followed by
7143 // a comma and metadata.
7144 if (EatIfPresent(lltok::comma))
7145 if (parseInstructionMetadata(*Inst))
7146 return true;
7147 break;
7148 case InstExtraComma:
7149 Inst->insertInto(BB, BB->end());
7150
7151 // If the instruction parser ate an extra comma at the end of it, it
7152 // *must* be followed by metadata.
7153 if (parseInstructionMetadata(*Inst))
7154 return true;
7155 break;
7156 }
7157
7158 // Set the name on the instruction.
7159 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7160 return true;
7161
7162 // Attach any preceding debug values to this instruction.
7163 for (DbgRecordPtr &DR : TrailingDbgRecord)
7164 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7165 TrailingDbgRecord.clear();
7166 if (ParserContext) {
7167 ParserContext->addInstructionLocation(
7168 Inst, FileLocRange(InstStart, Lex.getPrevTokEndLineColumnPos()));
7169 }
7170 } while (!Inst->isTerminator());
7171
7172 if (ParserContext)
7173 ParserContext->addBlockLocation(
7174 BB, FileLocRange(BBStart, Lex.getPrevTokEndLineColumnPos()));
7175
7176 assert(TrailingDbgRecord.empty() &&
7177 "All debug values should have been attached to an instruction.");
7178
7179 return false;
7180}
7181
7182/// parseDebugRecord
7183/// ::= #dbg_label '(' MDNode ')'
7184/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7185/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7186bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7187 using RecordKind = DbgRecord::Kind;
7188 using LocType = DbgVariableRecord::LocationType;
7189 LocTy DVRLoc = Lex.getLoc();
7190 if (Lex.getKind() != lltok::DbgRecordType)
7191 return error(DVRLoc, "expected debug record type here");
7192 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7193 .Case("declare", RecordKind::ValueKind)
7194 .Case("value", RecordKind::ValueKind)
7195 .Case("assign", RecordKind::ValueKind)
7196 .Case("label", RecordKind::LabelKind)
7197 .Case("declare_value", RecordKind::ValueKind);
7198
7199 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7200 // full DbgVariableRecord processing stage.
7201 if (RecordType == RecordKind::LabelKind) {
7202 Lex.Lex();
7203 if (parseToken(lltok::lparen, "Expected '(' here"))
7204 return true;
7205 MDNode *Label;
7206 if (parseMDNode(Label))
7207 return true;
7208 if (parseToken(lltok::comma, "Expected ',' here"))
7209 return true;
7210 MDNode *DbgLoc;
7211 if (parseMDNode(DbgLoc))
7212 return true;
7213 if (parseToken(lltok::rparen, "Expected ')' here"))
7214 return true;
7216 return false;
7217 }
7218
7219 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7220 .Case("declare", LocType::Declare)
7221 .Case("value", LocType::Value)
7222 .Case("assign", LocType::Assign)
7223 .Case("declare_value", LocType::DeclareValue);
7224
7225 Lex.Lex();
7226 if (parseToken(lltok::lparen, "Expected '(' here"))
7227 return true;
7228
7229 // Parse Value field.
7230 Metadata *ValLocMD;
7231 if (parseMetadata(ValLocMD, &PFS))
7232 return true;
7233 if (parseToken(lltok::comma, "Expected ',' here"))
7234 return true;
7235
7236 // Parse Variable field.
7237 MDNode *Variable;
7238 if (parseMDNode(Variable))
7239 return true;
7240 if (parseToken(lltok::comma, "Expected ',' here"))
7241 return true;
7242
7243 // Parse Expression field.
7244 MDNode *Expression;
7245 if (parseMDNode(Expression))
7246 return true;
7247 if (parseToken(lltok::comma, "Expected ',' here"))
7248 return true;
7249
7250 // Parse additional fields for #dbg_assign.
7251 MDNode *AssignID = nullptr;
7252 Metadata *AddressLocation = nullptr;
7253 MDNode *AddressExpression = nullptr;
7254 if (ValueType == LocType::Assign) {
7255 // Parse DIAssignID.
7256 if (parseMDNode(AssignID))
7257 return true;
7258 if (parseToken(lltok::comma, "Expected ',' here"))
7259 return true;
7260
7261 // Parse address ValueAsMetadata.
7262 if (parseMetadata(AddressLocation, &PFS))
7263 return true;
7264 if (parseToken(lltok::comma, "Expected ',' here"))
7265 return true;
7266
7267 // Parse address DIExpression.
7268 if (parseMDNode(AddressExpression))
7269 return true;
7270 if (parseToken(lltok::comma, "Expected ',' here"))
7271 return true;
7272 }
7273
7274 /// Parse DILocation.
7275 MDNode *DebugLoc;
7276 if (parseMDNode(DebugLoc))
7277 return true;
7278
7279 if (parseToken(lltok::rparen, "Expected ')' here"))
7280 return true;
7282 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7283 AddressExpression, DebugLoc);
7284 return false;
7285}
7286//===----------------------------------------------------------------------===//
7287// Instruction Parsing.
7288//===----------------------------------------------------------------------===//
7289
7290/// parseInstruction - parse one of the many different instructions.
7291///
7292int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7293 PerFunctionState &PFS) {
7294 lltok::Kind Token = Lex.getKind();
7295 if (Token == lltok::Eof)
7296 return tokError("found end of file when expecting more instructions");
7297 LocTy Loc = Lex.getLoc();
7298 unsigned KeywordVal = Lex.getUIntVal();
7299 Lex.Lex(); // Eat the keyword.
7300
7301 switch (Token) {
7302 default:
7303 return error(Loc, "expected instruction opcode");
7304 // Terminator Instructions.
7305 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7306 case lltok::kw_ret:
7307 return parseRet(Inst, BB, PFS);
7308 case lltok::kw_br:
7309 return parseBr(Inst, PFS);
7310 case lltok::kw_switch:
7311 return parseSwitch(Inst, PFS);
7313 return parseIndirectBr(Inst, PFS);
7314 case lltok::kw_invoke:
7315 return parseInvoke(Inst, PFS);
7316 case lltok::kw_resume:
7317 return parseResume(Inst, PFS);
7319 return parseCleanupRet(Inst, PFS);
7320 case lltok::kw_catchret:
7321 return parseCatchRet(Inst, PFS);
7323 return parseCatchSwitch(Inst, PFS);
7324 case lltok::kw_catchpad:
7325 return parseCatchPad(Inst, PFS);
7327 return parseCleanupPad(Inst, PFS);
7328 case lltok::kw_callbr:
7329 return parseCallBr(Inst, PFS);
7330 // Unary Operators.
7331 case lltok::kw_fneg: {
7332 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7333 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7334 if (Res != 0)
7335 return Res;
7336 if (FMF.any())
7337 Inst->setFastMathFlags(FMF);
7338 return false;
7339 }
7340 // Binary Operators.
7341 case lltok::kw_add:
7342 case lltok::kw_sub:
7343 case lltok::kw_mul:
7344 case lltok::kw_shl: {
7345 bool NUW = EatIfPresent(lltok::kw_nuw);
7346 bool NSW = EatIfPresent(lltok::kw_nsw);
7347 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7348
7349 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7350 return true;
7351
7352 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7353 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7354 return false;
7355 }
7356 case lltok::kw_fadd:
7357 case lltok::kw_fsub:
7358 case lltok::kw_fmul:
7359 case lltok::kw_fdiv:
7360 case lltok::kw_frem: {
7361 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7362 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7363 if (Res != 0)
7364 return Res;
7365 if (FMF.any())
7366 Inst->setFastMathFlags(FMF);
7367 return 0;
7368 }
7369
7370 case lltok::kw_sdiv:
7371 case lltok::kw_udiv:
7372 case lltok::kw_lshr:
7373 case lltok::kw_ashr: {
7374 bool Exact = EatIfPresent(lltok::kw_exact);
7375
7376 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7377 return true;
7378 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7379 return false;
7380 }
7381
7382 case lltok::kw_urem:
7383 case lltok::kw_srem:
7384 return parseArithmetic(Inst, PFS, KeywordVal,
7385 /*IsFP*/ false);
7386 case lltok::kw_or: {
7387 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7388 if (parseLogical(Inst, PFS, KeywordVal))
7389 return true;
7390 if (Disjoint)
7391 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7392 return false;
7393 }
7394 case lltok::kw_and:
7395 case lltok::kw_xor:
7396 return parseLogical(Inst, PFS, KeywordVal);
7397 case lltok::kw_icmp: {
7398 bool SameSign = EatIfPresent(lltok::kw_samesign);
7399 if (parseCompare(Inst, PFS, KeywordVal))
7400 return true;
7401 if (SameSign)
7402 cast<ICmpInst>(Inst)->setSameSign();
7403 return false;
7404 }
7405 case lltok::kw_fcmp: {
7406 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7407 int Res = parseCompare(Inst, PFS, KeywordVal);
7408 if (Res != 0)
7409 return Res;
7410 if (FMF.any())
7411 Inst->setFastMathFlags(FMF);
7412 return 0;
7413 }
7414
7415 // Casts.
7416 case lltok::kw_uitofp:
7417 case lltok::kw_zext: {
7418 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7419 bool Res = parseCast(Inst, PFS, KeywordVal);
7420 if (Res != 0)
7421 return Res;
7422 if (NonNeg)
7423 Inst->setNonNeg();
7424 return 0;
7425 }
7426 case lltok::kw_trunc: {
7427 bool NUW = EatIfPresent(lltok::kw_nuw);
7428 bool NSW = EatIfPresent(lltok::kw_nsw);
7429 if (!NUW)
7430 NUW = EatIfPresent(lltok::kw_nuw);
7431 if (parseCast(Inst, PFS, KeywordVal))
7432 return true;
7433 if (NUW)
7434 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7435 if (NSW)
7436 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7437 return false;
7438 }
7439 case lltok::kw_sext:
7440 case lltok::kw_bitcast:
7442 case lltok::kw_sitofp:
7443 case lltok::kw_fptoui:
7444 case lltok::kw_fptosi:
7445 case lltok::kw_inttoptr:
7447 case lltok::kw_ptrtoint:
7448 return parseCast(Inst, PFS, KeywordVal);
7449 case lltok::kw_fptrunc:
7450 case lltok::kw_fpext: {
7451 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7452 if (parseCast(Inst, PFS, KeywordVal))
7453 return true;
7454 if (FMF.any())
7455 Inst->setFastMathFlags(FMF);
7456 return false;
7457 }
7458
7459 // Other.
7460 case lltok::kw_select: {
7461 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7462 int Res = parseSelect(Inst, PFS);
7463 if (Res != 0)
7464 return Res;
7465 if (FMF.any()) {
7466 if (!isa<FPMathOperator>(Inst))
7467 return error(Loc, "fast-math-flags specified for select without "
7468 "floating-point scalar or vector return type");
7469 Inst->setFastMathFlags(FMF);
7470 }
7471 return 0;
7472 }
7473 case lltok::kw_va_arg:
7474 return parseVAArg(Inst, PFS);
7476 return parseExtractElement(Inst, PFS);
7478 return parseInsertElement(Inst, PFS);
7480 return parseShuffleVector(Inst, PFS);
7481 case lltok::kw_phi: {
7482 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7483 int Res = parsePHI(Inst, PFS);
7484 if (Res != 0)
7485 return Res;
7486 if (FMF.any()) {
7487 if (!isa<FPMathOperator>(Inst))
7488 return error(Loc, "fast-math-flags specified for phi without "
7489 "floating-point scalar or vector return type");
7490 Inst->setFastMathFlags(FMF);
7491 }
7492 return 0;
7493 }
7495 return parseLandingPad(Inst, PFS);
7496 case lltok::kw_freeze:
7497 return parseFreeze(Inst, PFS);
7498 // Call.
7499 case lltok::kw_call:
7500 return parseCall(Inst, PFS, CallInst::TCK_None);
7501 case lltok::kw_tail:
7502 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7503 case lltok::kw_musttail:
7504 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7505 case lltok::kw_notail:
7506 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7507 // Memory.
7508 case lltok::kw_alloca:
7509 return parseAlloc(Inst, PFS);
7510 case lltok::kw_load:
7511 return parseLoad(Inst, PFS);
7512 case lltok::kw_store:
7513 return parseStore(Inst, PFS);
7514 case lltok::kw_cmpxchg:
7515 return parseCmpXchg(Inst, PFS);
7517 return parseAtomicRMW(Inst, PFS);
7518 case lltok::kw_fence:
7519 return parseFence(Inst, PFS);
7521 return parseGetElementPtr(Inst, PFS);
7523 return parseExtractValue(Inst, PFS);
7525 return parseInsertValue(Inst, PFS);
7526 }
7527}
7528
7529/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7530bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7531 if (Opc == Instruction::FCmp) {
7532 switch (Lex.getKind()) {
7533 default:
7534 return tokError("expected fcmp predicate (e.g. 'oeq')");
7535 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7536 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7537 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7538 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7539 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7540 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7541 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7542 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7543 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7544 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7545 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7546 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7547 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7548 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7549 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7550 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7551 }
7552 } else {
7553 switch (Lex.getKind()) {
7554 default:
7555 return tokError("expected icmp predicate (e.g. 'eq')");
7556 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7557 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7558 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7559 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7560 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7561 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7562 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7563 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7564 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7565 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7566 }
7567 }
7568 Lex.Lex();
7569 return false;
7570}
7571
7572//===----------------------------------------------------------------------===//
7573// Terminator Instructions.
7574//===----------------------------------------------------------------------===//
7575
7576/// parseRet - parse a return instruction.
7577/// ::= 'ret' void (',' !dbg, !1)*
7578/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7579bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7580 PerFunctionState &PFS) {
7581 SMLoc TypeLoc = Lex.getLoc();
7582 Type *Ty = nullptr;
7583 if (parseType(Ty, true /*void allowed*/))
7584 return true;
7585
7586 Type *ResType = PFS.getFunction().getReturnType();
7587
7588 if (Ty->isVoidTy()) {
7589 if (!ResType->isVoidTy())
7590 return error(TypeLoc, "value doesn't match function result type '" +
7591 getTypeString(ResType) + "'");
7592
7593 Inst = ReturnInst::Create(Context);
7594 return false;
7595 }
7596
7597 Value *RV;
7598 if (parseValue(Ty, RV, PFS))
7599 return true;
7600
7601 if (ResType != RV->getType())
7602 return error(TypeLoc, "value doesn't match function result type '" +
7603 getTypeString(ResType) + "'");
7604
7605 Inst = ReturnInst::Create(Context, RV);
7606 return false;
7607}
7608
7609/// parseBr
7610/// ::= 'br' TypeAndValue
7611/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7612bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7613 LocTy Loc, Loc2;
7614 Value *Op0;
7615 BasicBlock *Op1, *Op2;
7616 if (parseTypeAndValue(Op0, Loc, PFS))
7617 return true;
7618
7619 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7620 Inst = BranchInst::Create(BB);
7621 return false;
7622 }
7623
7624 if (Op0->getType() != Type::getInt1Ty(Context))
7625 return error(Loc, "branch condition must have 'i1' type");
7626
7627 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7628 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7629 parseToken(lltok::comma, "expected ',' after true destination") ||
7630 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7631 return true;
7632
7633 Inst = BranchInst::Create(Op1, Op2, Op0);
7634 return false;
7635}
7636
7637/// parseSwitch
7638/// Instruction
7639/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7640/// JumpTable
7641/// ::= (TypeAndValue ',' TypeAndValue)*
7642bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7643 LocTy CondLoc, BBLoc;
7644 Value *Cond;
7645 BasicBlock *DefaultBB;
7646 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7647 parseToken(lltok::comma, "expected ',' after switch condition") ||
7648 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7649 parseToken(lltok::lsquare, "expected '[' with switch table"))
7650 return true;
7651
7652 if (!Cond->getType()->isIntegerTy())
7653 return error(CondLoc, "switch condition must have integer type");
7654
7655 // parse the jump table pairs.
7656 SmallPtrSet<Value*, 32> SeenCases;
7658 while (Lex.getKind() != lltok::rsquare) {
7659 Value *Constant;
7660 BasicBlock *DestBB;
7661
7662 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7663 parseToken(lltok::comma, "expected ',' after case value") ||
7664 parseTypeAndBasicBlock(DestBB, PFS))
7665 return true;
7666
7667 if (!SeenCases.insert(Constant).second)
7668 return error(CondLoc, "duplicate case value in switch");
7669 if (!isa<ConstantInt>(Constant))
7670 return error(CondLoc, "case value is not a constant integer");
7671
7672 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7673 }
7674
7675 Lex.Lex(); // Eat the ']'.
7676
7677 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7678 for (const auto &[OnVal, Dest] : Table)
7679 SI->addCase(OnVal, Dest);
7680 Inst = SI;
7681 return false;
7682}
7683
7684/// parseIndirectBr
7685/// Instruction
7686/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7687bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7688 LocTy AddrLoc;
7689 Value *Address;
7690 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7691 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7692 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7693 return true;
7694
7695 if (!Address->getType()->isPointerTy())
7696 return error(AddrLoc, "indirectbr address must have pointer type");
7697
7698 // parse the destination list.
7699 SmallVector<BasicBlock*, 16> DestList;
7700
7701 if (Lex.getKind() != lltok::rsquare) {
7702 BasicBlock *DestBB;
7703 if (parseTypeAndBasicBlock(DestBB, PFS))
7704 return true;
7705 DestList.push_back(DestBB);
7706
7707 while (EatIfPresent(lltok::comma)) {
7708 if (parseTypeAndBasicBlock(DestBB, PFS))
7709 return true;
7710 DestList.push_back(DestBB);
7711 }
7712 }
7713
7714 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7715 return true;
7716
7717 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7718 for (BasicBlock *Dest : DestList)
7719 IBI->addDestination(Dest);
7720 Inst = IBI;
7721 return false;
7722}
7723
7724// If RetType is a non-function pointer type, then this is the short syntax
7725// for the call, which means that RetType is just the return type. Infer the
7726// rest of the function argument types from the arguments that are present.
7727bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7728 FunctionType *&FuncTy) {
7729 FuncTy = dyn_cast<FunctionType>(RetType);
7730 if (!FuncTy) {
7731 // Pull out the types of all of the arguments...
7732 SmallVector<Type *, 8> ParamTypes;
7733 ParamTypes.reserve(ArgList.size());
7734 for (const ParamInfo &Arg : ArgList)
7735 ParamTypes.push_back(Arg.V->getType());
7736
7737 if (!FunctionType::isValidReturnType(RetType))
7738 return true;
7739
7740 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7741 }
7742 return false;
7743}
7744
7745/// parseInvoke
7746/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7747/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7748bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7749 LocTy CallLoc = Lex.getLoc();
7750 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7751 std::vector<unsigned> FwdRefAttrGrps;
7752 LocTy NoBuiltinLoc;
7753 unsigned CC;
7754 unsigned InvokeAddrSpace;
7755 Type *RetType = nullptr;
7756 LocTy RetTypeLoc;
7757 ValID CalleeID;
7760
7761 BasicBlock *NormalBB, *UnwindBB;
7762 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7763 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7764 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7765 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7766 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7767 NoBuiltinLoc) ||
7768 parseOptionalOperandBundles(BundleList, PFS) ||
7769 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7770 parseTypeAndBasicBlock(NormalBB, PFS) ||
7771 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7772 parseTypeAndBasicBlock(UnwindBB, PFS))
7773 return true;
7774
7775 // If RetType is a non-function pointer type, then this is the short syntax
7776 // for the call, which means that RetType is just the return type. Infer the
7777 // rest of the function argument types from the arguments that are present.
7778 FunctionType *Ty;
7779 if (resolveFunctionType(RetType, ArgList, Ty))
7780 return error(RetTypeLoc, "Invalid result type for LLVM function");
7781
7782 CalleeID.FTy = Ty;
7783
7784 // Look up the callee.
7785 Value *Callee;
7786 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7787 Callee, &PFS))
7788 return true;
7789
7790 // Set up the Attribute for the function.
7791 SmallVector<Value *, 8> Args;
7793
7794 // Loop through FunctionType's arguments and ensure they are specified
7795 // correctly. Also, gather any parameter attributes.
7796 FunctionType::param_iterator I = Ty->param_begin();
7797 FunctionType::param_iterator E = Ty->param_end();
7798 for (const ParamInfo &Arg : ArgList) {
7799 Type *ExpectedTy = nullptr;
7800 if (I != E) {
7801 ExpectedTy = *I++;
7802 } else if (!Ty->isVarArg()) {
7803 return error(Arg.Loc, "too many arguments specified");
7804 }
7805
7806 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7807 return error(Arg.Loc, "argument is not of expected type '" +
7808 getTypeString(ExpectedTy) + "'");
7809 Args.push_back(Arg.V);
7810 ArgAttrs.push_back(Arg.Attrs);
7811 }
7812
7813 if (I != E)
7814 return error(CallLoc, "not enough parameters specified for call");
7815
7816 // Finish off the Attribute and check them
7817 AttributeList PAL =
7818 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7819 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7820
7821 InvokeInst *II =
7822 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7823 II->setCallingConv(CC);
7824 II->setAttributes(PAL);
7825 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7826 Inst = II;
7827 return false;
7828}
7829
7830/// parseResume
7831/// ::= 'resume' TypeAndValue
7832bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7833 Value *Exn; LocTy ExnLoc;
7834 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7835 return true;
7836
7837 ResumeInst *RI = ResumeInst::Create(Exn);
7838 Inst = RI;
7839 return false;
7840}
7841
7842bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7843 PerFunctionState &PFS) {
7844 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7845 return true;
7846
7847 while (Lex.getKind() != lltok::rsquare) {
7848 // If this isn't the first argument, we need a comma.
7849 if (!Args.empty() &&
7850 parseToken(lltok::comma, "expected ',' in argument list"))
7851 return true;
7852
7853 // parse the argument.
7854 LocTy ArgLoc;
7855 Type *ArgTy = nullptr;
7856 if (parseType(ArgTy, ArgLoc))
7857 return true;
7858
7859 Value *V;
7860 if (ArgTy->isMetadataTy()) {
7861 if (parseMetadataAsValue(V, PFS))
7862 return true;
7863 } else {
7864 if (parseValue(ArgTy, V, PFS))
7865 return true;
7866 }
7867 Args.push_back(V);
7868 }
7869
7870 Lex.Lex(); // Lex the ']'.
7871 return false;
7872}
7873
7874/// parseCleanupRet
7875/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7876bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7877 Value *CleanupPad = nullptr;
7878
7879 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7880 return true;
7881
7882 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7883 return true;
7884
7885 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7886 return true;
7887
7888 BasicBlock *UnwindBB = nullptr;
7889 if (Lex.getKind() == lltok::kw_to) {
7890 Lex.Lex();
7891 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7892 return true;
7893 } else {
7894 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7895 return true;
7896 }
7897 }
7898
7899 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7900 return false;
7901}
7902
7903/// parseCatchRet
7904/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7905bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7906 Value *CatchPad = nullptr;
7907
7908 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7909 return true;
7910
7911 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7912 return true;
7913
7914 BasicBlock *BB;
7915 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7916 parseTypeAndBasicBlock(BB, PFS))
7917 return true;
7918
7919 Inst = CatchReturnInst::Create(CatchPad, BB);
7920 return false;
7921}
7922
7923/// parseCatchSwitch
7924/// ::= 'catchswitch' within Parent
7925bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7926 Value *ParentPad;
7927
7928 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7929 return true;
7930
7931 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7932 Lex.getKind() != lltok::LocalVarID)
7933 return tokError("expected scope value for catchswitch");
7934
7935 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7936 return true;
7937
7938 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7939 return true;
7940
7942 do {
7943 BasicBlock *DestBB;
7944 if (parseTypeAndBasicBlock(DestBB, PFS))
7945 return true;
7946 Table.push_back(DestBB);
7947 } while (EatIfPresent(lltok::comma));
7948
7949 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7950 return true;
7951
7952 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7953 return true;
7954
7955 BasicBlock *UnwindBB = nullptr;
7956 if (EatIfPresent(lltok::kw_to)) {
7957 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7958 return true;
7959 } else {
7960 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7961 return true;
7962 }
7963
7964 auto *CatchSwitch =
7965 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7966 for (BasicBlock *DestBB : Table)
7967 CatchSwitch->addHandler(DestBB);
7968 Inst = CatchSwitch;
7969 return false;
7970}
7971
7972/// parseCatchPad
7973/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7974bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7975 Value *CatchSwitch = nullptr;
7976
7977 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7978 return true;
7979
7980 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7981 return tokError("expected scope value for catchpad");
7982
7983 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7984 return true;
7985
7986 SmallVector<Value *, 8> Args;
7987 if (parseExceptionArgs(Args, PFS))
7988 return true;
7989
7990 Inst = CatchPadInst::Create(CatchSwitch, Args);
7991 return false;
7992}
7993
7994/// parseCleanupPad
7995/// ::= 'cleanuppad' within Parent ParamList
7996bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7997 Value *ParentPad = nullptr;
7998
7999 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8000 return true;
8001
8002 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8003 Lex.getKind() != lltok::LocalVarID)
8004 return tokError("expected scope value for cleanuppad");
8005
8006 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8007 return true;
8008
8009 SmallVector<Value *, 8> Args;
8010 if (parseExceptionArgs(Args, PFS))
8011 return true;
8012
8013 Inst = CleanupPadInst::Create(ParentPad, Args);
8014 return false;
8015}
8016
8017//===----------------------------------------------------------------------===//
8018// Unary Operators.
8019//===----------------------------------------------------------------------===//
8020
8021/// parseUnaryOp
8022/// ::= UnaryOp TypeAndValue ',' Value
8023///
8024/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8025/// operand is allowed.
8026bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8027 unsigned Opc, bool IsFP) {
8028 LocTy Loc; Value *LHS;
8029 if (parseTypeAndValue(LHS, Loc, PFS))
8030 return true;
8031
8032 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8034
8035 if (!Valid)
8036 return error(Loc, "invalid operand type for instruction");
8037
8039 return false;
8040}
8041
8042/// parseCallBr
8043/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8044/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8045/// '[' LabelList ']'
8046bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8047 LocTy CallLoc = Lex.getLoc();
8048 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8049 std::vector<unsigned> FwdRefAttrGrps;
8050 LocTy NoBuiltinLoc;
8051 unsigned CC;
8052 Type *RetType = nullptr;
8053 LocTy RetTypeLoc;
8054 ValID CalleeID;
8057
8058 BasicBlock *DefaultDest;
8059 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8060 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8061 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8062 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8063 NoBuiltinLoc) ||
8064 parseOptionalOperandBundles(BundleList, PFS) ||
8065 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8066 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8067 parseToken(lltok::lsquare, "expected '[' in callbr"))
8068 return true;
8069
8070 // parse the destination list.
8071 SmallVector<BasicBlock *, 16> IndirectDests;
8072
8073 if (Lex.getKind() != lltok::rsquare) {
8074 BasicBlock *DestBB;
8075 if (parseTypeAndBasicBlock(DestBB, PFS))
8076 return true;
8077 IndirectDests.push_back(DestBB);
8078
8079 while (EatIfPresent(lltok::comma)) {
8080 if (parseTypeAndBasicBlock(DestBB, PFS))
8081 return true;
8082 IndirectDests.push_back(DestBB);
8083 }
8084 }
8085
8086 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8087 return true;
8088
8089 // If RetType is a non-function pointer type, then this is the short syntax
8090 // for the call, which means that RetType is just the return type. Infer the
8091 // rest of the function argument types from the arguments that are present.
8092 FunctionType *Ty;
8093 if (resolveFunctionType(RetType, ArgList, Ty))
8094 return error(RetTypeLoc, "Invalid result type for LLVM function");
8095
8096 CalleeID.FTy = Ty;
8097
8098 // Look up the callee.
8099 Value *Callee;
8100 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8101 &PFS))
8102 return true;
8103
8104 // Set up the Attribute for the function.
8105 SmallVector<Value *, 8> Args;
8107
8108 // Loop through FunctionType's arguments and ensure they are specified
8109 // correctly. Also, gather any parameter attributes.
8110 FunctionType::param_iterator I = Ty->param_begin();
8111 FunctionType::param_iterator E = Ty->param_end();
8112 for (const ParamInfo &Arg : ArgList) {
8113 Type *ExpectedTy = nullptr;
8114 if (I != E) {
8115 ExpectedTy = *I++;
8116 } else if (!Ty->isVarArg()) {
8117 return error(Arg.Loc, "too many arguments specified");
8118 }
8119
8120 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8121 return error(Arg.Loc, "argument is not of expected type '" +
8122 getTypeString(ExpectedTy) + "'");
8123 Args.push_back(Arg.V);
8124 ArgAttrs.push_back(Arg.Attrs);
8125 }
8126
8127 if (I != E)
8128 return error(CallLoc, "not enough parameters specified for call");
8129
8130 // Finish off the Attribute and check them
8131 AttributeList PAL =
8132 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8133 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8134
8135 CallBrInst *CBI =
8136 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8137 BundleList);
8138 CBI->setCallingConv(CC);
8139 CBI->setAttributes(PAL);
8140 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8141 Inst = CBI;
8142 return false;
8143}
8144
8145//===----------------------------------------------------------------------===//
8146// Binary Operators.
8147//===----------------------------------------------------------------------===//
8148
8149/// parseArithmetic
8150/// ::= ArithmeticOps TypeAndValue ',' Value
8151///
8152/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8153/// operand is allowed.
8154bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8155 unsigned Opc, bool IsFP) {
8156 LocTy Loc; Value *LHS, *RHS;
8157 if (parseTypeAndValue(LHS, Loc, PFS) ||
8158 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8159 parseValue(LHS->getType(), RHS, PFS))
8160 return true;
8161
8162 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8164
8165 if (!Valid)
8166 return error(Loc, "invalid operand type for instruction");
8167
8169 return false;
8170}
8171
8172/// parseLogical
8173/// ::= ArithmeticOps TypeAndValue ',' Value {
8174bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8175 unsigned Opc) {
8176 LocTy Loc; Value *LHS, *RHS;
8177 if (parseTypeAndValue(LHS, Loc, PFS) ||
8178 parseToken(lltok::comma, "expected ',' in logical operation") ||
8179 parseValue(LHS->getType(), RHS, PFS))
8180 return true;
8181
8182 if (!LHS->getType()->isIntOrIntVectorTy())
8183 return error(Loc,
8184 "instruction requires integer or integer vector operands");
8185
8187 return false;
8188}
8189
8190/// parseCompare
8191/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8192/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8193bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8194 unsigned Opc) {
8195 // parse the integer/fp comparison predicate.
8196 LocTy Loc;
8197 unsigned Pred;
8198 Value *LHS, *RHS;
8199 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8200 parseToken(lltok::comma, "expected ',' after compare value") ||
8201 parseValue(LHS->getType(), RHS, PFS))
8202 return true;
8203
8204 if (Opc == Instruction::FCmp) {
8205 if (!LHS->getType()->isFPOrFPVectorTy())
8206 return error(Loc, "fcmp requires floating point operands");
8207 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8208 } else {
8209 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8210 if (!LHS->getType()->isIntOrIntVectorTy() &&
8212 return error(Loc, "icmp requires integer operands");
8213 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8214 }
8215 return false;
8216}
8217
8218//===----------------------------------------------------------------------===//
8219// Other Instructions.
8220//===----------------------------------------------------------------------===//
8221
8222/// parseCast
8223/// ::= CastOpc TypeAndValue 'to' Type
8224bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8225 unsigned Opc) {
8226 LocTy Loc;
8227 Value *Op;
8228 Type *DestTy = nullptr;
8229 if (parseTypeAndValue(Op, Loc, PFS) ||
8230 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8231 parseType(DestTy))
8232 return true;
8233
8235 return error(Loc, "invalid cast opcode for cast from '" +
8236 getTypeString(Op->getType()) + "' to '" +
8237 getTypeString(DestTy) + "'");
8238 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8239 return false;
8240}
8241
8242/// parseSelect
8243/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8244bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8245 LocTy Loc;
8246 Value *Op0, *Op1, *Op2;
8247 if (parseTypeAndValue(Op0, Loc, PFS) ||
8248 parseToken(lltok::comma, "expected ',' after select condition") ||
8249 parseTypeAndValue(Op1, PFS) ||
8250 parseToken(lltok::comma, "expected ',' after select value") ||
8251 parseTypeAndValue(Op2, PFS))
8252 return true;
8253
8254 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8255 return error(Loc, Reason);
8256
8257 Inst = SelectInst::Create(Op0, Op1, Op2);
8258 return false;
8259}
8260
8261/// parseVAArg
8262/// ::= 'va_arg' TypeAndValue ',' Type
8263bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8264 Value *Op;
8265 Type *EltTy = nullptr;
8266 LocTy TypeLoc;
8267 if (parseTypeAndValue(Op, PFS) ||
8268 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8269 parseType(EltTy, TypeLoc))
8270 return true;
8271
8272 if (!EltTy->isFirstClassType())
8273 return error(TypeLoc, "va_arg requires operand with first class type");
8274
8275 Inst = new VAArgInst(Op, EltTy);
8276 return false;
8277}
8278
8279/// parseExtractElement
8280/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8281bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8282 LocTy Loc;
8283 Value *Op0, *Op1;
8284 if (parseTypeAndValue(Op0, Loc, PFS) ||
8285 parseToken(lltok::comma, "expected ',' after extract value") ||
8286 parseTypeAndValue(Op1, PFS))
8287 return true;
8288
8290 return error(Loc, "invalid extractelement operands");
8291
8292 Inst = ExtractElementInst::Create(Op0, Op1);
8293 return false;
8294}
8295
8296/// parseInsertElement
8297/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8298bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8299 LocTy Loc;
8300 Value *Op0, *Op1, *Op2;
8301 if (parseTypeAndValue(Op0, Loc, PFS) ||
8302 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8303 parseTypeAndValue(Op1, PFS) ||
8304 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8305 parseTypeAndValue(Op2, PFS))
8306 return true;
8307
8308 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8309 return error(Loc, "invalid insertelement operands");
8310
8311 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8312 return false;
8313}
8314
8315/// parseShuffleVector
8316/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8317bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8318 LocTy Loc;
8319 Value *Op0, *Op1, *Op2;
8320 if (parseTypeAndValue(Op0, Loc, PFS) ||
8321 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8322 parseTypeAndValue(Op1, PFS) ||
8323 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8324 parseTypeAndValue(Op2, PFS))
8325 return true;
8326
8327 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8328 return error(Loc, "invalid shufflevector operands");
8329
8330 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8331 return false;
8332}
8333
8334/// parsePHI
8335/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8336int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8337 Type *Ty = nullptr; LocTy TypeLoc;
8338 Value *Op0, *Op1;
8339
8340 if (parseType(Ty, TypeLoc))
8341 return true;
8342
8343 if (!Ty->isFirstClassType())
8344 return error(TypeLoc, "phi node must have first class type");
8345
8346 bool First = true;
8347 bool AteExtraComma = false;
8349
8350 while (true) {
8351 if (First) {
8352 if (Lex.getKind() != lltok::lsquare)
8353 break;
8354 First = false;
8355 } else if (!EatIfPresent(lltok::comma))
8356 break;
8357
8358 if (Lex.getKind() == lltok::MetadataVar) {
8359 AteExtraComma = true;
8360 break;
8361 }
8362
8363 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8364 parseValue(Ty, Op0, PFS) ||
8365 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8366 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8367 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8368 return true;
8369
8370 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8371 }
8372
8373 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8374 for (const auto &[Val, BB] : PHIVals)
8375 PN->addIncoming(Val, BB);
8376 Inst = PN;
8377 return AteExtraComma ? InstExtraComma : InstNormal;
8378}
8379
8380/// parseLandingPad
8381/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8382/// Clause
8383/// ::= 'catch' TypeAndValue
8384/// ::= 'filter'
8385/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8386bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8387 Type *Ty = nullptr; LocTy TyLoc;
8388
8389 if (parseType(Ty, TyLoc))
8390 return true;
8391
8392 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8393 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8394
8395 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8397 if (EatIfPresent(lltok::kw_catch))
8399 else if (EatIfPresent(lltok::kw_filter))
8401 else
8402 return tokError("expected 'catch' or 'filter' clause type");
8403
8404 Value *V;
8405 LocTy VLoc;
8406 if (parseTypeAndValue(V, VLoc, PFS))
8407 return true;
8408
8409 // A 'catch' type expects a non-array constant. A filter clause expects an
8410 // array constant.
8411 if (CT == LandingPadInst::Catch) {
8412 if (isa<ArrayType>(V->getType()))
8413 return error(VLoc, "'catch' clause has an invalid type");
8414 } else {
8415 if (!isa<ArrayType>(V->getType()))
8416 return error(VLoc, "'filter' clause has an invalid type");
8417 }
8418
8420 if (!CV)
8421 return error(VLoc, "clause argument must be a constant");
8422 LP->addClause(CV);
8423 }
8424
8425 Inst = LP.release();
8426 return false;
8427}
8428
8429/// parseFreeze
8430/// ::= 'freeze' Type Value
8431bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8432 LocTy Loc;
8433 Value *Op;
8434 if (parseTypeAndValue(Op, Loc, PFS))
8435 return true;
8436
8437 Inst = new FreezeInst(Op);
8438 return false;
8439}
8440
8441/// parseCall
8442/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8443/// OptionalAttrs Type Value ParameterList OptionalAttrs
8444/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8445/// OptionalAttrs Type Value ParameterList OptionalAttrs
8446/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8447/// OptionalAttrs Type Value ParameterList OptionalAttrs
8448/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8449/// OptionalAttrs Type Value ParameterList OptionalAttrs
8450bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8452 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8453 std::vector<unsigned> FwdRefAttrGrps;
8454 LocTy BuiltinLoc;
8455 unsigned CallAddrSpace;
8456 unsigned CC;
8457 Type *RetType = nullptr;
8458 LocTy RetTypeLoc;
8459 ValID CalleeID;
8462 LocTy CallLoc = Lex.getLoc();
8463
8464 if (TCK != CallInst::TCK_None &&
8465 parseToken(lltok::kw_call,
8466 "expected 'tail call', 'musttail call', or 'notail call'"))
8467 return true;
8468
8469 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8470
8471 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8472 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8473 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8474 parseValID(CalleeID, &PFS) ||
8475 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8476 PFS.getFunction().isVarArg()) ||
8477 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8478 parseOptionalOperandBundles(BundleList, PFS))
8479 return true;
8480
8481 // If RetType is a non-function pointer type, then this is the short syntax
8482 // for the call, which means that RetType is just the return type. Infer the
8483 // rest of the function argument types from the arguments that are present.
8484 FunctionType *Ty;
8485 if (resolveFunctionType(RetType, ArgList, Ty))
8486 return error(RetTypeLoc, "Invalid result type for LLVM function");
8487
8488 CalleeID.FTy = Ty;
8489
8490 // Look up the callee.
8491 Value *Callee;
8492 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8493 Callee, &PFS))
8494 return true;
8495
8496 // Set up the Attribute for the function.
8498
8499 SmallVector<Value*, 8> Args;
8500
8501 // Loop through FunctionType's arguments and ensure they are specified
8502 // correctly. Also, gather any parameter attributes.
8503 FunctionType::param_iterator I = Ty->param_begin();
8504 FunctionType::param_iterator E = Ty->param_end();
8505 for (const ParamInfo &Arg : ArgList) {
8506 Type *ExpectedTy = nullptr;
8507 if (I != E) {
8508 ExpectedTy = *I++;
8509 } else if (!Ty->isVarArg()) {
8510 return error(Arg.Loc, "too many arguments specified");
8511 }
8512
8513 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8514 return error(Arg.Loc, "argument is not of expected type '" +
8515 getTypeString(ExpectedTy) + "'");
8516 Args.push_back(Arg.V);
8517 Attrs.push_back(Arg.Attrs);
8518 }
8519
8520 if (I != E)
8521 return error(CallLoc, "not enough parameters specified for call");
8522
8523 // Finish off the Attribute and check them
8524 AttributeList PAL =
8525 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8526 AttributeSet::get(Context, RetAttrs), Attrs);
8527
8528 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8529 CI->setTailCallKind(TCK);
8530 CI->setCallingConv(CC);
8531 if (FMF.any()) {
8532 if (!isa<FPMathOperator>(CI)) {
8533 CI->deleteValue();
8534 return error(CallLoc, "fast-math-flags specified for call without "
8535 "floating-point scalar or vector return type");
8536 }
8537 CI->setFastMathFlags(FMF);
8538 }
8539
8540 if (CalleeID.Kind == ValID::t_GlobalName &&
8541 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8542 if (SeenNewDbgInfoFormat) {
8543 CI->deleteValue();
8544 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8545 "using non-intrinsic debug info");
8546 }
8547 SeenOldDbgInfoFormat = true;
8548 }
8549 CI->setAttributes(PAL);
8550 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8551 Inst = CI;
8552 return false;
8553}
8554
8555//===----------------------------------------------------------------------===//
8556// Memory Instructions.
8557//===----------------------------------------------------------------------===//
8558
8559/// parseAlloc
8560/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8561/// (',' 'align' i32)? (',', 'addrspace(n))?
8562int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8563 Value *Size = nullptr;
8564 LocTy SizeLoc, TyLoc, ASLoc;
8565 MaybeAlign Alignment;
8566 unsigned AddrSpace = 0;
8567 Type *Ty = nullptr;
8568
8569 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8570 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8571
8572 if (parseType(Ty, TyLoc))
8573 return true;
8574
8576 return error(TyLoc, "invalid type for alloca");
8577
8578 bool AteExtraComma = false;
8579 if (EatIfPresent(lltok::comma)) {
8580 if (Lex.getKind() == lltok::kw_align) {
8581 if (parseOptionalAlignment(Alignment))
8582 return true;
8583 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8584 return true;
8585 } else if (Lex.getKind() == lltok::kw_addrspace) {
8586 ASLoc = Lex.getLoc();
8587 if (parseOptionalAddrSpace(AddrSpace))
8588 return true;
8589 } else if (Lex.getKind() == lltok::MetadataVar) {
8590 AteExtraComma = true;
8591 } else {
8592 if (parseTypeAndValue(Size, SizeLoc, PFS))
8593 return true;
8594 if (EatIfPresent(lltok::comma)) {
8595 if (Lex.getKind() == lltok::kw_align) {
8596 if (parseOptionalAlignment(Alignment))
8597 return true;
8598 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8599 return true;
8600 } else if (Lex.getKind() == lltok::kw_addrspace) {
8601 ASLoc = Lex.getLoc();
8602 if (parseOptionalAddrSpace(AddrSpace))
8603 return true;
8604 } else if (Lex.getKind() == lltok::MetadataVar) {
8605 AteExtraComma = true;
8606 }
8607 }
8608 }
8609 }
8610
8611 if (Size && !Size->getType()->isIntegerTy())
8612 return error(SizeLoc, "element count must have integer type");
8613
8614 SmallPtrSet<Type *, 4> Visited;
8615 if (!Alignment && !Ty->isSized(&Visited))
8616 return error(TyLoc, "Cannot allocate unsized type");
8617 if (!Alignment)
8618 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8619 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8620 AI->setUsedWithInAlloca(IsInAlloca);
8621 AI->setSwiftError(IsSwiftError);
8622 Inst = AI;
8623 return AteExtraComma ? InstExtraComma : InstNormal;
8624}
8625
8626/// parseLoad
8627/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8628/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8629/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8630int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8631 Value *Val; LocTy Loc;
8632 MaybeAlign Alignment;
8633 bool AteExtraComma = false;
8634 bool isAtomic = false;
8637
8638 if (Lex.getKind() == lltok::kw_atomic) {
8639 isAtomic = true;
8640 Lex.Lex();
8641 }
8642
8643 bool isVolatile = false;
8644 if (Lex.getKind() == lltok::kw_volatile) {
8645 isVolatile = true;
8646 Lex.Lex();
8647 }
8648
8649 Type *Ty;
8650 LocTy ExplicitTypeLoc = Lex.getLoc();
8651 if (parseType(Ty) ||
8652 parseToken(lltok::comma, "expected comma after load's type") ||
8653 parseTypeAndValue(Val, Loc, PFS) ||
8654 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8655 parseOptionalCommaAlign(Alignment, AteExtraComma))
8656 return true;
8657
8658 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8659 return error(Loc, "load operand must be a pointer to a first class type");
8660 if (isAtomic && !Alignment)
8661 return error(Loc, "atomic load must have explicit non-zero alignment");
8662 if (Ordering == AtomicOrdering::Release ||
8664 return error(Loc, "atomic load cannot use Release ordering");
8665
8666 SmallPtrSet<Type *, 4> Visited;
8667 if (!Alignment && !Ty->isSized(&Visited))
8668 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8669 if (!Alignment)
8670 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8671 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8672 return AteExtraComma ? InstExtraComma : InstNormal;
8673}
8674
8675/// parseStore
8676
8677/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8678/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8679/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8680int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8681 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8682 MaybeAlign Alignment;
8683 bool AteExtraComma = false;
8684 bool isAtomic = false;
8687
8688 if (Lex.getKind() == lltok::kw_atomic) {
8689 isAtomic = true;
8690 Lex.Lex();
8691 }
8692
8693 bool isVolatile = false;
8694 if (Lex.getKind() == lltok::kw_volatile) {
8695 isVolatile = true;
8696 Lex.Lex();
8697 }
8698
8699 if (parseTypeAndValue(Val, Loc, PFS) ||
8700 parseToken(lltok::comma, "expected ',' after store operand") ||
8701 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8702 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8703 parseOptionalCommaAlign(Alignment, AteExtraComma))
8704 return true;
8705
8706 if (!Ptr->getType()->isPointerTy())
8707 return error(PtrLoc, "store operand must be a pointer");
8708 if (!Val->getType()->isFirstClassType())
8709 return error(Loc, "store operand must be a first class value");
8710 if (isAtomic && !Alignment)
8711 return error(Loc, "atomic store must have explicit non-zero alignment");
8712 if (Ordering == AtomicOrdering::Acquire ||
8714 return error(Loc, "atomic store cannot use Acquire ordering");
8715 SmallPtrSet<Type *, 4> Visited;
8716 if (!Alignment && !Val->getType()->isSized(&Visited))
8717 return error(Loc, "storing unsized types is not allowed");
8718 if (!Alignment)
8719 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8720
8721 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8722 return AteExtraComma ? InstExtraComma : InstNormal;
8723}
8724
8725/// parseCmpXchg
8726/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8727/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8728/// 'Align'?
8729int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8730 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8731 bool AteExtraComma = false;
8732 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8733 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8735 bool isVolatile = false;
8736 bool isWeak = false;
8737 MaybeAlign Alignment;
8738
8739 if (EatIfPresent(lltok::kw_weak))
8740 isWeak = true;
8741
8742 if (EatIfPresent(lltok::kw_volatile))
8743 isVolatile = true;
8744
8745 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8746 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8747 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8748 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8749 parseTypeAndValue(New, NewLoc, PFS) ||
8750 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8751 parseOrdering(FailureOrdering) ||
8752 parseOptionalCommaAlign(Alignment, AteExtraComma))
8753 return true;
8754
8755 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8756 return tokError("invalid cmpxchg success ordering");
8757 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8758 return tokError("invalid cmpxchg failure ordering");
8759 if (!Ptr->getType()->isPointerTy())
8760 return error(PtrLoc, "cmpxchg operand must be a pointer");
8761 if (Cmp->getType() != New->getType())
8762 return error(NewLoc, "compare value and new value type do not match");
8763 if (!New->getType()->isFirstClassType())
8764 return error(NewLoc, "cmpxchg operand must be a first class value");
8765
8766 const Align DefaultAlignment(
8767 PFS.getFunction().getDataLayout().getTypeStoreSize(
8768 Cmp->getType()));
8769
8770 AtomicCmpXchgInst *CXI =
8771 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8772 SuccessOrdering, FailureOrdering, SSID);
8773 CXI->setVolatile(isVolatile);
8774 CXI->setWeak(isWeak);
8775
8776 Inst = CXI;
8777 return AteExtraComma ? InstExtraComma : InstNormal;
8778}
8779
8780/// parseAtomicRMW
8781/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8782/// 'singlethread'? AtomicOrdering
8783int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8784 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8785 bool AteExtraComma = false;
8788 bool isVolatile = false;
8789 bool IsFP = false;
8791 MaybeAlign Alignment;
8792
8793 if (EatIfPresent(lltok::kw_volatile))
8794 isVolatile = true;
8795
8796 switch (Lex.getKind()) {
8797 default:
8798 return tokError("expected binary operation in atomicrmw");
8812 break;
8815 break;
8818 break;
8819 case lltok::kw_usub_sat:
8821 break;
8822 case lltok::kw_fadd:
8824 IsFP = true;
8825 break;
8826 case lltok::kw_fsub:
8828 IsFP = true;
8829 break;
8830 case lltok::kw_fmax:
8832 IsFP = true;
8833 break;
8834 case lltok::kw_fmin:
8836 IsFP = true;
8837 break;
8838 case lltok::kw_fmaximum:
8840 IsFP = true;
8841 break;
8842 case lltok::kw_fminimum:
8844 IsFP = true;
8845 break;
8846 }
8847 Lex.Lex(); // Eat the operation.
8848
8849 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8850 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8851 parseTypeAndValue(Val, ValLoc, PFS) ||
8852 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8853 parseOptionalCommaAlign(Alignment, AteExtraComma))
8854 return true;
8855
8856 if (Ordering == AtomicOrdering::Unordered)
8857 return tokError("atomicrmw cannot be unordered");
8858 if (!Ptr->getType()->isPointerTy())
8859 return error(PtrLoc, "atomicrmw operand must be a pointer");
8860 if (Val->getType()->isScalableTy())
8861 return error(ValLoc, "atomicrmw operand may not be scalable");
8862
8864 if (!Val->getType()->isIntegerTy() &&
8865 !Val->getType()->isFloatingPointTy() &&
8866 !Val->getType()->isPointerTy()) {
8867 return error(
8868 ValLoc,
8870 " operand must be an integer, floating point, or pointer type");
8871 }
8872 } else if (IsFP) {
8873 if (!Val->getType()->isFPOrFPVectorTy()) {
8874 return error(ValLoc, "atomicrmw " +
8876 " operand must be a floating point type");
8877 }
8878 } else {
8879 if (!Val->getType()->isIntegerTy()) {
8880 return error(ValLoc, "atomicrmw " +
8882 " operand must be an integer");
8883 }
8884 }
8885
8886 unsigned Size =
8887 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8888 Val->getType());
8889 if (Size < 8 || (Size & (Size - 1)))
8890 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8891 " integer");
8892 const Align DefaultAlignment(
8893 PFS.getFunction().getDataLayout().getTypeStoreSize(
8894 Val->getType()));
8895 AtomicRMWInst *RMWI =
8896 new AtomicRMWInst(Operation, Ptr, Val,
8897 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8898 RMWI->setVolatile(isVolatile);
8899 Inst = RMWI;
8900 return AteExtraComma ? InstExtraComma : InstNormal;
8901}
8902
8903/// parseFence
8904/// ::= 'fence' 'singlethread'? AtomicOrdering
8905int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8908 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8909 return true;
8910
8911 if (Ordering == AtomicOrdering::Unordered)
8912 return tokError("fence cannot be unordered");
8913 if (Ordering == AtomicOrdering::Monotonic)
8914 return tokError("fence cannot be monotonic");
8915
8916 Inst = new FenceInst(Context, Ordering, SSID);
8917 return InstNormal;
8918}
8919
8920/// parseGetElementPtr
8921/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8922int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8923 Value *Ptr = nullptr;
8924 Value *Val = nullptr;
8925 LocTy Loc, EltLoc;
8926 GEPNoWrapFlags NW;
8927
8928 while (true) {
8929 if (EatIfPresent(lltok::kw_inbounds))
8931 else if (EatIfPresent(lltok::kw_nusw))
8933 else if (EatIfPresent(lltok::kw_nuw))
8935 else
8936 break;
8937 }
8938
8939 Type *Ty = nullptr;
8940 if (parseType(Ty) ||
8941 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8942 parseTypeAndValue(Ptr, Loc, PFS))
8943 return true;
8944
8945 Type *BaseType = Ptr->getType();
8946 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8947 if (!BasePointerType)
8948 return error(Loc, "base of getelementptr must be a pointer");
8949
8950 SmallVector<Value*, 16> Indices;
8951 bool AteExtraComma = false;
8952 // GEP returns a vector of pointers if at least one of parameters is a vector.
8953 // All vector parameters should have the same vector width.
8954 ElementCount GEPWidth = BaseType->isVectorTy()
8955 ? cast<VectorType>(BaseType)->getElementCount()
8957
8958 while (EatIfPresent(lltok::comma)) {
8959 if (Lex.getKind() == lltok::MetadataVar) {
8960 AteExtraComma = true;
8961 break;
8962 }
8963 if (parseTypeAndValue(Val, EltLoc, PFS))
8964 return true;
8965 if (!Val->getType()->isIntOrIntVectorTy())
8966 return error(EltLoc, "getelementptr index must be an integer");
8967
8968 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8969 ElementCount ValNumEl = ValVTy->getElementCount();
8970 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8971 return error(
8972 EltLoc,
8973 "getelementptr vector index has a wrong number of elements");
8974 GEPWidth = ValNumEl;
8975 }
8976 Indices.push_back(Val);
8977 }
8978
8979 SmallPtrSet<Type*, 4> Visited;
8980 if (!Indices.empty() && !Ty->isSized(&Visited))
8981 return error(Loc, "base element of getelementptr must be sized");
8982
8983 auto *STy = dyn_cast<StructType>(Ty);
8984 if (STy && STy->isScalableTy())
8985 return error(Loc, "getelementptr cannot target structure that contains "
8986 "scalable vector type");
8987
8988 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8989 return error(Loc, "invalid getelementptr indices");
8990 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8991 Inst = GEP;
8992 GEP->setNoWrapFlags(NW);
8993 return AteExtraComma ? InstExtraComma : InstNormal;
8994}
8995
8996/// parseExtractValue
8997/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8998int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8999 Value *Val; LocTy Loc;
9000 SmallVector<unsigned, 4> Indices;
9001 bool AteExtraComma;
9002 if (parseTypeAndValue(Val, Loc, PFS) ||
9003 parseIndexList(Indices, AteExtraComma))
9004 return true;
9005
9006 if (!Val->getType()->isAggregateType())
9007 return error(Loc, "extractvalue operand must be aggregate type");
9008
9009 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9010 return error(Loc, "invalid indices for extractvalue");
9011 Inst = ExtractValueInst::Create(Val, Indices);
9012 return AteExtraComma ? InstExtraComma : InstNormal;
9013}
9014
9015/// parseInsertValue
9016/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9017int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9018 Value *Val0, *Val1; LocTy Loc0, Loc1;
9019 SmallVector<unsigned, 4> Indices;
9020 bool AteExtraComma;
9021 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9022 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9023 parseTypeAndValue(Val1, Loc1, PFS) ||
9024 parseIndexList(Indices, AteExtraComma))
9025 return true;
9026
9027 if (!Val0->getType()->isAggregateType())
9028 return error(Loc0, "insertvalue operand must be aggregate type");
9029
9030 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9031 if (!IndexedType)
9032 return error(Loc0, "invalid indices for insertvalue");
9033 if (IndexedType != Val1->getType())
9034 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9035 getTypeString(Val1->getType()) + "' instead of '" +
9036 getTypeString(IndexedType) + "'");
9037 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9038 return AteExtraComma ? InstExtraComma : InstNormal;
9039}
9040
9041//===----------------------------------------------------------------------===//
9042// Embedded metadata.
9043//===----------------------------------------------------------------------===//
9044
9045/// parseMDNodeVector
9046/// ::= { Element (',' Element)* }
9047/// Element
9048/// ::= 'null' | Metadata
9049bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9050 if (parseToken(lltok::lbrace, "expected '{' here"))
9051 return true;
9052
9053 // Check for an empty list.
9054 if (EatIfPresent(lltok::rbrace))
9055 return false;
9056
9057 do {
9058 if (EatIfPresent(lltok::kw_null)) {
9059 Elts.push_back(nullptr);
9060 continue;
9061 }
9062
9063 Metadata *MD;
9064 if (parseMetadata(MD, nullptr))
9065 return true;
9066 Elts.push_back(MD);
9067 } while (EatIfPresent(lltok::comma));
9068
9069 return parseToken(lltok::rbrace, "expected end of metadata node");
9070}
9071
9072//===----------------------------------------------------------------------===//
9073// Use-list order directives.
9074//===----------------------------------------------------------------------===//
9075bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9076 SMLoc Loc) {
9077 if (!V->hasUseList())
9078 return false;
9079 if (V->use_empty())
9080 return error(Loc, "value has no uses");
9081
9082 unsigned NumUses = 0;
9083 SmallDenseMap<const Use *, unsigned, 16> Order;
9084 for (const Use &U : V->uses()) {
9085 if (++NumUses > Indexes.size())
9086 break;
9087 Order[&U] = Indexes[NumUses - 1];
9088 }
9089 if (NumUses < 2)
9090 return error(Loc, "value only has one use");
9091 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9092 return error(Loc,
9093 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9094
9095 V->sortUseList([&](const Use &L, const Use &R) {
9096 return Order.lookup(&L) < Order.lookup(&R);
9097 });
9098 return false;
9099}
9100
9101/// parseUseListOrderIndexes
9102/// ::= '{' uint32 (',' uint32)+ '}'
9103bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9104 SMLoc Loc = Lex.getLoc();
9105 if (parseToken(lltok::lbrace, "expected '{' here"))
9106 return true;
9107 if (Lex.getKind() == lltok::rbrace)
9108 return tokError("expected non-empty list of uselistorder indexes");
9109
9110 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9111 // indexes should be distinct numbers in the range [0, size-1], and should
9112 // not be in order.
9113 unsigned Offset = 0;
9114 unsigned Max = 0;
9115 bool IsOrdered = true;
9116 assert(Indexes.empty() && "Expected empty order vector");
9117 do {
9118 unsigned Index;
9119 if (parseUInt32(Index))
9120 return true;
9121
9122 // Update consistency checks.
9123 Offset += Index - Indexes.size();
9124 Max = std::max(Max, Index);
9125 IsOrdered &= Index == Indexes.size();
9126
9127 Indexes.push_back(Index);
9128 } while (EatIfPresent(lltok::comma));
9129
9130 if (parseToken(lltok::rbrace, "expected '}' here"))
9131 return true;
9132
9133 if (Indexes.size() < 2)
9134 return error(Loc, "expected >= 2 uselistorder indexes");
9135 if (Offset != 0 || Max >= Indexes.size())
9136 return error(Loc,
9137 "expected distinct uselistorder indexes in range [0, size)");
9138 if (IsOrdered)
9139 return error(Loc, "expected uselistorder indexes to change the order");
9140
9141 return false;
9142}
9143
9144/// parseUseListOrder
9145/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9146bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9147 SMLoc Loc = Lex.getLoc();
9148 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9149 return true;
9150
9151 Value *V;
9152 SmallVector<unsigned, 16> Indexes;
9153 if (parseTypeAndValue(V, PFS) ||
9154 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9155 parseUseListOrderIndexes(Indexes))
9156 return true;
9157
9158 return sortUseListOrder(V, Indexes, Loc);
9159}
9160
9161/// parseUseListOrderBB
9162/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9163bool LLParser::parseUseListOrderBB() {
9164 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9165 SMLoc Loc = Lex.getLoc();
9166 Lex.Lex();
9167
9168 ValID Fn, Label;
9169 SmallVector<unsigned, 16> Indexes;
9170 if (parseValID(Fn, /*PFS=*/nullptr) ||
9171 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9172 parseValID(Label, /*PFS=*/nullptr) ||
9173 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9174 parseUseListOrderIndexes(Indexes))
9175 return true;
9176
9177 // Check the function.
9178 GlobalValue *GV;
9179 if (Fn.Kind == ValID::t_GlobalName)
9180 GV = M->getNamedValue(Fn.StrVal);
9181 else if (Fn.Kind == ValID::t_GlobalID)
9182 GV = NumberedVals.get(Fn.UIntVal);
9183 else
9184 return error(Fn.Loc, "expected function name in uselistorder_bb");
9185 if (!GV)
9186 return error(Fn.Loc,
9187 "invalid function forward reference in uselistorder_bb");
9188 auto *F = dyn_cast<Function>(GV);
9189 if (!F)
9190 return error(Fn.Loc, "expected function name in uselistorder_bb");
9191 if (F->isDeclaration())
9192 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9193
9194 // Check the basic block.
9195 if (Label.Kind == ValID::t_LocalID)
9196 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9197 if (Label.Kind != ValID::t_LocalName)
9198 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9199 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9200 if (!V)
9201 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9202 if (!isa<BasicBlock>(V))
9203 return error(Label.Loc, "expected basic block in uselistorder_bb");
9204
9205 return sortUseListOrder(V, Indexes, Loc);
9206}
9207
9208/// ModuleEntry
9209/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9210/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9211bool LLParser::parseModuleEntry(unsigned ID) {
9212 assert(Lex.getKind() == lltok::kw_module);
9213 Lex.Lex();
9214
9215 std::string Path;
9216 if (parseToken(lltok::colon, "expected ':' here") ||
9217 parseToken(lltok::lparen, "expected '(' here") ||
9218 parseToken(lltok::kw_path, "expected 'path' here") ||
9219 parseToken(lltok::colon, "expected ':' here") ||
9220 parseStringConstant(Path) ||
9221 parseToken(lltok::comma, "expected ',' here") ||
9222 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9223 parseToken(lltok::colon, "expected ':' here") ||
9224 parseToken(lltok::lparen, "expected '(' here"))
9225 return true;
9226
9227 ModuleHash Hash;
9228 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9229 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9230 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9231 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9232 parseUInt32(Hash[4]))
9233 return true;
9234
9235 if (parseToken(lltok::rparen, "expected ')' here") ||
9236 parseToken(lltok::rparen, "expected ')' here"))
9237 return true;
9238
9239 auto ModuleEntry = Index->addModule(Path, Hash);
9240 ModuleIdMap[ID] = ModuleEntry->first();
9241
9242 return false;
9243}
9244
9245/// TypeIdEntry
9246/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9247bool LLParser::parseTypeIdEntry(unsigned ID) {
9248 assert(Lex.getKind() == lltok::kw_typeid);
9249 Lex.Lex();
9250
9251 std::string Name;
9252 if (parseToken(lltok::colon, "expected ':' here") ||
9253 parseToken(lltok::lparen, "expected '(' here") ||
9254 parseToken(lltok::kw_name, "expected 'name' here") ||
9255 parseToken(lltok::colon, "expected ':' here") ||
9256 parseStringConstant(Name))
9257 return true;
9258
9259 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9260 if (parseToken(lltok::comma, "expected ',' here") ||
9261 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9262 return true;
9263
9264 // Check if this ID was forward referenced, and if so, update the
9265 // corresponding GUIDs.
9266 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9267 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9268 for (auto TIDRef : FwdRefTIDs->second) {
9269 assert(!*TIDRef.first &&
9270 "Forward referenced type id GUID expected to be 0");
9271 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9272 }
9273 ForwardRefTypeIds.erase(FwdRefTIDs);
9274 }
9275
9276 return false;
9277}
9278
9279/// TypeIdSummary
9280/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9281bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9282 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9283 parseToken(lltok::colon, "expected ':' here") ||
9284 parseToken(lltok::lparen, "expected '(' here") ||
9285 parseTypeTestResolution(TIS.TTRes))
9286 return true;
9287
9288 if (EatIfPresent(lltok::comma)) {
9289 // Expect optional wpdResolutions field
9290 if (parseOptionalWpdResolutions(TIS.WPDRes))
9291 return true;
9292 }
9293
9294 if (parseToken(lltok::rparen, "expected ')' here"))
9295 return true;
9296
9297 return false;
9298}
9299
9301 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9302
9303/// TypeIdCompatibleVtableEntry
9304/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9305/// TypeIdCompatibleVtableInfo
9306/// ')'
9307bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9309 Lex.Lex();
9310
9311 std::string Name;
9312 if (parseToken(lltok::colon, "expected ':' here") ||
9313 parseToken(lltok::lparen, "expected '(' here") ||
9314 parseToken(lltok::kw_name, "expected 'name' here") ||
9315 parseToken(lltok::colon, "expected ':' here") ||
9316 parseStringConstant(Name))
9317 return true;
9318
9320 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9321 if (parseToken(lltok::comma, "expected ',' here") ||
9322 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9323 parseToken(lltok::colon, "expected ':' here") ||
9324 parseToken(lltok::lparen, "expected '(' here"))
9325 return true;
9326
9327 IdToIndexMapType IdToIndexMap;
9328 // parse each call edge
9329 do {
9331 if (parseToken(lltok::lparen, "expected '(' here") ||
9332 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9333 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9334 parseToken(lltok::comma, "expected ',' here"))
9335 return true;
9336
9337 LocTy Loc = Lex.getLoc();
9338 unsigned GVId;
9339 ValueInfo VI;
9340 if (parseGVReference(VI, GVId))
9341 return true;
9342
9343 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9344 // forward reference. We will save the location of the ValueInfo needing an
9345 // update, but can only do so once the std::vector is finalized.
9346 if (VI == EmptyVI)
9347 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9348 TI.push_back({Offset, VI});
9349
9350 if (parseToken(lltok::rparen, "expected ')' in call"))
9351 return true;
9352 } while (EatIfPresent(lltok::comma));
9353
9354 // Now that the TI vector is finalized, it is safe to save the locations
9355 // of any forward GV references that need updating later.
9356 for (auto I : IdToIndexMap) {
9357 auto &Infos = ForwardRefValueInfos[I.first];
9358 for (auto P : I.second) {
9359 assert(TI[P.first].VTableVI == EmptyVI &&
9360 "Forward referenced ValueInfo expected to be empty");
9361 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9362 }
9363 }
9364
9365 if (parseToken(lltok::rparen, "expected ')' here") ||
9366 parseToken(lltok::rparen, "expected ')' here"))
9367 return true;
9368
9369 // Check if this ID was forward referenced, and if so, update the
9370 // corresponding GUIDs.
9371 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9372 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9373 for (auto TIDRef : FwdRefTIDs->second) {
9374 assert(!*TIDRef.first &&
9375 "Forward referenced type id GUID expected to be 0");
9376 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9377 }
9378 ForwardRefTypeIds.erase(FwdRefTIDs);
9379 }
9380
9381 return false;
9382}
9383
9384/// TypeTestResolution
9385/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9386/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9387/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9388/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9389/// [',' 'inlinesBits' ':' UInt64]? ')'
9390bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9391 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9392 parseToken(lltok::colon, "expected ':' here") ||
9393 parseToken(lltok::lparen, "expected '(' here") ||
9394 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9395 parseToken(lltok::colon, "expected ':' here"))
9396 return true;
9397
9398 switch (Lex.getKind()) {
9399 case lltok::kw_unknown:
9401 break;
9402 case lltok::kw_unsat:
9404 break;
9407 break;
9408 case lltok::kw_inline:
9410 break;
9411 case lltok::kw_single:
9413 break;
9414 case lltok::kw_allOnes:
9416 break;
9417 default:
9418 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9419 }
9420 Lex.Lex();
9421
9422 if (parseToken(lltok::comma, "expected ',' here") ||
9423 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9424 parseToken(lltok::colon, "expected ':' here") ||
9425 parseUInt32(TTRes.SizeM1BitWidth))
9426 return true;
9427
9428 // parse optional fields
9429 while (EatIfPresent(lltok::comma)) {
9430 switch (Lex.getKind()) {
9432 Lex.Lex();
9433 if (parseToken(lltok::colon, "expected ':'") ||
9434 parseUInt64(TTRes.AlignLog2))
9435 return true;
9436 break;
9437 case lltok::kw_sizeM1:
9438 Lex.Lex();
9439 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9440 return true;
9441 break;
9442 case lltok::kw_bitMask: {
9443 unsigned Val;
9444 Lex.Lex();
9445 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9446 return true;
9447 assert(Val <= 0xff);
9448 TTRes.BitMask = (uint8_t)Val;
9449 break;
9450 }
9452 Lex.Lex();
9453 if (parseToken(lltok::colon, "expected ':'") ||
9454 parseUInt64(TTRes.InlineBits))
9455 return true;
9456 break;
9457 default:
9458 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9459 }
9460 }
9461
9462 if (parseToken(lltok::rparen, "expected ')' here"))
9463 return true;
9464
9465 return false;
9466}
9467
9468/// OptionalWpdResolutions
9469/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9470/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9471bool LLParser::parseOptionalWpdResolutions(
9472 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9473 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9474 parseToken(lltok::colon, "expected ':' here") ||
9475 parseToken(lltok::lparen, "expected '(' here"))
9476 return true;
9477
9478 do {
9479 uint64_t Offset;
9480 WholeProgramDevirtResolution WPDRes;
9481 if (parseToken(lltok::lparen, "expected '(' here") ||
9482 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9483 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9484 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9485 parseToken(lltok::rparen, "expected ')' here"))
9486 return true;
9487 WPDResMap[Offset] = WPDRes;
9488 } while (EatIfPresent(lltok::comma));
9489
9490 if (parseToken(lltok::rparen, "expected ')' here"))
9491 return true;
9492
9493 return false;
9494}
9495
9496/// WpdRes
9497/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9498/// [',' OptionalResByArg]? ')'
9499/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9500/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9501/// [',' OptionalResByArg]? ')'
9502/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9503/// [',' OptionalResByArg]? ')'
9504bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9505 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9506 parseToken(lltok::colon, "expected ':' here") ||
9507 parseToken(lltok::lparen, "expected '(' here") ||
9508 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9509 parseToken(lltok::colon, "expected ':' here"))
9510 return true;
9511
9512 switch (Lex.getKind()) {
9513 case lltok::kw_indir:
9515 break;
9518 break;
9521 break;
9522 default:
9523 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9524 }
9525 Lex.Lex();
9526
9527 // parse optional fields
9528 while (EatIfPresent(lltok::comma)) {
9529 switch (Lex.getKind()) {
9531 Lex.Lex();
9532 if (parseToken(lltok::colon, "expected ':' here") ||
9533 parseStringConstant(WPDRes.SingleImplName))
9534 return true;
9535 break;
9536 case lltok::kw_resByArg:
9537 if (parseOptionalResByArg(WPDRes.ResByArg))
9538 return true;
9539 break;
9540 default:
9541 return error(Lex.getLoc(),
9542 "expected optional WholeProgramDevirtResolution field");
9543 }
9544 }
9545
9546 if (parseToken(lltok::rparen, "expected ')' here"))
9547 return true;
9548
9549 return false;
9550}
9551
9552/// OptionalResByArg
9553/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9554/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9555/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9556/// 'virtualConstProp' )
9557/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9558/// [',' 'bit' ':' UInt32]? ')'
9559bool LLParser::parseOptionalResByArg(
9560 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9561 &ResByArg) {
9562 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9563 parseToken(lltok::colon, "expected ':' here") ||
9564 parseToken(lltok::lparen, "expected '(' here"))
9565 return true;
9566
9567 do {
9568 std::vector<uint64_t> Args;
9569 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9570 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9571 parseToken(lltok::colon, "expected ':' here") ||
9572 parseToken(lltok::lparen, "expected '(' here") ||
9573 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9574 parseToken(lltok::colon, "expected ':' here"))
9575 return true;
9576
9577 WholeProgramDevirtResolution::ByArg ByArg;
9578 switch (Lex.getKind()) {
9579 case lltok::kw_indir:
9581 break;
9584 break;
9587 break;
9590 break;
9591 default:
9592 return error(Lex.getLoc(),
9593 "unexpected WholeProgramDevirtResolution::ByArg kind");
9594 }
9595 Lex.Lex();
9596
9597 // parse optional fields
9598 while (EatIfPresent(lltok::comma)) {
9599 switch (Lex.getKind()) {
9600 case lltok::kw_info:
9601 Lex.Lex();
9602 if (parseToken(lltok::colon, "expected ':' here") ||
9603 parseUInt64(ByArg.Info))
9604 return true;
9605 break;
9606 case lltok::kw_byte:
9607 Lex.Lex();
9608 if (parseToken(lltok::colon, "expected ':' here") ||
9609 parseUInt32(ByArg.Byte))
9610 return true;
9611 break;
9612 case lltok::kw_bit:
9613 Lex.Lex();
9614 if (parseToken(lltok::colon, "expected ':' here") ||
9615 parseUInt32(ByArg.Bit))
9616 return true;
9617 break;
9618 default:
9619 return error(Lex.getLoc(),
9620 "expected optional whole program devirt field");
9621 }
9622 }
9623
9624 if (parseToken(lltok::rparen, "expected ')' here"))
9625 return true;
9626
9627 ResByArg[Args] = ByArg;
9628 } while (EatIfPresent(lltok::comma));
9629
9630 if (parseToken(lltok::rparen, "expected ')' here"))
9631 return true;
9632
9633 return false;
9634}
9635
9636/// OptionalResByArg
9637/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9638bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9639 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9640 parseToken(lltok::colon, "expected ':' here") ||
9641 parseToken(lltok::lparen, "expected '(' here"))
9642 return true;
9643
9644 do {
9645 uint64_t Val;
9646 if (parseUInt64(Val))
9647 return true;
9648 Args.push_back(Val);
9649 } while (EatIfPresent(lltok::comma));
9650
9651 if (parseToken(lltok::rparen, "expected ')' here"))
9652 return true;
9653
9654 return false;
9655}
9656
9657static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9658
9659static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9660 bool ReadOnly = Fwd->isReadOnly();
9661 bool WriteOnly = Fwd->isWriteOnly();
9662 assert(!(ReadOnly && WriteOnly));
9663 *Fwd = Resolved;
9664 if (ReadOnly)
9665 Fwd->setReadOnly();
9666 if (WriteOnly)
9667 Fwd->setWriteOnly();
9668}
9669
9670/// Stores the given Name/GUID and associated summary into the Index.
9671/// Also updates any forward references to the associated entry ID.
9672bool LLParser::addGlobalValueToIndex(
9673 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9674 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9675 // First create the ValueInfo utilizing the Name or GUID.
9676 ValueInfo VI;
9677 if (GUID != 0) {
9678 assert(Name.empty());
9679 VI = Index->getOrInsertValueInfo(GUID);
9680 } else {
9681 assert(!Name.empty());
9682 if (M) {
9683 auto *GV = M->getNamedValue(Name);
9684 if (!GV)
9685 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9686
9687 VI = Index->getOrInsertValueInfo(GV);
9688 } else {
9689 assert(
9690 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9691 "Need a source_filename to compute GUID for local");
9693 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9694 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9695 }
9696 }
9697
9698 // Resolve forward references from calls/refs
9699 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9700 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9701 for (auto VIRef : FwdRefVIs->second) {
9702 assert(VIRef.first->getRef() == FwdVIRef &&
9703 "Forward referenced ValueInfo expected to be empty");
9704 resolveFwdRef(VIRef.first, VI);
9705 }
9706 ForwardRefValueInfos.erase(FwdRefVIs);
9707 }
9708
9709 // Resolve forward references from aliases
9710 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9711 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9712 for (auto AliaseeRef : FwdRefAliasees->second) {
9713 assert(!AliaseeRef.first->hasAliasee() &&
9714 "Forward referencing alias already has aliasee");
9715 assert(Summary && "Aliasee must be a definition");
9716 AliaseeRef.first->setAliasee(VI, Summary.get());
9717 }
9718 ForwardRefAliasees.erase(FwdRefAliasees);
9719 }
9720
9721 // Add the summary if one was provided.
9722 if (Summary)
9723 Index->addGlobalValueSummary(VI, std::move(Summary));
9724
9725 // Save the associated ValueInfo for use in later references by ID.
9726 if (ID == NumberedValueInfos.size())
9727 NumberedValueInfos.push_back(VI);
9728 else {
9729 // Handle non-continuous numbers (to make test simplification easier).
9730 if (ID > NumberedValueInfos.size())
9731 NumberedValueInfos.resize(ID + 1);
9732 NumberedValueInfos[ID] = VI;
9733 }
9734
9735 return false;
9736}
9737
9738/// parseSummaryIndexFlags
9739/// ::= 'flags' ':' UInt64
9740bool LLParser::parseSummaryIndexFlags() {
9741 assert(Lex.getKind() == lltok::kw_flags);
9742 Lex.Lex();
9743
9744 if (parseToken(lltok::colon, "expected ':' here"))
9745 return true;
9746 uint64_t Flags;
9747 if (parseUInt64(Flags))
9748 return true;
9749 if (Index)
9750 Index->setFlags(Flags);
9751 return false;
9752}
9753
9754/// parseBlockCount
9755/// ::= 'blockcount' ':' UInt64
9756bool LLParser::parseBlockCount() {
9757 assert(Lex.getKind() == lltok::kw_blockcount);
9758 Lex.Lex();
9759
9760 if (parseToken(lltok::colon, "expected ':' here"))
9761 return true;
9762 uint64_t BlockCount;
9763 if (parseUInt64(BlockCount))
9764 return true;
9765 if (Index)
9766 Index->setBlockCount(BlockCount);
9767 return false;
9768}
9769
9770/// parseGVEntry
9771/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9772/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9773/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9774bool LLParser::parseGVEntry(unsigned ID) {
9775 assert(Lex.getKind() == lltok::kw_gv);
9776 Lex.Lex();
9777
9778 if (parseToken(lltok::colon, "expected ':' here") ||
9779 parseToken(lltok::lparen, "expected '(' here"))
9780 return true;
9781
9782 LocTy Loc = Lex.getLoc();
9783 std::string Name;
9785 switch (Lex.getKind()) {
9786 case lltok::kw_name:
9787 Lex.Lex();
9788 if (parseToken(lltok::colon, "expected ':' here") ||
9789 parseStringConstant(Name))
9790 return true;
9791 // Can't create GUID/ValueInfo until we have the linkage.
9792 break;
9793 case lltok::kw_guid:
9794 Lex.Lex();
9795 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9796 return true;
9797 break;
9798 default:
9799 return error(Lex.getLoc(), "expected name or guid tag");
9800 }
9801
9802 if (!EatIfPresent(lltok::comma)) {
9803 // No summaries. Wrap up.
9804 if (parseToken(lltok::rparen, "expected ')' here"))
9805 return true;
9806 // This was created for a call to an external or indirect target.
9807 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9808 // created for indirect calls with VP. A Name with no GUID came from
9809 // an external definition. We pass ExternalLinkage since that is only
9810 // used when the GUID must be computed from Name, and in that case
9811 // the symbol must have external linkage.
9812 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9813 nullptr, Loc);
9814 }
9815
9816 // Have a list of summaries
9817 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9818 parseToken(lltok::colon, "expected ':' here") ||
9819 parseToken(lltok::lparen, "expected '(' here"))
9820 return true;
9821 do {
9822 switch (Lex.getKind()) {
9823 case lltok::kw_function:
9824 if (parseFunctionSummary(Name, GUID, ID))
9825 return true;
9826 break;
9827 case lltok::kw_variable:
9828 if (parseVariableSummary(Name, GUID, ID))
9829 return true;
9830 break;
9831 case lltok::kw_alias:
9832 if (parseAliasSummary(Name, GUID, ID))
9833 return true;
9834 break;
9835 default:
9836 return error(Lex.getLoc(), "expected summary type");
9837 }
9838 } while (EatIfPresent(lltok::comma));
9839
9840 if (parseToken(lltok::rparen, "expected ')' here") ||
9841 parseToken(lltok::rparen, "expected ')' here"))
9842 return true;
9843
9844 return false;
9845}
9846
9847/// FunctionSummary
9848/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9849/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9850/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9851/// [',' OptionalRefs]? ')'
9852bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9853 unsigned ID) {
9854 LocTy Loc = Lex.getLoc();
9855 assert(Lex.getKind() == lltok::kw_function);
9856 Lex.Lex();
9857
9858 StringRef ModulePath;
9859 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9861 /*NotEligibleToImport=*/false,
9862 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9864 unsigned InstCount;
9866 FunctionSummary::TypeIdInfo TypeIdInfo;
9867 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9869 std::vector<CallsiteInfo> Callsites;
9870 std::vector<AllocInfo> Allocs;
9871 // Default is all-zeros (conservative values).
9872 FunctionSummary::FFlags FFlags = {};
9873 if (parseToken(lltok::colon, "expected ':' here") ||
9874 parseToken(lltok::lparen, "expected '(' here") ||
9875 parseModuleReference(ModulePath) ||
9876 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9877 parseToken(lltok::comma, "expected ',' here") ||
9878 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9879 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9880 return true;
9881
9882 // parse optional fields
9883 while (EatIfPresent(lltok::comma)) {
9884 switch (Lex.getKind()) {
9886 if (parseOptionalFFlags(FFlags))
9887 return true;
9888 break;
9889 case lltok::kw_calls:
9890 if (parseOptionalCalls(Calls))
9891 return true;
9892 break;
9894 if (parseOptionalTypeIdInfo(TypeIdInfo))
9895 return true;
9896 break;
9897 case lltok::kw_refs:
9898 if (parseOptionalRefs(Refs))
9899 return true;
9900 break;
9901 case lltok::kw_params:
9902 if (parseOptionalParamAccesses(ParamAccesses))
9903 return true;
9904 break;
9905 case lltok::kw_allocs:
9906 if (parseOptionalAllocs(Allocs))
9907 return true;
9908 break;
9910 if (parseOptionalCallsites(Callsites))
9911 return true;
9912 break;
9913 default:
9914 return error(Lex.getLoc(), "expected optional function summary field");
9915 }
9916 }
9917
9918 if (parseToken(lltok::rparen, "expected ')' here"))
9919 return true;
9920
9921 auto FS = std::make_unique<FunctionSummary>(
9922 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9923 std::move(TypeIdInfo.TypeTests),
9924 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9925 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9926 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9927 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9928 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9929
9930 FS->setModulePath(ModulePath);
9931
9932 return addGlobalValueToIndex(Name, GUID,
9934 std::move(FS), Loc);
9935}
9936
9937/// VariableSummary
9938/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9939/// [',' OptionalRefs]? ')'
9940bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9941 unsigned ID) {
9942 LocTy Loc = Lex.getLoc();
9943 assert(Lex.getKind() == lltok::kw_variable);
9944 Lex.Lex();
9945
9946 StringRef ModulePath;
9947 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9949 /*NotEligibleToImport=*/false,
9950 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9952 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9953 /* WriteOnly */ false,
9954 /* Constant */ false,
9957 VTableFuncList VTableFuncs;
9958 if (parseToken(lltok::colon, "expected ':' here") ||
9959 parseToken(lltok::lparen, "expected '(' here") ||
9960 parseModuleReference(ModulePath) ||
9961 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9962 parseToken(lltok::comma, "expected ',' here") ||
9963 parseGVarFlags(GVarFlags))
9964 return true;
9965
9966 // parse optional fields
9967 while (EatIfPresent(lltok::comma)) {
9968 switch (Lex.getKind()) {
9970 if (parseOptionalVTableFuncs(VTableFuncs))
9971 return true;
9972 break;
9973 case lltok::kw_refs:
9974 if (parseOptionalRefs(Refs))
9975 return true;
9976 break;
9977 default:
9978 return error(Lex.getLoc(), "expected optional variable summary field");
9979 }
9980 }
9981
9982 if (parseToken(lltok::rparen, "expected ')' here"))
9983 return true;
9984
9985 auto GS =
9986 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9987
9988 GS->setModulePath(ModulePath);
9989 GS->setVTableFuncs(std::move(VTableFuncs));
9990
9991 return addGlobalValueToIndex(Name, GUID,
9993 std::move(GS), Loc);
9994}
9995
9996/// AliasSummary
9997/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9998/// 'aliasee' ':' GVReference ')'
9999bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10000 unsigned ID) {
10001 assert(Lex.getKind() == lltok::kw_alias);
10002 LocTy Loc = Lex.getLoc();
10003 Lex.Lex();
10004
10005 StringRef ModulePath;
10006 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10008 /*NotEligibleToImport=*/false,
10009 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10011 if (parseToken(lltok::colon, "expected ':' here") ||
10012 parseToken(lltok::lparen, "expected '(' here") ||
10013 parseModuleReference(ModulePath) ||
10014 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10015 parseToken(lltok::comma, "expected ',' here") ||
10016 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10017 parseToken(lltok::colon, "expected ':' here"))
10018 return true;
10019
10020 ValueInfo AliaseeVI;
10021 unsigned GVId;
10022 auto AS = std::make_unique<AliasSummary>(GVFlags);
10023 AS->setModulePath(ModulePath);
10024
10025 if (!EatIfPresent(lltok::kw_null)) {
10026 if (parseGVReference(AliaseeVI, GVId))
10027 return true;
10028
10029 // Record forward reference if the aliasee is not parsed yet.
10030 if (AliaseeVI.getRef() == FwdVIRef) {
10031 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10032 } else {
10033 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10034 assert(Summary && "Aliasee must be a definition");
10035 AS->setAliasee(AliaseeVI, Summary);
10036 }
10037 }
10038
10039 if (parseToken(lltok::rparen, "expected ')' here"))
10040 return true;
10041
10042 return addGlobalValueToIndex(Name, GUID,
10044 std::move(AS), Loc);
10045}
10046
10047/// Flag
10048/// ::= [0|1]
10049bool LLParser::parseFlag(unsigned &Val) {
10050 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10051 return tokError("expected integer");
10052 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10053 Lex.Lex();
10054 return false;
10055}
10056
10057/// OptionalFFlags
10058/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10059/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10060/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10061/// [',' 'noInline' ':' Flag]? ')'
10062/// [',' 'alwaysInline' ':' Flag]? ')'
10063/// [',' 'noUnwind' ':' Flag]? ')'
10064/// [',' 'mayThrow' ':' Flag]? ')'
10065/// [',' 'hasUnknownCall' ':' Flag]? ')'
10066/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10067
10068bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10069 assert(Lex.getKind() == lltok::kw_funcFlags);
10070 Lex.Lex();
10071
10072 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10073 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10074 return true;
10075
10076 do {
10077 unsigned Val = 0;
10078 switch (Lex.getKind()) {
10079 case lltok::kw_readNone:
10080 Lex.Lex();
10081 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10082 return true;
10083 FFlags.ReadNone = Val;
10084 break;
10085 case lltok::kw_readOnly:
10086 Lex.Lex();
10087 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10088 return true;
10089 FFlags.ReadOnly = Val;
10090 break;
10092 Lex.Lex();
10093 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10094 return true;
10095 FFlags.NoRecurse = Val;
10096 break;
10098 Lex.Lex();
10099 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10100 return true;
10101 FFlags.ReturnDoesNotAlias = Val;
10102 break;
10103 case lltok::kw_noInline:
10104 Lex.Lex();
10105 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10106 return true;
10107 FFlags.NoInline = Val;
10108 break;
10110 Lex.Lex();
10111 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10112 return true;
10113 FFlags.AlwaysInline = Val;
10114 break;
10115 case lltok::kw_noUnwind:
10116 Lex.Lex();
10117 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10118 return true;
10119 FFlags.NoUnwind = Val;
10120 break;
10121 case lltok::kw_mayThrow:
10122 Lex.Lex();
10123 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10124 return true;
10125 FFlags.MayThrow = Val;
10126 break;
10128 Lex.Lex();
10129 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10130 return true;
10131 FFlags.HasUnknownCall = Val;
10132 break;
10134 Lex.Lex();
10135 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10136 return true;
10137 FFlags.MustBeUnreachable = Val;
10138 break;
10139 default:
10140 return error(Lex.getLoc(), "expected function flag type");
10141 }
10142 } while (EatIfPresent(lltok::comma));
10143
10144 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10145 return true;
10146
10147 return false;
10148}
10149
10150/// OptionalCalls
10151/// := 'calls' ':' '(' Call [',' Call]* ')'
10152/// Call ::= '(' 'callee' ':' GVReference
10153/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10154/// [ ',' 'tail' ]? ')'
10155bool LLParser::parseOptionalCalls(
10156 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10157 assert(Lex.getKind() == lltok::kw_calls);
10158 Lex.Lex();
10159
10160 if (parseToken(lltok::colon, "expected ':' in calls") ||
10161 parseToken(lltok::lparen, "expected '(' in calls"))
10162 return true;
10163
10164 IdToIndexMapType IdToIndexMap;
10165 // parse each call edge
10166 do {
10167 ValueInfo VI;
10168 if (parseToken(lltok::lparen, "expected '(' in call") ||
10169 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10170 parseToken(lltok::colon, "expected ':'"))
10171 return true;
10172
10173 LocTy Loc = Lex.getLoc();
10174 unsigned GVId;
10175 if (parseGVReference(VI, GVId))
10176 return true;
10177
10179 unsigned RelBF = 0;
10180 unsigned HasTailCall = false;
10181
10182 // parse optional fields
10183 while (EatIfPresent(lltok::comma)) {
10184 switch (Lex.getKind()) {
10185 case lltok::kw_hotness:
10186 Lex.Lex();
10187 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10188 return true;
10189 break;
10190 // Deprecated, keep in order to support old files.
10191 case lltok::kw_relbf:
10192 Lex.Lex();
10193 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10194 return true;
10195 break;
10196 case lltok::kw_tail:
10197 Lex.Lex();
10198 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10199 return true;
10200 break;
10201 default:
10202 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10203 }
10204 }
10205 // Keep track of the Call array index needing a forward reference.
10206 // We will save the location of the ValueInfo needing an update, but
10207 // can only do so once the std::vector is finalized.
10208 if (VI.getRef() == FwdVIRef)
10209 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10210 Calls.push_back(
10211 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10212
10213 if (parseToken(lltok::rparen, "expected ')' in call"))
10214 return true;
10215 } while (EatIfPresent(lltok::comma));
10216
10217 // Now that the Calls vector is finalized, it is safe to save the locations
10218 // of any forward GV references that need updating later.
10219 for (auto I : IdToIndexMap) {
10220 auto &Infos = ForwardRefValueInfos[I.first];
10221 for (auto P : I.second) {
10222 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10223 "Forward referenced ValueInfo expected to be empty");
10224 Infos.emplace_back(&Calls[P.first].first, P.second);
10225 }
10226 }
10227
10228 if (parseToken(lltok::rparen, "expected ')' in calls"))
10229 return true;
10230
10231 return false;
10232}
10233
10234/// Hotness
10235/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10236bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10237 switch (Lex.getKind()) {
10238 case lltok::kw_unknown:
10240 break;
10241 case lltok::kw_cold:
10243 break;
10244 case lltok::kw_none:
10246 break;
10247 case lltok::kw_hot:
10249 break;
10250 case lltok::kw_critical:
10252 break;
10253 default:
10254 return error(Lex.getLoc(), "invalid call edge hotness");
10255 }
10256 Lex.Lex();
10257 return false;
10258}
10259
10260/// OptionalVTableFuncs
10261/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10262/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10263bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10264 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10265 Lex.Lex();
10266
10267 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10268 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10269 return true;
10270
10271 IdToIndexMapType IdToIndexMap;
10272 // parse each virtual function pair
10273 do {
10274 ValueInfo VI;
10275 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10276 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10277 parseToken(lltok::colon, "expected ':'"))
10278 return true;
10279
10280 LocTy Loc = Lex.getLoc();
10281 unsigned GVId;
10282 if (parseGVReference(VI, GVId))
10283 return true;
10284
10285 uint64_t Offset;
10286 if (parseToken(lltok::comma, "expected comma") ||
10287 parseToken(lltok::kw_offset, "expected offset") ||
10288 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10289 return true;
10290
10291 // Keep track of the VTableFuncs array index needing a forward reference.
10292 // We will save the location of the ValueInfo needing an update, but
10293 // can only do so once the std::vector is finalized.
10294 if (VI == EmptyVI)
10295 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10296 VTableFuncs.push_back({VI, Offset});
10297
10298 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10299 return true;
10300 } while (EatIfPresent(lltok::comma));
10301
10302 // Now that the VTableFuncs vector is finalized, it is safe to save the
10303 // locations of any forward GV references that need updating later.
10304 for (auto I : IdToIndexMap) {
10305 auto &Infos = ForwardRefValueInfos[I.first];
10306 for (auto P : I.second) {
10307 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10308 "Forward referenced ValueInfo expected to be empty");
10309 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10310 }
10311 }
10312
10313 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10314 return true;
10315
10316 return false;
10317}
10318
10319/// ParamNo := 'param' ':' UInt64
10320bool LLParser::parseParamNo(uint64_t &ParamNo) {
10321 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10322 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10323 return true;
10324 return false;
10325}
10326
10327/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10328bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10329 APSInt Lower;
10330 APSInt Upper;
10331 auto ParseAPSInt = [&](APSInt &Val) {
10332 if (Lex.getKind() != lltok::APSInt)
10333 return tokError("expected integer");
10334 Val = Lex.getAPSIntVal();
10335 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10336 Val.setIsSigned(true);
10337 Lex.Lex();
10338 return false;
10339 };
10340 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10341 parseToken(lltok::colon, "expected ':' here") ||
10342 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10343 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10344 parseToken(lltok::rsquare, "expected ']' here"))
10345 return true;
10346
10347 ++Upper;
10348 Range =
10349 (Lower == Upper && !Lower.isMaxValue())
10350 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10351 : ConstantRange(Lower, Upper);
10352
10353 return false;
10354}
10355
10356/// ParamAccessCall
10357/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10358bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10359 IdLocListType &IdLocList) {
10360 if (parseToken(lltok::lparen, "expected '(' here") ||
10361 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10362 parseToken(lltok::colon, "expected ':' here"))
10363 return true;
10364
10365 unsigned GVId;
10366 ValueInfo VI;
10367 LocTy Loc = Lex.getLoc();
10368 if (parseGVReference(VI, GVId))
10369 return true;
10370
10371 Call.Callee = VI;
10372 IdLocList.emplace_back(GVId, Loc);
10373
10374 if (parseToken(lltok::comma, "expected ',' here") ||
10375 parseParamNo(Call.ParamNo) ||
10376 parseToken(lltok::comma, "expected ',' here") ||
10377 parseParamAccessOffset(Call.Offsets))
10378 return true;
10379
10380 if (parseToken(lltok::rparen, "expected ')' here"))
10381 return true;
10382
10383 return false;
10384}
10385
10386/// ParamAccess
10387/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10388/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10389bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10390 IdLocListType &IdLocList) {
10391 if (parseToken(lltok::lparen, "expected '(' here") ||
10392 parseParamNo(Param.ParamNo) ||
10393 parseToken(lltok::comma, "expected ',' here") ||
10394 parseParamAccessOffset(Param.Use))
10395 return true;
10396
10397 if (EatIfPresent(lltok::comma)) {
10398 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10399 parseToken(lltok::colon, "expected ':' here") ||
10400 parseToken(lltok::lparen, "expected '(' here"))
10401 return true;
10402 do {
10403 FunctionSummary::ParamAccess::Call Call;
10404 if (parseParamAccessCall(Call, IdLocList))
10405 return true;
10406 Param.Calls.push_back(Call);
10407 } while (EatIfPresent(lltok::comma));
10408
10409 if (parseToken(lltok::rparen, "expected ')' here"))
10410 return true;
10411 }
10412
10413 if (parseToken(lltok::rparen, "expected ')' here"))
10414 return true;
10415
10416 return false;
10417}
10418
10419/// OptionalParamAccesses
10420/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10421bool LLParser::parseOptionalParamAccesses(
10422 std::vector<FunctionSummary::ParamAccess> &Params) {
10423 assert(Lex.getKind() == lltok::kw_params);
10424 Lex.Lex();
10425
10426 if (parseToken(lltok::colon, "expected ':' here") ||
10427 parseToken(lltok::lparen, "expected '(' here"))
10428 return true;
10429
10430 IdLocListType VContexts;
10431 size_t CallsNum = 0;
10432 do {
10433 FunctionSummary::ParamAccess ParamAccess;
10434 if (parseParamAccess(ParamAccess, VContexts))
10435 return true;
10436 CallsNum += ParamAccess.Calls.size();
10437 assert(VContexts.size() == CallsNum);
10438 (void)CallsNum;
10439 Params.emplace_back(std::move(ParamAccess));
10440 } while (EatIfPresent(lltok::comma));
10441
10442 if (parseToken(lltok::rparen, "expected ')' here"))
10443 return true;
10444
10445 // Now that the Params is finalized, it is safe to save the locations
10446 // of any forward GV references that need updating later.
10447 IdLocListType::const_iterator ItContext = VContexts.begin();
10448 for (auto &PA : Params) {
10449 for (auto &C : PA.Calls) {
10450 if (C.Callee.getRef() == FwdVIRef)
10451 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10452 ItContext->second);
10453 ++ItContext;
10454 }
10455 }
10456 assert(ItContext == VContexts.end());
10457
10458 return false;
10459}
10460
10461/// OptionalRefs
10462/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10463bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10464 assert(Lex.getKind() == lltok::kw_refs);
10465 Lex.Lex();
10466
10467 if (parseToken(lltok::colon, "expected ':' in refs") ||
10468 parseToken(lltok::lparen, "expected '(' in refs"))
10469 return true;
10470
10471 struct ValueContext {
10472 ValueInfo VI;
10473 unsigned GVId;
10474 LocTy Loc;
10475 };
10476 std::vector<ValueContext> VContexts;
10477 // parse each ref edge
10478 do {
10479 ValueContext VC;
10480 VC.Loc = Lex.getLoc();
10481 if (parseGVReference(VC.VI, VC.GVId))
10482 return true;
10483 VContexts.push_back(VC);
10484 } while (EatIfPresent(lltok::comma));
10485
10486 // Sort value contexts so that ones with writeonly
10487 // and readonly ValueInfo are at the end of VContexts vector.
10488 // See FunctionSummary::specialRefCounts()
10489 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10490 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10491 });
10492
10493 IdToIndexMapType IdToIndexMap;
10494 for (auto &VC : VContexts) {
10495 // Keep track of the Refs array index needing a forward reference.
10496 // We will save the location of the ValueInfo needing an update, but
10497 // can only do so once the std::vector is finalized.
10498 if (VC.VI.getRef() == FwdVIRef)
10499 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10500 Refs.push_back(VC.VI);
10501 }
10502
10503 // Now that the Refs vector is finalized, it is safe to save the locations
10504 // of any forward GV references that need updating later.
10505 for (auto I : IdToIndexMap) {
10506 auto &Infos = ForwardRefValueInfos[I.first];
10507 for (auto P : I.second) {
10508 assert(Refs[P.first].getRef() == FwdVIRef &&
10509 "Forward referenced ValueInfo expected to be empty");
10510 Infos.emplace_back(&Refs[P.first], P.second);
10511 }
10512 }
10513
10514 if (parseToken(lltok::rparen, "expected ')' in refs"))
10515 return true;
10516
10517 return false;
10518}
10519
10520/// OptionalTypeIdInfo
10521/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10522/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10523/// [',' TypeCheckedLoadConstVCalls]? ')'
10524bool LLParser::parseOptionalTypeIdInfo(
10525 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10526 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10527 Lex.Lex();
10528
10529 if (parseToken(lltok::colon, "expected ':' here") ||
10530 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10531 return true;
10532
10533 do {
10534 switch (Lex.getKind()) {
10536 if (parseTypeTests(TypeIdInfo.TypeTests))
10537 return true;
10538 break;
10540 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10541 TypeIdInfo.TypeTestAssumeVCalls))
10542 return true;
10543 break;
10545 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10546 TypeIdInfo.TypeCheckedLoadVCalls))
10547 return true;
10548 break;
10550 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10551 TypeIdInfo.TypeTestAssumeConstVCalls))
10552 return true;
10553 break;
10555 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10556 TypeIdInfo.TypeCheckedLoadConstVCalls))
10557 return true;
10558 break;
10559 default:
10560 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10561 }
10562 } while (EatIfPresent(lltok::comma));
10563
10564 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10565 return true;
10566
10567 return false;
10568}
10569
10570/// TypeTests
10571/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10572/// [',' (SummaryID | UInt64)]* ')'
10573bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10574 assert(Lex.getKind() == lltok::kw_typeTests);
10575 Lex.Lex();
10576
10577 if (parseToken(lltok::colon, "expected ':' here") ||
10578 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10579 return true;
10580
10581 IdToIndexMapType IdToIndexMap;
10582 do {
10584 if (Lex.getKind() == lltok::SummaryID) {
10585 unsigned ID = Lex.getUIntVal();
10586 LocTy Loc = Lex.getLoc();
10587 // Keep track of the TypeTests array index needing a forward reference.
10588 // We will save the location of the GUID needing an update, but
10589 // can only do so once the std::vector is finalized.
10590 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10591 Lex.Lex();
10592 } else if (parseUInt64(GUID))
10593 return true;
10594 TypeTests.push_back(GUID);
10595 } while (EatIfPresent(lltok::comma));
10596
10597 // Now that the TypeTests vector is finalized, it is safe to save the
10598 // locations of any forward GV references that need updating later.
10599 for (auto I : IdToIndexMap) {
10600 auto &Ids = ForwardRefTypeIds[I.first];
10601 for (auto P : I.second) {
10602 assert(TypeTests[P.first] == 0 &&
10603 "Forward referenced type id GUID expected to be 0");
10604 Ids.emplace_back(&TypeTests[P.first], P.second);
10605 }
10606 }
10607
10608 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10609 return true;
10610
10611 return false;
10612}
10613
10614/// VFuncIdList
10615/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10616bool LLParser::parseVFuncIdList(
10617 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10618 assert(Lex.getKind() == Kind);
10619 Lex.Lex();
10620
10621 if (parseToken(lltok::colon, "expected ':' here") ||
10622 parseToken(lltok::lparen, "expected '(' here"))
10623 return true;
10624
10625 IdToIndexMapType IdToIndexMap;
10626 do {
10627 FunctionSummary::VFuncId VFuncId;
10628 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10629 return true;
10630 VFuncIdList.push_back(VFuncId);
10631 } while (EatIfPresent(lltok::comma));
10632
10633 if (parseToken(lltok::rparen, "expected ')' here"))
10634 return true;
10635
10636 // Now that the VFuncIdList vector is finalized, it is safe to save the
10637 // locations of any forward GV references that need updating later.
10638 for (auto I : IdToIndexMap) {
10639 auto &Ids = ForwardRefTypeIds[I.first];
10640 for (auto P : I.second) {
10641 assert(VFuncIdList[P.first].GUID == 0 &&
10642 "Forward referenced type id GUID expected to be 0");
10643 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10644 }
10645 }
10646
10647 return false;
10648}
10649
10650/// ConstVCallList
10651/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10652bool LLParser::parseConstVCallList(
10653 lltok::Kind Kind,
10654 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10655 assert(Lex.getKind() == Kind);
10656 Lex.Lex();
10657
10658 if (parseToken(lltok::colon, "expected ':' here") ||
10659 parseToken(lltok::lparen, "expected '(' here"))
10660 return true;
10661
10662 IdToIndexMapType IdToIndexMap;
10663 do {
10664 FunctionSummary::ConstVCall ConstVCall;
10665 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10666 return true;
10667 ConstVCallList.push_back(ConstVCall);
10668 } while (EatIfPresent(lltok::comma));
10669
10670 if (parseToken(lltok::rparen, "expected ')' here"))
10671 return true;
10672
10673 // Now that the ConstVCallList vector is finalized, it is safe to save the
10674 // locations of any forward GV references that need updating later.
10675 for (auto I : IdToIndexMap) {
10676 auto &Ids = ForwardRefTypeIds[I.first];
10677 for (auto P : I.second) {
10678 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10679 "Forward referenced type id GUID expected to be 0");
10680 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10681 }
10682 }
10683
10684 return false;
10685}
10686
10687/// ConstVCall
10688/// ::= '(' VFuncId ',' Args ')'
10689bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10690 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10691 if (parseToken(lltok::lparen, "expected '(' here") ||
10692 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10693 return true;
10694
10695 if (EatIfPresent(lltok::comma))
10696 if (parseArgs(ConstVCall.Args))
10697 return true;
10698
10699 if (parseToken(lltok::rparen, "expected ')' here"))
10700 return true;
10701
10702 return false;
10703}
10704
10705/// VFuncId
10706/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10707/// 'offset' ':' UInt64 ')'
10708bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10709 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10710 assert(Lex.getKind() == lltok::kw_vFuncId);
10711 Lex.Lex();
10712
10713 if (parseToken(lltok::colon, "expected ':' here") ||
10714 parseToken(lltok::lparen, "expected '(' here"))
10715 return true;
10716
10717 if (Lex.getKind() == lltok::SummaryID) {
10718 VFuncId.GUID = 0;
10719 unsigned ID = Lex.getUIntVal();
10720 LocTy Loc = Lex.getLoc();
10721 // Keep track of the array index needing a forward reference.
10722 // We will save the location of the GUID needing an update, but
10723 // can only do so once the caller's std::vector is finalized.
10724 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10725 Lex.Lex();
10726 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10727 parseToken(lltok::colon, "expected ':' here") ||
10728 parseUInt64(VFuncId.GUID))
10729 return true;
10730
10731 if (parseToken(lltok::comma, "expected ',' here") ||
10732 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10733 parseToken(lltok::colon, "expected ':' here") ||
10734 parseUInt64(VFuncId.Offset) ||
10735 parseToken(lltok::rparen, "expected ')' here"))
10736 return true;
10737
10738 return false;
10739}
10740
10741/// GVFlags
10742/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10743/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10744/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10745/// 'canAutoHide' ':' Flag ',' ')'
10746bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10747 assert(Lex.getKind() == lltok::kw_flags);
10748 Lex.Lex();
10749
10750 if (parseToken(lltok::colon, "expected ':' here") ||
10751 parseToken(lltok::lparen, "expected '(' here"))
10752 return true;
10753
10754 do {
10755 unsigned Flag = 0;
10756 switch (Lex.getKind()) {
10757 case lltok::kw_linkage:
10758 Lex.Lex();
10759 if (parseToken(lltok::colon, "expected ':'"))
10760 return true;
10761 bool HasLinkage;
10762 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10763 assert(HasLinkage && "Linkage not optional in summary entry");
10764 Lex.Lex();
10765 break;
10767 Lex.Lex();
10768 if (parseToken(lltok::colon, "expected ':'"))
10769 return true;
10770 parseOptionalVisibility(Flag);
10771 GVFlags.Visibility = Flag;
10772 break;
10774 Lex.Lex();
10775 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10776 return true;
10777 GVFlags.NotEligibleToImport = Flag;
10778 break;
10779 case lltok::kw_live:
10780 Lex.Lex();
10781 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10782 return true;
10783 GVFlags.Live = Flag;
10784 break;
10785 case lltok::kw_dsoLocal:
10786 Lex.Lex();
10787 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10788 return true;
10789 GVFlags.DSOLocal = Flag;
10790 break;
10792 Lex.Lex();
10793 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10794 return true;
10795 GVFlags.CanAutoHide = Flag;
10796 break;
10798 Lex.Lex();
10799 if (parseToken(lltok::colon, "expected ':'"))
10800 return true;
10802 if (parseOptionalImportType(Lex.getKind(), IK))
10803 return true;
10804 GVFlags.ImportType = static_cast<unsigned>(IK);
10805 Lex.Lex();
10806 break;
10807 default:
10808 return error(Lex.getLoc(), "expected gv flag type");
10809 }
10810 } while (EatIfPresent(lltok::comma));
10811
10812 if (parseToken(lltok::rparen, "expected ')' here"))
10813 return true;
10814
10815 return false;
10816}
10817
10818/// GVarFlags
10819/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10820/// ',' 'writeonly' ':' Flag
10821/// ',' 'constant' ':' Flag ')'
10822bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10823 assert(Lex.getKind() == lltok::kw_varFlags);
10824 Lex.Lex();
10825
10826 if (parseToken(lltok::colon, "expected ':' here") ||
10827 parseToken(lltok::lparen, "expected '(' here"))
10828 return true;
10829
10830 auto ParseRest = [this](unsigned int &Val) {
10831 Lex.Lex();
10832 if (parseToken(lltok::colon, "expected ':'"))
10833 return true;
10834 return parseFlag(Val);
10835 };
10836
10837 do {
10838 unsigned Flag = 0;
10839 switch (Lex.getKind()) {
10840 case lltok::kw_readonly:
10841 if (ParseRest(Flag))
10842 return true;
10843 GVarFlags.MaybeReadOnly = Flag;
10844 break;
10845 case lltok::kw_writeonly:
10846 if (ParseRest(Flag))
10847 return true;
10848 GVarFlags.MaybeWriteOnly = Flag;
10849 break;
10850 case lltok::kw_constant:
10851 if (ParseRest(Flag))
10852 return true;
10853 GVarFlags.Constant = Flag;
10854 break;
10856 if (ParseRest(Flag))
10857 return true;
10858 GVarFlags.VCallVisibility = Flag;
10859 break;
10860 default:
10861 return error(Lex.getLoc(), "expected gvar flag type");
10862 }
10863 } while (EatIfPresent(lltok::comma));
10864 return parseToken(lltok::rparen, "expected ')' here");
10865}
10866
10867/// ModuleReference
10868/// ::= 'module' ':' UInt
10869bool LLParser::parseModuleReference(StringRef &ModulePath) {
10870 // parse module id.
10871 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10872 parseToken(lltok::colon, "expected ':' here") ||
10873 parseToken(lltok::SummaryID, "expected module ID"))
10874 return true;
10875
10876 unsigned ModuleID = Lex.getUIntVal();
10877 auto I = ModuleIdMap.find(ModuleID);
10878 // We should have already parsed all module IDs
10879 assert(I != ModuleIdMap.end());
10880 ModulePath = I->second;
10881 return false;
10882}
10883
10884/// GVReference
10885/// ::= SummaryID
10886bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10887 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10888 if (!ReadOnly)
10889 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10890 if (parseToken(lltok::SummaryID, "expected GV ID"))
10891 return true;
10892
10893 GVId = Lex.getUIntVal();
10894 // Check if we already have a VI for this GV
10895 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10896 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10897 VI = NumberedValueInfos[GVId];
10898 } else
10899 // We will create a forward reference to the stored location.
10900 VI = ValueInfo(false, FwdVIRef);
10901
10902 if (ReadOnly)
10903 VI.setReadOnly();
10904 if (WriteOnly)
10905 VI.setWriteOnly();
10906 return false;
10907}
10908
10909/// OptionalAllocs
10910/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10911/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10912/// ',' MemProfs ')'
10913/// Version ::= UInt32
10914bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10915 assert(Lex.getKind() == lltok::kw_allocs);
10916 Lex.Lex();
10917
10918 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10919 parseToken(lltok::lparen, "expected '(' in allocs"))
10920 return true;
10921
10922 // parse each alloc
10923 do {
10924 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10925 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10926 parseToken(lltok::colon, "expected ':'") ||
10927 parseToken(lltok::lparen, "expected '(' in versions"))
10928 return true;
10929
10930 SmallVector<uint8_t> Versions;
10931 do {
10932 uint8_t V = 0;
10933 if (parseAllocType(V))
10934 return true;
10935 Versions.push_back(V);
10936 } while (EatIfPresent(lltok::comma));
10937
10938 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10939 parseToken(lltok::comma, "expected ',' in alloc"))
10940 return true;
10941
10942 std::vector<MIBInfo> MIBs;
10943 if (parseMemProfs(MIBs))
10944 return true;
10945
10946 Allocs.push_back({Versions, MIBs});
10947
10948 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10949 return true;
10950 } while (EatIfPresent(lltok::comma));
10951
10952 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10953 return true;
10954
10955 return false;
10956}
10957
10958/// MemProfs
10959/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10960/// MemProf ::= '(' 'type' ':' AllocType
10961/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10962/// StackId ::= UInt64
10963bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10964 assert(Lex.getKind() == lltok::kw_memProf);
10965 Lex.Lex();
10966
10967 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10968 parseToken(lltok::lparen, "expected '(' in memprof"))
10969 return true;
10970
10971 // parse each MIB
10972 do {
10973 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10974 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10975 parseToken(lltok::colon, "expected ':'"))
10976 return true;
10977
10978 uint8_t AllocType;
10979 if (parseAllocType(AllocType))
10980 return true;
10981
10982 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10983 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10984 parseToken(lltok::colon, "expected ':'") ||
10985 parseToken(lltok::lparen, "expected '(' in stackIds"))
10986 return true;
10987
10988 SmallVector<unsigned> StackIdIndices;
10989 // Combined index alloc records may not have a stack id list.
10990 if (Lex.getKind() != lltok::rparen) {
10991 do {
10992 uint64_t StackId = 0;
10993 if (parseUInt64(StackId))
10994 return true;
10995 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10996 } while (EatIfPresent(lltok::comma));
10997 }
10998
10999 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11000 return true;
11001
11002 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11003
11004 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11005 return true;
11006 } while (EatIfPresent(lltok::comma));
11007
11008 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11009 return true;
11010
11011 return false;
11012}
11013
11014/// AllocType
11015/// := ('none'|'notcold'|'cold'|'hot')
11016bool LLParser::parseAllocType(uint8_t &AllocType) {
11017 switch (Lex.getKind()) {
11018 case lltok::kw_none:
11020 break;
11021 case lltok::kw_notcold:
11023 break;
11024 case lltok::kw_cold:
11026 break;
11027 case lltok::kw_hot:
11028 AllocType = (uint8_t)AllocationType::Hot;
11029 break;
11030 default:
11031 return error(Lex.getLoc(), "invalid alloc type");
11032 }
11033 Lex.Lex();
11034 return false;
11035}
11036
11037/// OptionalCallsites
11038/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11039/// Callsite ::= '(' 'callee' ':' GVReference
11040/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11041/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11042/// Version ::= UInt32
11043/// StackId ::= UInt64
11044bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11045 assert(Lex.getKind() == lltok::kw_callsites);
11046 Lex.Lex();
11047
11048 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11049 parseToken(lltok::lparen, "expected '(' in callsites"))
11050 return true;
11051
11052 IdToIndexMapType IdToIndexMap;
11053 // parse each callsite
11054 do {
11055 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11056 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11057 parseToken(lltok::colon, "expected ':'"))
11058 return true;
11059
11060 ValueInfo VI;
11061 unsigned GVId = 0;
11062 LocTy Loc = Lex.getLoc();
11063 if (!EatIfPresent(lltok::kw_null)) {
11064 if (parseGVReference(VI, GVId))
11065 return true;
11066 }
11067
11068 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11069 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11070 parseToken(lltok::colon, "expected ':'") ||
11071 parseToken(lltok::lparen, "expected '(' in clones"))
11072 return true;
11073
11074 SmallVector<unsigned> Clones;
11075 do {
11076 unsigned V = 0;
11077 if (parseUInt32(V))
11078 return true;
11079 Clones.push_back(V);
11080 } while (EatIfPresent(lltok::comma));
11081
11082 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11083 parseToken(lltok::comma, "expected ',' in callsite") ||
11084 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11085 parseToken(lltok::colon, "expected ':'") ||
11086 parseToken(lltok::lparen, "expected '(' in stackIds"))
11087 return true;
11088
11089 SmallVector<unsigned> StackIdIndices;
11090 // Synthesized callsite records will not have a stack id list.
11091 if (Lex.getKind() != lltok::rparen) {
11092 do {
11093 uint64_t StackId = 0;
11094 if (parseUInt64(StackId))
11095 return true;
11096 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11097 } while (EatIfPresent(lltok::comma));
11098 }
11099
11100 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11101 return true;
11102
11103 // Keep track of the Callsites array index needing a forward reference.
11104 // We will save the location of the ValueInfo needing an update, but
11105 // can only do so once the SmallVector is finalized.
11106 if (VI.getRef() == FwdVIRef)
11107 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11108 Callsites.push_back({VI, Clones, StackIdIndices});
11109
11110 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11111 return true;
11112 } while (EatIfPresent(lltok::comma));
11113
11114 // Now that the Callsites vector is finalized, it is safe to save the
11115 // locations of any forward GV references that need updating later.
11116 for (auto I : IdToIndexMap) {
11117 auto &Infos = ForwardRefValueInfos[I.first];
11118 for (auto P : I.second) {
11119 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11120 "Forward referenced ValueInfo expected to be empty");
11121 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11122 }
11123 }
11124
11125 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11126 return true;
11127
11128 return false;
11129}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:245
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static 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:152
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:68
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
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:1191
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1238
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:120
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
iterator begin() const
Definition ArrayRef.h:130
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:765
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:141
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:122
@ None
No attributes have been set.
Definition Attributes.h:124
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:483
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:372
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
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:1397
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:1284
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
unsigned size() const
Definition DenseMap.h:110
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool any() const
Definition FMF.h:56
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition Type.cpp:403
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:398
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:838
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:450
arg_iterator arg_begin()
Definition Function.h:872
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1044
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:613
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition Globals.cpp:670
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:215
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:276
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:78
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:246
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:94
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:162
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:252
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:229
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:534
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:581
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:68
lltok::Kind getKind() const
Definition LLLexer.h:72
LocTy getLoc() const
Definition LLLexer.h:71
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:124
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:215
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:108
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:95
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:76
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1080
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1580
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1540
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
static MemoryEffectsBase readOnly()
Definition ModRef.h:130
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:198
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:140
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:146
static MemoryEffectsBase writeOnly()
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:163
static MemoryEffectsBase none()
Definition ModRef.h:125
static MemoryEffectsBase unknown()
Definition ModRef.h:120
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:875
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:221
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:413
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:619
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:703
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition Type.cpp:538
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:440
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:913
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:287
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:281
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:249
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:294
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:258
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:509
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
static constexpr uint64_t MaximumAlignment
Definition Value.h:830
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:598
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:631
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:703
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:765
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:220
MacinfoRecordType
Definition Dwarf.h:815
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:821
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:153
@ kw_riscv_vls_cc
Definition LLToken.h:189
@ kw_cxx_fast_tlscc
Definition LLToken.h:172
@ kw_extractvalue
Definition LLToken.h:366
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:501
@ kw_arm_apcscc
Definition LLToken.h:145
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:140
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:151
@ kw_provenance
Definition LLToken.h:222
@ kw_mustBeUnreachable
Definition LLToken.h:412
@ kw_internal
Definition LLToken.h:54
@ kw_no_sanitize_hwaddress
Definition LLToken.h:480
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:451
@ kw_canAutoHide
Definition LLToken.h:396
@ kw_alwaysInline
Definition LLToken.h:408
@ kw_insertelement
Definition LLToken.h:363
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:192
@ kw_inaccessiblememonly
Definition LLToken.h:215
@ kw_amdgpu_gfx
Definition LLToken.h:183
@ kw_getelementptr
Definition LLToken.h:360
@ kw_m68k_rtdcc
Definition LLToken.h:186
@ kw_preserve_nonecc
Definition LLToken.h:167
@ kw_x86_fastcallcc
Definition LLToken.h:141
@ kw_visibility
Definition LLToken.h:392
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:191
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:454
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:139
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:431
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:149
@ kw_amdgpu_kernel
Definition LLToken.h:182
@ kw_uselistorder
Definition LLToken.h:379
@ kw_blockcount
Definition LLToken.h:390
@ kw_notEligibleToImport
Definition LLToken.h:393
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:143
@ kw_ptx_device
Definition LLToken.h:157
@ kw_personality
Definition LLToken.h:335
@ DwarfEnumKind
Definition LLToken.h:514
@ kw_declaration
Definition LLToken.h:399
@ DwarfAttEncoding
Definition LLToken.h:500
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:158
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:411
@ kw_x86_intrcc
Definition LLToken.h:169
@ kw_addrspacecast
Definition LLToken.h:330
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:498
@ kw_x86_thiscallcc
Definition LLToken.h:142
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:190
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:380
@ NameTableKind
Definition LLToken.h:506
@ kw_inlineBits
Definition LLToken.h:449
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:214
@ kw_blockaddress
Definition LLToken.h:368
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:184
@ kw_landingpad
Definition LLToken.h:334
@ kw_aarch64_vector_pcs
Definition LLToken.h:148
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:430
@ FixedPointKind
Definition LLToken.h:507
@ kw_target_mem1
Definition LLToken.h:210
@ kw_ptx_kernel
Definition LLToken.h:156
@ kw_extractelement
Definition LLToken.h:362
@ kw_branchFunnel
Definition LLToken.h:455
@ kw_typeidCompatibleVTable
Definition LLToken.h:436
@ kw_vTableFuncs
Definition LLToken.h:422
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:429
@ kw_no_sanitize_address
Definition LLToken.h:477
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:216
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:483
@ DwarfSourceLangName
Definition LLToken.h:503
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:181
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:348
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:146
@ kw_read_provenance
Definition LLToken.h:223
@ kw_cleanuppad
Definition LLToken.h:351
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:456
@ kw_target_mem0
Definition LLToken.h:209
@ kw_swifttailcc
Definition LLToken.h:164
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:428
@ kw_attributes
Definition LLToken.h:195
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:459
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:445
@ kw_nodeduplicate
Definition LLToken.h:252
@ kw_avr_signalcc
Definition LLToken.h:155
@ kw_exactmatch
Definition LLToken.h:250
@ kw_unreachable
Definition LLToken.h:346
@ kw_intel_ocl_bicc
Definition LLToken.h:138
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:406
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:150
@ kw_preserve_allcc
Definition LLToken.h:166
@ kw_importType
Definition LLToken.h:397
@ kw_cleanupret
Definition LLToken.h:347
@ kw_shufflevector
Definition LLToken.h:364
@ kw_riscv_vector_cc
Definition LLToken.h:188
@ kw_avr_intrcc
Definition LLToken.h:154
@ kw_definition
Definition LLToken.h:398
@ kw_virtualConstProp
Definition LLToken.h:461
@ kw_vcall_visibility
Definition LLToken.h:450
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:208
@ kw_preserve_mostcc
Definition LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:147
@ kw_typeTestRes
Definition LLToken.h:438
@ kw_x86_regcallcc
Definition LLToken.h:144
@ kw_typeIdInfo
Definition LLToken.h:426
@ kw_amdgpu_cs_chain
Definition LLToken.h:180
@ kw_dso_local_equivalent
Definition LLToken.h:369
@ kw_x86_64_sysvcc
Definition LLToken.h:160
@ DbgRecordType
Definition LLToken.h:513
@ kw_address_is_null
Definition LLToken.h:221
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:152
@ kw_uniqueRetVal
Definition LLToken.h:460
@ kw_insertvalue
Definition LLToken.h:367
@ kw_indirectbr
Definition LLToken.h:343
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:578
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1667
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
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:301
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:154
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:156
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:361
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:310
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ TargetMem0
Represents target specific state.
Definition ModRef.h:70
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:36
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2002
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:1915
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:320
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.