LLVM 22.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
50#include "llvm/Support/ModRef.h"
53#include <algorithm>
54#include <cassert>
55#include <cstring>
56#include <optional>
57#include <vector>
58
59using namespace llvm;
60
62 "allow-incomplete-ir", cl::init(false), cl::Hidden,
64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
66
67static std::string getTypeString(Type *T) {
68 std::string Result;
69 raw_string_ostream Tmp(Result);
70 Tmp << *T;
71 return Tmp.str();
72}
73
74/// Run: module ::= toplevelentity*
75bool LLParser::Run(bool UpgradeDebugInfo,
76 DataLayoutCallbackTy DataLayoutCallback) {
77 // Prime the lexer.
78 Lex.Lex();
79
80 if (Context.shouldDiscardValueNames())
81 return error(
82 Lex.getLoc(),
83 "Can't read textual IR with a Context that discards named Values");
84
85 if (M) {
86 if (parseTargetDefinitions(DataLayoutCallback))
87 return true;
88 }
89
90 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
91 validateEndOfIndex();
92}
93
95 const SlotMapping *Slots) {
96 restoreParsingState(Slots);
97 Lex.Lex();
98
99 Type *Ty = nullptr;
100 if (parseType(Ty) || parseConstantValue(Ty, C))
101 return true;
102 if (Lex.getKind() != lltok::Eof)
103 return error(Lex.getLoc(), "expected end of string");
104 return false;
105}
106
108 const SlotMapping *Slots) {
109 restoreParsingState(Slots);
110 Lex.Lex();
111
112 Read = 0;
113 SMLoc Start = Lex.getLoc();
114 Ty = nullptr;
115 if (parseType(Ty))
116 return true;
117 SMLoc End = Lex.getLoc();
118 Read = End.getPointer() - Start.getPointer();
119
120 return false;
121}
122
124 const SlotMapping *Slots) {
125 restoreParsingState(Slots);
126 Lex.Lex();
127
128 Read = 0;
129 SMLoc Start = Lex.getLoc();
130 Result = nullptr;
131 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
132 SMLoc End = Lex.getLoc();
133 Read = End.getPointer() - Start.getPointer();
134
135 return Status;
136}
137
138void LLParser::restoreParsingState(const SlotMapping *Slots) {
139 if (!Slots)
140 return;
141 NumberedVals = Slots->GlobalValues;
142 NumberedMetadata = Slots->MetadataNodes;
143 for (const auto &I : Slots->NamedTypes)
144 NamedTypes.insert(
145 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
146 for (const auto &I : Slots->Types)
147 NumberedTypes.insert(
148 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
149}
150
152 // White-list intrinsics that are safe to drop.
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
155 return;
156
158 for (Value *V : II->args())
159 if (auto *MV = dyn_cast<MetadataAsValue>(V))
160 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
161 if (MD->isTemporary())
162 MVs.push_back(MV);
163
164 if (!MVs.empty()) {
165 assert(II->use_empty() && "Cannot have uses");
166 II->eraseFromParent();
167
168 // Also remove no longer used MetadataAsValue wrappers.
169 for (MetadataAsValue *MV : MVs)
170 if (MV->use_empty())
171 delete MV;
172 }
173}
174
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
177 for (Function &F : *M) {
178 F.eraseMetadataIf(Pred);
179 for (Instruction &I : make_early_inc_range(instructions(F))) {
180 I.eraseMetadataIf(Pred);
181
182 if (auto *II = dyn_cast<IntrinsicInst>(&I))
184 }
185 }
186
187 for (GlobalVariable &GV : M->globals())
188 GV.eraseMetadataIf(Pred);
189
190 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
191 // Check whether there is only a single use left, which would be in our
192 // own NumberedMetadata.
193 if (Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(ID);
195 ForwardRefMDNodes.erase(ID);
196 }
197 }
198}
199
200/// validateEndOfModule - Do final validity and basic correctness checks at the
201/// end of the module.
202bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
203 if (!M)
204 return false;
205
206 // We should have already returned an error if we observed both intrinsics and
207 // records in this IR.
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
210
211 // Handle any function attribute group forward references.
212 for (const auto &RAG : ForwardRefAttrGroups) {
213 Value *V = RAG.first;
214 const std::vector<unsigned> &Attrs = RAG.second;
215 AttrBuilder B(Context);
216
217 for (const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
220 B.merge(R->second);
221 }
222
223 if (Function *Fn = dyn_cast<Function>(V)) {
224 AttributeList AS = Fn->getAttributes();
225 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
226 AS = AS.removeFnAttributes(Context);
227
228 FnAttrs.merge(B);
229
230 // If the alignment was parsed as an attribute, move to the alignment
231 // field.
232 if (MaybeAlign A = FnAttrs.getAlignment()) {
233 Fn->setAlignment(*A);
234 FnAttrs.removeAttribute(Attribute::Alignment);
235 }
236
237 AS = AS.addFnAttributes(Context, FnAttrs);
238 Fn->setAttributes(AS);
239 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
240 AttributeList AS = CI->getAttributes();
241 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
242 AS = AS.removeFnAttributes(Context);
243 FnAttrs.merge(B);
244 AS = AS.addFnAttributes(Context, FnAttrs);
245 CI->setAttributes(AS);
246 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
247 AttributeList AS = II->getAttributes();
248 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
249 AS = AS.removeFnAttributes(Context);
250 FnAttrs.merge(B);
251 AS = AS.addFnAttributes(Context, FnAttrs);
252 II->setAttributes(AS);
253 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
254 AttributeList AS = CBI->getAttributes();
255 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
256 AS = AS.removeFnAttributes(Context);
257 FnAttrs.merge(B);
258 AS = AS.addFnAttributes(Context, FnAttrs);
259 CBI->setAttributes(AS);
260 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
261 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
262 Attrs.merge(B);
263 GV->setAttributes(AttributeSet::get(Context,Attrs));
264 } else {
265 llvm_unreachable("invalid object with forward attribute group reference");
266 }
267 }
268
269 // If there are entries in ForwardRefBlockAddresses at this point, the
270 // function was never defined.
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
274
275 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
276 GlobalValue *FwdRef) {
277 GlobalValue *GV = nullptr;
278 if (GVRef.Kind == ValID::t_GlobalName) {
279 GV = M->getNamedValue(GVRef.StrVal);
280 } else {
281 GV = NumberedVals.get(GVRef.UIntVal);
282 }
283
284 if (!GV)
285 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
286 "' referenced by dso_local_equivalent");
287
288 if (!GV->getValueType()->isFunctionTy())
289 return error(GVRef.Loc,
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
292
293 auto *Equiv = DSOLocalEquivalent::get(GV);
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
296 return false;
297 };
298
299 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
300 // point, they are references after the function was defined. Resolve those
301 // now.
302 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
304 return true;
305 }
306 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
308 return true;
309 }
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
312
313 for (const auto &NT : NumberedTypes)
314 if (NT.second.second.isValid())
315 return error(NT.second.second,
316 "use of undefined type '%" + Twine(NT.first) + "'");
317
318 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
319 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
320 if (I->second.second.isValid())
321 return error(I->second.second,
322 "use of undefined type named '" + I->getKey() + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 if (IID == Intrinsic::not_intrinsic)
333 // Don't do anything for unknown intrinsics.
334 continue;
335
336 // Automatically create declarations for intrinsics. Intrinsics can only
337 // be called directly, so the call function type directly determines the
338 // declaration function type.
339 //
340 // Additionally, automatically add the required mangling suffix to the
341 // intrinsic name. This means that we may replace a single forward
342 // declaration with multiple functions here.
343 for (Use &U : make_early_inc_range(Info.first->uses())) {
344 auto *CB = dyn_cast<CallBase>(U.getUser());
345 if (!CB || !CB->isCallee(&U))
346 return error(Info.second, "intrinsic can only be used as callee");
347
348 SmallVector<Type *> OverloadTys;
349 if (!Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
350 OverloadTys))
351 return error(Info.second, "invalid intrinsic signature");
352
353 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
354 }
355
356 Info.first->eraseFromParent();
357 ForwardRefVals.erase(Name);
358 continue;
359 }
360
361 // If incomplete IR is allowed, also add declarations for
362 // non-intrinsics.
364 continue;
365
366 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
367 FunctionType *FTy = nullptr;
368 for (Use &U : V->uses()) {
369 auto *CB = dyn_cast<CallBase>(U.getUser());
370 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
371 return nullptr;
372 FTy = CB->getFunctionType();
373 }
374 return FTy;
375 };
376
377 // First check whether this global is only used in calls with the same
378 // type, in which case we'll insert a function. Otherwise, fall back to
379 // using a dummy i8 type.
380 Type *Ty = GetCommonFunctionType(Info.first);
381 if (!Ty)
382 Ty = Type::getInt8Ty(Context);
383
384 GlobalValue *GV;
385 if (auto *FTy = dyn_cast<FunctionType>(Ty))
387 else
388 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
390 /*Initializer*/ nullptr, Name);
391 Info.first->replaceAllUsesWith(GV);
392 Info.first->eraseFromParent();
393 ForwardRefVals.erase(Name);
394 }
395
396 if (!ForwardRefVals.empty())
397 return error(ForwardRefVals.begin()->second.second,
398 "use of undefined value '@" + ForwardRefVals.begin()->first +
399 "'");
400
401 if (!ForwardRefValIDs.empty())
402 return error(ForwardRefValIDs.begin()->second.second,
403 "use of undefined value '@" +
404 Twine(ForwardRefValIDs.begin()->first) + "'");
405
406 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
407 dropUnknownMetadataReferences();
408
409 if (!ForwardRefMDNodes.empty())
410 return error(ForwardRefMDNodes.begin()->second.second,
411 "use of undefined metadata '!" +
412 Twine(ForwardRefMDNodes.begin()->first) + "'");
413
414 // Resolve metadata cycles.
415 for (auto &N : NumberedMetadata) {
416 if (N.second && !N.second->isResolved())
417 N.second->resolveCycles();
418 }
419
420 for (auto *Inst : InstsWithTBAATag) {
421 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
422 // With incomplete IR, the tbaa metadata may have been dropped.
424 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
425 if (MD) {
426 auto *UpgradedMD = UpgradeTBAANode(*MD);
427 if (MD != UpgradedMD)
428 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
429 }
430 }
431
432 // Look for intrinsic functions and CallInst that need to be upgraded. We use
433 // make_early_inc_range here because we may remove some functions.
434 for (Function &F : llvm::make_early_inc_range(*M))
436
437 if (UpgradeDebugInfo)
439
443
444 if (!Slots)
445 return false;
446 // Initialize the slot mapping.
447 // Because by this point we've parsed and validated everything, we can "steal"
448 // the mapping from LLParser as it doesn't need it anymore.
449 Slots->GlobalValues = std::move(NumberedVals);
450 Slots->MetadataNodes = std::move(NumberedMetadata);
451 for (const auto &I : NamedTypes)
452 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
453 for (const auto &I : NumberedTypes)
454 Slots->Types.insert(std::make_pair(I.first, I.second.first));
455
456 return false;
457}
458
459/// Do final validity and basic correctness checks at the end of the index.
460bool LLParser::validateEndOfIndex() {
461 if (!Index)
462 return false;
463
464 if (!ForwardRefValueInfos.empty())
465 return error(ForwardRefValueInfos.begin()->second.front().second,
466 "use of undefined summary '^" +
467 Twine(ForwardRefValueInfos.begin()->first) + "'");
468
469 if (!ForwardRefAliasees.empty())
470 return error(ForwardRefAliasees.begin()->second.front().second,
471 "use of undefined summary '^" +
472 Twine(ForwardRefAliasees.begin()->first) + "'");
473
474 if (!ForwardRefTypeIds.empty())
475 return error(ForwardRefTypeIds.begin()->second.front().second,
476 "use of undefined type id summary '^" +
477 Twine(ForwardRefTypeIds.begin()->first) + "'");
478
479 return false;
480}
481
482//===----------------------------------------------------------------------===//
483// Top-Level Entities
484//===----------------------------------------------------------------------===//
485
486bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
487 // Delay parsing of the data layout string until the target triple is known.
488 // Then, pass both the the target triple and the tentative data layout string
489 // to DataLayoutCallback, allowing to override the DL string.
490 // This enables importing modules with invalid DL strings.
491 std::string TentativeDLStr = M->getDataLayoutStr();
492 LocTy DLStrLoc;
493
494 bool Done = false;
495 while (!Done) {
496 switch (Lex.getKind()) {
497 case lltok::kw_target:
498 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
499 return true;
500 break;
502 if (parseSourceFileName())
503 return true;
504 break;
505 default:
506 Done = true;
507 }
508 }
509 // Run the override callback to potentially change the data layout string, and
510 // parse the data layout string.
511 if (auto LayoutOverride =
512 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
513 TentativeDLStr = *LayoutOverride;
514 DLStrLoc = {};
515 }
516 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
517 if (!MaybeDL)
518 return error(DLStrLoc, toString(MaybeDL.takeError()));
519 M->setDataLayout(MaybeDL.get());
520 return false;
521}
522
523bool LLParser::parseTopLevelEntities() {
524 // If there is no Module, then parse just the summary index entries.
525 if (!M) {
526 while (true) {
527 switch (Lex.getKind()) {
528 case lltok::Eof:
529 return false;
530 case lltok::SummaryID:
531 if (parseSummaryEntry())
532 return true;
533 break;
535 if (parseSourceFileName())
536 return true;
537 break;
538 default:
539 // Skip everything else
540 Lex.Lex();
541 }
542 }
543 }
544 while (true) {
545 switch (Lex.getKind()) {
546 default:
547 return tokError("expected top-level entity");
548 case lltok::Eof: return false;
550 if (parseDeclare())
551 return true;
552 break;
553 case lltok::kw_define:
554 if (parseDefine())
555 return true;
556 break;
557 case lltok::kw_module:
558 if (parseModuleAsm())
559 return true;
560 break;
562 if (parseUnnamedType())
563 return true;
564 break;
565 case lltok::LocalVar:
566 if (parseNamedType())
567 return true;
568 break;
569 case lltok::GlobalID:
570 if (parseUnnamedGlobal())
571 return true;
572 break;
573 case lltok::GlobalVar:
574 if (parseNamedGlobal())
575 return true;
576 break;
577 case lltok::ComdatVar: if (parseComdat()) return true; break;
578 case lltok::exclaim:
579 if (parseStandaloneMetadata())
580 return true;
581 break;
582 case lltok::SummaryID:
583 if (parseSummaryEntry())
584 return true;
585 break;
587 if (parseNamedMetadata())
588 return true;
589 break;
591 if (parseUnnamedAttrGrp())
592 return true;
593 break;
595 if (parseUseListOrder())
596 return true;
597 break;
599 if (parseUseListOrderBB())
600 return true;
601 break;
602 }
603 }
604}
605
606/// toplevelentity
607/// ::= 'module' 'asm' STRINGCONSTANT
608bool LLParser::parseModuleAsm() {
609 assert(Lex.getKind() == lltok::kw_module);
610 Lex.Lex();
611
612 std::string AsmStr;
613 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
614 parseStringConstant(AsmStr))
615 return true;
616
617 M->appendModuleInlineAsm(AsmStr);
618 return false;
619}
620
621/// toplevelentity
622/// ::= 'target' 'triple' '=' STRINGCONSTANT
623/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
624bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
625 LocTy &DLStrLoc) {
626 assert(Lex.getKind() == lltok::kw_target);
627 std::string Str;
628 switch (Lex.Lex()) {
629 default:
630 return tokError("unknown target property");
631 case lltok::kw_triple:
632 Lex.Lex();
633 if (parseToken(lltok::equal, "expected '=' after target triple") ||
634 parseStringConstant(Str))
635 return true;
636 M->setTargetTriple(Triple(std::move(Str)));
637 return false;
639 Lex.Lex();
640 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
641 return true;
642 DLStrLoc = Lex.getLoc();
643 if (parseStringConstant(TentativeDLStr))
644 return true;
645 return false;
646 }
647}
648
649/// toplevelentity
650/// ::= 'source_filename' '=' STRINGCONSTANT
651bool LLParser::parseSourceFileName() {
652 assert(Lex.getKind() == lltok::kw_source_filename);
653 Lex.Lex();
654 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
655 parseStringConstant(SourceFileName))
656 return true;
657 if (M)
658 M->setSourceFileName(SourceFileName);
659 return false;
660}
661
662/// parseUnnamedType:
663/// ::= LocalVarID '=' 'type' type
664bool LLParser::parseUnnamedType() {
665 LocTy TypeLoc = Lex.getLoc();
666 unsigned TypeID = Lex.getUIntVal();
667 Lex.Lex(); // eat LocalVarID;
668
669 if (parseToken(lltok::equal, "expected '=' after name") ||
670 parseToken(lltok::kw_type, "expected 'type' after '='"))
671 return true;
672
673 Type *Result = nullptr;
674 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
675 return true;
676
677 if (!isa<StructType>(Result)) {
678 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
679 if (Entry.first)
680 return error(TypeLoc, "non-struct types may not be recursive");
681 Entry.first = Result;
682 Entry.second = SMLoc();
683 }
684
685 return false;
686}
687
688/// toplevelentity
689/// ::= LocalVar '=' 'type' type
690bool LLParser::parseNamedType() {
691 std::string Name = Lex.getStrVal();
692 LocTy NameLoc = Lex.getLoc();
693 Lex.Lex(); // eat LocalVar.
694
695 if (parseToken(lltok::equal, "expected '=' after name") ||
696 parseToken(lltok::kw_type, "expected 'type' after name"))
697 return true;
698
699 Type *Result = nullptr;
700 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
701 return true;
702
703 if (!isa<StructType>(Result)) {
704 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
705 if (Entry.first)
706 return error(NameLoc, "non-struct types may not be recursive");
707 Entry.first = Result;
708 Entry.second = SMLoc();
709 }
710
711 return false;
712}
713
714/// toplevelentity
715/// ::= 'declare' FunctionHeader
716bool LLParser::parseDeclare() {
717 assert(Lex.getKind() == lltok::kw_declare);
718 Lex.Lex();
719
720 std::vector<std::pair<unsigned, MDNode *>> MDs;
721 while (Lex.getKind() == lltok::MetadataVar) {
722 unsigned MDK;
723 MDNode *N;
724 if (parseMetadataAttachment(MDK, N))
725 return true;
726 MDs.push_back({MDK, N});
727 }
728
729 Function *F;
730 unsigned FunctionNumber = -1;
731 SmallVector<unsigned> UnnamedArgNums;
732 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
733 return true;
734 for (auto &MD : MDs)
735 F->addMetadata(MD.first, *MD.second);
736 return false;
737}
738
739/// toplevelentity
740/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
741bool LLParser::parseDefine() {
742 assert(Lex.getKind() == lltok::kw_define);
743 Lex.Lex();
744
745 Function *F;
746 unsigned FunctionNumber = -1;
747 SmallVector<unsigned> UnnamedArgNums;
748 return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
749 parseOptionalFunctionMetadata(*F) ||
750 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
751}
752
753/// parseGlobalType
754/// ::= 'constant'
755/// ::= 'global'
756bool LLParser::parseGlobalType(bool &IsConstant) {
757 if (Lex.getKind() == lltok::kw_constant)
758 IsConstant = true;
759 else if (Lex.getKind() == lltok::kw_global)
760 IsConstant = false;
761 else {
762 IsConstant = false;
763 return tokError("expected 'global' or 'constant'");
764 }
765 Lex.Lex();
766 return false;
767}
768
769bool LLParser::parseOptionalUnnamedAddr(
770 GlobalVariable::UnnamedAddr &UnnamedAddr) {
771 if (EatIfPresent(lltok::kw_unnamed_addr))
773 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
775 else
776 UnnamedAddr = GlobalValue::UnnamedAddr::None;
777 return false;
778}
779
780/// parseUnnamedGlobal:
781/// OptionalVisibility (ALIAS | IFUNC) ...
782/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
783/// OptionalDLLStorageClass
784/// ... -> global variable
785/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
786/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
787/// OptionalVisibility
788/// OptionalDLLStorageClass
789/// ... -> global variable
790bool LLParser::parseUnnamedGlobal() {
791 unsigned VarID;
792 std::string Name;
793 LocTy NameLoc = Lex.getLoc();
794
795 // Handle the GlobalID form.
796 if (Lex.getKind() == lltok::GlobalID) {
797 VarID = Lex.getUIntVal();
798 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
799 return true;
800
801 Lex.Lex(); // eat GlobalID;
802 if (parseToken(lltok::equal, "expected '=' after name"))
803 return true;
804 } else {
805 VarID = NumberedVals.getNext();
806 }
807
808 bool HasLinkage;
809 unsigned Linkage, Visibility, DLLStorageClass;
810 bool DSOLocal;
812 GlobalVariable::UnnamedAddr UnnamedAddr;
813 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
814 DSOLocal) ||
815 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
816 return true;
817
818 switch (Lex.getKind()) {
819 default:
820 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
821 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
822 case lltok::kw_alias:
823 case lltok::kw_ifunc:
824 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
825 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
826 }
827}
828
829/// parseNamedGlobal:
830/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
831/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
832/// OptionalVisibility OptionalDLLStorageClass
833/// ... -> global variable
834bool LLParser::parseNamedGlobal() {
835 assert(Lex.getKind() == lltok::GlobalVar);
836 LocTy NameLoc = Lex.getLoc();
837 std::string Name = Lex.getStrVal();
838 Lex.Lex();
839
840 bool HasLinkage;
841 unsigned Linkage, Visibility, DLLStorageClass;
842 bool DSOLocal;
844 GlobalVariable::UnnamedAddr UnnamedAddr;
845 if (parseToken(lltok::equal, "expected '=' in global variable") ||
846 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
847 DSOLocal) ||
848 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
849 return true;
850
851 switch (Lex.getKind()) {
852 default:
853 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
854 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
855 case lltok::kw_alias:
856 case lltok::kw_ifunc:
857 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
858 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
859 }
860}
861
862bool LLParser::parseComdat() {
863 assert(Lex.getKind() == lltok::ComdatVar);
864 std::string Name = Lex.getStrVal();
865 LocTy NameLoc = Lex.getLoc();
866 Lex.Lex();
867
868 if (parseToken(lltok::equal, "expected '=' here"))
869 return true;
870
871 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
872 return tokError("expected comdat type");
873
875 switch (Lex.getKind()) {
876 default:
877 return tokError("unknown selection kind");
878 case lltok::kw_any:
879 SK = Comdat::Any;
880 break;
883 break;
885 SK = Comdat::Largest;
886 break;
889 break;
891 SK = Comdat::SameSize;
892 break;
893 }
894 Lex.Lex();
895
896 // See if the comdat was forward referenced, if so, use the comdat.
897 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
898 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
899 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
900 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
901
902 Comdat *C;
903 if (I != ComdatSymTab.end())
904 C = &I->second;
905 else
906 C = M->getOrInsertComdat(Name);
907 C->setSelectionKind(SK);
908
909 return false;
910}
911
912// MDString:
913// ::= '!' STRINGCONSTANT
914bool LLParser::parseMDString(MDString *&Result) {
915 std::string Str;
916 if (parseStringConstant(Str))
917 return true;
918 Result = MDString::get(Context, Str);
919 return false;
920}
921
922// MDNode:
923// ::= '!' MDNodeNumber
924bool LLParser::parseMDNodeID(MDNode *&Result) {
925 // !{ ..., !42, ... }
926 LocTy IDLoc = Lex.getLoc();
927 unsigned MID = 0;
928 if (parseUInt32(MID))
929 return true;
930
931 // If not a forward reference, just return it now.
932 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
933 if (!Inserted) {
934 Result = It->second;
935 return false;
936 }
937
938 // Otherwise, create MDNode forward reference.
939 auto &FwdRef = ForwardRefMDNodes[MID];
940 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
941
942 Result = FwdRef.first.get();
943 It->second.reset(Result);
944 return false;
945}
946
947/// parseNamedMetadata:
948/// !foo = !{ !1, !2 }
949bool LLParser::parseNamedMetadata() {
950 assert(Lex.getKind() == lltok::MetadataVar);
951 std::string Name = Lex.getStrVal();
952 Lex.Lex();
953
954 if (parseToken(lltok::equal, "expected '=' here") ||
955 parseToken(lltok::exclaim, "Expected '!' here") ||
956 parseToken(lltok::lbrace, "Expected '{' here"))
957 return true;
958
959 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
960 if (Lex.getKind() != lltok::rbrace)
961 do {
962 MDNode *N = nullptr;
963 // parse DIExpressions inline as a special case. They are still MDNodes,
964 // so they can still appear in named metadata. Remove this logic if they
965 // become plain Metadata.
966 if (Lex.getKind() == lltok::MetadataVar &&
967 Lex.getStrVal() == "DIExpression") {
968 if (parseDIExpression(N, /*IsDistinct=*/false))
969 return true;
970 // DIArgLists should only appear inline in a function, as they may
971 // contain LocalAsMetadata arguments which require a function context.
972 } else if (Lex.getKind() == lltok::MetadataVar &&
973 Lex.getStrVal() == "DIArgList") {
974 return tokError("found DIArgList outside of function");
975 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
976 parseMDNodeID(N)) {
977 return true;
978 }
979 NMD->addOperand(N);
980 } while (EatIfPresent(lltok::comma));
981
982 return parseToken(lltok::rbrace, "expected end of metadata node");
983}
984
985/// parseStandaloneMetadata:
986/// !42 = !{...}
987bool LLParser::parseStandaloneMetadata() {
988 assert(Lex.getKind() == lltok::exclaim);
989 Lex.Lex();
990 unsigned MetadataID = 0;
991
992 MDNode *Init;
993 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
994 return true;
995
996 // Detect common error, from old metadata syntax.
997 if (Lex.getKind() == lltok::Type)
998 return tokError("unexpected type in metadata definition");
999
1000 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1001 if (Lex.getKind() == lltok::MetadataVar) {
1002 if (parseSpecializedMDNode(Init, IsDistinct))
1003 return true;
1004 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1005 parseMDTuple(Init, IsDistinct))
1006 return true;
1007
1008 // See if this was forward referenced, if so, handle it.
1009 auto FI = ForwardRefMDNodes.find(MetadataID);
1010 if (FI != ForwardRefMDNodes.end()) {
1011 auto *ToReplace = FI->second.first.get();
1012 // DIAssignID has its own special forward-reference "replacement" for
1013 // attachments (the temporary attachments are never actually attached).
1014 if (isa<DIAssignID>(Init)) {
1015 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1016 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1017 "Inst unexpectedly already has DIAssignID attachment");
1018 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1019 }
1020 }
1021
1022 ToReplace->replaceAllUsesWith(Init);
1023 ForwardRefMDNodes.erase(FI);
1024
1025 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1026 } else {
1027 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1028 if (!Inserted)
1029 return tokError("Metadata id is already used");
1030 It->second.reset(Init);
1031 }
1032
1033 return false;
1034}
1035
1036// Skips a single module summary entry.
1037bool LLParser::skipModuleSummaryEntry() {
1038 // Each module summary entry consists of a tag for the entry
1039 // type, followed by a colon, then the fields which may be surrounded by
1040 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1041 // support is in place we will look for the tokens corresponding to the
1042 // expected tags.
1043 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1044 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1045 Lex.getKind() != lltok::kw_blockcount)
1046 return tokError(
1047 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1048 "start of summary entry");
1049 if (Lex.getKind() == lltok::kw_flags)
1050 return parseSummaryIndexFlags();
1051 if (Lex.getKind() == lltok::kw_blockcount)
1052 return parseBlockCount();
1053 Lex.Lex();
1054 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1055 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1056 return true;
1057 // Now walk through the parenthesized entry, until the number of open
1058 // parentheses goes back down to 0 (the first '(' was parsed above).
1059 unsigned NumOpenParen = 1;
1060 do {
1061 switch (Lex.getKind()) {
1062 case lltok::lparen:
1063 NumOpenParen++;
1064 break;
1065 case lltok::rparen:
1066 NumOpenParen--;
1067 break;
1068 case lltok::Eof:
1069 return tokError("found end of file while parsing summary entry");
1070 default:
1071 // Skip everything in between parentheses.
1072 break;
1073 }
1074 Lex.Lex();
1075 } while (NumOpenParen > 0);
1076 return false;
1077}
1078
1079/// SummaryEntry
1080/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1081bool LLParser::parseSummaryEntry() {
1082 assert(Lex.getKind() == lltok::SummaryID);
1083 unsigned SummaryID = Lex.getUIntVal();
1084
1085 // For summary entries, colons should be treated as distinct tokens,
1086 // not an indication of the end of a label token.
1087 Lex.setIgnoreColonInIdentifiers(true);
1088
1089 Lex.Lex();
1090 if (parseToken(lltok::equal, "expected '=' here"))
1091 return true;
1092
1093 // If we don't have an index object, skip the summary entry.
1094 if (!Index)
1095 return skipModuleSummaryEntry();
1096
1097 bool result = false;
1098 switch (Lex.getKind()) {
1099 case lltok::kw_gv:
1100 result = parseGVEntry(SummaryID);
1101 break;
1102 case lltok::kw_module:
1103 result = parseModuleEntry(SummaryID);
1104 break;
1105 case lltok::kw_typeid:
1106 result = parseTypeIdEntry(SummaryID);
1107 break;
1109 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1110 break;
1111 case lltok::kw_flags:
1112 result = parseSummaryIndexFlags();
1113 break;
1115 result = parseBlockCount();
1116 break;
1117 default:
1118 result = error(Lex.getLoc(), "unexpected summary kind");
1119 break;
1120 }
1121 Lex.setIgnoreColonInIdentifiers(false);
1122 return result;
1123}
1124
1133
1134// If there was an explicit dso_local, update GV. In the absence of an explicit
1135// dso_local we keep the default value.
1136static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1137 if (DSOLocal)
1138 GV.setDSOLocal(true);
1139}
1140
1141/// parseAliasOrIFunc:
1142/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1143/// OptionalVisibility OptionalDLLStorageClass
1144/// OptionalThreadLocal OptionalUnnamedAddr
1145/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1146///
1147/// AliaseeOrResolver
1148/// ::= TypeAndValue
1149///
1150/// SymbolAttrs
1151/// ::= ',' 'partition' StringConstant
1152///
1153/// Everything through OptionalUnnamedAddr has already been parsed.
1154///
1155bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1156 LocTy NameLoc, unsigned L, unsigned Visibility,
1157 unsigned DLLStorageClass, bool DSOLocal,
1159 GlobalVariable::UnnamedAddr UnnamedAddr) {
1160 bool IsAlias;
1161 if (Lex.getKind() == lltok::kw_alias)
1162 IsAlias = true;
1163 else if (Lex.getKind() == lltok::kw_ifunc)
1164 IsAlias = false;
1165 else
1166 llvm_unreachable("Not an alias or ifunc!");
1167 Lex.Lex();
1168
1170
1171 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1172 return error(NameLoc, "invalid linkage type for alias");
1173
1174 if (!isValidVisibilityForLinkage(Visibility, L))
1175 return error(NameLoc,
1176 "symbol with local linkage must have default visibility");
1177
1178 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1179 return error(NameLoc,
1180 "symbol with local linkage cannot have a DLL storage class");
1181
1182 Type *Ty;
1183 LocTy ExplicitTypeLoc = Lex.getLoc();
1184 if (parseType(Ty) ||
1185 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1186 return true;
1187
1188 Constant *Aliasee;
1189 LocTy AliaseeLoc = Lex.getLoc();
1190 if (Lex.getKind() != lltok::kw_bitcast &&
1191 Lex.getKind() != lltok::kw_getelementptr &&
1192 Lex.getKind() != lltok::kw_addrspacecast &&
1193 Lex.getKind() != lltok::kw_inttoptr) {
1194 if (parseGlobalTypeAndValue(Aliasee))
1195 return true;
1196 } else {
1197 // The bitcast dest type is not present, it is implied by the dest type.
1198 ValID ID;
1199 if (parseValID(ID, /*PFS=*/nullptr))
1200 return true;
1201 if (ID.Kind != ValID::t_Constant)
1202 return error(AliaseeLoc, "invalid aliasee");
1203 Aliasee = ID.ConstantVal;
1204 }
1205
1206 Type *AliaseeType = Aliasee->getType();
1207 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1208 if (!PTy)
1209 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1210 unsigned AddrSpace = PTy->getAddressSpace();
1211
1212 GlobalValue *GVal = nullptr;
1213
1214 // See if the alias was forward referenced, if so, prepare to replace the
1215 // forward reference.
1216 if (!Name.empty()) {
1217 auto I = ForwardRefVals.find(Name);
1218 if (I != ForwardRefVals.end()) {
1219 GVal = I->second.first;
1220 ForwardRefVals.erase(Name);
1221 } else if (M->getNamedValue(Name)) {
1222 return error(NameLoc, "redefinition of global '@" + Name + "'");
1223 }
1224 } else {
1225 auto I = ForwardRefValIDs.find(NameID);
1226 if (I != ForwardRefValIDs.end()) {
1227 GVal = I->second.first;
1228 ForwardRefValIDs.erase(I);
1229 }
1230 }
1231
1232 // Okay, create the alias/ifunc but do not insert it into the module yet.
1233 std::unique_ptr<GlobalAlias> GA;
1234 std::unique_ptr<GlobalIFunc> GI;
1235 GlobalValue *GV;
1236 if (IsAlias) {
1237 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1238 /*Parent=*/nullptr));
1239 GV = GA.get();
1240 } else {
1241 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1242 /*Parent=*/nullptr));
1243 GV = GI.get();
1244 }
1245 GV->setThreadLocalMode(TLM);
1248 GV->setUnnamedAddr(UnnamedAddr);
1249 maybeSetDSOLocal(DSOLocal, *GV);
1250
1251 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1252 // Now parse them if there are any.
1253 while (Lex.getKind() == lltok::comma) {
1254 Lex.Lex();
1255
1256 if (Lex.getKind() == lltok::kw_partition) {
1257 Lex.Lex();
1258 GV->setPartition(Lex.getStrVal());
1259 if (parseToken(lltok::StringConstant, "expected partition string"))
1260 return true;
1261 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1262 if (parseGlobalObjectMetadataAttachment(*GI.get()))
1263 return true;
1264 } else {
1265 return tokError("unknown alias or ifunc property!");
1266 }
1267 }
1268
1269 if (Name.empty())
1270 NumberedVals.add(NameID, GV);
1271
1272 if (GVal) {
1273 // Verify that types agree.
1274 if (GVal->getType() != GV->getType())
1275 return error(
1276 ExplicitTypeLoc,
1277 "forward reference and definition of alias have different types");
1278
1279 // If they agree, just RAUW the old value with the alias and remove the
1280 // forward ref info.
1281 GVal->replaceAllUsesWith(GV);
1282 GVal->eraseFromParent();
1283 }
1284
1285 // Insert into the module, we know its name won't collide now.
1286 if (IsAlias)
1287 M->insertAlias(GA.release());
1288 else
1289 M->insertIFunc(GI.release());
1290 assert(GV->getName() == Name && "Should not be a name conflict!");
1291
1292 return false;
1293}
1294
1295static bool isSanitizer(lltok::Kind Kind) {
1296 switch (Kind) {
1299 case lltok::kw_sanitize_memtag:
1301 return true;
1302 default:
1303 return false;
1304 }
1305}
1306
1307bool LLParser::parseSanitizer(GlobalVariable *GV) {
1308 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1310 if (GV->hasSanitizerMetadata())
1311 Meta = GV->getSanitizerMetadata();
1312
1313 switch (Lex.getKind()) {
1315 Meta.NoAddress = true;
1316 break;
1318 Meta.NoHWAddress = true;
1319 break;
1320 case lltok::kw_sanitize_memtag:
1321 Meta.Memtag = true;
1322 break;
1324 Meta.IsDynInit = true;
1325 break;
1326 default:
1327 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1328 }
1329 GV->setSanitizerMetadata(Meta);
1330 Lex.Lex();
1331 return false;
1332}
1333
1334/// parseGlobal
1335/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1336/// OptionalVisibility OptionalDLLStorageClass
1337/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1338/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1339/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1340/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1341/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1342/// Const OptionalAttrs
1343///
1344/// Everything up to and including OptionalUnnamedAddr has been parsed
1345/// already.
1346///
1347bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1348 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1349 unsigned Visibility, unsigned DLLStorageClass,
1350 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1351 GlobalVariable::UnnamedAddr UnnamedAddr) {
1352 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1353 return error(NameLoc,
1354 "symbol with local linkage must have default visibility");
1355
1356 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1357 return error(NameLoc,
1358 "symbol with local linkage cannot have a DLL storage class");
1359
1360 unsigned AddrSpace;
1361 bool IsConstant, IsExternallyInitialized;
1362 LocTy IsExternallyInitializedLoc;
1363 LocTy TyLoc;
1364
1365 Type *Ty = nullptr;
1366 if (parseOptionalAddrSpace(AddrSpace) ||
1367 parseOptionalToken(lltok::kw_externally_initialized,
1368 IsExternallyInitialized,
1369 &IsExternallyInitializedLoc) ||
1370 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1371 return true;
1372
1373 // If the linkage is specified and is external, then no initializer is
1374 // present.
1375 Constant *Init = nullptr;
1376 if (!HasLinkage ||
1379 if (parseGlobalValue(Ty, Init))
1380 return true;
1381 }
1382
1384 return error(TyLoc, "invalid type for global variable");
1385
1386 GlobalValue *GVal = nullptr;
1387
1388 // See if the global was forward referenced, if so, use the global.
1389 if (!Name.empty()) {
1390 auto I = ForwardRefVals.find(Name);
1391 if (I != ForwardRefVals.end()) {
1392 GVal = I->second.first;
1393 ForwardRefVals.erase(I);
1394 } else if (M->getNamedValue(Name)) {
1395 return error(NameLoc, "redefinition of global '@" + Name + "'");
1396 }
1397 } else {
1398 // Handle @"", where a name is syntactically specified, but semantically
1399 // missing.
1400 if (NameID == (unsigned)-1)
1401 NameID = NumberedVals.getNext();
1402
1403 auto I = ForwardRefValIDs.find(NameID);
1404 if (I != ForwardRefValIDs.end()) {
1405 GVal = I->second.first;
1406 ForwardRefValIDs.erase(I);
1407 }
1408 }
1409
1410 GlobalVariable *GV = new GlobalVariable(
1411 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1413
1414 if (Name.empty())
1415 NumberedVals.add(NameID, GV);
1416
1417 // Set the parsed properties on the global.
1418 if (Init)
1419 GV->setInitializer(Init);
1420 GV->setConstant(IsConstant);
1422 maybeSetDSOLocal(DSOLocal, *GV);
1425 GV->setExternallyInitialized(IsExternallyInitialized);
1426 GV->setThreadLocalMode(TLM);
1427 GV->setUnnamedAddr(UnnamedAddr);
1428
1429 if (GVal) {
1430 if (GVal->getAddressSpace() != AddrSpace)
1431 return error(
1432 TyLoc,
1433 "forward reference and definition of global have different types");
1434
1435 GVal->replaceAllUsesWith(GV);
1436 GVal->eraseFromParent();
1437 }
1438
1439 // parse attributes on the global.
1440 while (Lex.getKind() == lltok::comma) {
1441 Lex.Lex();
1442
1443 if (Lex.getKind() == lltok::kw_section) {
1444 Lex.Lex();
1445 GV->setSection(Lex.getStrVal());
1446 if (parseToken(lltok::StringConstant, "expected global section string"))
1447 return true;
1448 } else if (Lex.getKind() == lltok::kw_partition) {
1449 Lex.Lex();
1450 GV->setPartition(Lex.getStrVal());
1451 if (parseToken(lltok::StringConstant, "expected partition string"))
1452 return true;
1453 } else if (Lex.getKind() == lltok::kw_align) {
1454 MaybeAlign Alignment;
1455 if (parseOptionalAlignment(Alignment))
1456 return true;
1457 if (Alignment)
1458 GV->setAlignment(*Alignment);
1459 } else if (Lex.getKind() == lltok::kw_code_model) {
1461 if (parseOptionalCodeModel(CodeModel))
1462 return true;
1463 GV->setCodeModel(CodeModel);
1464 } else if (Lex.getKind() == lltok::MetadataVar) {
1465 if (parseGlobalObjectMetadataAttachment(*GV))
1466 return true;
1467 } else if (isSanitizer(Lex.getKind())) {
1468 if (parseSanitizer(GV))
1469 return true;
1470 } else {
1471 Comdat *C;
1472 if (parseOptionalComdat(Name, C))
1473 return true;
1474 if (C)
1475 GV->setComdat(C);
1476 else
1477 return tokError("unknown global variable property!");
1478 }
1479 }
1480
1481 AttrBuilder Attrs(M->getContext());
1482 LocTy BuiltinLoc;
1483 std::vector<unsigned> FwdRefAttrGrps;
1484 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1485 return true;
1486 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1487 GV->setAttributes(AttributeSet::get(Context, Attrs));
1488 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1489 }
1490
1491 return false;
1492}
1493
1494/// parseUnnamedAttrGrp
1495/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1496bool LLParser::parseUnnamedAttrGrp() {
1497 assert(Lex.getKind() == lltok::kw_attributes);
1498 LocTy AttrGrpLoc = Lex.getLoc();
1499 Lex.Lex();
1500
1501 if (Lex.getKind() != lltok::AttrGrpID)
1502 return tokError("expected attribute group id");
1503
1504 unsigned VarID = Lex.getUIntVal();
1505 std::vector<unsigned> unused;
1506 LocTy BuiltinLoc;
1507 Lex.Lex();
1508
1509 if (parseToken(lltok::equal, "expected '=' here") ||
1510 parseToken(lltok::lbrace, "expected '{' here"))
1511 return true;
1512
1513 auto R = NumberedAttrBuilders.find(VarID);
1514 if (R == NumberedAttrBuilders.end())
1515 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1516
1517 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1518 parseToken(lltok::rbrace, "expected end of attribute group"))
1519 return true;
1520
1521 if (!R->second.hasAttributes())
1522 return error(AttrGrpLoc, "attribute group has no attributes");
1523
1524 return false;
1525}
1526
1528 switch (Kind) {
1529#define GET_ATTR_NAMES
1530#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1531 case lltok::kw_##DISPLAY_NAME: \
1532 return Attribute::ENUM_NAME;
1533#include "llvm/IR/Attributes.inc"
1534 default:
1535 return Attribute::None;
1536 }
1537}
1538
1539bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1540 bool InAttrGroup) {
1541 if (Attribute::isTypeAttrKind(Attr))
1542 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1543
1544 switch (Attr) {
1545 case Attribute::Alignment: {
1546 MaybeAlign Alignment;
1547 if (InAttrGroup) {
1548 uint32_t Value = 0;
1549 Lex.Lex();
1550 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1551 return true;
1552 Alignment = Align(Value);
1553 } else {
1554 if (parseOptionalAlignment(Alignment, true))
1555 return true;
1556 }
1557 B.addAlignmentAttr(Alignment);
1558 return false;
1559 }
1560 case Attribute::StackAlignment: {
1561 unsigned Alignment;
1562 if (InAttrGroup) {
1563 Lex.Lex();
1564 if (parseToken(lltok::equal, "expected '=' here") ||
1565 parseUInt32(Alignment))
1566 return true;
1567 } else {
1568 if (parseOptionalStackAlignment(Alignment))
1569 return true;
1570 }
1571 B.addStackAlignmentAttr(Alignment);
1572 return false;
1573 }
1574 case Attribute::AllocSize: {
1575 unsigned ElemSizeArg;
1576 std::optional<unsigned> NumElemsArg;
1577 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1578 return true;
1579 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1580 return false;
1581 }
1582 case Attribute::VScaleRange: {
1583 unsigned MinValue, MaxValue;
1584 if (parseVScaleRangeArguments(MinValue, MaxValue))
1585 return true;
1586 B.addVScaleRangeAttr(MinValue,
1587 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1588 return false;
1589 }
1590 case Attribute::Dereferenceable: {
1591 uint64_t Bytes;
1592 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1593 return true;
1594 B.addDereferenceableAttr(Bytes);
1595 return false;
1596 }
1597 case Attribute::DereferenceableOrNull: {
1598 uint64_t Bytes;
1599 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1600 return true;
1601 B.addDereferenceableOrNullAttr(Bytes);
1602 return false;
1603 }
1604 case Attribute::UWTable: {
1606 if (parseOptionalUWTableKind(Kind))
1607 return true;
1608 B.addUWTableAttr(Kind);
1609 return false;
1610 }
1611 case Attribute::AllocKind: {
1613 if (parseAllocKind(Kind))
1614 return true;
1615 B.addAllocKindAttr(Kind);
1616 return false;
1617 }
1618 case Attribute::Memory: {
1619 std::optional<MemoryEffects> ME = parseMemoryAttr();
1620 if (!ME)
1621 return true;
1622 B.addMemoryAttr(*ME);
1623 return false;
1624 }
1625 case Attribute::NoFPClass: {
1626 if (FPClassTest NoFPClass =
1627 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1628 B.addNoFPClassAttr(NoFPClass);
1629 return false;
1630 }
1631
1632 return true;
1633 }
1634 case Attribute::Range:
1635 return parseRangeAttr(B);
1636 case Attribute::Initializes:
1637 return parseInitializesAttr(B);
1638 case Attribute::Captures:
1639 return parseCapturesAttr(B);
1640 default:
1641 B.addAttribute(Attr);
1642 Lex.Lex();
1643 return false;
1644 }
1645}
1646
1648 switch (Kind) {
1649 case lltok::kw_readnone:
1650 ME &= MemoryEffects::none();
1651 return true;
1652 case lltok::kw_readonly:
1654 return true;
1655 case lltok::kw_writeonly:
1657 return true;
1660 return true;
1663 return true;
1666 return true;
1667 default:
1668 return false;
1669 }
1670}
1671
1672/// parseFnAttributeValuePairs
1673/// ::= <attr> | <attr> '=' <value>
1674bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1675 std::vector<unsigned> &FwdRefAttrGrps,
1676 bool InAttrGrp, LocTy &BuiltinLoc) {
1677 bool HaveError = false;
1678
1679 B.clear();
1680
1682 while (true) {
1683 lltok::Kind Token = Lex.getKind();
1684 if (Token == lltok::rbrace)
1685 break; // Finished.
1686
1687 if (Token == lltok::StringConstant) {
1688 if (parseStringAttribute(B))
1689 return true;
1690 continue;
1691 }
1692
1693 if (Token == lltok::AttrGrpID) {
1694 // Allow a function to reference an attribute group:
1695 //
1696 // define void @foo() #1 { ... }
1697 if (InAttrGrp) {
1698 HaveError |= error(
1699 Lex.getLoc(),
1700 "cannot have an attribute group reference in an attribute group");
1701 } else {
1702 // Save the reference to the attribute group. We'll fill it in later.
1703 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1704 }
1705 Lex.Lex();
1706 continue;
1707 }
1708
1709 SMLoc Loc = Lex.getLoc();
1710 if (Token == lltok::kw_builtin)
1711 BuiltinLoc = Loc;
1712
1713 if (upgradeMemoryAttr(ME, Token)) {
1714 Lex.Lex();
1715 continue;
1716 }
1717
1719 if (Attr == Attribute::None) {
1720 if (!InAttrGrp)
1721 break;
1722 return error(Lex.getLoc(), "unterminated attribute group");
1723 }
1724
1725 if (parseEnumAttribute(Attr, B, InAttrGrp))
1726 return true;
1727
1728 // As a hack, we allow function alignment to be initially parsed as an
1729 // attribute on a function declaration/definition or added to an attribute
1730 // group and later moved to the alignment field.
1731 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1732 HaveError |= error(Loc, "this attribute does not apply to functions");
1733 }
1734
1735 if (ME != MemoryEffects::unknown())
1736 B.addMemoryAttr(ME);
1737 return HaveError;
1738}
1739
1740//===----------------------------------------------------------------------===//
1741// GlobalValue Reference/Resolution Routines.
1742//===----------------------------------------------------------------------===//
1743
1745 // The used global type does not matter. We will later RAUW it with a
1746 // global/function of the correct type.
1747 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1750 PTy->getAddressSpace());
1751}
1752
1753Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1754 Value *Val) {
1755 Type *ValTy = Val->getType();
1756 if (ValTy == Ty)
1757 return Val;
1758 if (Ty->isLabelTy())
1759 error(Loc, "'" + Name + "' is not a basic block");
1760 else
1761 error(Loc, "'" + Name + "' defined with type '" +
1762 getTypeString(Val->getType()) + "' but expected '" +
1763 getTypeString(Ty) + "'");
1764 return nullptr;
1765}
1766
1767/// getGlobalVal - Get a value with the specified name or ID, creating a
1768/// forward reference record if needed. This can return null if the value
1769/// exists but does not have the right type.
1770GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1771 LocTy Loc) {
1773 if (!PTy) {
1774 error(Loc, "global variable reference must have pointer type");
1775 return nullptr;
1776 }
1777
1778 // Look this name up in the normal function symbol table.
1779 GlobalValue *Val =
1780 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1781
1782 // If this is a forward reference for the value, see if we already created a
1783 // forward ref record.
1784 if (!Val) {
1785 auto I = ForwardRefVals.find(Name);
1786 if (I != ForwardRefVals.end())
1787 Val = I->second.first;
1788 }
1789
1790 // If we have the value in the symbol table or fwd-ref table, return it.
1791 if (Val)
1793 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1794
1795 // Otherwise, create a new forward reference for this value and remember it.
1796 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1797 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1798 return FwdVal;
1799}
1800
1801GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1803 if (!PTy) {
1804 error(Loc, "global variable reference must have pointer type");
1805 return nullptr;
1806 }
1807
1808 GlobalValue *Val = NumberedVals.get(ID);
1809
1810 // If this is a forward reference for the value, see if we already created a
1811 // forward ref record.
1812 if (!Val) {
1813 auto I = ForwardRefValIDs.find(ID);
1814 if (I != ForwardRefValIDs.end())
1815 Val = I->second.first;
1816 }
1817
1818 // If we have the value in the symbol table or fwd-ref table, return it.
1819 if (Val)
1821 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1822
1823 // Otherwise, create a new forward reference for this value and remember it.
1824 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1825 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1826 return FwdVal;
1827}
1828
1829//===----------------------------------------------------------------------===//
1830// Comdat Reference/Resolution Routines.
1831//===----------------------------------------------------------------------===//
1832
1833Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1834 // Look this name up in the comdat symbol table.
1835 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1836 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1837 if (I != ComdatSymTab.end())
1838 return &I->second;
1839
1840 // Otherwise, create a new forward reference for this value and remember it.
1841 Comdat *C = M->getOrInsertComdat(Name);
1842 ForwardRefComdats[Name] = Loc;
1843 return C;
1844}
1845
1846//===----------------------------------------------------------------------===//
1847// Helper Routines.
1848//===----------------------------------------------------------------------===//
1849
1850/// parseToken - If the current token has the specified kind, eat it and return
1851/// success. Otherwise, emit the specified error and return failure.
1852bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1853 if (Lex.getKind() != T)
1854 return tokError(ErrMsg);
1855 Lex.Lex();
1856 return false;
1857}
1858
1859/// parseStringConstant
1860/// ::= StringConstant
1861bool LLParser::parseStringConstant(std::string &Result) {
1862 if (Lex.getKind() != lltok::StringConstant)
1863 return tokError("expected string constant");
1864 Result = Lex.getStrVal();
1865 Lex.Lex();
1866 return false;
1867}
1868
1869/// parseUInt32
1870/// ::= uint32
1871bool LLParser::parseUInt32(uint32_t &Val) {
1872 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1873 return tokError("expected integer");
1874 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1875 if (Val64 != unsigned(Val64))
1876 return tokError("expected 32-bit integer (too large)");
1877 Val = Val64;
1878 Lex.Lex();
1879 return false;
1880}
1881
1882/// parseUInt64
1883/// ::= uint64
1884bool LLParser::parseUInt64(uint64_t &Val) {
1885 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1886 return tokError("expected integer");
1887 Val = Lex.getAPSIntVal().getLimitedValue();
1888 Lex.Lex();
1889 return false;
1890}
1891
1892/// parseTLSModel
1893/// := 'localdynamic'
1894/// := 'initialexec'
1895/// := 'localexec'
1896bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1897 switch (Lex.getKind()) {
1898 default:
1899 return tokError("expected localdynamic, initialexec or localexec");
1902 break;
1905 break;
1908 break;
1909 }
1910
1911 Lex.Lex();
1912 return false;
1913}
1914
1915/// parseOptionalThreadLocal
1916/// := /*empty*/
1917/// := 'thread_local'
1918/// := 'thread_local' '(' tlsmodel ')'
1919bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1921 if (!EatIfPresent(lltok::kw_thread_local))
1922 return false;
1923
1925 if (Lex.getKind() == lltok::lparen) {
1926 Lex.Lex();
1927 return parseTLSModel(TLM) ||
1928 parseToken(lltok::rparen, "expected ')' after thread local model");
1929 }
1930 return false;
1931}
1932
1933/// parseOptionalAddrSpace
1934/// := /*empty*/
1935/// := 'addrspace' '(' uint32 ')'
1936bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1937 AddrSpace = DefaultAS;
1938 if (!EatIfPresent(lltok::kw_addrspace))
1939 return false;
1940
1941 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1942 if (Lex.getKind() == lltok::StringConstant) {
1943 auto AddrSpaceStr = Lex.getStrVal();
1944 if (AddrSpaceStr == "A") {
1945 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1946 } else if (AddrSpaceStr == "G") {
1947 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1948 } else if (AddrSpaceStr == "P") {
1949 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1950 } else {
1951 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1952 }
1953 Lex.Lex();
1954 return false;
1955 }
1956 if (Lex.getKind() != lltok::APSInt)
1957 return tokError("expected integer or string constant");
1958 SMLoc Loc = Lex.getLoc();
1959 if (parseUInt32(AddrSpace))
1960 return true;
1961 if (!isUInt<24>(AddrSpace))
1962 return error(Loc, "invalid address space, must be a 24-bit integer");
1963 return false;
1964 };
1965
1966 return parseToken(lltok::lparen, "expected '(' in address space") ||
1967 ParseAddrspaceValue(AddrSpace) ||
1968 parseToken(lltok::rparen, "expected ')' in address space");
1969}
1970
1971/// parseStringAttribute
1972/// := StringConstant
1973/// := StringConstant '=' StringConstant
1974bool LLParser::parseStringAttribute(AttrBuilder &B) {
1975 std::string Attr = Lex.getStrVal();
1976 Lex.Lex();
1977 std::string Val;
1978 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1979 return true;
1980 B.addAttribute(Attr, Val);
1981 return false;
1982}
1983
1984/// Parse a potentially empty list of parameter or return attributes.
1985bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1986 bool HaveError = false;
1987
1988 B.clear();
1989
1990 while (true) {
1991 lltok::Kind Token = Lex.getKind();
1992 if (Token == lltok::StringConstant) {
1993 if (parseStringAttribute(B))
1994 return true;
1995 continue;
1996 }
1997
1998 if (Token == lltok::kw_nocapture) {
1999 Lex.Lex();
2000 B.addCapturesAttr(CaptureInfo::none());
2001 continue;
2002 }
2003
2004 SMLoc Loc = Lex.getLoc();
2006 if (Attr == Attribute::None)
2007 return HaveError;
2008
2009 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2010 return true;
2011
2012 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2013 HaveError |= error(Loc, "this attribute does not apply to parameters");
2014 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2015 HaveError |= error(Loc, "this attribute does not apply to return values");
2016 }
2017}
2018
2019static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2020 HasLinkage = true;
2021 switch (Kind) {
2022 default:
2023 HasLinkage = false;
2025 case lltok::kw_private:
2027 case lltok::kw_internal:
2029 case lltok::kw_weak:
2031 case lltok::kw_weak_odr:
2033 case lltok::kw_linkonce:
2041 case lltok::kw_common:
2045 case lltok::kw_external:
2047 }
2048}
2049
2050/// parseOptionalLinkage
2051/// ::= /*empty*/
2052/// ::= 'private'
2053/// ::= 'internal'
2054/// ::= 'weak'
2055/// ::= 'weak_odr'
2056/// ::= 'linkonce'
2057/// ::= 'linkonce_odr'
2058/// ::= 'available_externally'
2059/// ::= 'appending'
2060/// ::= 'common'
2061/// ::= 'extern_weak'
2062/// ::= 'external'
2063bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2064 unsigned &Visibility,
2065 unsigned &DLLStorageClass, bool &DSOLocal) {
2066 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2067 if (HasLinkage)
2068 Lex.Lex();
2069 parseOptionalDSOLocal(DSOLocal);
2070 parseOptionalVisibility(Visibility);
2071 parseOptionalDLLStorageClass(DLLStorageClass);
2072
2073 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2074 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2075 }
2076
2077 return false;
2078}
2079
2080void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2081 switch (Lex.getKind()) {
2082 default:
2083 DSOLocal = false;
2084 break;
2086 DSOLocal = true;
2087 Lex.Lex();
2088 break;
2090 DSOLocal = false;
2091 Lex.Lex();
2092 break;
2093 }
2094}
2095
2096/// parseOptionalVisibility
2097/// ::= /*empty*/
2098/// ::= 'default'
2099/// ::= 'hidden'
2100/// ::= 'protected'
2101///
2102void LLParser::parseOptionalVisibility(unsigned &Res) {
2103 switch (Lex.getKind()) {
2104 default:
2106 return;
2107 case lltok::kw_default:
2109 break;
2110 case lltok::kw_hidden:
2112 break;
2115 break;
2116 }
2117 Lex.Lex();
2118}
2119
2120bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2122 switch (Kind) {
2123 default:
2124 return tokError("unknown import kind. Expect definition or declaration.");
2127 return false;
2130 return false;
2131 }
2132}
2133
2134/// parseOptionalDLLStorageClass
2135/// ::= /*empty*/
2136/// ::= 'dllimport'
2137/// ::= 'dllexport'
2138///
2139void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2140 switch (Lex.getKind()) {
2141 default:
2143 return;
2146 break;
2149 break;
2150 }
2151 Lex.Lex();
2152}
2153
2154/// parseOptionalCallingConv
2155/// ::= /*empty*/
2156/// ::= 'ccc'
2157/// ::= 'fastcc'
2158/// ::= 'intel_ocl_bicc'
2159/// ::= 'coldcc'
2160/// ::= 'cfguard_checkcc'
2161/// ::= 'x86_stdcallcc'
2162/// ::= 'x86_fastcallcc'
2163/// ::= 'x86_thiscallcc'
2164/// ::= 'x86_vectorcallcc'
2165/// ::= 'arm_apcscc'
2166/// ::= 'arm_aapcscc'
2167/// ::= 'arm_aapcs_vfpcc'
2168/// ::= 'aarch64_vector_pcs'
2169/// ::= 'aarch64_sve_vector_pcs'
2170/// ::= 'aarch64_sme_preservemost_from_x0'
2171/// ::= 'aarch64_sme_preservemost_from_x1'
2172/// ::= 'aarch64_sme_preservemost_from_x2'
2173/// ::= 'msp430_intrcc'
2174/// ::= 'avr_intrcc'
2175/// ::= 'avr_signalcc'
2176/// ::= 'ptx_kernel'
2177/// ::= 'ptx_device'
2178/// ::= 'spir_func'
2179/// ::= 'spir_kernel'
2180/// ::= 'x86_64_sysvcc'
2181/// ::= 'win64cc'
2182/// ::= 'anyregcc'
2183/// ::= 'preserve_mostcc'
2184/// ::= 'preserve_allcc'
2185/// ::= 'preserve_nonecc'
2186/// ::= 'ghccc'
2187/// ::= 'swiftcc'
2188/// ::= 'swifttailcc'
2189/// ::= 'x86_intrcc'
2190/// ::= 'hhvmcc'
2191/// ::= 'hhvm_ccc'
2192/// ::= 'cxx_fast_tlscc'
2193/// ::= 'amdgpu_vs'
2194/// ::= 'amdgpu_ls'
2195/// ::= 'amdgpu_hs'
2196/// ::= 'amdgpu_es'
2197/// ::= 'amdgpu_gs'
2198/// ::= 'amdgpu_ps'
2199/// ::= 'amdgpu_cs'
2200/// ::= 'amdgpu_cs_chain'
2201/// ::= 'amdgpu_cs_chain_preserve'
2202/// ::= 'amdgpu_kernel'
2203/// ::= 'tailcc'
2204/// ::= 'm68k_rtdcc'
2205/// ::= 'graalcc'
2206/// ::= 'riscv_vector_cc'
2207/// ::= 'riscv_vls_cc'
2208/// ::= 'cc' UINT
2209///
2210bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2211 switch (Lex.getKind()) {
2212 default: CC = CallingConv::C; return false;
2213 case lltok::kw_ccc: CC = CallingConv::C; break;
2214 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2215 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2228 break;
2231 break;
2234 break;
2237 break;
2247 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2248 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2252 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2253 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2256 case lltok::kw_hhvmcc:
2258 break;
2259 case lltok::kw_hhvm_ccc:
2261 break;
2273 break;
2276 break;
2280 break;
2281 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2283 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2286 break;
2288 // Default ABI_VLEN
2290 Lex.Lex();
2291 if (!EatIfPresent(lltok::lparen))
2292 break;
2293 uint32_t ABIVlen;
2294 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2295 return true;
2296 switch (ABIVlen) {
2297 default:
2298 return tokError("unknown RISC-V ABI VLEN");
2299#define CC_VLS_CASE(ABIVlen) \
2300 case ABIVlen: \
2301 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2302 break;
2303 CC_VLS_CASE(32)
2304 CC_VLS_CASE(64)
2305 CC_VLS_CASE(128)
2306 CC_VLS_CASE(256)
2307 CC_VLS_CASE(512)
2308 CC_VLS_CASE(1024)
2309 CC_VLS_CASE(2048)
2310 CC_VLS_CASE(4096)
2311 CC_VLS_CASE(8192)
2312 CC_VLS_CASE(16384)
2313 CC_VLS_CASE(32768)
2314 CC_VLS_CASE(65536)
2315#undef CC_VLS_CASE
2316 }
2317 return false;
2318 case lltok::kw_cc: {
2319 Lex.Lex();
2320 return parseUInt32(CC);
2321 }
2322 }
2323
2324 Lex.Lex();
2325 return false;
2326}
2327
2328/// parseMetadataAttachment
2329/// ::= !dbg !42
2330bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2331 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2332
2333 std::string Name = Lex.getStrVal();
2334 Kind = M->getMDKindID(Name);
2335 Lex.Lex();
2336
2337 return parseMDNode(MD);
2338}
2339
2340/// parseInstructionMetadata
2341/// ::= !dbg !42 (',' !dbg !57)*
2342bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2343 do {
2344 if (Lex.getKind() != lltok::MetadataVar)
2345 return tokError("expected metadata after comma");
2346
2347 unsigned MDK;
2348 MDNode *N;
2349 if (parseMetadataAttachment(MDK, N))
2350 return true;
2351
2352 if (MDK == LLVMContext::MD_DIAssignID)
2353 TempDIAssignIDAttachments[N].push_back(&Inst);
2354 else
2355 Inst.setMetadata(MDK, N);
2356
2357 if (MDK == LLVMContext::MD_tbaa)
2358 InstsWithTBAATag.push_back(&Inst);
2359
2360 // If this is the end of the list, we're done.
2361 } while (EatIfPresent(lltok::comma));
2362 return false;
2363}
2364
2365/// parseGlobalObjectMetadataAttachment
2366/// ::= !dbg !57
2367bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2368 unsigned MDK;
2369 MDNode *N;
2370 if (parseMetadataAttachment(MDK, N))
2371 return true;
2372
2373 GO.addMetadata(MDK, *N);
2374 return false;
2375}
2376
2377/// parseOptionalFunctionMetadata
2378/// ::= (!dbg !57)*
2379bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2380 while (Lex.getKind() == lltok::MetadataVar)
2381 if (parseGlobalObjectMetadataAttachment(F))
2382 return true;
2383 return false;
2384}
2385
2386/// parseOptionalAlignment
2387/// ::= /* empty */
2388/// ::= 'align' 4
2389bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2390 Alignment = std::nullopt;
2391 if (!EatIfPresent(lltok::kw_align))
2392 return false;
2393 LocTy AlignLoc = Lex.getLoc();
2394 uint64_t Value = 0;
2395
2396 LocTy ParenLoc = Lex.getLoc();
2397 bool HaveParens = false;
2398 if (AllowParens) {
2399 if (EatIfPresent(lltok::lparen))
2400 HaveParens = true;
2401 }
2402
2403 if (parseUInt64(Value))
2404 return true;
2405
2406 if (HaveParens && !EatIfPresent(lltok::rparen))
2407 return error(ParenLoc, "expected ')'");
2408
2409 if (!isPowerOf2_64(Value))
2410 return error(AlignLoc, "alignment is not a power of two");
2412 return error(AlignLoc, "huge alignments are not supported yet");
2413 Alignment = Align(Value);
2414 return false;
2415}
2416
2417/// parseOptionalCodeModel
2418/// ::= /* empty */
2419/// ::= 'code_model' "large"
2420bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2421 Lex.Lex();
2422 auto StrVal = Lex.getStrVal();
2423 auto ErrMsg = "expected global code model string";
2424 if (StrVal == "tiny")
2425 model = CodeModel::Tiny;
2426 else if (StrVal == "small")
2427 model = CodeModel::Small;
2428 else if (StrVal == "kernel")
2429 model = CodeModel::Kernel;
2430 else if (StrVal == "medium")
2431 model = CodeModel::Medium;
2432 else if (StrVal == "large")
2433 model = CodeModel::Large;
2434 else
2435 return tokError(ErrMsg);
2436 if (parseToken(lltok::StringConstant, ErrMsg))
2437 return true;
2438 return false;
2439}
2440
2441/// parseOptionalDerefAttrBytes
2442/// ::= /* empty */
2443/// ::= AttrKind '(' 4 ')'
2444///
2445/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2446bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2447 uint64_t &Bytes) {
2448 assert((AttrKind == lltok::kw_dereferenceable ||
2449 AttrKind == lltok::kw_dereferenceable_or_null) &&
2450 "contract!");
2451
2452 Bytes = 0;
2453 if (!EatIfPresent(AttrKind))
2454 return false;
2455 LocTy ParenLoc = Lex.getLoc();
2456 if (!EatIfPresent(lltok::lparen))
2457 return error(ParenLoc, "expected '('");
2458 LocTy DerefLoc = Lex.getLoc();
2459 if (parseUInt64(Bytes))
2460 return true;
2461 ParenLoc = Lex.getLoc();
2462 if (!EatIfPresent(lltok::rparen))
2463 return error(ParenLoc, "expected ')'");
2464 if (!Bytes)
2465 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2466 return false;
2467}
2468
2469bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2470 Lex.Lex();
2472 if (!EatIfPresent(lltok::lparen))
2473 return false;
2474 LocTy KindLoc = Lex.getLoc();
2475 if (Lex.getKind() == lltok::kw_sync)
2477 else if (Lex.getKind() == lltok::kw_async)
2479 else
2480 return error(KindLoc, "expected unwind table kind");
2481 Lex.Lex();
2482 return parseToken(lltok::rparen, "expected ')'");
2483}
2484
2485bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2486 Lex.Lex();
2487 LocTy ParenLoc = Lex.getLoc();
2488 if (!EatIfPresent(lltok::lparen))
2489 return error(ParenLoc, "expected '('");
2490 LocTy KindLoc = Lex.getLoc();
2491 std::string Arg;
2492 if (parseStringConstant(Arg))
2493 return error(KindLoc, "expected allockind value");
2494 for (StringRef A : llvm::split(Arg, ",")) {
2495 if (A == "alloc") {
2497 } else if (A == "realloc") {
2499 } else if (A == "free") {
2501 } else if (A == "uninitialized") {
2503 } else if (A == "zeroed") {
2505 } else if (A == "aligned") {
2507 } else {
2508 return error(KindLoc, Twine("unknown allockind ") + A);
2509 }
2510 }
2511 ParenLoc = Lex.getLoc();
2512 if (!EatIfPresent(lltok::rparen))
2513 return error(ParenLoc, "expected ')'");
2514 if (Kind == AllocFnKind::Unknown)
2515 return error(KindLoc, "expected allockind value");
2516 return false;
2517}
2518
2519static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2520 switch (Tok) {
2521 case lltok::kw_argmem:
2522 return IRMemLocation::ArgMem;
2525 case lltok::kw_errnomem:
2527 default:
2528 return std::nullopt;
2529 }
2530}
2531
2532static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2533 switch (Tok) {
2534 case lltok::kw_none:
2535 return ModRefInfo::NoModRef;
2536 case lltok::kw_read:
2537 return ModRefInfo::Ref;
2538 case lltok::kw_write:
2539 return ModRefInfo::Mod;
2541 return ModRefInfo::ModRef;
2542 default:
2543 return std::nullopt;
2544 }
2545}
2546
2547std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2549
2550 // We use syntax like memory(argmem: read), so the colon should not be
2551 // interpreted as a label terminator.
2552 Lex.setIgnoreColonInIdentifiers(true);
2553 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2554
2555 Lex.Lex();
2556 if (!EatIfPresent(lltok::lparen)) {
2557 tokError("expected '('");
2558 return std::nullopt;
2559 }
2560
2561 bool SeenLoc = false;
2562 do {
2563 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2564 if (Loc) {
2565 Lex.Lex();
2566 if (!EatIfPresent(lltok::colon)) {
2567 tokError("expected ':' after location");
2568 return std::nullopt;
2569 }
2570 }
2571
2572 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2573 if (!MR) {
2574 if (!Loc)
2575 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2576 "or access kind (none, read, write, readwrite)");
2577 else
2578 tokError("expected access kind (none, read, write, readwrite)");
2579 return std::nullopt;
2580 }
2581
2582 Lex.Lex();
2583 if (Loc) {
2584 SeenLoc = true;
2585 ME = ME.getWithModRef(*Loc, *MR);
2586 } else {
2587 if (SeenLoc) {
2588 tokError("default access kind must be specified first");
2589 return std::nullopt;
2590 }
2591 ME = MemoryEffects(*MR);
2592 }
2593
2594 if (EatIfPresent(lltok::rparen))
2595 return ME;
2596 } while (EatIfPresent(lltok::comma));
2597
2598 tokError("unterminated memory attribute");
2599 return std::nullopt;
2600}
2601
2602static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2603 switch (Tok) {
2604 case lltok::kw_all:
2605 return fcAllFlags;
2606 case lltok::kw_nan:
2607 return fcNan;
2608 case lltok::kw_snan:
2609 return fcSNan;
2610 case lltok::kw_qnan:
2611 return fcQNan;
2612 case lltok::kw_inf:
2613 return fcInf;
2614 case lltok::kw_ninf:
2615 return fcNegInf;
2616 case lltok::kw_pinf:
2617 return fcPosInf;
2618 case lltok::kw_norm:
2619 return fcNormal;
2620 case lltok::kw_nnorm:
2621 return fcNegNormal;
2622 case lltok::kw_pnorm:
2623 return fcPosNormal;
2624 case lltok::kw_sub:
2625 return fcSubnormal;
2626 case lltok::kw_nsub:
2627 return fcNegSubnormal;
2628 case lltok::kw_psub:
2629 return fcPosSubnormal;
2630 case lltok::kw_zero:
2631 return fcZero;
2632 case lltok::kw_nzero:
2633 return fcNegZero;
2634 case lltok::kw_pzero:
2635 return fcPosZero;
2636 default:
2637 return 0;
2638 }
2639}
2640
2641unsigned LLParser::parseNoFPClassAttr() {
2642 unsigned Mask = fcNone;
2643
2644 Lex.Lex();
2645 if (!EatIfPresent(lltok::lparen)) {
2646 tokError("expected '('");
2647 return 0;
2648 }
2649
2650 do {
2651 uint64_t Value = 0;
2652 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2653 if (TestMask != 0) {
2654 Mask |= TestMask;
2655 // TODO: Disallow overlapping masks to avoid copy paste errors
2656 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2657 !parseUInt64(Value)) {
2658 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2659 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2660 return 0;
2661 }
2662
2663 if (!EatIfPresent(lltok::rparen)) {
2664 error(Lex.getLoc(), "expected ')'");
2665 return 0;
2666 }
2667
2668 return Value;
2669 } else {
2670 error(Lex.getLoc(), "expected nofpclass test mask");
2671 return 0;
2672 }
2673
2674 Lex.Lex();
2675 if (EatIfPresent(lltok::rparen))
2676 return Mask;
2677 } while (1);
2678
2679 llvm_unreachable("unterminated nofpclass attribute");
2680}
2681
2682/// parseOptionalCommaAlign
2683/// ::=
2684/// ::= ',' align 4
2685///
2686/// This returns with AteExtraComma set to true if it ate an excess comma at the
2687/// end.
2688bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2689 bool &AteExtraComma) {
2690 AteExtraComma = false;
2691 while (EatIfPresent(lltok::comma)) {
2692 // Metadata at the end is an early exit.
2693 if (Lex.getKind() == lltok::MetadataVar) {
2694 AteExtraComma = true;
2695 return false;
2696 }
2697
2698 if (Lex.getKind() != lltok::kw_align)
2699 return error(Lex.getLoc(), "expected metadata or 'align'");
2700
2701 if (parseOptionalAlignment(Alignment))
2702 return true;
2703 }
2704
2705 return false;
2706}
2707
2708/// parseOptionalCommaAddrSpace
2709/// ::=
2710/// ::= ',' addrspace(1)
2711///
2712/// This returns with AteExtraComma set to true if it ate an excess comma at the
2713/// end.
2714bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2715 bool &AteExtraComma) {
2716 AteExtraComma = false;
2717 while (EatIfPresent(lltok::comma)) {
2718 // Metadata at the end is an early exit.
2719 if (Lex.getKind() == lltok::MetadataVar) {
2720 AteExtraComma = true;
2721 return false;
2722 }
2723
2724 Loc = Lex.getLoc();
2725 if (Lex.getKind() != lltok::kw_addrspace)
2726 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2727
2728 if (parseOptionalAddrSpace(AddrSpace))
2729 return true;
2730 }
2731
2732 return false;
2733}
2734
2735bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2736 std::optional<unsigned> &HowManyArg) {
2737 Lex.Lex();
2738
2739 auto StartParen = Lex.getLoc();
2740 if (!EatIfPresent(lltok::lparen))
2741 return error(StartParen, "expected '('");
2742
2743 if (parseUInt32(BaseSizeArg))
2744 return true;
2745
2746 if (EatIfPresent(lltok::comma)) {
2747 auto HowManyAt = Lex.getLoc();
2748 unsigned HowMany;
2749 if (parseUInt32(HowMany))
2750 return true;
2751 if (HowMany == BaseSizeArg)
2752 return error(HowManyAt,
2753 "'allocsize' indices can't refer to the same parameter");
2754 HowManyArg = HowMany;
2755 } else
2756 HowManyArg = std::nullopt;
2757
2758 auto EndParen = Lex.getLoc();
2759 if (!EatIfPresent(lltok::rparen))
2760 return error(EndParen, "expected ')'");
2761 return false;
2762}
2763
2764bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2765 unsigned &MaxValue) {
2766 Lex.Lex();
2767
2768 auto StartParen = Lex.getLoc();
2769 if (!EatIfPresent(lltok::lparen))
2770 return error(StartParen, "expected '('");
2771
2772 if (parseUInt32(MinValue))
2773 return true;
2774
2775 if (EatIfPresent(lltok::comma)) {
2776 if (parseUInt32(MaxValue))
2777 return true;
2778 } else
2779 MaxValue = MinValue;
2780
2781 auto EndParen = Lex.getLoc();
2782 if (!EatIfPresent(lltok::rparen))
2783 return error(EndParen, "expected ')'");
2784 return false;
2785}
2786
2787/// parseScopeAndOrdering
2788/// if isAtomic: ::= SyncScope? AtomicOrdering
2789/// else: ::=
2790///
2791/// This sets Scope and Ordering to the parsed values.
2792bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2793 AtomicOrdering &Ordering) {
2794 if (!IsAtomic)
2795 return false;
2796
2797 return parseScope(SSID) || parseOrdering(Ordering);
2798}
2799
2800/// parseScope
2801/// ::= syncscope("singlethread" | "<target scope>")?
2802///
2803/// This sets synchronization scope ID to the ID of the parsed value.
2804bool LLParser::parseScope(SyncScope::ID &SSID) {
2805 SSID = SyncScope::System;
2806 if (EatIfPresent(lltok::kw_syncscope)) {
2807 auto StartParenAt = Lex.getLoc();
2808 if (!EatIfPresent(lltok::lparen))
2809 return error(StartParenAt, "Expected '(' in syncscope");
2810
2811 std::string SSN;
2812 auto SSNAt = Lex.getLoc();
2813 if (parseStringConstant(SSN))
2814 return error(SSNAt, "Expected synchronization scope name");
2815
2816 auto EndParenAt = Lex.getLoc();
2817 if (!EatIfPresent(lltok::rparen))
2818 return error(EndParenAt, "Expected ')' in syncscope");
2819
2820 SSID = Context.getOrInsertSyncScopeID(SSN);
2821 }
2822
2823 return false;
2824}
2825
2826/// parseOrdering
2827/// ::= AtomicOrdering
2828///
2829/// This sets Ordering to the parsed value.
2830bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2831 switch (Lex.getKind()) {
2832 default:
2833 return tokError("Expected ordering on atomic instruction");
2836 // Not specified yet:
2837 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2841 case lltok::kw_seq_cst:
2843 break;
2844 }
2845 Lex.Lex();
2846 return false;
2847}
2848
2849/// parseOptionalStackAlignment
2850/// ::= /* empty */
2851/// ::= 'alignstack' '(' 4 ')'
2852bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2853 Alignment = 0;
2854 if (!EatIfPresent(lltok::kw_alignstack))
2855 return false;
2856 LocTy ParenLoc = Lex.getLoc();
2857 if (!EatIfPresent(lltok::lparen))
2858 return error(ParenLoc, "expected '('");
2859 LocTy AlignLoc = Lex.getLoc();
2860 if (parseUInt32(Alignment))
2861 return true;
2862 ParenLoc = Lex.getLoc();
2863 if (!EatIfPresent(lltok::rparen))
2864 return error(ParenLoc, "expected ')'");
2865 if (!isPowerOf2_32(Alignment))
2866 return error(AlignLoc, "stack alignment is not a power of two");
2867 return false;
2868}
2869
2870/// parseIndexList - This parses the index list for an insert/extractvalue
2871/// instruction. This sets AteExtraComma in the case where we eat an extra
2872/// comma at the end of the line and find that it is followed by metadata.
2873/// Clients that don't allow metadata can call the version of this function that
2874/// only takes one argument.
2875///
2876/// parseIndexList
2877/// ::= (',' uint32)+
2878///
2879bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2880 bool &AteExtraComma) {
2881 AteExtraComma = false;
2882
2883 if (Lex.getKind() != lltok::comma)
2884 return tokError("expected ',' as start of index list");
2885
2886 while (EatIfPresent(lltok::comma)) {
2887 if (Lex.getKind() == lltok::MetadataVar) {
2888 if (Indices.empty())
2889 return tokError("expected index");
2890 AteExtraComma = true;
2891 return false;
2892 }
2893 unsigned Idx = 0;
2894 if (parseUInt32(Idx))
2895 return true;
2896 Indices.push_back(Idx);
2897 }
2898
2899 return false;
2900}
2901
2902//===----------------------------------------------------------------------===//
2903// Type Parsing.
2904//===----------------------------------------------------------------------===//
2905
2906/// parseType - parse a type.
2907bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2908 SMLoc TypeLoc = Lex.getLoc();
2909 switch (Lex.getKind()) {
2910 default:
2911 return tokError(Msg);
2912 case lltok::Type:
2913 // Type ::= 'float' | 'void' (etc)
2914 Result = Lex.getTyVal();
2915 Lex.Lex();
2916
2917 // Handle "ptr" opaque pointer type.
2918 //
2919 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2920 if (Result->isPointerTy()) {
2921 unsigned AddrSpace;
2922 if (parseOptionalAddrSpace(AddrSpace))
2923 return true;
2924 Result = PointerType::get(getContext(), AddrSpace);
2925
2926 // Give a nice error for 'ptr*'.
2927 if (Lex.getKind() == lltok::star)
2928 return tokError("ptr* is invalid - use ptr instead");
2929
2930 // Fall through to parsing the type suffixes only if this 'ptr' is a
2931 // function return. Otherwise, return success, implicitly rejecting other
2932 // suffixes.
2933 if (Lex.getKind() != lltok::lparen)
2934 return false;
2935 }
2936 break;
2937 case lltok::kw_target: {
2938 // Type ::= TargetExtType
2939 if (parseTargetExtType(Result))
2940 return true;
2941 break;
2942 }
2943 case lltok::lbrace:
2944 // Type ::= StructType
2945 if (parseAnonStructType(Result, false))
2946 return true;
2947 break;
2948 case lltok::lsquare:
2949 // Type ::= '[' ... ']'
2950 Lex.Lex(); // eat the lsquare.
2951 if (parseArrayVectorType(Result, false))
2952 return true;
2953 break;
2954 case lltok::less: // Either vector or packed struct.
2955 // Type ::= '<' ... '>'
2956 Lex.Lex();
2957 if (Lex.getKind() == lltok::lbrace) {
2958 if (parseAnonStructType(Result, true) ||
2959 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2960 return true;
2961 } else if (parseArrayVectorType(Result, true))
2962 return true;
2963 break;
2964 case lltok::LocalVar: {
2965 // Type ::= %foo
2966 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2967
2968 // If the type hasn't been defined yet, create a forward definition and
2969 // remember where that forward def'n was seen (in case it never is defined).
2970 if (!Entry.first) {
2971 Entry.first = StructType::create(Context, Lex.getStrVal());
2972 Entry.second = Lex.getLoc();
2973 }
2974 Result = Entry.first;
2975 Lex.Lex();
2976 break;
2977 }
2978
2979 case lltok::LocalVarID: {
2980 // Type ::= %4
2981 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2982
2983 // If the type hasn't been defined yet, create a forward definition and
2984 // remember where that forward def'n was seen (in case it never is defined).
2985 if (!Entry.first) {
2986 Entry.first = StructType::create(Context);
2987 Entry.second = Lex.getLoc();
2988 }
2989 Result = Entry.first;
2990 Lex.Lex();
2991 break;
2992 }
2993 }
2994
2995 // parse the type suffixes.
2996 while (true) {
2997 switch (Lex.getKind()) {
2998 // End of type.
2999 default:
3000 if (!AllowVoid && Result->isVoidTy())
3001 return error(TypeLoc, "void type only allowed for function results");
3002 return false;
3003
3004 // Type ::= Type '*'
3005 case lltok::star:
3006 if (Result->isLabelTy())
3007 return tokError("basic block pointers are invalid");
3008 if (Result->isVoidTy())
3009 return tokError("pointers to void are invalid - use i8* instead");
3011 return tokError("pointer to this type is invalid");
3012 Result = PointerType::getUnqual(Context);
3013 Lex.Lex();
3014 break;
3015
3016 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3017 case lltok::kw_addrspace: {
3018 if (Result->isLabelTy())
3019 return tokError("basic block pointers are invalid");
3020 if (Result->isVoidTy())
3021 return tokError("pointers to void are invalid; use i8* instead");
3023 return tokError("pointer to this type is invalid");
3024 unsigned AddrSpace;
3025 if (parseOptionalAddrSpace(AddrSpace) ||
3026 parseToken(lltok::star, "expected '*' in address space"))
3027 return true;
3028
3029 Result = PointerType::get(Context, AddrSpace);
3030 break;
3031 }
3032
3033 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3034 case lltok::lparen:
3035 if (parseFunctionType(Result))
3036 return true;
3037 break;
3038 }
3039 }
3040}
3041
3042/// parseParameterList
3043/// ::= '(' ')'
3044/// ::= '(' Arg (',' Arg)* ')'
3045/// Arg
3046/// ::= Type OptionalAttributes Value OptionalAttributes
3047bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3048 PerFunctionState &PFS, bool IsMustTailCall,
3049 bool InVarArgsFunc) {
3050 if (parseToken(lltok::lparen, "expected '(' in call"))
3051 return true;
3052
3053 while (Lex.getKind() != lltok::rparen) {
3054 // If this isn't the first argument, we need a comma.
3055 if (!ArgList.empty() &&
3056 parseToken(lltok::comma, "expected ',' in argument list"))
3057 return true;
3058
3059 // parse an ellipsis if this is a musttail call in a variadic function.
3060 if (Lex.getKind() == lltok::dotdotdot) {
3061 const char *Msg = "unexpected ellipsis in argument list for ";
3062 if (!IsMustTailCall)
3063 return tokError(Twine(Msg) + "non-musttail call");
3064 if (!InVarArgsFunc)
3065 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3066 Lex.Lex(); // Lex the '...', it is purely for readability.
3067 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3068 }
3069
3070 // parse the argument.
3071 LocTy ArgLoc;
3072 Type *ArgTy = nullptr;
3073 Value *V;
3074 if (parseType(ArgTy, ArgLoc))
3075 return true;
3077 return error(ArgLoc, "invalid type for function argument");
3078
3079 AttrBuilder ArgAttrs(M->getContext());
3080
3081 if (ArgTy->isMetadataTy()) {
3082 if (parseMetadataAsValue(V, PFS))
3083 return true;
3084 } else {
3085 // Otherwise, handle normal operands.
3086 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3087 return true;
3088 }
3089 ArgList.push_back(ParamInfo(
3090 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3091 }
3092
3093 if (IsMustTailCall && InVarArgsFunc)
3094 return tokError("expected '...' at end of argument list for musttail call "
3095 "in varargs function");
3096
3097 Lex.Lex(); // Lex the ')'.
3098 return false;
3099}
3100
3101/// parseRequiredTypeAttr
3102/// ::= attrname(<ty>)
3103bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3104 Attribute::AttrKind AttrKind) {
3105 Type *Ty = nullptr;
3106 if (!EatIfPresent(AttrToken))
3107 return true;
3108 if (!EatIfPresent(lltok::lparen))
3109 return error(Lex.getLoc(), "expected '('");
3110 if (parseType(Ty))
3111 return true;
3112 if (!EatIfPresent(lltok::rparen))
3113 return error(Lex.getLoc(), "expected ')'");
3114
3115 B.addTypeAttr(AttrKind, Ty);
3116 return false;
3117}
3118
3119/// parseRangeAttr
3120/// ::= range(<ty> <n>,<n>)
3121bool LLParser::parseRangeAttr(AttrBuilder &B) {
3122 Lex.Lex();
3123
3124 APInt Lower;
3125 APInt Upper;
3126 Type *Ty = nullptr;
3127 LocTy TyLoc;
3128
3129 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3130 if (Lex.getKind() != lltok::APSInt)
3131 return tokError("expected integer");
3132 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3133 return tokError(
3134 "integer is too large for the bit width of specified type");
3135 Val = Lex.getAPSIntVal().extend(BitWidth);
3136 Lex.Lex();
3137 return false;
3138 };
3139
3140 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3141 return true;
3142 if (!Ty->isIntegerTy())
3143 return error(TyLoc, "the range must have integer type!");
3144
3145 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3146
3147 if (ParseAPSInt(BitWidth, Lower) ||
3148 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3149 return true;
3150 if (Lower == Upper && !Lower.isZero())
3151 return tokError("the range represent the empty set but limits aren't 0!");
3152
3153 if (parseToken(lltok::rparen, "expected ')'"))
3154 return true;
3155
3156 B.addRangeAttr(ConstantRange(Lower, Upper));
3157 return false;
3158}
3159
3160/// parseInitializesAttr
3161/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3162bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3163 Lex.Lex();
3164
3165 auto ParseAPSInt = [&](APInt &Val) {
3166 if (Lex.getKind() != lltok::APSInt)
3167 return tokError("expected integer");
3168 Val = Lex.getAPSIntVal().extend(64);
3169 Lex.Lex();
3170 return false;
3171 };
3172
3173 if (parseToken(lltok::lparen, "expected '('"))
3174 return true;
3175
3177 // Parse each constant range.
3178 do {
3179 APInt Lower, Upper;
3180 if (parseToken(lltok::lparen, "expected '('"))
3181 return true;
3182
3183 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3184 ParseAPSInt(Upper))
3185 return true;
3186
3187 if (Lower == Upper)
3188 return tokError("the range should not represent the full or empty set!");
3189
3190 if (parseToken(lltok::rparen, "expected ')'"))
3191 return true;
3192
3193 RangeList.push_back(ConstantRange(Lower, Upper));
3194 } while (EatIfPresent(lltok::comma));
3195
3196 if (parseToken(lltok::rparen, "expected ')'"))
3197 return true;
3198
3199 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3200 if (!CRLOrNull.has_value())
3201 return tokError("Invalid (unordered or overlapping) range list");
3202 B.addInitializesAttr(*CRLOrNull);
3203 return false;
3204}
3205
3206bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3208 std::optional<CaptureComponents> Ret;
3209
3210 // We use syntax like captures(ret: address, provenance), so the colon
3211 // should not be interpreted as a label terminator.
3212 Lex.setIgnoreColonInIdentifiers(true);
3213 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
3214
3215 Lex.Lex();
3216 if (parseToken(lltok::lparen, "expected '('"))
3217 return true;
3218
3219 CaptureComponents *Current = &Other;
3220 bool SeenComponent = false;
3221 while (true) {
3222 if (EatIfPresent(lltok::kw_ret)) {
3223 if (parseToken(lltok::colon, "expected ':'"))
3224 return true;
3225 if (Ret)
3226 return tokError("duplicate 'ret' location");
3228 Current = &*Ret;
3229 SeenComponent = false;
3230 }
3231
3232 if (EatIfPresent(lltok::kw_none)) {
3233 if (SeenComponent)
3234 return tokError("cannot use 'none' with other component");
3235 *Current = CaptureComponents::None;
3236 } else {
3237 if (SeenComponent && capturesNothing(*Current))
3238 return tokError("cannot use 'none' with other component");
3239
3240 if (EatIfPresent(lltok::kw_address_is_null))
3242 else if (EatIfPresent(lltok::kw_address))
3243 *Current |= CaptureComponents::Address;
3244 else if (EatIfPresent(lltok::kw_provenance))
3246 else if (EatIfPresent(lltok::kw_read_provenance))
3248 else
3249 return tokError("expected one of 'none', 'address', 'address_is_null', "
3250 "'provenance' or 'read_provenance'");
3251 }
3252
3253 SeenComponent = true;
3254 if (EatIfPresent(lltok::rparen))
3255 break;
3256
3257 if (parseToken(lltok::comma, "expected ',' or ')'"))
3258 return true;
3259 }
3260
3261 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3262 return false;
3263}
3264
3265/// parseOptionalOperandBundles
3266/// ::= /*empty*/
3267/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3268///
3269/// OperandBundle
3270/// ::= bundle-tag '(' ')'
3271/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3272///
3273/// bundle-tag ::= String Constant
3274bool LLParser::parseOptionalOperandBundles(
3275 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3276 LocTy BeginLoc = Lex.getLoc();
3277 if (!EatIfPresent(lltok::lsquare))
3278 return false;
3279
3280 while (Lex.getKind() != lltok::rsquare) {
3281 // If this isn't the first operand bundle, we need a comma.
3282 if (!BundleList.empty() &&
3283 parseToken(lltok::comma, "expected ',' in input list"))
3284 return true;
3285
3286 std::string Tag;
3287 if (parseStringConstant(Tag))
3288 return true;
3289
3290 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3291 return true;
3292
3293 std::vector<Value *> Inputs;
3294 while (Lex.getKind() != lltok::rparen) {
3295 // If this isn't the first input, we need a comma.
3296 if (!Inputs.empty() &&
3297 parseToken(lltok::comma, "expected ',' in input list"))
3298 return true;
3299
3300 Type *Ty = nullptr;
3301 Value *Input = nullptr;
3302 if (parseType(Ty))
3303 return true;
3304 if (Ty->isMetadataTy()) {
3305 if (parseMetadataAsValue(Input, PFS))
3306 return true;
3307 } else if (parseValue(Ty, Input, PFS)) {
3308 return true;
3309 }
3310 Inputs.push_back(Input);
3311 }
3312
3313 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3314
3315 Lex.Lex(); // Lex the ')'.
3316 }
3317
3318 if (BundleList.empty())
3319 return error(BeginLoc, "operand bundle set must not be empty");
3320
3321 Lex.Lex(); // Lex the ']'.
3322 return false;
3323}
3324
3325bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3326 unsigned NextID, unsigned ID) {
3327 if (ID < NextID)
3328 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3329 Twine(NextID) + "' or greater");
3330
3331 return false;
3332}
3333
3334/// parseArgumentList - parse the argument list for a function type or function
3335/// prototype.
3336/// ::= '(' ArgTypeListI ')'
3337/// ArgTypeListI
3338/// ::= /*empty*/
3339/// ::= '...'
3340/// ::= ArgTypeList ',' '...'
3341/// ::= ArgType (',' ArgType)*
3342///
3343bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3344 SmallVectorImpl<unsigned> &UnnamedArgNums,
3345 bool &IsVarArg) {
3346 unsigned CurValID = 0;
3347 IsVarArg = false;
3348 assert(Lex.getKind() == lltok::lparen);
3349 Lex.Lex(); // eat the (.
3350
3351 if (Lex.getKind() != lltok::rparen) {
3352 do {
3353 // Handle ... at end of arg list.
3354 if (EatIfPresent(lltok::dotdotdot)) {
3355 IsVarArg = true;
3356 break;
3357 }
3358
3359 // Otherwise must be an argument type.
3360 LocTy TypeLoc = Lex.getLoc();
3361 Type *ArgTy = nullptr;
3362 AttrBuilder Attrs(M->getContext());
3363 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3364 return true;
3365
3366 if (ArgTy->isVoidTy())
3367 return error(TypeLoc, "argument can not have void type");
3368
3369 std::string Name;
3370 if (Lex.getKind() == lltok::LocalVar) {
3371 Name = Lex.getStrVal();
3372 Lex.Lex();
3373 } else {
3374 unsigned ArgID;
3375 if (Lex.getKind() == lltok::LocalVarID) {
3376 ArgID = Lex.getUIntVal();
3377 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3378 return true;
3379 Lex.Lex();
3380 } else {
3381 ArgID = CurValID;
3382 }
3383 UnnamedArgNums.push_back(ArgID);
3384 CurValID = ArgID + 1;
3385 }
3386
3388 return error(TypeLoc, "invalid type for function argument");
3389
3390 ArgList.emplace_back(TypeLoc, ArgTy,
3391 AttributeSet::get(ArgTy->getContext(), Attrs),
3392 std::move(Name));
3393 } while (EatIfPresent(lltok::comma));
3394 }
3395
3396 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3397}
3398
3399/// parseFunctionType
3400/// ::= Type ArgumentList OptionalAttrs
3401bool LLParser::parseFunctionType(Type *&Result) {
3402 assert(Lex.getKind() == lltok::lparen);
3403
3405 return tokError("invalid function return type");
3406
3408 bool IsVarArg;
3409 SmallVector<unsigned> UnnamedArgNums;
3410 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3411 return true;
3412
3413 // Reject names on the arguments lists.
3414 for (const ArgInfo &Arg : ArgList) {
3415 if (!Arg.Name.empty())
3416 return error(Arg.Loc, "argument name invalid in function type");
3417 if (Arg.Attrs.hasAttributes())
3418 return error(Arg.Loc, "argument attributes invalid in function type");
3419 }
3420
3421 SmallVector<Type*, 16> ArgListTy;
3422 for (const ArgInfo &Arg : ArgList)
3423 ArgListTy.push_back(Arg.Ty);
3424
3425 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3426 return false;
3427}
3428
3429/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3430/// other structs.
3431bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3433 if (parseStructBody(Elts))
3434 return true;
3435
3436 Result = StructType::get(Context, Elts, Packed);
3437 return false;
3438}
3439
3440/// parseStructDefinition - parse a struct in a 'type' definition.
3441bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3442 std::pair<Type *, LocTy> &Entry,
3443 Type *&ResultTy) {
3444 // If the type was already defined, diagnose the redefinition.
3445 if (Entry.first && !Entry.second.isValid())
3446 return error(TypeLoc, "redefinition of type");
3447
3448 // If we have opaque, just return without filling in the definition for the
3449 // struct. This counts as a definition as far as the .ll file goes.
3450 if (EatIfPresent(lltok::kw_opaque)) {
3451 // This type is being defined, so clear the location to indicate this.
3452 Entry.second = SMLoc();
3453
3454 // If this type number has never been uttered, create it.
3455 if (!Entry.first)
3456 Entry.first = StructType::create(Context, Name);
3457 ResultTy = Entry.first;
3458 return false;
3459 }
3460
3461 // If the type starts with '<', then it is either a packed struct or a vector.
3462 bool isPacked = EatIfPresent(lltok::less);
3463
3464 // If we don't have a struct, then we have a random type alias, which we
3465 // accept for compatibility with old files. These types are not allowed to be
3466 // forward referenced and not allowed to be recursive.
3467 if (Lex.getKind() != lltok::lbrace) {
3468 if (Entry.first)
3469 return error(TypeLoc, "forward references to non-struct type");
3470
3471 ResultTy = nullptr;
3472 if (isPacked)
3473 return parseArrayVectorType(ResultTy, true);
3474 return parseType(ResultTy);
3475 }
3476
3477 // This type is being defined, so clear the location to indicate this.
3478 Entry.second = SMLoc();
3479
3480 // If this type number has never been uttered, create it.
3481 if (!Entry.first)
3482 Entry.first = StructType::create(Context, Name);
3483
3484 StructType *STy = cast<StructType>(Entry.first);
3485
3487 if (parseStructBody(Body) ||
3488 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3489 return true;
3490
3491 if (auto E = STy->setBodyOrError(Body, isPacked))
3492 return tokError(toString(std::move(E)));
3493
3494 ResultTy = STy;
3495 return false;
3496}
3497
3498/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3499/// StructType
3500/// ::= '{' '}'
3501/// ::= '{' Type (',' Type)* '}'
3502/// ::= '<' '{' '}' '>'
3503/// ::= '<' '{' Type (',' Type)* '}' '>'
3504bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3505 assert(Lex.getKind() == lltok::lbrace);
3506 Lex.Lex(); // Consume the '{'
3507
3508 // Handle the empty struct.
3509 if (EatIfPresent(lltok::rbrace))
3510 return false;
3511
3512 LocTy EltTyLoc = Lex.getLoc();
3513 Type *Ty = nullptr;
3514 if (parseType(Ty))
3515 return true;
3516 Body.push_back(Ty);
3517
3519 return error(EltTyLoc, "invalid element type for struct");
3520
3521 while (EatIfPresent(lltok::comma)) {
3522 EltTyLoc = Lex.getLoc();
3523 if (parseType(Ty))
3524 return true;
3525
3527 return error(EltTyLoc, "invalid element type for struct");
3528
3529 Body.push_back(Ty);
3530 }
3531
3532 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3533}
3534
3535/// parseArrayVectorType - parse an array or vector type, assuming the first
3536/// token has already been consumed.
3537/// Type
3538/// ::= '[' APSINTVAL 'x' Types ']'
3539/// ::= '<' APSINTVAL 'x' Types '>'
3540/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3541bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3542 bool Scalable = false;
3543
3544 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3545 Lex.Lex(); // consume the 'vscale'
3546 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3547 return true;
3548
3549 Scalable = true;
3550 }
3551
3552 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3553 Lex.getAPSIntVal().getBitWidth() > 64)
3554 return tokError("expected number in address space");
3555
3556 LocTy SizeLoc = Lex.getLoc();
3557 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3558 Lex.Lex();
3559
3560 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3561 return true;
3562
3563 LocTy TypeLoc = Lex.getLoc();
3564 Type *EltTy = nullptr;
3565 if (parseType(EltTy))
3566 return true;
3567
3568 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3569 "expected end of sequential type"))
3570 return true;
3571
3572 if (IsVector) {
3573 if (Size == 0)
3574 return error(SizeLoc, "zero element vector is illegal");
3575 if ((unsigned)Size != Size)
3576 return error(SizeLoc, "size too large for vector");
3578 return error(TypeLoc, "invalid vector element type");
3579 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3580 } else {
3582 return error(TypeLoc, "invalid array element type");
3583 Result = ArrayType::get(EltTy, Size);
3584 }
3585 return false;
3586}
3587
3588/// parseTargetExtType - handle target extension type syntax
3589/// TargetExtType
3590/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3591///
3592/// TargetExtTypeParams
3593/// ::= /*empty*/
3594/// ::= ',' Type TargetExtTypeParams
3595///
3596/// TargetExtIntParams
3597/// ::= /*empty*/
3598/// ::= ',' uint32 TargetExtIntParams
3599bool LLParser::parseTargetExtType(Type *&Result) {
3600 Lex.Lex(); // Eat the 'target' keyword.
3601
3602 // Get the mandatory type name.
3603 std::string TypeName;
3604 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3605 parseStringConstant(TypeName))
3606 return true;
3607
3608 // Parse all of the integer and type parameters at the same time; the use of
3609 // SeenInt will allow us to catch cases where type parameters follow integer
3610 // parameters.
3611 SmallVector<Type *> TypeParams;
3612 SmallVector<unsigned> IntParams;
3613 bool SeenInt = false;
3614 while (Lex.getKind() == lltok::comma) {
3615 Lex.Lex(); // Eat the comma.
3616
3617 if (Lex.getKind() == lltok::APSInt) {
3618 SeenInt = true;
3619 unsigned IntVal;
3620 if (parseUInt32(IntVal))
3621 return true;
3622 IntParams.push_back(IntVal);
3623 } else if (SeenInt) {
3624 // The only other kind of parameter we support is type parameters, which
3625 // must precede the integer parameters. This is therefore an error.
3626 return tokError("expected uint32 param");
3627 } else {
3628 Type *TypeParam;
3629 if (parseType(TypeParam, /*AllowVoid=*/true))
3630 return true;
3631 TypeParams.push_back(TypeParam);
3632 }
3633 }
3634
3635 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3636 return true;
3637
3638 auto TTy =
3639 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3640 if (auto E = TTy.takeError())
3641 return tokError(toString(std::move(E)));
3642
3643 Result = *TTy;
3644 return false;
3645}
3646
3647//===----------------------------------------------------------------------===//
3648// Function Semantic Analysis.
3649//===----------------------------------------------------------------------===//
3650
3651LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3652 int functionNumber,
3653 ArrayRef<unsigned> UnnamedArgNums)
3654 : P(p), F(f), FunctionNumber(functionNumber) {
3655
3656 // Insert unnamed arguments into the NumberedVals list.
3657 auto It = UnnamedArgNums.begin();
3658 for (Argument &A : F.args()) {
3659 if (!A.hasName()) {
3660 unsigned ArgNum = *It++;
3661 NumberedVals.add(ArgNum, &A);
3662 }
3663 }
3664}
3665
3666LLParser::PerFunctionState::~PerFunctionState() {
3667 // If there were any forward referenced non-basicblock values, delete them.
3668
3669 for (const auto &P : ForwardRefVals) {
3670 if (isa<BasicBlock>(P.second.first))
3671 continue;
3672 P.second.first->replaceAllUsesWith(
3673 PoisonValue::get(P.second.first->getType()));
3674 P.second.first->deleteValue();
3675 }
3676
3677 for (const auto &P : ForwardRefValIDs) {
3678 if (isa<BasicBlock>(P.second.first))
3679 continue;
3680 P.second.first->replaceAllUsesWith(
3681 PoisonValue::get(P.second.first->getType()));
3682 P.second.first->deleteValue();
3683 }
3684}
3685
3686bool LLParser::PerFunctionState::finishFunction() {
3687 if (!ForwardRefVals.empty())
3688 return P.error(ForwardRefVals.begin()->second.second,
3689 "use of undefined value '%" + ForwardRefVals.begin()->first +
3690 "'");
3691 if (!ForwardRefValIDs.empty())
3692 return P.error(ForwardRefValIDs.begin()->second.second,
3693 "use of undefined value '%" +
3694 Twine(ForwardRefValIDs.begin()->first) + "'");
3695 return false;
3696}
3697
3698/// getVal - Get a value with the specified name or ID, creating a
3699/// forward reference record if needed. This can return null if the value
3700/// exists but does not have the right type.
3701Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3702 LocTy Loc) {
3703 // Look this name up in the normal function symbol table.
3704 Value *Val = F.getValueSymbolTable()->lookup(Name);
3705
3706 // If this is a forward reference for the value, see if we already created a
3707 // forward ref record.
3708 if (!Val) {
3709 auto I = ForwardRefVals.find(Name);
3710 if (I != ForwardRefVals.end())
3711 Val = I->second.first;
3712 }
3713
3714 // If we have the value in the symbol table or fwd-ref table, return it.
3715 if (Val)
3716 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3717
3718 // Don't make placeholders with invalid type.
3719 if (!Ty->isFirstClassType()) {
3720 P.error(Loc, "invalid use of a non-first-class type");
3721 return nullptr;
3722 }
3723
3724 // Otherwise, create a new forward reference for this value and remember it.
3725 Value *FwdVal;
3726 if (Ty->isLabelTy()) {
3727 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3728 } else {
3729 FwdVal = new Argument(Ty, Name);
3730 }
3731 if (FwdVal->getName() != Name) {
3732 P.error(Loc, "name is too long which can result in name collisions, "
3733 "consider making the name shorter or "
3734 "increasing -non-global-value-max-name-size");
3735 return nullptr;
3736 }
3737
3738 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3739 return FwdVal;
3740}
3741
3742Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3743 // Look this name up in the normal function symbol table.
3744 Value *Val = NumberedVals.get(ID);
3745
3746 // If this is a forward reference for the value, see if we already created a
3747 // forward ref record.
3748 if (!Val) {
3749 auto I = ForwardRefValIDs.find(ID);
3750 if (I != ForwardRefValIDs.end())
3751 Val = I->second.first;
3752 }
3753
3754 // If we have the value in the symbol table or fwd-ref table, return it.
3755 if (Val)
3756 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3757
3758 if (!Ty->isFirstClassType()) {
3759 P.error(Loc, "invalid use of a non-first-class type");
3760 return nullptr;
3761 }
3762
3763 // Otherwise, create a new forward reference for this value and remember it.
3764 Value *FwdVal;
3765 if (Ty->isLabelTy()) {
3766 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3767 } else {
3768 FwdVal = new Argument(Ty);
3769 }
3770
3771 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3772 return FwdVal;
3773}
3774
3775/// setInstName - After an instruction is parsed and inserted into its
3776/// basic block, this installs its name.
3777bool LLParser::PerFunctionState::setInstName(int NameID,
3778 const std::string &NameStr,
3779 LocTy NameLoc, Instruction *Inst) {
3780 // If this instruction has void type, it cannot have a name or ID specified.
3781 if (Inst->getType()->isVoidTy()) {
3782 if (NameID != -1 || !NameStr.empty())
3783 return P.error(NameLoc, "instructions returning void cannot have a name");
3784 return false;
3785 }
3786
3787 // If this was a numbered instruction, verify that the instruction is the
3788 // expected value and resolve any forward references.
3789 if (NameStr.empty()) {
3790 // If neither a name nor an ID was specified, just use the next ID.
3791 if (NameID == -1)
3792 NameID = NumberedVals.getNext();
3793
3794 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3795 NameID))
3796 return true;
3797
3798 auto FI = ForwardRefValIDs.find(NameID);
3799 if (FI != ForwardRefValIDs.end()) {
3800 Value *Sentinel = FI->second.first;
3801 if (Sentinel->getType() != Inst->getType())
3802 return P.error(NameLoc, "instruction forward referenced with type '" +
3803 getTypeString(FI->second.first->getType()) +
3804 "'");
3805
3806 Sentinel->replaceAllUsesWith(Inst);
3807 Sentinel->deleteValue();
3808 ForwardRefValIDs.erase(FI);
3809 }
3810
3811 NumberedVals.add(NameID, Inst);
3812 return false;
3813 }
3814
3815 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3816 auto FI = ForwardRefVals.find(NameStr);
3817 if (FI != ForwardRefVals.end()) {
3818 Value *Sentinel = FI->second.first;
3819 if (Sentinel->getType() != Inst->getType())
3820 return P.error(NameLoc, "instruction forward referenced with type '" +
3821 getTypeString(FI->second.first->getType()) +
3822 "'");
3823
3824 Sentinel->replaceAllUsesWith(Inst);
3825 Sentinel->deleteValue();
3826 ForwardRefVals.erase(FI);
3827 }
3828
3829 // Set the name on the instruction.
3830 Inst->setName(NameStr);
3831
3832 if (Inst->getName() != NameStr)
3833 return P.error(NameLoc, "multiple definition of local value named '" +
3834 NameStr + "'");
3835 return false;
3836}
3837
3838/// getBB - Get a basic block with the specified name or ID, creating a
3839/// forward reference record if needed.
3840BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3841 LocTy Loc) {
3843 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3844}
3845
3846BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3848 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3849}
3850
3851/// defineBB - Define the specified basic block, which is either named or
3852/// unnamed. If there is an error, this returns null otherwise it returns
3853/// the block being defined.
3854BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3855 int NameID, LocTy Loc) {
3856 BasicBlock *BB;
3857 if (Name.empty()) {
3858 if (NameID != -1) {
3859 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3860 return nullptr;
3861 } else {
3862 NameID = NumberedVals.getNext();
3863 }
3864 BB = getBB(NameID, Loc);
3865 if (!BB) {
3866 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3867 return nullptr;
3868 }
3869 } else {
3870 BB = getBB(Name, Loc);
3871 if (!BB) {
3872 P.error(Loc, "unable to create block named '" + Name + "'");
3873 return nullptr;
3874 }
3875 }
3876
3877 // Move the block to the end of the function. Forward ref'd blocks are
3878 // inserted wherever they happen to be referenced.
3879 F.splice(F.end(), &F, BB->getIterator());
3880
3881 // Remove the block from forward ref sets.
3882 if (Name.empty()) {
3883 ForwardRefValIDs.erase(NameID);
3884 NumberedVals.add(NameID, BB);
3885 } else {
3886 // BB forward references are already in the function symbol table.
3887 ForwardRefVals.erase(Name);
3888 }
3889
3890 return BB;
3891}
3892
3893//===----------------------------------------------------------------------===//
3894// Constants.
3895//===----------------------------------------------------------------------===//
3896
3897/// parseValID - parse an abstract value that doesn't necessarily have a
3898/// type implied. For example, if we parse "4" we don't know what integer type
3899/// it has. The value will later be combined with its type and checked for
3900/// basic correctness. PFS is used to convert function-local operands of
3901/// metadata (since metadata operands are not just parsed here but also
3902/// converted to values). PFS can be null when we are not parsing metadata
3903/// values inside a function.
3904bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3905 ID.Loc = Lex.getLoc();
3906 switch (Lex.getKind()) {
3907 default:
3908 return tokError("expected value token");
3909 case lltok::GlobalID: // @42
3910 ID.UIntVal = Lex.getUIntVal();
3911 ID.Kind = ValID::t_GlobalID;
3912 break;
3913 case lltok::GlobalVar: // @foo
3914 ID.StrVal = Lex.getStrVal();
3915 ID.Kind = ValID::t_GlobalName;
3916 break;
3917 case lltok::LocalVarID: // %42
3918 ID.UIntVal = Lex.getUIntVal();
3919 ID.Kind = ValID::t_LocalID;
3920 break;
3921 case lltok::LocalVar: // %foo
3922 ID.StrVal = Lex.getStrVal();
3923 ID.Kind = ValID::t_LocalName;
3924 break;
3925 case lltok::APSInt:
3926 ID.APSIntVal = Lex.getAPSIntVal();
3927 ID.Kind = ValID::t_APSInt;
3928 break;
3929 case lltok::APFloat:
3930 ID.APFloatVal = Lex.getAPFloatVal();
3931 ID.Kind = ValID::t_APFloat;
3932 break;
3933 case lltok::kw_true:
3934 ID.ConstantVal = ConstantInt::getTrue(Context);
3935 ID.Kind = ValID::t_Constant;
3936 break;
3937 case lltok::kw_false:
3938 ID.ConstantVal = ConstantInt::getFalse(Context);
3939 ID.Kind = ValID::t_Constant;
3940 break;
3941 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3942 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3943 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3944 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3945 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3946
3947 case lltok::lbrace: {
3948 // ValID ::= '{' ConstVector '}'
3949 Lex.Lex();
3951 if (parseGlobalValueVector(Elts) ||
3952 parseToken(lltok::rbrace, "expected end of struct constant"))
3953 return true;
3954
3955 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3956 ID.UIntVal = Elts.size();
3957 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3958 Elts.size() * sizeof(Elts[0]));
3960 return false;
3961 }
3962 case lltok::less: {
3963 // ValID ::= '<' ConstVector '>' --> Vector.
3964 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3965 Lex.Lex();
3966 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3967
3969 LocTy FirstEltLoc = Lex.getLoc();
3970 if (parseGlobalValueVector(Elts) ||
3971 (isPackedStruct &&
3972 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3973 parseToken(lltok::greater, "expected end of constant"))
3974 return true;
3975
3976 if (isPackedStruct) {
3977 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3978 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3979 Elts.size() * sizeof(Elts[0]));
3980 ID.UIntVal = Elts.size();
3982 return false;
3983 }
3984
3985 if (Elts.empty())
3986 return error(ID.Loc, "constant vector must not be empty");
3987
3988 if (!Elts[0]->getType()->isIntegerTy() &&
3989 !Elts[0]->getType()->isFloatingPointTy() &&
3990 !Elts[0]->getType()->isPointerTy())
3991 return error(
3992 FirstEltLoc,
3993 "vector elements must have integer, pointer or floating point type");
3994
3995 // Verify that all the vector elements have the same type.
3996 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3997 if (Elts[i]->getType() != Elts[0]->getType())
3998 return error(FirstEltLoc, "vector element #" + Twine(i) +
3999 " is not of type '" +
4000 getTypeString(Elts[0]->getType()));
4001
4002 ID.ConstantVal = ConstantVector::get(Elts);
4003 ID.Kind = ValID::t_Constant;
4004 return false;
4005 }
4006 case lltok::lsquare: { // Array Constant
4007 Lex.Lex();
4009 LocTy FirstEltLoc = Lex.getLoc();
4010 if (parseGlobalValueVector(Elts) ||
4011 parseToken(lltok::rsquare, "expected end of array constant"))
4012 return true;
4013
4014 // Handle empty element.
4015 if (Elts.empty()) {
4016 // Use undef instead of an array because it's inconvenient to determine
4017 // the element type at this point, there being no elements to examine.
4018 ID.Kind = ValID::t_EmptyArray;
4019 return false;
4020 }
4021
4022 if (!Elts[0]->getType()->isFirstClassType())
4023 return error(FirstEltLoc, "invalid array element type: " +
4024 getTypeString(Elts[0]->getType()));
4025
4026 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4027
4028 // Verify all elements are correct type!
4029 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4030 if (Elts[i]->getType() != Elts[0]->getType())
4031 return error(FirstEltLoc, "array element #" + Twine(i) +
4032 " is not of type '" +
4033 getTypeString(Elts[0]->getType()));
4034 }
4035
4036 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4037 ID.Kind = ValID::t_Constant;
4038 return false;
4039 }
4040 case lltok::kw_c: // c "foo"
4041 Lex.Lex();
4042 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4043 false);
4044 if (parseToken(lltok::StringConstant, "expected string"))
4045 return true;
4046 ID.Kind = ValID::t_Constant;
4047 return false;
4048
4049 case lltok::kw_asm: {
4050 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4051 // STRINGCONSTANT
4052 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4053 Lex.Lex();
4054 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4055 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4056 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4057 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4058 parseStringConstant(ID.StrVal) ||
4059 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4060 parseToken(lltok::StringConstant, "expected constraint string"))
4061 return true;
4062 ID.StrVal2 = Lex.getStrVal();
4063 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4064 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4065 ID.Kind = ValID::t_InlineAsm;
4066 return false;
4067 }
4068
4070 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4071 Lex.Lex();
4072
4073 ValID Fn, Label;
4074
4075 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4076 parseValID(Fn, PFS) ||
4077 parseToken(lltok::comma,
4078 "expected comma in block address expression") ||
4079 parseValID(Label, PFS) ||
4080 parseToken(lltok::rparen, "expected ')' in block address expression"))
4081 return true;
4082
4084 return error(Fn.Loc, "expected function name in blockaddress");
4085 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4086 return error(Label.Loc, "expected basic block name in blockaddress");
4087
4088 // Try to find the function (but skip it if it's forward-referenced).
4089 GlobalValue *GV = nullptr;
4090 if (Fn.Kind == ValID::t_GlobalID) {
4091 GV = NumberedVals.get(Fn.UIntVal);
4092 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4093 GV = M->getNamedValue(Fn.StrVal);
4094 }
4095 Function *F = nullptr;
4096 if (GV) {
4097 // Confirm that it's actually a function with a definition.
4098 if (!isa<Function>(GV))
4099 return error(Fn.Loc, "expected function name in blockaddress");
4100 F = cast<Function>(GV);
4101 if (F->isDeclaration())
4102 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4103 }
4104
4105 if (!F) {
4106 // Make a global variable as a placeholder for this reference.
4107 GlobalValue *&FwdRef =
4108 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4109 if (!FwdRef) {
4110 unsigned FwdDeclAS;
4111 if (ExpectedTy) {
4112 // If we know the type that the blockaddress is being assigned to,
4113 // we can use the address space of that type.
4114 if (!ExpectedTy->isPointerTy())
4115 return error(ID.Loc,
4116 "type of blockaddress must be a pointer and not '" +
4117 getTypeString(ExpectedTy) + "'");
4118 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4119 } else if (PFS) {
4120 // Otherwise, we default the address space of the current function.
4121 FwdDeclAS = PFS->getFunction().getAddressSpace();
4122 } else {
4123 llvm_unreachable("Unknown address space for blockaddress");
4124 }
4125 FwdRef = new GlobalVariable(
4126 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4127 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4128 }
4129
4130 ID.ConstantVal = FwdRef;
4131 ID.Kind = ValID::t_Constant;
4132 return false;
4133 }
4134
4135 // We found the function; now find the basic block. Don't use PFS, since we
4136 // might be inside a constant expression.
4137 BasicBlock *BB;
4138 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4139 if (Label.Kind == ValID::t_LocalID)
4140 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4141 else
4142 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4143 if (!BB)
4144 return error(Label.Loc, "referenced value is not a basic block");
4145 } else {
4146 if (Label.Kind == ValID::t_LocalID)
4147 return error(Label.Loc, "cannot take address of numeric label after "
4148 "the function is defined");
4150 F->getValueSymbolTable()->lookup(Label.StrVal));
4151 if (!BB)
4152 return error(Label.Loc, "referenced value is not a basic block");
4153 }
4154
4155 ID.ConstantVal = BlockAddress::get(F, BB);
4156 ID.Kind = ValID::t_Constant;
4157 return false;
4158 }
4159
4161 // ValID ::= 'dso_local_equivalent' @foo
4162 Lex.Lex();
4163
4164 ValID Fn;
4165
4166 if (parseValID(Fn, PFS))
4167 return true;
4168
4170 return error(Fn.Loc,
4171 "expected global value name in dso_local_equivalent");
4172
4173 // Try to find the function (but skip it if it's forward-referenced).
4174 GlobalValue *GV = nullptr;
4175 if (Fn.Kind == ValID::t_GlobalID) {
4176 GV = NumberedVals.get(Fn.UIntVal);
4177 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4178 GV = M->getNamedValue(Fn.StrVal);
4179 }
4180
4181 if (!GV) {
4182 // Make a placeholder global variable as a placeholder for this reference.
4183 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4184 ? ForwardRefDSOLocalEquivalentIDs
4185 : ForwardRefDSOLocalEquivalentNames;
4186 GlobalValue *&FwdRef = FwdRefMap[Fn];
4187 if (!FwdRef) {
4188 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4189 GlobalValue::InternalLinkage, nullptr, "",
4191 }
4192
4193 ID.ConstantVal = FwdRef;
4194 ID.Kind = ValID::t_Constant;
4195 return false;
4196 }
4197
4198 if (!GV->getValueType()->isFunctionTy())
4199 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4200 "in dso_local_equivalent");
4201
4202 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4203 ID.Kind = ValID::t_Constant;
4204 return false;
4205 }
4206
4207 case lltok::kw_no_cfi: {
4208 // ValID ::= 'no_cfi' @foo
4209 Lex.Lex();
4210
4211 if (parseValID(ID, PFS))
4212 return true;
4213
4214 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4215 return error(ID.Loc, "expected global value name in no_cfi");
4216
4217 ID.NoCFI = true;
4218 return false;
4219 }
4220 case lltok::kw_ptrauth: {
4221 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4222 // (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4223 Lex.Lex();
4224
4225 Constant *Ptr, *Key;
4226 Constant *Disc = nullptr, *AddrDisc = nullptr;
4227
4228 if (parseToken(lltok::lparen,
4229 "expected '(' in constant ptrauth expression") ||
4230 parseGlobalTypeAndValue(Ptr) ||
4231 parseToken(lltok::comma,
4232 "expected comma in constant ptrauth expression") ||
4233 parseGlobalTypeAndValue(Key))
4234 return true;
4235 // If present, parse the optional disc/addrdisc.
4236 if (EatIfPresent(lltok::comma))
4237 if (parseGlobalTypeAndValue(Disc) ||
4238 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4239 return true;
4240 if (parseToken(lltok::rparen,
4241 "expected ')' in constant ptrauth expression"))
4242 return true;
4243
4244 if (!Ptr->getType()->isPointerTy())
4245 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4246
4247 auto *KeyC = dyn_cast<ConstantInt>(Key);
4248 if (!KeyC || KeyC->getBitWidth() != 32)
4249 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4250
4251 ConstantInt *DiscC = nullptr;
4252 if (Disc) {
4253 DiscC = dyn_cast<ConstantInt>(Disc);
4254 if (!DiscC || DiscC->getBitWidth() != 64)
4255 return error(
4256 ID.Loc,
4257 "constant ptrauth integer discriminator must be i64 constant");
4258 } else {
4259 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4260 }
4261
4262 if (AddrDisc) {
4263 if (!AddrDisc->getType()->isPointerTy())
4264 return error(
4265 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4266 } else {
4267 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4268 }
4269
4270 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4271 ID.Kind = ValID::t_Constant;
4272 return false;
4273 }
4274
4275 case lltok::kw_trunc:
4276 case lltok::kw_bitcast:
4278 case lltok::kw_inttoptr:
4280 case lltok::kw_ptrtoint: {
4281 unsigned Opc = Lex.getUIntVal();
4282 Type *DestTy = nullptr;
4283 Constant *SrcVal;
4284 Lex.Lex();
4285 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4286 parseGlobalTypeAndValue(SrcVal) ||
4287 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4288 parseType(DestTy) ||
4289 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4290 return true;
4291 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4292 return error(ID.Loc, "invalid cast opcode for cast from '" +
4293 getTypeString(SrcVal->getType()) + "' to '" +
4294 getTypeString(DestTy) + "'");
4296 SrcVal, DestTy);
4297 ID.Kind = ValID::t_Constant;
4298 return false;
4299 }
4301 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4303 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4304 case lltok::kw_udiv:
4305 return error(ID.Loc, "udiv constexprs are no longer supported");
4306 case lltok::kw_sdiv:
4307 return error(ID.Loc, "sdiv constexprs are no longer supported");
4308 case lltok::kw_urem:
4309 return error(ID.Loc, "urem constexprs are no longer supported");
4310 case lltok::kw_srem:
4311 return error(ID.Loc, "srem constexprs are no longer supported");
4312 case lltok::kw_fadd:
4313 return error(ID.Loc, "fadd constexprs are no longer supported");
4314 case lltok::kw_fsub:
4315 return error(ID.Loc, "fsub constexprs are no longer supported");
4316 case lltok::kw_fmul:
4317 return error(ID.Loc, "fmul constexprs are no longer supported");
4318 case lltok::kw_fdiv:
4319 return error(ID.Loc, "fdiv constexprs are no longer supported");
4320 case lltok::kw_frem:
4321 return error(ID.Loc, "frem constexprs are no longer supported");
4322 case lltok::kw_and:
4323 return error(ID.Loc, "and constexprs are no longer supported");
4324 case lltok::kw_or:
4325 return error(ID.Loc, "or constexprs are no longer supported");
4326 case lltok::kw_lshr:
4327 return error(ID.Loc, "lshr constexprs are no longer supported");
4328 case lltok::kw_ashr:
4329 return error(ID.Loc, "ashr constexprs are no longer supported");
4330 case lltok::kw_shl:
4331 return error(ID.Loc, "shl constexprs are no longer supported");
4332 case lltok::kw_mul:
4333 return error(ID.Loc, "mul constexprs are no longer supported");
4334 case lltok::kw_fneg:
4335 return error(ID.Loc, "fneg constexprs are no longer supported");
4336 case lltok::kw_select:
4337 return error(ID.Loc, "select constexprs are no longer supported");
4338 case lltok::kw_zext:
4339 return error(ID.Loc, "zext constexprs are no longer supported");
4340 case lltok::kw_sext:
4341 return error(ID.Loc, "sext constexprs are no longer supported");
4342 case lltok::kw_fptrunc:
4343 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4344 case lltok::kw_fpext:
4345 return error(ID.Loc, "fpext constexprs are no longer supported");
4346 case lltok::kw_uitofp:
4347 return error(ID.Loc, "uitofp constexprs are no longer supported");
4348 case lltok::kw_sitofp:
4349 return error(ID.Loc, "sitofp constexprs are no longer supported");
4350 case lltok::kw_fptoui:
4351 return error(ID.Loc, "fptoui constexprs are no longer supported");
4352 case lltok::kw_fptosi:
4353 return error(ID.Loc, "fptosi constexprs are no longer supported");
4354 case lltok::kw_icmp:
4355 return error(ID.Loc, "icmp constexprs are no longer supported");
4356 case lltok::kw_fcmp:
4357 return error(ID.Loc, "fcmp constexprs are no longer supported");
4358
4359 // Binary Operators.
4360 case lltok::kw_add:
4361 case lltok::kw_sub:
4362 case lltok::kw_xor: {
4363 bool NUW = false;
4364 bool NSW = false;
4365 unsigned Opc = Lex.getUIntVal();
4366 Constant *Val0, *Val1;
4367 Lex.Lex();
4368 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4369 Opc == Instruction::Mul) {
4370 if (EatIfPresent(lltok::kw_nuw))
4371 NUW = true;
4372 if (EatIfPresent(lltok::kw_nsw)) {
4373 NSW = true;
4374 if (EatIfPresent(lltok::kw_nuw))
4375 NUW = true;
4376 }
4377 }
4378 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4379 parseGlobalTypeAndValue(Val0) ||
4380 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4381 parseGlobalTypeAndValue(Val1) ||
4382 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4383 return true;
4384 if (Val0->getType() != Val1->getType())
4385 return error(ID.Loc, "operands of constexpr must have same type");
4386 // Check that the type is valid for the operator.
4387 if (!Val0->getType()->isIntOrIntVectorTy())
4388 return error(ID.Loc,
4389 "constexpr requires integer or integer vector operands");
4390 unsigned Flags = 0;
4393 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4394 ID.Kind = ValID::t_Constant;
4395 return false;
4396 }
4397
4398 case lltok::kw_splat: {
4399 Lex.Lex();
4400 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4401 return true;
4402 Constant *C;
4403 if (parseGlobalTypeAndValue(C))
4404 return true;
4405 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4406 return true;
4407
4408 ID.ConstantVal = C;
4410 return false;
4411 }
4412
4417 unsigned Opc = Lex.getUIntVal();
4419 GEPNoWrapFlags NW;
4420 bool HasInRange = false;
4421 APSInt InRangeStart;
4422 APSInt InRangeEnd;
4423 Type *Ty;
4424 Lex.Lex();
4425
4426 if (Opc == Instruction::GetElementPtr) {
4427 while (true) {
4428 if (EatIfPresent(lltok::kw_inbounds))
4430 else if (EatIfPresent(lltok::kw_nusw))
4432 else if (EatIfPresent(lltok::kw_nuw))
4434 else
4435 break;
4436 }
4437
4438 if (EatIfPresent(lltok::kw_inrange)) {
4439 if (parseToken(lltok::lparen, "expected '('"))
4440 return true;
4441 if (Lex.getKind() != lltok::APSInt)
4442 return tokError("expected integer");
4443 InRangeStart = Lex.getAPSIntVal();
4444 Lex.Lex();
4445 if (parseToken(lltok::comma, "expected ','"))
4446 return true;
4447 if (Lex.getKind() != lltok::APSInt)
4448 return tokError("expected integer");
4449 InRangeEnd = Lex.getAPSIntVal();
4450 Lex.Lex();
4451 if (parseToken(lltok::rparen, "expected ')'"))
4452 return true;
4453 HasInRange = true;
4454 }
4455 }
4456
4457 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4458 return true;
4459
4460 if (Opc == Instruction::GetElementPtr) {
4461 if (parseType(Ty) ||
4462 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4463 return true;
4464 }
4465
4466 if (parseGlobalValueVector(Elts) ||
4467 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4468 return true;
4469
4470 if (Opc == Instruction::GetElementPtr) {
4471 if (Elts.size() == 0 ||
4472 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4473 return error(ID.Loc, "base of getelementptr must be a pointer");
4474
4475 Type *BaseType = Elts[0]->getType();
4476 std::optional<ConstantRange> InRange;
4477 if (HasInRange) {
4478 unsigned IndexWidth =
4479 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4480 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4481 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4482 if (InRangeStart.sge(InRangeEnd))
4483 return error(ID.Loc, "expected end to be larger than start");
4484 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4485 }
4486
4487 unsigned GEPWidth =
4488 BaseType->isVectorTy()
4489 ? cast<FixedVectorType>(BaseType)->getNumElements()
4490 : 0;
4491
4492 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4493 for (Constant *Val : Indices) {
4494 Type *ValTy = Val->getType();
4495 if (!ValTy->isIntOrIntVectorTy())
4496 return error(ID.Loc, "getelementptr index must be an integer");
4497 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4498 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4499 if (GEPWidth && (ValNumEl != GEPWidth))
4500 return error(
4501 ID.Loc,
4502 "getelementptr vector index has a wrong number of elements");
4503 // GEPWidth may have been unknown because the base is a scalar,
4504 // but it is known now.
4505 GEPWidth = ValNumEl;
4506 }
4507 }
4508
4509 SmallPtrSet<Type*, 4> Visited;
4510 if (!Indices.empty() && !Ty->isSized(&Visited))
4511 return error(ID.Loc, "base element of getelementptr must be sized");
4512
4513 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4514 return error(ID.Loc, "invalid getelementptr indices");
4515
4516 ID.ConstantVal =
4517 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4518 } else if (Opc == Instruction::ShuffleVector) {
4519 if (Elts.size() != 3)
4520 return error(ID.Loc, "expected three operands to shufflevector");
4521 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4522 return error(ID.Loc, "invalid operands to shufflevector");
4523 SmallVector<int, 16> Mask;
4525 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4526 } else if (Opc == Instruction::ExtractElement) {
4527 if (Elts.size() != 2)
4528 return error(ID.Loc, "expected two operands to extractelement");
4529 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4530 return error(ID.Loc, "invalid extractelement operands");
4531 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4532 } else {
4533 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4534 if (Elts.size() != 3)
4535 return error(ID.Loc, "expected three operands to insertelement");
4536 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4537 return error(ID.Loc, "invalid insertelement operands");
4538 ID.ConstantVal =
4539 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4540 }
4541
4542 ID.Kind = ValID::t_Constant;
4543 return false;
4544 }
4545 }
4546
4547 Lex.Lex();
4548 return false;
4549}
4550
4551/// parseGlobalValue - parse a global value with the specified type.
4552bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4553 C = nullptr;
4554 ValID ID;
4555 Value *V = nullptr;
4556 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4557 convertValIDToValue(Ty, ID, V, nullptr);
4558 if (V && !(C = dyn_cast<Constant>(V)))
4559 return error(ID.Loc, "global values must be constants");
4560 return Parsed;
4561}
4562
4563bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4564 Type *Ty = nullptr;
4565 return parseType(Ty) || parseGlobalValue(Ty, V);
4566}
4567
4568bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4569 C = nullptr;
4570
4571 LocTy KwLoc = Lex.getLoc();
4572 if (!EatIfPresent(lltok::kw_comdat))
4573 return false;
4574
4575 if (EatIfPresent(lltok::lparen)) {
4576 if (Lex.getKind() != lltok::ComdatVar)
4577 return tokError("expected comdat variable");
4578 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4579 Lex.Lex();
4580 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4581 return true;
4582 } else {
4583 if (GlobalName.empty())
4584 return tokError("comdat cannot be unnamed");
4585 C = getComdat(std::string(GlobalName), KwLoc);
4586 }
4587
4588 return false;
4589}
4590
4591/// parseGlobalValueVector
4592/// ::= /*empty*/
4593/// ::= TypeAndValue (',' TypeAndValue)*
4594bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4595 // Empty list.
4596 if (Lex.getKind() == lltok::rbrace ||
4597 Lex.getKind() == lltok::rsquare ||
4598 Lex.getKind() == lltok::greater ||
4599 Lex.getKind() == lltok::rparen)
4600 return false;
4601
4602 do {
4603 // Let the caller deal with inrange.
4604 if (Lex.getKind() == lltok::kw_inrange)
4605 return false;
4606
4607 Constant *C;
4608 if (parseGlobalTypeAndValue(C))
4609 return true;
4610 Elts.push_back(C);
4611 } while (EatIfPresent(lltok::comma));
4612
4613 return false;
4614}
4615
4616bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4618 if (parseMDNodeVector(Elts))
4619 return true;
4620
4621 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4622 return false;
4623}
4624
4625/// MDNode:
4626/// ::= !{ ... }
4627/// ::= !7
4628/// ::= !DILocation(...)
4629bool LLParser::parseMDNode(MDNode *&N) {
4630 if (Lex.getKind() == lltok::MetadataVar)
4631 return parseSpecializedMDNode(N);
4632
4633 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4634}
4635
4636bool LLParser::parseMDNodeTail(MDNode *&N) {
4637 // !{ ... }
4638 if (Lex.getKind() == lltok::lbrace)
4639 return parseMDTuple(N);
4640
4641 // !42
4642 return parseMDNodeID(N);
4643}
4644
4645namespace {
4646
4647/// Structure to represent an optional metadata field.
4648template <class FieldTy> struct MDFieldImpl {
4649 typedef MDFieldImpl ImplTy;
4650 FieldTy Val;
4651 bool Seen;
4652
4653 void assign(FieldTy Val) {
4654 Seen = true;
4655 this->Val = std::move(Val);
4656 }
4657
4658 explicit MDFieldImpl(FieldTy Default)
4659 : Val(std::move(Default)), Seen(false) {}
4660};
4661
4662/// Structure to represent an optional metadata field that
4663/// can be of either type (A or B) and encapsulates the
4664/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4665/// to reimplement the specifics for representing each Field.
4666template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4667 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4668 FieldTypeA A;
4669 FieldTypeB B;
4670 bool Seen;
4671
4672 enum {
4673 IsInvalid = 0,
4674 IsTypeA = 1,
4675 IsTypeB = 2
4676 } WhatIs;
4677
4678 void assign(FieldTypeA A) {
4679 Seen = true;
4680 this->A = std::move(A);
4681 WhatIs = IsTypeA;
4682 }
4683
4684 void assign(FieldTypeB B) {
4685 Seen = true;
4686 this->B = std::move(B);
4687 WhatIs = IsTypeB;
4688 }
4689
4690 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4691 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4692 WhatIs(IsInvalid) {}
4693};
4694
4695struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4696 uint64_t Max;
4697
4698 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4699 : ImplTy(Default), Max(Max) {}
4700};
4701
4702struct LineField : public MDUnsignedField {
4703 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4704};
4705
4706struct ColumnField : public MDUnsignedField {
4707 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4708};
4709
4710struct DwarfTagField : public MDUnsignedField {
4711 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4712 DwarfTagField(dwarf::Tag DefaultTag)
4713 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4714};
4715
4716struct DwarfMacinfoTypeField : public MDUnsignedField {
4717 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4718 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4719 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4720};
4721
4722struct DwarfAttEncodingField : public MDUnsignedField {
4723 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4724};
4725
4726struct DwarfVirtualityField : public MDUnsignedField {
4727 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4728};
4729
4730struct DwarfLangField : public MDUnsignedField {
4731 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4732};
4733
4734struct DwarfCCField : public MDUnsignedField {
4735 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4736};
4737
4738struct DwarfEnumKindField : public MDUnsignedField {
4739 DwarfEnumKindField()
4740 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4741 dwarf::DW_APPLE_ENUM_KIND_max) {}
4742};
4743
4744struct EmissionKindField : public MDUnsignedField {
4745 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4746};
4747
4748struct FixedPointKindField : public MDUnsignedField {
4749 FixedPointKindField()
4750 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4751};
4752
4753struct NameTableKindField : public MDUnsignedField {
4754 NameTableKindField()
4755 : MDUnsignedField(
4756 0, (unsigned)
4757 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4758};
4759
4760struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4761 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4762};
4763
4764struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4765 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4766};
4767
4768struct MDAPSIntField : public MDFieldImpl<APSInt> {
4769 MDAPSIntField() : ImplTy(APSInt()) {}
4770};
4771
4772struct MDSignedField : public MDFieldImpl<int64_t> {
4773 int64_t Min = INT64_MIN;
4774 int64_t Max = INT64_MAX;
4775
4776 MDSignedField(int64_t Default = 0)
4777 : ImplTy(Default) {}
4778 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4779 : ImplTy(Default), Min(Min), Max(Max) {}
4780};
4781
4782struct MDBoolField : public MDFieldImpl<bool> {
4783 MDBoolField(bool Default = false) : ImplTy(Default) {}
4784};
4785
4786struct MDField : public MDFieldImpl<Metadata *> {
4787 bool AllowNull;
4788
4789 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4790};
4791
4792struct MDStringField : public MDFieldImpl<MDString *> {
4793 enum class EmptyIs {
4794 Null, //< Allow empty input string, map to nullptr
4795 Empty, //< Allow empty input string, map to an empty MDString
4796 Error, //< Disallow empty string, map to an error
4797 } EmptyIs;
4798 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
4799 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4800};
4801
4802struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4803 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4804};
4805
4806struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4807 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4808};
4809
4810struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4811 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4812 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4813
4814 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4815 bool AllowNull = true)
4816 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4817
4818 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4819 bool isMDField() const { return WhatIs == IsTypeB; }
4820 int64_t getMDSignedValue() const {
4821 assert(isMDSignedField() && "Wrong field type");
4822 return A.Val;
4823 }
4824 Metadata *getMDFieldValue() const {
4825 assert(isMDField() && "Wrong field type");
4826 return B.Val;
4827 }
4828};
4829
4830struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4831 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
4832 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
4833
4834 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
4835 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
4836
4837 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
4838 bool isMDField() const { return WhatIs == IsTypeB; }
4839 uint64_t getMDUnsignedValue() const {
4840 assert(isMDUnsignedField() && "Wrong field type");
4841 return A.Val;
4842 }
4843 Metadata *getMDFieldValue() const {
4844 assert(isMDField() && "Wrong field type");
4845 return B.Val;
4846 }
4847
4848 Metadata *getValueAsMetadata(LLVMContext &Context) const {
4849 if (isMDUnsignedField())
4851 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
4852 if (isMDField())
4853 return getMDFieldValue();
4854 return nullptr;
4855 }
4856};
4857
4858} // end anonymous namespace
4859
4860namespace llvm {
4861
4862template <>
4863bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4864 if (Lex.getKind() != lltok::APSInt)
4865 return tokError("expected integer");
4866
4867 Result.assign(Lex.getAPSIntVal());
4868 Lex.Lex();
4869 return false;
4870}
4871
4872template <>
4873bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4874 MDUnsignedField &Result) {
4875 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4876 return tokError("expected unsigned integer");
4877
4878 auto &U = Lex.getAPSIntVal();
4879 if (U.ugt(Result.Max))
4880 return tokError("value for '" + Name + "' too large, limit is " +
4881 Twine(Result.Max));
4882 Result.assign(U.getZExtValue());
4883 assert(Result.Val <= Result.Max && "Expected value in range");
4884 Lex.Lex();
4885 return false;
4886}
4887
4888template <>
4889bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4890 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4891}
4892template <>
4893bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4894 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4895}
4896
4897template <>
4898bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4899 if (Lex.getKind() == lltok::APSInt)
4900 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4901
4902 if (Lex.getKind() != lltok::DwarfTag)
4903 return tokError("expected DWARF tag");
4904
4905 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4907 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4908 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4909
4910 Result.assign(Tag);
4911 Lex.Lex();
4912 return false;
4913}
4914
4915template <>
4916bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4917 DwarfMacinfoTypeField &Result) {
4918 if (Lex.getKind() == lltok::APSInt)
4919 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4920
4921 if (Lex.getKind() != lltok::DwarfMacinfo)
4922 return tokError("expected DWARF macinfo type");
4923
4924 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4925 if (Macinfo == dwarf::DW_MACINFO_invalid)
4926 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4927 Lex.getStrVal() + "'");
4928 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4929
4930 Result.assign(Macinfo);
4931 Lex.Lex();
4932 return false;
4933}
4934
4935template <>
4936bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4937 DwarfVirtualityField &Result) {
4938 if (Lex.getKind() == lltok::APSInt)
4939 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4940
4941 if (Lex.getKind() != lltok::DwarfVirtuality)
4942 return tokError("expected DWARF virtuality code");
4943
4944 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4945 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4946 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4947 Lex.getStrVal() + "'");
4948 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4949 Result.assign(Virtuality);
4950 Lex.Lex();
4951 return false;
4952}
4953
4954template <>
4955bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4956 DwarfEnumKindField &Result) {
4957 if (Lex.getKind() == lltok::APSInt)
4958 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4959
4960 if (Lex.getKind() != lltok::DwarfEnumKind)
4961 return tokError("expected DWARF enum kind code");
4962
4963 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
4964 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
4965 return tokError("invalid DWARF enum kind code" + Twine(" '") +
4966 Lex.getStrVal() + "'");
4967 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
4968 Result.assign(EnumKind);
4969 Lex.Lex();
4970 return false;
4971}
4972
4973template <>
4974bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4975 if (Lex.getKind() == lltok::APSInt)
4976 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4977
4978 if (Lex.getKind() != lltok::DwarfLang)
4979 return tokError("expected DWARF language");
4980
4981 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4982 if (!Lang)
4983 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4984 "'");
4985 assert(Lang <= Result.Max && "Expected valid DWARF language");
4986 Result.assign(Lang);
4987 Lex.Lex();
4988 return false;
4989}
4990
4991template <>
4992bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4993 if (Lex.getKind() == lltok::APSInt)
4994 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4995
4996 if (Lex.getKind() != lltok::DwarfCC)
4997 return tokError("expected DWARF calling convention");
4998
4999 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5000 if (!CC)
5001 return tokError("invalid DWARF calling convention" + Twine(" '") +
5002 Lex.getStrVal() + "'");
5003 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5004 Result.assign(CC);
5005 Lex.Lex();
5006 return false;
5007}
5008
5009template <>
5010bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5011 EmissionKindField &Result) {
5012 if (Lex.getKind() == lltok::APSInt)
5013 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5014
5015 if (Lex.getKind() != lltok::EmissionKind)
5016 return tokError("expected emission kind");
5017
5018 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5019 if (!Kind)
5020 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5021 "'");
5022 assert(*Kind <= Result.Max && "Expected valid emission kind");
5023 Result.assign(*Kind);
5024 Lex.Lex();
5025 return false;
5026}
5027
5028template <>
5029bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5030 FixedPointKindField &Result) {
5031 if (Lex.getKind() == lltok::APSInt)
5032 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5033
5034 if (Lex.getKind() != lltok::FixedPointKind)
5035 return tokError("expected fixed-point kind");
5036
5037 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5038 if (!Kind)
5039 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5040 "'");
5041 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5042 Result.assign(*Kind);
5043 Lex.Lex();
5044 return false;
5045}
5046
5047template <>
5048bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5049 NameTableKindField &Result) {
5050 if (Lex.getKind() == lltok::APSInt)
5051 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5052
5053 if (Lex.getKind() != lltok::NameTableKind)
5054 return tokError("expected nameTable kind");
5055
5056 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5057 if (!Kind)
5058 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5059 "'");
5060 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5061 Result.assign((unsigned)*Kind);
5062 Lex.Lex();
5063 return false;
5064}
5065
5066template <>
5067bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5068 DwarfAttEncodingField &Result) {
5069 if (Lex.getKind() == lltok::APSInt)
5070 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5071
5072 if (Lex.getKind() != lltok::DwarfAttEncoding)
5073 return tokError("expected DWARF type attribute encoding");
5074
5075 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5076 if (!Encoding)
5077 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5078 Lex.getStrVal() + "'");
5079 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5080 Result.assign(Encoding);
5081 Lex.Lex();
5082 return false;
5083}
5084
5085/// DIFlagField
5086/// ::= uint32
5087/// ::= DIFlagVector
5088/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5089template <>
5090bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5091
5092 // parser for a single flag.
5093 auto parseFlag = [&](DINode::DIFlags &Val) {
5094 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5095 uint32_t TempVal = static_cast<uint32_t>(Val);
5096 bool Res = parseUInt32(TempVal);
5097 Val = static_cast<DINode::DIFlags>(TempVal);
5098 return Res;
5099 }
5100
5101 if (Lex.getKind() != lltok::DIFlag)
5102 return tokError("expected debug info flag");
5103
5104 Val = DINode::getFlag(Lex.getStrVal());
5105 if (!Val)
5106 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5107 "'");
5108 Lex.Lex();
5109 return false;
5110 };
5111
5112 // parse the flags and combine them together.
5113 DINode::DIFlags Combined = DINode::FlagZero;
5114 do {
5115 DINode::DIFlags Val;
5116 if (parseFlag(Val))
5117 return true;
5118 Combined |= Val;
5119 } while (EatIfPresent(lltok::bar));
5120
5121 Result.assign(Combined);
5122 return false;
5123}
5124
5125/// DISPFlagField
5126/// ::= uint32
5127/// ::= DISPFlagVector
5128/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5129template <>
5130bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5131
5132 // parser for a single flag.
5133 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5134 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5135 uint32_t TempVal = static_cast<uint32_t>(Val);
5136 bool Res = parseUInt32(TempVal);
5137 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5138 return Res;
5139 }
5140
5141 if (Lex.getKind() != lltok::DISPFlag)
5142 return tokError("expected debug info flag");
5143
5144 Val = DISubprogram::getFlag(Lex.getStrVal());
5145 if (!Val)
5146 return tokError(Twine("invalid subprogram debug info flag '") +
5147 Lex.getStrVal() + "'");
5148 Lex.Lex();
5149 return false;
5150 };
5151
5152 // parse the flags and combine them together.
5153 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5154 do {
5156 if (parseFlag(Val))
5157 return true;
5158 Combined |= Val;
5159 } while (EatIfPresent(lltok::bar));
5160
5161 Result.assign(Combined);
5162 return false;
5163}
5164
5165template <>
5166bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5167 if (Lex.getKind() != lltok::APSInt)
5168 return tokError("expected signed integer");
5169
5170 auto &S = Lex.getAPSIntVal();
5171 if (S < Result.Min)
5172 return tokError("value for '" + Name + "' too small, limit is " +
5173 Twine(Result.Min));
5174 if (S > Result.Max)
5175 return tokError("value for '" + Name + "' too large, limit is " +
5176 Twine(Result.Max));
5177 Result.assign(S.getExtValue());
5178 assert(Result.Val >= Result.Min && "Expected value in range");
5179 assert(Result.Val <= Result.Max && "Expected value in range");
5180 Lex.Lex();
5181 return false;
5182}
5183
5184template <>
5185bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5186 switch (Lex.getKind()) {
5187 default:
5188 return tokError("expected 'true' or 'false'");
5189 case lltok::kw_true:
5190 Result.assign(true);
5191 break;
5192 case lltok::kw_false:
5193 Result.assign(false);
5194 break;
5195 }
5196 Lex.Lex();
5197 return false;
5198}
5199
5200template <>
5201bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5202 if (Lex.getKind() == lltok::kw_null) {
5203 if (!Result.AllowNull)
5204 return tokError("'" + Name + "' cannot be null");
5205 Lex.Lex();
5206 Result.assign(nullptr);
5207 return false;
5208 }
5209
5210 Metadata *MD;
5211 if (parseMetadata(MD, nullptr))
5212 return true;
5213
5214 Result.assign(MD);
5215 return false;
5216}
5217
5218template <>
5219bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5220 MDSignedOrMDField &Result) {
5221 // Try to parse a signed int.
5222 if (Lex.getKind() == lltok::APSInt) {
5223 MDSignedField Res = Result.A;
5224 if (!parseMDField(Loc, Name, Res)) {
5225 Result.assign(Res);
5226 return false;
5227 }
5228 return true;
5229 }
5230
5231 // Otherwise, try to parse as an MDField.
5232 MDField Res = Result.B;
5233 if (!parseMDField(Loc, Name, Res)) {
5234 Result.assign(Res);
5235 return false;
5236 }
5237
5238 return true;
5239}
5240
5241template <>
5242bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5243 MDUnsignedOrMDField &Result) {
5244 // Try to parse an unsigned int.
5245 if (Lex.getKind() == lltok::APSInt) {
5246 MDUnsignedField Res = Result.A;
5247 if (!parseMDField(Loc, Name, Res)) {
5248 Result.assign(Res);
5249 return false;
5250 }
5251 return true;
5252 }
5253
5254 // Otherwise, try to parse as an MDField.
5255 MDField Res = Result.B;
5256 if (!parseMDField(Loc, Name, Res)) {
5257 Result.assign(Res);
5258 return false;
5259 }
5260
5261 return true;
5262}
5263
5264template <>
5265bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5266 LocTy ValueLoc = Lex.getLoc();
5267 std::string S;
5268 if (parseStringConstant(S))
5269 return true;
5270
5271 if (S.empty()) {
5272 switch (Result.EmptyIs) {
5273 case MDStringField::EmptyIs::Null:
5274 Result.assign(nullptr);
5275 return false;
5276 case MDStringField::EmptyIs::Empty:
5277 break;
5278 case MDStringField::EmptyIs::Error:
5279 return error(ValueLoc, "'" + Name + "' cannot be empty");
5280 }
5281 }
5282
5283 Result.assign(MDString::get(Context, S));
5284 return false;
5285}
5286
5287template <>
5288bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5290 if (parseMDNodeVector(MDs))
5291 return true;
5292
5293 Result.assign(std::move(MDs));
5294 return false;
5295}
5296
5297template <>
5298bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5299 ChecksumKindField &Result) {
5300 std::optional<DIFile::ChecksumKind> CSKind =
5301 DIFile::getChecksumKind(Lex.getStrVal());
5302
5303 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5304 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5305 "'");
5306
5307 Result.assign(*CSKind);
5308 Lex.Lex();
5309 return false;
5310}
5311
5312} // end namespace llvm
5313
5314template <class ParserTy>
5315bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5316 do {
5317 if (Lex.getKind() != lltok::LabelStr)
5318 return tokError("expected field label here");
5319
5320 if (ParseField())
5321 return true;
5322 } while (EatIfPresent(lltok::comma));
5323
5324 return false;
5325}
5326
5327template <class ParserTy>
5328bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5329 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5330 Lex.Lex();
5331
5332 if (parseToken(lltok::lparen, "expected '(' here"))
5333 return true;
5334 if (Lex.getKind() != lltok::rparen)
5335 if (parseMDFieldsImplBody(ParseField))
5336 return true;
5337
5338 ClosingLoc = Lex.getLoc();
5339 return parseToken(lltok::rparen, "expected ')' here");
5340}
5341
5342template <class FieldTy>
5343bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5344 if (Result.Seen)
5345 return tokError("field '" + Name + "' cannot be specified more than once");
5346
5347 LocTy Loc = Lex.getLoc();
5348 Lex.Lex();
5349 return parseMDField(Loc, Name, Result);
5350}
5351
5352bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5353 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5354
5355#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5356 if (Lex.getStrVal() == #CLASS) \
5357 return parse##CLASS(N, IsDistinct);
5358#include "llvm/IR/Metadata.def"
5359
5360 return tokError("expected metadata type");
5361}
5362
5363#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5364#define NOP_FIELD(NAME, TYPE, INIT)
5365#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5366 if (!NAME.Seen) \
5367 return error(ClosingLoc, "missing required field '" #NAME "'");
5368#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5369 if (Lex.getStrVal() == #NAME) \
5370 return parseMDField(#NAME, NAME);
5371#define PARSE_MD_FIELDS() \
5372 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5373 do { \
5374 LocTy ClosingLoc; \
5375 if (parseMDFieldsImpl( \
5376 [&]() -> bool { \
5377 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5378 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5379 "'"); \
5380 }, \
5381 ClosingLoc)) \
5382 return true; \
5383 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5384 } while (false)
5385#define GET_OR_DISTINCT(CLASS, ARGS) \
5386 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5387
5388/// parseDILocationFields:
5389/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5390/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5391bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5392#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5393 OPTIONAL(line, LineField, ); \
5394 OPTIONAL(column, ColumnField, ); \
5395 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5396 OPTIONAL(inlinedAt, MDField, ); \
5397 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5398 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5399 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5401#undef VISIT_MD_FIELDS
5402
5403 Result = GET_OR_DISTINCT(
5404 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5405 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5406 return false;
5407}
5408
5409/// parseDIAssignID:
5410/// ::= distinct !DIAssignID()
5411bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5412 if (!IsDistinct)
5413 return tokError("missing 'distinct', required for !DIAssignID()");
5414
5415 Lex.Lex();
5416
5417 // Now eat the parens.
5418 if (parseToken(lltok::lparen, "expected '(' here"))
5419 return true;
5420 if (parseToken(lltok::rparen, "expected ')' here"))
5421 return true;
5422
5424 return false;
5425}
5426
5427/// parseGenericDINode:
5428/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5429bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5430#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5431 REQUIRED(tag, DwarfTagField, ); \
5432 OPTIONAL(header, MDStringField, ); \
5433 OPTIONAL(operands, MDFieldList, );
5435#undef VISIT_MD_FIELDS
5436
5437 Result = GET_OR_DISTINCT(GenericDINode,
5438 (Context, tag.Val, header.Val, operands.Val));
5439 return false;
5440}
5441
5442/// parseDISubrangeType:
5443/// ::= !DISubrangeType(name: "whatever", file: !0,
5444/// line: 7, scope: !1, baseType: !2, size: 32,
5445/// align: 32, flags: 0, lowerBound: !3
5446/// upperBound: !4, stride: !5, bias: !6)
5447bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5448#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5449 OPTIONAL(name, MDStringField, ); \
5450 OPTIONAL(file, MDField, ); \
5451 OPTIONAL(line, LineField, ); \
5452 OPTIONAL(scope, MDField, ); \
5453 OPTIONAL(baseType, MDField, ); \
5454 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5455 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5456 OPTIONAL(flags, DIFlagField, ); \
5457 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5458 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5459 OPTIONAL(stride, MDSignedOrMDField, ); \
5460 OPTIONAL(bias, MDSignedOrMDField, );
5462#undef VISIT_MD_FIELDS
5463
5464 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5465 if (Bound.isMDSignedField())
5467 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5468 if (Bound.isMDField())
5469 return Bound.getMDFieldValue();
5470 return nullptr;
5471 };
5472
5473 Metadata *LowerBound = convToMetadata(lowerBound);
5474 Metadata *UpperBound = convToMetadata(upperBound);
5475 Metadata *Stride = convToMetadata(stride);
5476 Metadata *Bias = convToMetadata(bias);
5477
5479 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5480 size.getValueAsMetadata(Context), align.Val, flags.Val,
5481 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5482
5483 return false;
5484}
5485
5486/// parseDISubrange:
5487/// ::= !DISubrange(count: 30, lowerBound: 2)
5488/// ::= !DISubrange(count: !node, lowerBound: 2)
5489/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5490bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5491#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5492 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5493 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5494 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5495 OPTIONAL(stride, MDSignedOrMDField, );
5497#undef VISIT_MD_FIELDS
5498
5499 Metadata *Count = nullptr;
5500 Metadata *LowerBound = nullptr;
5501 Metadata *UpperBound = nullptr;
5502 Metadata *Stride = nullptr;
5503
5504 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5505 if (Bound.isMDSignedField())
5507 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5508 if (Bound.isMDField())
5509 return Bound.getMDFieldValue();
5510 return nullptr;
5511 };
5512
5513 Count = convToMetadata(count);
5514 LowerBound = convToMetadata(lowerBound);
5515 UpperBound = convToMetadata(upperBound);
5516 Stride = convToMetadata(stride);
5517
5518 Result = GET_OR_DISTINCT(DISubrange,
5519 (Context, Count, LowerBound, UpperBound, Stride));
5520
5521 return false;
5522}
5523
5524/// parseDIGenericSubrange:
5525/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5526/// !node3)
5527bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5528#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5529 OPTIONAL(count, MDSignedOrMDField, ); \
5530 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5531 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5532 OPTIONAL(stride, MDSignedOrMDField, );
5534#undef VISIT_MD_FIELDS
5535
5536 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5537 if (Bound.isMDSignedField())
5538 return DIExpression::get(
5539 Context, {dwarf::DW_OP_consts,
5540 static_cast<uint64_t>(Bound.getMDSignedValue())});
5541 if (Bound.isMDField())
5542 return Bound.getMDFieldValue();
5543 return nullptr;
5544 };
5545
5546 Metadata *Count = ConvToMetadata(count);
5547 Metadata *LowerBound = ConvToMetadata(lowerBound);
5548 Metadata *UpperBound = ConvToMetadata(upperBound);
5549 Metadata *Stride = ConvToMetadata(stride);
5550
5551 Result = GET_OR_DISTINCT(DIGenericSubrange,
5552 (Context, Count, LowerBound, UpperBound, Stride));
5553
5554 return false;
5555}
5556
5557/// parseDIEnumerator:
5558/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5559bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5560#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5561 REQUIRED(name, MDStringField, ); \
5562 REQUIRED(value, MDAPSIntField, ); \
5563 OPTIONAL(isUnsigned, MDBoolField, (false));
5565#undef VISIT_MD_FIELDS
5566
5567 if (isUnsigned.Val && value.Val.isNegative())
5568 return tokError("unsigned enumerator with negative value");
5569
5570 APSInt Value(value.Val);
5571 // Add a leading zero so that unsigned values with the msb set are not
5572 // mistaken for negative values when used for signed enumerators.
5573 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5574 Value = Value.zext(Value.getBitWidth() + 1);
5575
5576 Result =
5577 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5578
5579 return false;
5580}
5581
5582/// parseDIBasicType:
5583/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5584/// encoding: DW_ATE_encoding, flags: 0)
5585bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5586#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5587 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5588 OPTIONAL(name, MDStringField, ); \
5589 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5590 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5591 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5592 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5593 OPTIONAL(flags, DIFlagField, );
5595#undef VISIT_MD_FIELDS
5596
5597 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val,
5598 size.getValueAsMetadata(Context),
5599 align.Val, encoding.Val,
5600 num_extra_inhabitants.Val, flags.Val));
5601 return false;
5602}
5603
5604/// parseDIFixedPointType:
5605/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5606/// align: 32, encoding: DW_ATE_signed_fixed,
5607/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5608/// denominator: 8)
5609bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5610#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5611 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5612 OPTIONAL(name, MDStringField, ); \
5613 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5614 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5615 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5616 OPTIONAL(flags, DIFlagField, ); \
5617 OPTIONAL(kind, FixedPointKindField, ); \
5618 OPTIONAL(factor, MDSignedField, ); \
5619 OPTIONAL(numerator, MDAPSIntField, ); \
5620 OPTIONAL(denominator, MDAPSIntField, );
5622#undef VISIT_MD_FIELDS
5623
5624 Result = GET_OR_DISTINCT(DIFixedPointType,
5625 (Context, tag.Val, name.Val,
5626 size.getValueAsMetadata(Context), align.Val,
5627 encoding.Val, flags.Val, kind.Val, factor.Val,
5628 numerator.Val, denominator.Val));
5629 return false;
5630}
5631
5632/// parseDIStringType:
5633/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5634bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5635#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5636 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5637 OPTIONAL(name, MDStringField, ); \
5638 OPTIONAL(stringLength, MDField, ); \
5639 OPTIONAL(stringLengthExpression, MDField, ); \
5640 OPTIONAL(stringLocationExpression, MDField, ); \
5641 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5642 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5643 OPTIONAL(encoding, DwarfAttEncodingField, );
5645#undef VISIT_MD_FIELDS
5646
5648 DIStringType,
5649 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5650 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5651 align.Val, encoding.Val));
5652 return false;
5653}
5654
5655/// parseDIDerivedType:
5656/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5657/// line: 7, scope: !1, baseType: !2, size: 32,
5658/// align: 32, offset: 0, flags: 0, extraData: !3,
5659/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5660/// ptrAuthIsAddressDiscriminated: true,
5661/// ptrAuthExtraDiscriminator: 0x1234,
5662/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5663/// )
5664bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5665#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5666 REQUIRED(tag, DwarfTagField, ); \
5667 OPTIONAL(name, MDStringField, ); \
5668 OPTIONAL(file, MDField, ); \
5669 OPTIONAL(line, LineField, ); \
5670 OPTIONAL(scope, MDField, ); \
5671 REQUIRED(baseType, MDField, ); \
5672 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5673 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5674 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5675 OPTIONAL(flags, DIFlagField, ); \
5676 OPTIONAL(extraData, MDField, ); \
5677 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5678 OPTIONAL(annotations, MDField, ); \
5679 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5680 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5681 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5682 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5683 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5685#undef VISIT_MD_FIELDS
5686
5687 std::optional<unsigned> DWARFAddressSpace;
5688 if (dwarfAddressSpace.Val != UINT32_MAX)
5689 DWARFAddressSpace = dwarfAddressSpace.Val;
5690 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5691 if (ptrAuthKey.Val)
5692 PtrAuthData.emplace(
5693 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5694 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5695 ptrAuthAuthenticatesNullValues.Val);
5696
5698 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5699 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5700 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5701 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5702 return false;
5703}
5704
5705bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5706#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5707 REQUIRED(tag, DwarfTagField, ); \
5708 OPTIONAL(name, MDStringField, ); \
5709 OPTIONAL(file, MDField, ); \
5710 OPTIONAL(line, LineField, ); \
5711 OPTIONAL(scope, MDField, ); \
5712 OPTIONAL(baseType, MDField, ); \
5713 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5714 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5715 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5716 OPTIONAL(flags, DIFlagField, ); \
5717 OPTIONAL(elements, MDField, ); \
5718 OPTIONAL(runtimeLang, DwarfLangField, ); \
5719 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5720 OPTIONAL(vtableHolder, MDField, ); \
5721 OPTIONAL(templateParams, MDField, ); \
5722 OPTIONAL(identifier, MDStringField, ); \
5723 OPTIONAL(discriminator, MDField, ); \
5724 OPTIONAL(dataLocation, MDField, ); \
5725 OPTIONAL(associated, MDField, ); \
5726 OPTIONAL(allocated, MDField, ); \
5727 OPTIONAL(rank, MDSignedOrMDField, ); \
5728 OPTIONAL(annotations, MDField, ); \
5729 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5730 OPTIONAL(specification, MDField, ); \
5731 OPTIONAL(bitStride, MDField, );
5733#undef VISIT_MD_FIELDS
5734
5735 Metadata *Rank = nullptr;
5736 if (rank.isMDSignedField())
5738 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5739 else if (rank.isMDField())
5740 Rank = rank.getMDFieldValue();
5741
5742 std::optional<unsigned> EnumKind;
5743 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5744 EnumKind = enumKind.Val;
5745
5746 // If this has an identifier try to build an ODR type.
5747 if (identifier.Val)
5748 if (auto *CT = DICompositeType::buildODRType(
5749 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5750 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
5751 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5752 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5753 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5754 dataLocation.Val, associated.Val, allocated.Val, Rank,
5755 annotations.Val, bitStride.Val)) {
5756 Result = CT;
5757 return false;
5758 }
5759
5760 // Create a new node, and save it in the context if it belongs in the type
5761 // map.
5763 DICompositeType,
5764 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5765 size.getValueAsMetadata(Context), align.Val,
5766 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5767 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5768 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5769 allocated.Val, Rank, annotations.Val, specification.Val,
5770 num_extra_inhabitants.Val, bitStride.Val));
5771 return false;
5772}
5773
5774bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5775#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5776 OPTIONAL(flags, DIFlagField, ); \
5777 OPTIONAL(cc, DwarfCCField, ); \
5778 REQUIRED(types, MDField, );
5780#undef VISIT_MD_FIELDS
5781
5782 Result = GET_OR_DISTINCT(DISubroutineType,
5783 (Context, flags.Val, cc.Val, types.Val));
5784 return false;
5785}
5786
5787/// parseDIFileType:
5788/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5789/// checksumkind: CSK_MD5,
5790/// checksum: "000102030405060708090a0b0c0d0e0f",
5791/// source: "source file contents")
5792bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5793 // The default constructed value for checksumkind is required, but will never
5794 // be used, as the parser checks if the field was actually Seen before using
5795 // the Val.
5796#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5797 REQUIRED(filename, MDStringField, ); \
5798 REQUIRED(directory, MDStringField, ); \
5799 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5800 OPTIONAL(checksum, MDStringField, ); \
5801 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5803#undef VISIT_MD_FIELDS
5804
5805 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5806 if (checksumkind.Seen && checksum.Seen)
5807 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5808 else if (checksumkind.Seen || checksum.Seen)
5809 return tokError("'checksumkind' and 'checksum' must be provided together");
5810
5811 MDString *Source = nullptr;
5812 if (source.Seen)
5813 Source = source.Val;
5815 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5816 return false;
5817}
5818
5819/// parseDICompileUnit:
5820/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5821/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5822/// splitDebugFilename: "abc.debug",
5823/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5824/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5825/// sysroot: "/", sdk: "MacOSX.sdk")
5826bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5827 if (!IsDistinct)
5828 return tokError("missing 'distinct', required for !DICompileUnit");
5829
5830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5831 REQUIRED(language, DwarfLangField, ); \
5832 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5833 OPTIONAL(producer, MDStringField, ); \
5834 OPTIONAL(isOptimized, MDBoolField, ); \
5835 OPTIONAL(flags, MDStringField, ); \
5836 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5837 OPTIONAL(splitDebugFilename, MDStringField, ); \
5838 OPTIONAL(emissionKind, EmissionKindField, ); \
5839 OPTIONAL(enums, MDField, ); \
5840 OPTIONAL(retainedTypes, MDField, ); \
5841 OPTIONAL(globals, MDField, ); \
5842 OPTIONAL(imports, MDField, ); \
5843 OPTIONAL(macros, MDField, ); \
5844 OPTIONAL(dwoId, MDUnsignedField, ); \
5845 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5846 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5847 OPTIONAL(nameTableKind, NameTableKindField, ); \
5848 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5849 OPTIONAL(sysroot, MDStringField, ); \
5850 OPTIONAL(sdk, MDStringField, );
5852#undef VISIT_MD_FIELDS
5853
5855 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5856 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5857 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5858 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5859 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5860 return false;
5861}
5862
5863/// parseDISubprogram:
5864/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5865/// file: !1, line: 7, type: !2, isLocal: false,
5866/// isDefinition: true, scopeLine: 8, containingType: !3,
5867/// virtuality: DW_VIRTUALTIY_pure_virtual,
5868/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5869/// spFlags: 10, isOptimized: false, templateParams: !4,
5870/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5871/// annotations: !8)
5872bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5873 auto Loc = Lex.getLoc();
5874#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5875 OPTIONAL(scope, MDField, ); \
5876 OPTIONAL(name, MDStringField, ); \
5877 OPTIONAL(linkageName, MDStringField, ); \
5878 OPTIONAL(file, MDField, ); \
5879 OPTIONAL(line, LineField, ); \
5880 OPTIONAL(type, MDField, ); \
5881 OPTIONAL(isLocal, MDBoolField, ); \
5882 OPTIONAL(isDefinition, MDBoolField, (true)); \
5883 OPTIONAL(scopeLine, LineField, ); \
5884 OPTIONAL(containingType, MDField, ); \
5885 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5886 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5887 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5888 OPTIONAL(flags, DIFlagField, ); \
5889 OPTIONAL(spFlags, DISPFlagField, ); \
5890 OPTIONAL(isOptimized, MDBoolField, ); \
5891 OPTIONAL(unit, MDField, ); \
5892 OPTIONAL(templateParams, MDField, ); \
5893 OPTIONAL(declaration, MDField, ); \
5894 OPTIONAL(retainedNodes, MDField, ); \
5895 OPTIONAL(thrownTypes, MDField, ); \
5896 OPTIONAL(annotations, MDField, ); \
5897 OPTIONAL(targetFuncName, MDStringField, ); \
5898 OPTIONAL(keyInstructions, MDBoolField, );
5900#undef VISIT_MD_FIELDS
5901
5902 // An explicit spFlags field takes precedence over individual fields in
5903 // older IR versions.
5904 DISubprogram::DISPFlags SPFlags =
5905 spFlags.Seen ? spFlags.Val
5906 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5907 isOptimized.Val, virtuality.Val);
5908 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5909 return error(
5910 Loc,
5911 "missing 'distinct', required for !DISubprogram that is a Definition");
5913 DISubprogram,
5914 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5915 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5916 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5917 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5918 targetFuncName.Val, keyInstructions.Val));
5919 return false;
5920}
5921
5922/// parseDILexicalBlock:
5923/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5924bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5925#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5926 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5927 OPTIONAL(file, MDField, ); \
5928 OPTIONAL(line, LineField, ); \
5929 OPTIONAL(column, ColumnField, );
5931#undef VISIT_MD_FIELDS
5932
5934 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5935 return false;
5936}
5937
5938/// parseDILexicalBlockFile:
5939/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5940bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5943 OPTIONAL(file, MDField, ); \
5944 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5946#undef VISIT_MD_FIELDS
5947
5948 Result = GET_OR_DISTINCT(DILexicalBlockFile,
5949 (Context, scope.Val, file.Val, discriminator.Val));
5950 return false;
5951}
5952
5953/// parseDICommonBlock:
5954/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5955bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5956#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5957 REQUIRED(scope, MDField, ); \
5958 OPTIONAL(declaration, MDField, ); \
5959 OPTIONAL(name, MDStringField, ); \
5960 OPTIONAL(file, MDField, ); \
5961 OPTIONAL(line, LineField, );
5963#undef VISIT_MD_FIELDS
5964
5965 Result = GET_OR_DISTINCT(DICommonBlock,
5966 (Context, scope.Val, declaration.Val, name.Val,
5967 file.Val, line.Val));
5968 return false;
5969}
5970
5971/// parseDINamespace:
5972/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5973bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5974#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5975 REQUIRED(scope, MDField, ); \
5976 OPTIONAL(name, MDStringField, ); \
5977 OPTIONAL(exportSymbols, MDBoolField, );
5979#undef VISIT_MD_FIELDS
5980
5981 Result = GET_OR_DISTINCT(DINamespace,
5982 (Context, scope.Val, name.Val, exportSymbols.Val));
5983 return false;
5984}
5985
5986/// parseDIMacro:
5987/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5988/// "SomeValue")
5989bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5990#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5991 REQUIRED(type, DwarfMacinfoTypeField, ); \
5992 OPTIONAL(line, LineField, ); \
5993 REQUIRED(name, MDStringField, ); \
5994 OPTIONAL(value, MDStringField, );
5996#undef VISIT_MD_FIELDS
5997
5998 Result = GET_OR_DISTINCT(DIMacro,
5999 (Context, type.Val, line.Val, name.Val, value.Val));
6000 return false;
6001}
6002
6003/// parseDIMacroFile:
6004/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6005bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6006#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6007 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6008 OPTIONAL(line, LineField, ); \
6009 REQUIRED(file, MDField, ); \
6010 OPTIONAL(nodes, MDField, );
6012#undef VISIT_MD_FIELDS
6013
6014 Result = GET_OR_DISTINCT(DIMacroFile,
6015 (Context, type.Val, line.Val, file.Val, nodes.Val));
6016 return false;
6017}
6018
6019/// parseDIModule:
6020/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6021/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6022/// file: !1, line: 4, isDecl: false)
6023bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6024#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6025 REQUIRED(scope, MDField, ); \
6026 REQUIRED(name, MDStringField, ); \
6027 OPTIONAL(configMacros, MDStringField, ); \
6028 OPTIONAL(includePath, MDStringField, ); \
6029 OPTIONAL(apinotes, MDStringField, ); \
6030 OPTIONAL(file, MDField, ); \
6031 OPTIONAL(line, LineField, ); \
6032 OPTIONAL(isDecl, MDBoolField, );
6034#undef VISIT_MD_FIELDS
6035
6036 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6037 configMacros.Val, includePath.Val,
6038 apinotes.Val, line.Val, isDecl.Val));
6039 return false;
6040}
6041
6042/// parseDITemplateTypeParameter:
6043/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6044bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6045#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6046 OPTIONAL(name, MDStringField, ); \
6047 REQUIRED(type, MDField, ); \
6048 OPTIONAL(defaulted, MDBoolField, );
6050#undef VISIT_MD_FIELDS
6051
6052 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6053 (Context, name.Val, type.Val, defaulted.Val));
6054 return false;
6055}
6056
6057/// parseDITemplateValueParameter:
6058/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6059/// name: "V", type: !1, defaulted: false,
6060/// value: i32 7)
6061bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6062#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6063 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6064 OPTIONAL(name, MDStringField, ); \
6065 OPTIONAL(type, MDField, ); \
6066 OPTIONAL(defaulted, MDBoolField, ); \
6067 REQUIRED(value, MDField, );
6068
6070#undef VISIT_MD_FIELDS
6071
6073 DITemplateValueParameter,
6074 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6075 return false;
6076}
6077
6078/// parseDIGlobalVariable:
6079/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6080/// file: !1, line: 7, type: !2, isLocal: false,
6081/// isDefinition: true, templateParams: !3,
6082/// declaration: !4, align: 8)
6083bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6084#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6085 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6086 OPTIONAL(scope, MDField, ); \
6087 OPTIONAL(linkageName, MDStringField, ); \
6088 OPTIONAL(file, MDField, ); \
6089 OPTIONAL(line, LineField, ); \
6090 OPTIONAL(type, MDField, ); \
6091 OPTIONAL(isLocal, MDBoolField, ); \
6092 OPTIONAL(isDefinition, MDBoolField, (true)); \
6093 OPTIONAL(templateParams, MDField, ); \
6094 OPTIONAL(declaration, MDField, ); \
6095 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6096 OPTIONAL(annotations, MDField, );
6098#undef VISIT_MD_FIELDS
6099
6100 Result =
6101 GET_OR_DISTINCT(DIGlobalVariable,
6102 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6103 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6104 declaration.Val, templateParams.Val, align.Val,
6105 annotations.Val));
6106 return false;
6107}
6108
6109/// parseDILocalVariable:
6110/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6111/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6112/// align: 8)
6113/// ::= !DILocalVariable(scope: !0, name: "foo",
6114/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6115/// align: 8)
6116bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6117#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6118 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6119 OPTIONAL(name, MDStringField, ); \
6120 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6121 OPTIONAL(file, MDField, ); \
6122 OPTIONAL(line, LineField, ); \
6123 OPTIONAL(type, MDField, ); \
6124 OPTIONAL(flags, DIFlagField, ); \
6125 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6126 OPTIONAL(annotations, MDField, );
6128#undef VISIT_MD_FIELDS
6129
6130 Result = GET_OR_DISTINCT(DILocalVariable,
6131 (Context, scope.Val, name.Val, file.Val, line.Val,
6132 type.Val, arg.Val, flags.Val, align.Val,
6133 annotations.Val));
6134 return false;
6135}
6136
6137/// parseDILabel:
6138/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6139bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6140#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6141 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6142 REQUIRED(name, MDStringField, ); \
6143 REQUIRED(file, MDField, ); \
6144 REQUIRED(line, LineField, ); \
6145 OPTIONAL(column, ColumnField, ); \
6146 OPTIONAL(isArtificial, MDBoolField, ); \
6147 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6149#undef VISIT_MD_FIELDS
6150
6151 std::optional<unsigned> CoroSuspendIdx =
6152 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6153 : std::nullopt;
6154
6155 Result = GET_OR_DISTINCT(DILabel,
6156 (Context, scope.Val, name.Val, file.Val, line.Val,
6157 column.Val, isArtificial.Val, CoroSuspendIdx));
6158 return false;
6159}
6160
6161/// parseDIExpressionBody:
6162/// ::= (0, 7, -1)
6163bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6164 if (parseToken(lltok::lparen, "expected '(' here"))
6165 return true;
6166
6167 SmallVector<uint64_t, 8> Elements;
6168 if (Lex.getKind() != lltok::rparen)
6169 do {
6170 if (Lex.getKind() == lltok::DwarfOp) {
6171 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6172 Lex.Lex();
6173 Elements.push_back(Op);
6174 continue;
6175 }
6176 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6177 }
6178
6179 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6180 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6181 Lex.Lex();
6182 Elements.push_back(Op);
6183 continue;
6184 }
6185 return tokError(Twine("invalid DWARF attribute encoding '") +
6186 Lex.getStrVal() + "'");
6187 }
6188
6189 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6190 return tokError("expected unsigned integer");
6191
6192 auto &U = Lex.getAPSIntVal();
6193 if (U.ugt(UINT64_MAX))
6194 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6195 Elements.push_back(U.getZExtValue());
6196 Lex.Lex();
6197 } while (EatIfPresent(lltok::comma));
6198
6199 if (parseToken(lltok::rparen, "expected ')' here"))
6200 return true;
6201
6202 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6203 return false;
6204}
6205
6206/// parseDIExpression:
6207/// ::= !DIExpression(0, 7, -1)
6208bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6209 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6210 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6211 Lex.Lex();
6212
6213 return parseDIExpressionBody(Result, IsDistinct);
6214}
6215
6216/// ParseDIArgList:
6217/// ::= !DIArgList(i32 7, i64 %0)
6218bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6219 assert(PFS && "Expected valid function state");
6220 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6221 Lex.Lex();
6222
6223 if (parseToken(lltok::lparen, "expected '(' here"))
6224 return true;
6225
6227 if (Lex.getKind() != lltok::rparen)
6228 do {
6229 Metadata *MD;
6230 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6231 return true;
6232 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6233 } while (EatIfPresent(lltok::comma));
6234
6235 if (parseToken(lltok::rparen, "expected ')' here"))
6236 return true;
6237
6238 MD = DIArgList::get(Context, Args);
6239 return false;
6240}
6241
6242/// parseDIGlobalVariableExpression:
6243/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6244bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6245 bool IsDistinct) {
6246#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6247 REQUIRED(var, MDField, ); \
6248 REQUIRED(expr, MDField, );
6250#undef VISIT_MD_FIELDS
6251
6252 Result =
6253 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6254 return false;
6255}
6256
6257/// parseDIObjCProperty:
6258/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6259/// getter: "getFoo", attributes: 7, type: !2)
6260bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6261#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6262 OPTIONAL(name, MDStringField, ); \
6263 OPTIONAL(file, MDField, ); \
6264 OPTIONAL(line, LineField, ); \
6265 OPTIONAL(setter, MDStringField, ); \
6266 OPTIONAL(getter, MDStringField, ); \
6267 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6268 OPTIONAL(type, MDField, );
6270#undef VISIT_MD_FIELDS
6271
6272 Result = GET_OR_DISTINCT(DIObjCProperty,
6273 (Context, name.Val, file.Val, line.Val, setter.Val,
6274 getter.Val, attributes.Val, type.Val));
6275 return false;
6276}
6277
6278/// parseDIImportedEntity:
6279/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6280/// line: 7, name: "foo", elements: !2)
6281bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6282#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6283 REQUIRED(tag, DwarfTagField, ); \
6284 REQUIRED(scope, MDField, ); \
6285 OPTIONAL(entity, MDField, ); \
6286 OPTIONAL(file, MDField, ); \
6287 OPTIONAL(line, LineField, ); \
6288 OPTIONAL(name, MDStringField, ); \
6289 OPTIONAL(elements, MDField, );
6291#undef VISIT_MD_FIELDS
6292
6293 Result = GET_OR_DISTINCT(DIImportedEntity,
6294 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6295 line.Val, name.Val, elements.Val));
6296 return false;
6297}
6298
6299#undef PARSE_MD_FIELD
6300#undef NOP_FIELD
6301#undef REQUIRE_FIELD
6302#undef DECLARE_FIELD
6303
6304/// parseMetadataAsValue
6305/// ::= metadata i32 %local
6306/// ::= metadata i32 @global
6307/// ::= metadata i32 7
6308/// ::= metadata !0
6309/// ::= metadata !{...}
6310/// ::= metadata !"string"
6311bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6312 // Note: the type 'metadata' has already been parsed.
6313 Metadata *MD;
6314 if (parseMetadata(MD, &PFS))
6315 return true;
6316
6317 V = MetadataAsValue::get(Context, MD);
6318 return false;
6319}
6320
6321/// parseValueAsMetadata
6322/// ::= i32 %local
6323/// ::= i32 @global
6324/// ::= i32 7
6325bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6326 PerFunctionState *PFS) {
6327 Type *Ty;
6328 LocTy Loc;
6329 if (parseType(Ty, TypeMsg, Loc))
6330 return true;
6331 if (Ty->isMetadataTy())
6332 return error(Loc, "invalid metadata-value-metadata roundtrip");
6333
6334 Value *V;
6335 if (parseValue(Ty, V, PFS))
6336 return true;
6337
6338 MD = ValueAsMetadata::get(V);
6339 return false;
6340}
6341
6342/// parseMetadata
6343/// ::= i32 %local
6344/// ::= i32 @global
6345/// ::= i32 7
6346/// ::= !42
6347/// ::= !{...}
6348/// ::= !"string"
6349/// ::= !DILocation(...)
6350bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6351 if (Lex.getKind() == lltok::MetadataVar) {
6352 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6353 // so parsing this requires a Function State.
6354 if (Lex.getStrVal() == "DIArgList") {
6355 Metadata *AL;
6356 if (parseDIArgList(AL, PFS))
6357 return true;
6358 MD = AL;
6359 return false;
6360 }
6361 MDNode *N;
6362 if (parseSpecializedMDNode(N)) {
6363 return true;
6364 }
6365 MD = N;
6366 return false;
6367 }
6368
6369 // ValueAsMetadata:
6370 // <type> <value>
6371 if (Lex.getKind() != lltok::exclaim)
6372 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6373
6374 // '!'.
6375 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6376 Lex.Lex();
6377
6378 // MDString:
6379 // ::= '!' STRINGCONSTANT
6380 if (Lex.getKind() == lltok::StringConstant) {
6381 MDString *S;
6382 if (parseMDString(S))
6383 return true;
6384 MD = S;
6385 return false;
6386 }
6387
6388 // MDNode:
6389 // !{ ... }
6390 // !7
6391 MDNode *N;
6392 if (parseMDNodeTail(N))
6393 return true;
6394 MD = N;
6395 return false;
6396}
6397
6398//===----------------------------------------------------------------------===//
6399// Function Parsing.
6400//===----------------------------------------------------------------------===//
6401
6402bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6403 PerFunctionState *PFS) {
6404 if (Ty->isFunctionTy())
6405 return error(ID.Loc, "functions are not values, refer to them as pointers");
6406
6407 switch (ID.Kind) {
6408 case ValID::t_LocalID:
6409 if (!PFS)
6410 return error(ID.Loc, "invalid use of function-local name");
6411 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6412 return V == nullptr;
6413 case ValID::t_LocalName:
6414 if (!PFS)
6415 return error(ID.Loc, "invalid use of function-local name");
6416 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6417 return V == nullptr;
6418 case ValID::t_InlineAsm: {
6419 if (!ID.FTy)
6420 return error(ID.Loc, "invalid type for inline asm constraint string");
6421 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6422 return error(ID.Loc, toString(std::move(Err)));
6423 V = InlineAsm::get(
6424 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6425 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6426 return false;
6427 }
6429 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6430 if (V && ID.NoCFI)
6432 return V == nullptr;
6433 case ValID::t_GlobalID:
6434 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6435 if (V && ID.NoCFI)
6437 return V == nullptr;
6438 case ValID::t_APSInt:
6439 if (!Ty->isIntegerTy())
6440 return error(ID.Loc, "integer constant must have integer type");
6441 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6442 V = ConstantInt::get(Context, ID.APSIntVal);
6443 return false;
6444 case ValID::t_APFloat:
6445 if (!Ty->isFloatingPointTy() ||
6446 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6447 return error(ID.Loc, "floating point constant invalid for type");
6448
6449 // The lexer has no type info, so builds all half, bfloat, float, and double
6450 // FP constants as double. Fix this here. Long double does not need this.
6451 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6452 // Check for signaling before potentially converting and losing that info.
6453 bool IsSNAN = ID.APFloatVal.isSignaling();
6454 bool Ignored;
6455 if (Ty->isHalfTy())
6457 &Ignored);
6458 else if (Ty->isBFloatTy())
6459 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6460 &Ignored);
6461 else if (Ty->isFloatTy())
6463 &Ignored);
6464 if (IsSNAN) {
6465 // The convert call above may quiet an SNaN, so manufacture another
6466 // SNaN. The bitcast works because the payload (significand) parameter
6467 // is truncated to fit.
6468 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6469 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6470 ID.APFloatVal.isNegative(), &Payload);
6471 }
6472 }
6473 V = ConstantFP::get(Context, ID.APFloatVal);
6474
6475 if (V->getType() != Ty)
6476 return error(ID.Loc, "floating point constant does not have type '" +
6477 getTypeString(Ty) + "'");
6478
6479 return false;
6480 case ValID::t_Null:
6481 if (!Ty->isPointerTy())
6482 return error(ID.Loc, "null must be a pointer type");
6484 return false;
6485 case ValID::t_Undef:
6486 // FIXME: LabelTy should not be a first-class type.
6487 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6488 return error(ID.Loc, "invalid type for undef constant");
6489 V = UndefValue::get(Ty);
6490 return false;
6492 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6493 return error(ID.Loc, "invalid empty array initializer");
6494 V = PoisonValue::get(Ty);
6495 return false;
6496 case ValID::t_Zero:
6497 // FIXME: LabelTy should not be a first-class type.
6498 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6499 return error(ID.Loc, "invalid type for null constant");
6500 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6501 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6502 return error(ID.Loc, "invalid type for null constant");
6504 return false;
6505 case ValID::t_None:
6506 if (!Ty->isTokenTy())
6507 return error(ID.Loc, "invalid type for none constant");
6509 return false;
6510 case ValID::t_Poison:
6511 // FIXME: LabelTy should not be a first-class type.
6512 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6513 return error(ID.Loc, "invalid type for poison constant");
6514 V = PoisonValue::get(Ty);
6515 return false;
6516 case ValID::t_Constant:
6517 if (ID.ConstantVal->getType() != Ty)
6518 return error(ID.Loc, "constant expression type mismatch: got type '" +
6519 getTypeString(ID.ConstantVal->getType()) +
6520 "' but expected '" + getTypeString(Ty) + "'");
6521 V = ID.ConstantVal;
6522 return false;
6524 if (!Ty->isVectorTy())
6525 return error(ID.Loc, "vector constant must have vector type");
6526 if (ID.ConstantVal->getType() != Ty->getScalarType())
6527 return error(ID.Loc, "constant expression type mismatch: got type '" +
6528 getTypeString(ID.ConstantVal->getType()) +
6529 "' but expected '" +
6530 getTypeString(Ty->getScalarType()) + "'");
6531 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6532 ID.ConstantVal);
6533 return false;
6536 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6537 if (ST->getNumElements() != ID.UIntVal)
6538 return error(ID.Loc,
6539 "initializer with struct type has wrong # elements");
6540 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6541 return error(ID.Loc, "packed'ness of initializer and type don't match");
6542
6543 // Verify that the elements are compatible with the structtype.
6544 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6545 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6546 return error(
6547 ID.Loc,
6548 "element " + Twine(i) +
6549 " of struct initializer doesn't match struct element type");
6550
6552 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6553 } else
6554 return error(ID.Loc, "constant expression type mismatch");
6555 return false;
6556 }
6557 llvm_unreachable("Invalid ValID");
6558}
6559
6560bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6561 C = nullptr;
6562 ValID ID;
6563 auto Loc = Lex.getLoc();
6564 if (parseValID(ID, /*PFS=*/nullptr))
6565 return true;
6566 switch (ID.Kind) {
6567 case ValID::t_APSInt:
6568 case ValID::t_APFloat:
6569 case ValID::t_Undef:
6570 case ValID::t_Poison:
6571 case ValID::t_Zero:
6572 case ValID::t_Constant:
6576 Value *V;
6577 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6578 return true;
6579 assert(isa<Constant>(V) && "Expected a constant value");
6580 C = cast<Constant>(V);
6581 return false;
6582 }
6583 case ValID::t_Null:
6585 return false;
6586 default:
6587 return error(Loc, "expected a constant value");
6588 }
6589}
6590
6591bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6592 V = nullptr;
6593 ValID ID;
6594 return parseValID(ID, PFS, Ty) ||
6595 convertValIDToValue(Ty, ID, V, PFS);
6596}
6597
6598bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6599 Type *Ty = nullptr;
6600 return parseType(Ty) || parseValue(Ty, V, PFS);
6601}
6602
6603bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6604 PerFunctionState &PFS) {
6605 Value *V;
6606 Loc = Lex.getLoc();
6607 if (parseTypeAndValue(V, PFS))
6608 return true;
6609 if (!isa<BasicBlock>(V))
6610 return error(Loc, "expected a basic block");
6611 BB = cast<BasicBlock>(V);
6612 return false;
6613}
6614
6616 // Exit early for the common (non-debug-intrinsic) case.
6617 // We can make this the only check when we begin supporting all "llvm.dbg"
6618 // intrinsics in the new debug info format.
6619 if (!Name.starts_with("llvm.dbg."))
6620 return false;
6622 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6623 FnID == Intrinsic::dbg_assign;
6624}
6625
6626/// FunctionHeader
6627/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6628/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6629/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6630/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6631bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6632 unsigned &FunctionNumber,
6633 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6634 // parse the linkage.
6635 LocTy LinkageLoc = Lex.getLoc();
6636 unsigned Linkage;
6637 unsigned Visibility;
6638 unsigned DLLStorageClass;
6639 bool DSOLocal;
6640 AttrBuilder RetAttrs(M->getContext());
6641 unsigned CC;
6642 bool HasLinkage;
6643 Type *RetType = nullptr;
6644 LocTy RetTypeLoc = Lex.getLoc();
6645 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6646 DSOLocal) ||
6647 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6648 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6649 return true;
6650
6651 // Verify that the linkage is ok.
6654 break; // always ok.
6656 if (IsDefine)
6657 return error(LinkageLoc, "invalid linkage for function definition");
6658 break;
6666 if (!IsDefine)
6667 return error(LinkageLoc, "invalid linkage for function declaration");
6668 break;
6671 return error(LinkageLoc, "invalid function linkage type");
6672 }
6673
6674 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6675 return error(LinkageLoc,
6676 "symbol with local linkage must have default visibility");
6677
6678 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6679 return error(LinkageLoc,
6680 "symbol with local linkage cannot have a DLL storage class");
6681
6682 if (!FunctionType::isValidReturnType(RetType))
6683 return error(RetTypeLoc, "invalid function return type");
6684
6685 LocTy NameLoc = Lex.getLoc();
6686
6687 std::string FunctionName;
6688 if (Lex.getKind() == lltok::GlobalVar) {
6689 FunctionName = Lex.getStrVal();
6690 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6691 FunctionNumber = Lex.getUIntVal();
6692 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6693 FunctionNumber))
6694 return true;
6695 } else {
6696 return tokError("expected function name");
6697 }
6698
6699 Lex.Lex();
6700
6701 if (Lex.getKind() != lltok::lparen)
6702 return tokError("expected '(' in function argument list");
6703
6705 bool IsVarArg;
6706 AttrBuilder FuncAttrs(M->getContext());
6707 std::vector<unsigned> FwdRefAttrGrps;
6708 LocTy BuiltinLoc;
6709 std::string Section;
6710 std::string Partition;
6711 MaybeAlign Alignment;
6712 std::string GC;
6714 unsigned AddrSpace = 0;
6715 Constant *Prefix = nullptr;
6716 Constant *Prologue = nullptr;
6717 Constant *PersonalityFn = nullptr;
6718 Comdat *C;
6719
6720 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6721 parseOptionalUnnamedAddr(UnnamedAddr) ||
6722 parseOptionalProgramAddrSpace(AddrSpace) ||
6723 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6724 BuiltinLoc) ||
6725 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6726 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6727 parseOptionalComdat(FunctionName, C) ||
6728 parseOptionalAlignment(Alignment) ||
6729 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6730 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6731 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6732 (EatIfPresent(lltok::kw_personality) &&
6733 parseGlobalTypeAndValue(PersonalityFn)))
6734 return true;
6735
6736 if (FuncAttrs.contains(Attribute::Builtin))
6737 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6738
6739 // If the alignment was parsed as an attribute, move to the alignment field.
6740 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6741 Alignment = A;
6742 FuncAttrs.removeAttribute(Attribute::Alignment);
6743 }
6744
6745 // Okay, if we got here, the function is syntactically valid. Convert types
6746 // and do semantic checks.
6747 std::vector<Type*> ParamTypeList;
6749
6750 for (const ArgInfo &Arg : ArgList) {
6751 ParamTypeList.push_back(Arg.Ty);
6752 Attrs.push_back(Arg.Attrs);
6753 }
6754
6755 AttributeList PAL =
6756 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6757 AttributeSet::get(Context, RetAttrs), Attrs);
6758
6759 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6760 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6761
6762 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6763 PointerType *PFT = PointerType::get(Context, AddrSpace);
6764
6765 Fn = nullptr;
6766 GlobalValue *FwdFn = nullptr;
6767 if (!FunctionName.empty()) {
6768 // If this was a definition of a forward reference, remove the definition
6769 // from the forward reference table and fill in the forward ref.
6770 auto FRVI = ForwardRefVals.find(FunctionName);
6771 if (FRVI != ForwardRefVals.end()) {
6772 FwdFn = FRVI->second.first;
6773 if (FwdFn->getType() != PFT)
6774 return error(FRVI->second.second,
6775 "invalid forward reference to "
6776 "function '" +
6777 FunctionName +
6778 "' with wrong type: "
6779 "expected '" +
6780 getTypeString(PFT) + "' but was '" +
6781 getTypeString(FwdFn->getType()) + "'");
6782 ForwardRefVals.erase(FRVI);
6783 } else if ((Fn = M->getFunction(FunctionName))) {
6784 // Reject redefinitions.
6785 return error(NameLoc,
6786 "invalid redefinition of function '" + FunctionName + "'");
6787 } else if (M->getNamedValue(FunctionName)) {
6788 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6789 }
6790
6791 } else {
6792 // Handle @"", where a name is syntactically specified, but semantically
6793 // missing.
6794 if (FunctionNumber == (unsigned)-1)
6795 FunctionNumber = NumberedVals.getNext();
6796
6797 // If this is a definition of a forward referenced function, make sure the
6798 // types agree.
6799 auto I = ForwardRefValIDs.find(FunctionNumber);
6800 if (I != ForwardRefValIDs.end()) {
6801 FwdFn = I->second.first;
6802 if (FwdFn->getType() != PFT)
6803 return error(NameLoc, "type of definition and forward reference of '@" +
6804 Twine(FunctionNumber) +
6805 "' disagree: "
6806 "expected '" +
6807 getTypeString(PFT) + "' but was '" +
6808 getTypeString(FwdFn->getType()) + "'");
6809 ForwardRefValIDs.erase(I);
6810 }
6811 }
6812
6814 FunctionName, M);
6815
6816 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6817
6818 if (FunctionName.empty())
6819 NumberedVals.add(FunctionNumber, Fn);
6820
6822 maybeSetDSOLocal(DSOLocal, *Fn);
6825 Fn->setCallingConv(CC);
6826 Fn->setAttributes(PAL);
6827 Fn->setUnnamedAddr(UnnamedAddr);
6828 if (Alignment)
6829 Fn->setAlignment(*Alignment);
6830 Fn->setSection(Section);
6831 Fn->setPartition(Partition);
6832 Fn->setComdat(C);
6833 Fn->setPersonalityFn(PersonalityFn);
6834 if (!GC.empty()) Fn->setGC(GC);
6835 Fn->setPrefixData(Prefix);
6836 Fn->setPrologueData(Prologue);
6837 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6838
6839 // Add all of the arguments we parsed to the function.
6840 Function::arg_iterator ArgIt = Fn->arg_begin();
6841 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6842 // If the argument has a name, insert it into the argument symbol table.
6843 if (ArgList[i].Name.empty()) continue;
6844
6845 // Set the name, if it conflicted, it will be auto-renamed.
6846 ArgIt->setName(ArgList[i].Name);
6847
6848 if (ArgIt->getName() != ArgList[i].Name)
6849 return error(ArgList[i].Loc,
6850 "redefinition of argument '%" + ArgList[i].Name + "'");
6851 }
6852
6853 if (FwdFn) {
6854 FwdFn->replaceAllUsesWith(Fn);
6855 FwdFn->eraseFromParent();
6856 }
6857
6858 if (IsDefine)
6859 return false;
6860
6861 // Check the declaration has no block address forward references.
6862 ValID ID;
6863 if (FunctionName.empty()) {
6864 ID.Kind = ValID::t_GlobalID;
6865 ID.UIntVal = FunctionNumber;
6866 } else {
6867 ID.Kind = ValID::t_GlobalName;
6868 ID.StrVal = FunctionName;
6869 }
6870 auto Blocks = ForwardRefBlockAddresses.find(ID);
6871 if (Blocks != ForwardRefBlockAddresses.end())
6872 return error(Blocks->first.Loc,
6873 "cannot take blockaddress inside a declaration");
6874 return false;
6875}
6876
6877bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6878 ValID ID;
6879 if (FunctionNumber == -1) {
6880 ID.Kind = ValID::t_GlobalName;
6881 ID.StrVal = std::string(F.getName());
6882 } else {
6883 ID.Kind = ValID::t_GlobalID;
6884 ID.UIntVal = FunctionNumber;
6885 }
6886
6887 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6888 if (Blocks == P.ForwardRefBlockAddresses.end())
6889 return false;
6890
6891 for (const auto &I : Blocks->second) {
6892 const ValID &BBID = I.first;
6893 GlobalValue *GV = I.second;
6894
6895 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6896 "Expected local id or name");
6897 BasicBlock *BB;
6898 if (BBID.Kind == ValID::t_LocalName)
6899 BB = getBB(BBID.StrVal, BBID.Loc);
6900 else
6901 BB = getBB(BBID.UIntVal, BBID.Loc);
6902 if (!BB)
6903 return P.error(BBID.Loc, "referenced value is not a basic block");
6904
6905 Value *ResolvedVal = BlockAddress::get(&F, BB);
6906 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6907 ResolvedVal);
6908 if (!ResolvedVal)
6909 return true;
6910 GV->replaceAllUsesWith(ResolvedVal);
6911 GV->eraseFromParent();
6912 }
6913
6914 P.ForwardRefBlockAddresses.erase(Blocks);
6915 return false;
6916}
6917
6918/// parseFunctionBody
6919/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6920bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6921 ArrayRef<unsigned> UnnamedArgNums) {
6922 if (Lex.getKind() != lltok::lbrace)
6923 return tokError("expected '{' in function body");
6924 Lex.Lex(); // eat the {.
6925
6926 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
6927
6928 // Resolve block addresses and allow basic blocks to be forward-declared
6929 // within this function.
6930 if (PFS.resolveForwardRefBlockAddresses())
6931 return true;
6932 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6933
6934 // We need at least one basic block.
6935 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6936 return tokError("function body requires at least one basic block");
6937
6938 while (Lex.getKind() != lltok::rbrace &&
6939 Lex.getKind() != lltok::kw_uselistorder)
6940 if (parseBasicBlock(PFS))
6941 return true;
6942
6943 while (Lex.getKind() != lltok::rbrace)
6944 if (parseUseListOrder(&PFS))
6945 return true;
6946
6947 // Eat the }.
6948 Lex.Lex();
6949
6950 // Verify function is ok.
6951 return PFS.finishFunction();
6952}
6953
6954/// parseBasicBlock
6955/// ::= (LabelStr|LabelID)? Instruction*
6956bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6957 // If this basic block starts out with a name, remember it.
6958 std::string Name;
6959 int NameID = -1;
6960 LocTy NameLoc = Lex.getLoc();
6961 if (Lex.getKind() == lltok::LabelStr) {
6962 Name = Lex.getStrVal();
6963 Lex.Lex();
6964 } else if (Lex.getKind() == lltok::LabelID) {
6965 NameID = Lex.getUIntVal();
6966 Lex.Lex();
6967 }
6968
6969 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6970 if (!BB)
6971 return true;
6972
6973 std::string NameStr;
6974
6975 // Parse the instructions and debug values in this block until we get a
6976 // terminator.
6977 Instruction *Inst;
6978 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
6979 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
6980 SmallVector<DbgRecordPtr> TrailingDbgRecord;
6981 do {
6982 // Handle debug records first - there should always be an instruction
6983 // following the debug records, i.e. they cannot appear after the block
6984 // terminator.
6985 while (Lex.getKind() == lltok::hash) {
6986 if (SeenOldDbgInfoFormat)
6987 return error(Lex.getLoc(), "debug record should not appear in a module "
6988 "containing debug info intrinsics");
6989 SeenNewDbgInfoFormat = true;
6990 Lex.Lex();
6991
6992 DbgRecord *DR;
6993 if (parseDebugRecord(DR, PFS))
6994 return true;
6995 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6996 }
6997
6998 // This instruction may have three possibilities for a name: a) none
6999 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7000 LocTy NameLoc = Lex.getLoc();
7001 int NameID = -1;
7002 NameStr = "";
7003
7004 if (Lex.getKind() == lltok::LocalVarID) {
7005 NameID = Lex.getUIntVal();
7006 Lex.Lex();
7007 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7008 return true;
7009 } else if (Lex.getKind() == lltok::LocalVar) {
7010 NameStr = Lex.getStrVal();
7011 Lex.Lex();
7012 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7013 return true;
7014 }
7015
7016 switch (parseInstruction(Inst, BB, PFS)) {
7017 default:
7018 llvm_unreachable("Unknown parseInstruction result!");
7019 case InstError: return true;
7020 case InstNormal:
7021 Inst->insertInto(BB, BB->end());
7022
7023 // With a normal result, we check to see if the instruction is followed by
7024 // a comma and metadata.
7025 if (EatIfPresent(lltok::comma))
7026 if (parseInstructionMetadata(*Inst))
7027 return true;
7028 break;
7029 case InstExtraComma:
7030 Inst->insertInto(BB, BB->end());
7031
7032 // If the instruction parser ate an extra comma at the end of it, it
7033 // *must* be followed by metadata.
7034 if (parseInstructionMetadata(*Inst))
7035 return true;
7036 break;
7037 }
7038
7039 // Set the name on the instruction.
7040 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7041 return true;
7042
7043 // Attach any preceding debug values to this instruction.
7044 for (DbgRecordPtr &DR : TrailingDbgRecord)
7045 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7046 TrailingDbgRecord.clear();
7047 } while (!Inst->isTerminator());
7048
7049 assert(TrailingDbgRecord.empty() &&
7050 "All debug values should have been attached to an instruction.");
7051
7052 return false;
7053}
7054
7055/// parseDebugRecord
7056/// ::= #dbg_label '(' MDNode ')'
7057/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7058/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7059bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7060 using RecordKind = DbgRecord::Kind;
7061 using LocType = DbgVariableRecord::LocationType;
7062 LocTy DVRLoc = Lex.getLoc();
7063 if (Lex.getKind() != lltok::DbgRecordType)
7064 return error(DVRLoc, "expected debug record type here");
7065 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7066 .Case("declare", RecordKind::ValueKind)
7067 .Case("value", RecordKind::ValueKind)
7068 .Case("assign", RecordKind::ValueKind)
7069 .Case("label", RecordKind::LabelKind);
7070
7071 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7072 // full DbgVariableRecord processing stage.
7073 if (RecordType == RecordKind::LabelKind) {
7074 Lex.Lex();
7075 if (parseToken(lltok::lparen, "Expected '(' here"))
7076 return true;
7077 MDNode *Label;
7078 if (parseMDNode(Label))
7079 return true;
7080 if (parseToken(lltok::comma, "Expected ',' here"))
7081 return true;
7082 MDNode *DbgLoc;
7083 if (parseMDNode(DbgLoc))
7084 return true;
7085 if (parseToken(lltok::rparen, "Expected ')' here"))
7086 return true;
7088 return false;
7089 }
7090
7091 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7092 .Case("declare", LocType::Declare)
7093 .Case("value", LocType::Value)
7094 .Case("assign", LocType::Assign);
7095
7096 Lex.Lex();
7097 if (parseToken(lltok::lparen, "Expected '(' here"))
7098 return true;
7099
7100 // Parse Value field.
7101 Metadata *ValLocMD;
7102 if (parseMetadata(ValLocMD, &PFS))
7103 return true;
7104 if (parseToken(lltok::comma, "Expected ',' here"))
7105 return true;
7106
7107 // Parse Variable field.
7108 MDNode *Variable;
7109 if (parseMDNode(Variable))
7110 return true;
7111 if (parseToken(lltok::comma, "Expected ',' here"))
7112 return true;
7113
7114 // Parse Expression field.
7115 MDNode *Expression;
7116 if (parseMDNode(Expression))
7117 return true;
7118 if (parseToken(lltok::comma, "Expected ',' here"))
7119 return true;
7120
7121 // Parse additional fields for #dbg_assign.
7122 MDNode *AssignID = nullptr;
7123 Metadata *AddressLocation = nullptr;
7124 MDNode *AddressExpression = nullptr;
7125 if (ValueType == LocType::Assign) {
7126 // Parse DIAssignID.
7127 if (parseMDNode(AssignID))
7128 return true;
7129 if (parseToken(lltok::comma, "Expected ',' here"))
7130 return true;
7131
7132 // Parse address ValueAsMetadata.
7133 if (parseMetadata(AddressLocation, &PFS))
7134 return true;
7135 if (parseToken(lltok::comma, "Expected ',' here"))
7136 return true;
7137
7138 // Parse address DIExpression.
7139 if (parseMDNode(AddressExpression))
7140 return true;
7141 if (parseToken(lltok::comma, "Expected ',' here"))
7142 return true;
7143 }
7144
7145 /// Parse DILocation.
7146 MDNode *DebugLoc;
7147 if (parseMDNode(DebugLoc))
7148 return true;
7149
7150 if (parseToken(lltok::rparen, "Expected ')' here"))
7151 return true;
7153 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7154 AddressExpression, DebugLoc);
7155 return false;
7156}
7157//===----------------------------------------------------------------------===//
7158// Instruction Parsing.
7159//===----------------------------------------------------------------------===//
7160
7161/// parseInstruction - parse one of the many different instructions.
7162///
7163int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7164 PerFunctionState &PFS) {
7165 lltok::Kind Token = Lex.getKind();
7166 if (Token == lltok::Eof)
7167 return tokError("found end of file when expecting more instructions");
7168 LocTy Loc = Lex.getLoc();
7169 unsigned KeywordVal = Lex.getUIntVal();
7170 Lex.Lex(); // Eat the keyword.
7171
7172 switch (Token) {
7173 default:
7174 return error(Loc, "expected instruction opcode");
7175 // Terminator Instructions.
7176 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7177 case lltok::kw_ret:
7178 return parseRet(Inst, BB, PFS);
7179 case lltok::kw_br:
7180 return parseBr(Inst, PFS);
7181 case lltok::kw_switch:
7182 return parseSwitch(Inst, PFS);
7184 return parseIndirectBr(Inst, PFS);
7185 case lltok::kw_invoke:
7186 return parseInvoke(Inst, PFS);
7187 case lltok::kw_resume:
7188 return parseResume(Inst, PFS);
7190 return parseCleanupRet(Inst, PFS);
7191 case lltok::kw_catchret:
7192 return parseCatchRet(Inst, PFS);
7194 return parseCatchSwitch(Inst, PFS);
7195 case lltok::kw_catchpad:
7196 return parseCatchPad(Inst, PFS);
7198 return parseCleanupPad(Inst, PFS);
7199 case lltok::kw_callbr:
7200 return parseCallBr(Inst, PFS);
7201 // Unary Operators.
7202 case lltok::kw_fneg: {
7203 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7204 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7205 if (Res != 0)
7206 return Res;
7207 if (FMF.any())
7208 Inst->setFastMathFlags(FMF);
7209 return false;
7210 }
7211 // Binary Operators.
7212 case lltok::kw_add:
7213 case lltok::kw_sub:
7214 case lltok::kw_mul:
7215 case lltok::kw_shl: {
7216 bool NUW = EatIfPresent(lltok::kw_nuw);
7217 bool NSW = EatIfPresent(lltok::kw_nsw);
7218 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7219
7220 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7221 return true;
7222
7223 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7224 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7225 return false;
7226 }
7227 case lltok::kw_fadd:
7228 case lltok::kw_fsub:
7229 case lltok::kw_fmul:
7230 case lltok::kw_fdiv:
7231 case lltok::kw_frem: {
7232 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7233 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7234 if (Res != 0)
7235 return Res;
7236 if (FMF.any())
7237 Inst->setFastMathFlags(FMF);
7238 return 0;
7239 }
7240
7241 case lltok::kw_sdiv:
7242 case lltok::kw_udiv:
7243 case lltok::kw_lshr:
7244 case lltok::kw_ashr: {
7245 bool Exact = EatIfPresent(lltok::kw_exact);
7246
7247 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7248 return true;
7249 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7250 return false;
7251 }
7252
7253 case lltok::kw_urem:
7254 case lltok::kw_srem:
7255 return parseArithmetic(Inst, PFS, KeywordVal,
7256 /*IsFP*/ false);
7257 case lltok::kw_or: {
7258 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7259 if (parseLogical(Inst, PFS, KeywordVal))
7260 return true;
7261 if (Disjoint)
7262 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7263 return false;
7264 }
7265 case lltok::kw_and:
7266 case lltok::kw_xor:
7267 return parseLogical(Inst, PFS, KeywordVal);
7268 case lltok::kw_icmp: {
7269 bool SameSign = EatIfPresent(lltok::kw_samesign);
7270 if (parseCompare(Inst, PFS, KeywordVal))
7271 return true;
7272 if (SameSign)
7273 cast<ICmpInst>(Inst)->setSameSign();
7274 return false;
7275 }
7276 case lltok::kw_fcmp: {
7277 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7278 int Res = parseCompare(Inst, PFS, KeywordVal);
7279 if (Res != 0)
7280 return Res;
7281 if (FMF.any())
7282 Inst->setFastMathFlags(FMF);
7283 return 0;
7284 }
7285
7286 // Casts.
7287 case lltok::kw_uitofp:
7288 case lltok::kw_zext: {
7289 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7290 bool Res = parseCast(Inst, PFS, KeywordVal);
7291 if (Res != 0)
7292 return Res;
7293 if (NonNeg)
7294 Inst->setNonNeg();
7295 return 0;
7296 }
7297 case lltok::kw_trunc: {
7298 bool NUW = EatIfPresent(lltok::kw_nuw);
7299 bool NSW = EatIfPresent(lltok::kw_nsw);
7300 if (!NUW)
7301 NUW = EatIfPresent(lltok::kw_nuw);
7302 if (parseCast(Inst, PFS, KeywordVal))
7303 return true;
7304 if (NUW)
7305 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7306 if (NSW)
7307 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7308 return false;
7309 }
7310 case lltok::kw_sext:
7311 case lltok::kw_bitcast:
7313 case lltok::kw_sitofp:
7314 case lltok::kw_fptoui:
7315 case lltok::kw_fptosi:
7316 case lltok::kw_inttoptr:
7318 case lltok::kw_ptrtoint:
7319 return parseCast(Inst, PFS, KeywordVal);
7320 case lltok::kw_fptrunc:
7321 case lltok::kw_fpext: {
7322 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7323 if (parseCast(Inst, PFS, KeywordVal))
7324 return true;
7325 if (FMF.any())
7326 Inst->setFastMathFlags(FMF);
7327 return false;
7328 }
7329
7330 // Other.
7331 case lltok::kw_select: {
7332 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7333 int Res = parseSelect(Inst, PFS);
7334 if (Res != 0)
7335 return Res;
7336 if (FMF.any()) {
7337 if (!isa<FPMathOperator>(Inst))
7338 return error(Loc, "fast-math-flags specified for select without "
7339 "floating-point scalar or vector return type");
7340 Inst->setFastMathFlags(FMF);
7341 }
7342 return 0;
7343 }
7344 case lltok::kw_va_arg:
7345 return parseVAArg(Inst, PFS);
7347 return parseExtractElement(Inst, PFS);
7349 return parseInsertElement(Inst, PFS);
7351 return parseShuffleVector(Inst, PFS);
7352 case lltok::kw_phi: {
7353 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7354 int Res = parsePHI(Inst, PFS);
7355 if (Res != 0)
7356 return Res;
7357 if (FMF.any()) {
7358 if (!isa<FPMathOperator>(Inst))
7359 return error(Loc, "fast-math-flags specified for phi without "
7360 "floating-point scalar or vector return type");
7361 Inst->setFastMathFlags(FMF);
7362 }
7363 return 0;
7364 }
7366 return parseLandingPad(Inst, PFS);
7367 case lltok::kw_freeze:
7368 return parseFreeze(Inst, PFS);
7369 // Call.
7370 case lltok::kw_call:
7371 return parseCall(Inst, PFS, CallInst::TCK_None);
7372 case lltok::kw_tail:
7373 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7374 case lltok::kw_musttail:
7375 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7376 case lltok::kw_notail:
7377 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7378 // Memory.
7379 case lltok::kw_alloca:
7380 return parseAlloc(Inst, PFS);
7381 case lltok::kw_load:
7382 return parseLoad(Inst, PFS);
7383 case lltok::kw_store:
7384 return parseStore(Inst, PFS);
7385 case lltok::kw_cmpxchg:
7386 return parseCmpXchg(Inst, PFS);
7388 return parseAtomicRMW(Inst, PFS);
7389 case lltok::kw_fence:
7390 return parseFence(Inst, PFS);
7392 return parseGetElementPtr(Inst, PFS);
7394 return parseExtractValue(Inst, PFS);
7396 return parseInsertValue(Inst, PFS);
7397 }
7398}
7399
7400/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7401bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7402 if (Opc == Instruction::FCmp) {
7403 switch (Lex.getKind()) {
7404 default:
7405 return tokError("expected fcmp predicate (e.g. 'oeq')");
7406 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7407 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7408 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7409 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7410 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7411 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7412 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7413 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7414 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7415 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7416 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7417 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7418 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7419 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7420 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7421 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7422 }
7423 } else {
7424 switch (Lex.getKind()) {
7425 default:
7426 return tokError("expected icmp predicate (e.g. 'eq')");
7427 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7428 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7429 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7430 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7431 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7432 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7433 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7434 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7435 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7436 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7437 }
7438 }
7439 Lex.Lex();
7440 return false;
7441}
7442
7443//===----------------------------------------------------------------------===//
7444// Terminator Instructions.
7445//===----------------------------------------------------------------------===//
7446
7447/// parseRet - parse a return instruction.
7448/// ::= 'ret' void (',' !dbg, !1)*
7449/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7450bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7451 PerFunctionState &PFS) {
7452 SMLoc TypeLoc = Lex.getLoc();
7453 Type *Ty = nullptr;
7454 if (parseType(Ty, true /*void allowed*/))
7455 return true;
7456
7457 Type *ResType = PFS.getFunction().getReturnType();
7458
7459 if (Ty->isVoidTy()) {
7460 if (!ResType->isVoidTy())
7461 return error(TypeLoc, "value doesn't match function result type '" +
7462 getTypeString(ResType) + "'");
7463
7464 Inst = ReturnInst::Create(Context);
7465 return false;
7466 }
7467
7468 Value *RV;
7469 if (parseValue(Ty, RV, PFS))
7470 return true;
7471
7472 if (ResType != RV->getType())
7473 return error(TypeLoc, "value doesn't match function result type '" +
7474 getTypeString(ResType) + "'");
7475
7476 Inst = ReturnInst::Create(Context, RV);
7477 return false;
7478}
7479
7480/// parseBr
7481/// ::= 'br' TypeAndValue
7482/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7483bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7484 LocTy Loc, Loc2;
7485 Value *Op0;
7486 BasicBlock *Op1, *Op2;
7487 if (parseTypeAndValue(Op0, Loc, PFS))
7488 return true;
7489
7490 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7491 Inst = BranchInst::Create(BB);
7492 return false;
7493 }
7494
7495 if (Op0->getType() != Type::getInt1Ty(Context))
7496 return error(Loc, "branch condition must have 'i1' type");
7497
7498 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7499 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7500 parseToken(lltok::comma, "expected ',' after true destination") ||
7501 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7502 return true;
7503
7504 Inst = BranchInst::Create(Op1, Op2, Op0);
7505 return false;
7506}
7507
7508/// parseSwitch
7509/// Instruction
7510/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7511/// JumpTable
7512/// ::= (TypeAndValue ',' TypeAndValue)*
7513bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7514 LocTy CondLoc, BBLoc;
7515 Value *Cond;
7516 BasicBlock *DefaultBB;
7517 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7518 parseToken(lltok::comma, "expected ',' after switch condition") ||
7519 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7520 parseToken(lltok::lsquare, "expected '[' with switch table"))
7521 return true;
7522
7523 if (!Cond->getType()->isIntegerTy())
7524 return error(CondLoc, "switch condition must have integer type");
7525
7526 // parse the jump table pairs.
7527 SmallPtrSet<Value*, 32> SeenCases;
7529 while (Lex.getKind() != lltok::rsquare) {
7530 Value *Constant;
7531 BasicBlock *DestBB;
7532
7533 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7534 parseToken(lltok::comma, "expected ',' after case value") ||
7535 parseTypeAndBasicBlock(DestBB, PFS))
7536 return true;
7537
7538 if (!SeenCases.insert(Constant).second)
7539 return error(CondLoc, "duplicate case value in switch");
7540 if (!isa<ConstantInt>(Constant))
7541 return error(CondLoc, "case value is not a constant integer");
7542
7543 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7544 }
7545
7546 Lex.Lex(); // Eat the ']'.
7547
7548 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7549 for (const auto &[OnVal, Dest] : Table)
7550 SI->addCase(OnVal, Dest);
7551 Inst = SI;
7552 return false;
7553}
7554
7555/// parseIndirectBr
7556/// Instruction
7557/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7558bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7559 LocTy AddrLoc;
7560 Value *Address;
7561 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7562 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7563 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7564 return true;
7565
7566 if (!Address->getType()->isPointerTy())
7567 return error(AddrLoc, "indirectbr address must have pointer type");
7568
7569 // parse the destination list.
7570 SmallVector<BasicBlock*, 16> DestList;
7571
7572 if (Lex.getKind() != lltok::rsquare) {
7573 BasicBlock *DestBB;
7574 if (parseTypeAndBasicBlock(DestBB, PFS))
7575 return true;
7576 DestList.push_back(DestBB);
7577
7578 while (EatIfPresent(lltok::comma)) {
7579 if (parseTypeAndBasicBlock(DestBB, PFS))
7580 return true;
7581 DestList.push_back(DestBB);
7582 }
7583 }
7584
7585 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7586 return true;
7587
7588 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7589 for (BasicBlock *Dest : DestList)
7590 IBI->addDestination(Dest);
7591 Inst = IBI;
7592 return false;
7593}
7594
7595// If RetType is a non-function pointer type, then this is the short syntax
7596// for the call, which means that RetType is just the return type. Infer the
7597// rest of the function argument types from the arguments that are present.
7598bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7599 FunctionType *&FuncTy) {
7600 FuncTy = dyn_cast<FunctionType>(RetType);
7601 if (!FuncTy) {
7602 // Pull out the types of all of the arguments...
7603 SmallVector<Type *, 8> ParamTypes;
7604 ParamTypes.reserve(ArgList.size());
7605 for (const ParamInfo &Arg : ArgList)
7606 ParamTypes.push_back(Arg.V->getType());
7607
7608 if (!FunctionType::isValidReturnType(RetType))
7609 return true;
7610
7611 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7612 }
7613 return false;
7614}
7615
7616/// parseInvoke
7617/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7618/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7619bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7620 LocTy CallLoc = Lex.getLoc();
7621 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7622 std::vector<unsigned> FwdRefAttrGrps;
7623 LocTy NoBuiltinLoc;
7624 unsigned CC;
7625 unsigned InvokeAddrSpace;
7626 Type *RetType = nullptr;
7627 LocTy RetTypeLoc;
7628 ValID CalleeID;
7631
7632 BasicBlock *NormalBB, *UnwindBB;
7633 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7634 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7635 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7636 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7637 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7638 NoBuiltinLoc) ||
7639 parseOptionalOperandBundles(BundleList, PFS) ||
7640 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7641 parseTypeAndBasicBlock(NormalBB, PFS) ||
7642 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7643 parseTypeAndBasicBlock(UnwindBB, PFS))
7644 return true;
7645
7646 // If RetType is a non-function pointer type, then this is the short syntax
7647 // for the call, which means that RetType is just the return type. Infer the
7648 // rest of the function argument types from the arguments that are present.
7649 FunctionType *Ty;
7650 if (resolveFunctionType(RetType, ArgList, Ty))
7651 return error(RetTypeLoc, "Invalid result type for LLVM function");
7652
7653 CalleeID.FTy = Ty;
7654
7655 // Look up the callee.
7656 Value *Callee;
7657 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7658 Callee, &PFS))
7659 return true;
7660
7661 // Set up the Attribute for the function.
7662 SmallVector<Value *, 8> Args;
7664
7665 // Loop through FunctionType's arguments and ensure they are specified
7666 // correctly. Also, gather any parameter attributes.
7667 FunctionType::param_iterator I = Ty->param_begin();
7668 FunctionType::param_iterator E = Ty->param_end();
7669 for (const ParamInfo &Arg : ArgList) {
7670 Type *ExpectedTy = nullptr;
7671 if (I != E) {
7672 ExpectedTy = *I++;
7673 } else if (!Ty->isVarArg()) {
7674 return error(Arg.Loc, "too many arguments specified");
7675 }
7676
7677 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7678 return error(Arg.Loc, "argument is not of expected type '" +
7679 getTypeString(ExpectedTy) + "'");
7680 Args.push_back(Arg.V);
7681 ArgAttrs.push_back(Arg.Attrs);
7682 }
7683
7684 if (I != E)
7685 return error(CallLoc, "not enough parameters specified for call");
7686
7687 // Finish off the Attribute and check them
7688 AttributeList PAL =
7689 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7690 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7691
7692 InvokeInst *II =
7693 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7694 II->setCallingConv(CC);
7695 II->setAttributes(PAL);
7696 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7697 Inst = II;
7698 return false;
7699}
7700
7701/// parseResume
7702/// ::= 'resume' TypeAndValue
7703bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7704 Value *Exn; LocTy ExnLoc;
7705 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7706 return true;
7707
7708 ResumeInst *RI = ResumeInst::Create(Exn);
7709 Inst = RI;
7710 return false;
7711}
7712
7713bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7714 PerFunctionState &PFS) {
7715 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7716 return true;
7717
7718 while (Lex.getKind() != lltok::rsquare) {
7719 // If this isn't the first argument, we need a comma.
7720 if (!Args.empty() &&
7721 parseToken(lltok::comma, "expected ',' in argument list"))
7722 return true;
7723
7724 // parse the argument.
7725 LocTy ArgLoc;
7726 Type *ArgTy = nullptr;
7727 if (parseType(ArgTy, ArgLoc))
7728 return true;
7729
7730 Value *V;
7731 if (ArgTy->isMetadataTy()) {
7732 if (parseMetadataAsValue(V, PFS))
7733 return true;
7734 } else {
7735 if (parseValue(ArgTy, V, PFS))
7736 return true;
7737 }
7738 Args.push_back(V);
7739 }
7740
7741 Lex.Lex(); // Lex the ']'.
7742 return false;
7743}
7744
7745/// parseCleanupRet
7746/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7747bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7748 Value *CleanupPad = nullptr;
7749
7750 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7751 return true;
7752
7753 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7754 return true;
7755
7756 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7757 return true;
7758
7759 BasicBlock *UnwindBB = nullptr;
7760 if (Lex.getKind() == lltok::kw_to) {
7761 Lex.Lex();
7762 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7763 return true;
7764 } else {
7765 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7766 return true;
7767 }
7768 }
7769
7770 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7771 return false;
7772}
7773
7774/// parseCatchRet
7775/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7776bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7777 Value *CatchPad = nullptr;
7778
7779 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7780 return true;
7781
7782 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7783 return true;
7784
7785 BasicBlock *BB;
7786 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7787 parseTypeAndBasicBlock(BB, PFS))
7788 return true;
7789
7790 Inst = CatchReturnInst::Create(CatchPad, BB);
7791 return false;
7792}
7793
7794/// parseCatchSwitch
7795/// ::= 'catchswitch' within Parent
7796bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7797 Value *ParentPad;
7798
7799 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7800 return true;
7801
7802 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7803 Lex.getKind() != lltok::LocalVarID)
7804 return tokError("expected scope value for catchswitch");
7805
7806 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7807 return true;
7808
7809 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7810 return true;
7811
7813 do {
7814 BasicBlock *DestBB;
7815 if (parseTypeAndBasicBlock(DestBB, PFS))
7816 return true;
7817 Table.push_back(DestBB);
7818 } while (EatIfPresent(lltok::comma));
7819
7820 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7821 return true;
7822
7823 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7824 return true;
7825
7826 BasicBlock *UnwindBB = nullptr;
7827 if (EatIfPresent(lltok::kw_to)) {
7828 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7829 return true;
7830 } else {
7831 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7832 return true;
7833 }
7834
7835 auto *CatchSwitch =
7836 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7837 for (BasicBlock *DestBB : Table)
7838 CatchSwitch->addHandler(DestBB);
7839 Inst = CatchSwitch;
7840 return false;
7841}
7842
7843/// parseCatchPad
7844/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7845bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7846 Value *CatchSwitch = nullptr;
7847
7848 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7849 return true;
7850
7851 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7852 return tokError("expected scope value for catchpad");
7853
7854 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7855 return true;
7856
7857 SmallVector<Value *, 8> Args;
7858 if (parseExceptionArgs(Args, PFS))
7859 return true;
7860
7861 Inst = CatchPadInst::Create(CatchSwitch, Args);
7862 return false;
7863}
7864
7865/// parseCleanupPad
7866/// ::= 'cleanuppad' within Parent ParamList
7867bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7868 Value *ParentPad = nullptr;
7869
7870 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7871 return true;
7872
7873 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7874 Lex.getKind() != lltok::LocalVarID)
7875 return tokError("expected scope value for cleanuppad");
7876
7877 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7878 return true;
7879
7880 SmallVector<Value *, 8> Args;
7881 if (parseExceptionArgs(Args, PFS))
7882 return true;
7883
7884 Inst = CleanupPadInst::Create(ParentPad, Args);
7885 return false;
7886}
7887
7888//===----------------------------------------------------------------------===//
7889// Unary Operators.
7890//===----------------------------------------------------------------------===//
7891
7892/// parseUnaryOp
7893/// ::= UnaryOp TypeAndValue ',' Value
7894///
7895/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7896/// operand is allowed.
7897bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7898 unsigned Opc, bool IsFP) {
7899 LocTy Loc; Value *LHS;
7900 if (parseTypeAndValue(LHS, Loc, PFS))
7901 return true;
7902
7903 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7905
7906 if (!Valid)
7907 return error(Loc, "invalid operand type for instruction");
7908
7910 return false;
7911}
7912
7913/// parseCallBr
7914/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7915/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7916/// '[' LabelList ']'
7917bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7918 LocTy CallLoc = Lex.getLoc();
7919 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7920 std::vector<unsigned> FwdRefAttrGrps;
7921 LocTy NoBuiltinLoc;
7922 unsigned CC;
7923 Type *RetType = nullptr;
7924 LocTy RetTypeLoc;
7925 ValID CalleeID;
7928
7929 BasicBlock *DefaultDest;
7930 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7931 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7932 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7933 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7934 NoBuiltinLoc) ||
7935 parseOptionalOperandBundles(BundleList, PFS) ||
7936 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7937 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7938 parseToken(lltok::lsquare, "expected '[' in callbr"))
7939 return true;
7940
7941 // parse the destination list.
7942 SmallVector<BasicBlock *, 16> IndirectDests;
7943
7944 if (Lex.getKind() != lltok::rsquare) {
7945 BasicBlock *DestBB;
7946 if (parseTypeAndBasicBlock(DestBB, PFS))
7947 return true;
7948 IndirectDests.push_back(DestBB);
7949
7950 while (EatIfPresent(lltok::comma)) {
7951 if (parseTypeAndBasicBlock(DestBB, PFS))
7952 return true;
7953 IndirectDests.push_back(DestBB);
7954 }
7955 }
7956
7957 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7958 return true;
7959
7960 // If RetType is a non-function pointer type, then this is the short syntax
7961 // for the call, which means that RetType is just the return type. Infer the
7962 // rest of the function argument types from the arguments that are present.
7963 FunctionType *Ty;
7964 if (resolveFunctionType(RetType, ArgList, Ty))
7965 return error(RetTypeLoc, "Invalid result type for LLVM function");
7966
7967 CalleeID.FTy = Ty;
7968
7969 // Look up the callee.
7970 Value *Callee;
7971 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
7972 &PFS))
7973 return true;
7974
7975 // Set up the Attribute for the function.
7976 SmallVector<Value *, 8> Args;
7978
7979 // Loop through FunctionType's arguments and ensure they are specified
7980 // correctly. Also, gather any parameter attributes.
7981 FunctionType::param_iterator I = Ty->param_begin();
7982 FunctionType::param_iterator E = Ty->param_end();
7983 for (const ParamInfo &Arg : ArgList) {
7984 Type *ExpectedTy = nullptr;
7985 if (I != E) {
7986 ExpectedTy = *I++;
7987 } else if (!Ty->isVarArg()) {
7988 return error(Arg.Loc, "too many arguments specified");
7989 }
7990
7991 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7992 return error(Arg.Loc, "argument is not of expected type '" +
7993 getTypeString(ExpectedTy) + "'");
7994 Args.push_back(Arg.V);
7995 ArgAttrs.push_back(Arg.Attrs);
7996 }
7997
7998 if (I != E)
7999 return error(CallLoc, "not enough parameters specified for call");
8000
8001 // Finish off the Attribute and check them
8002 AttributeList PAL =
8003 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8004 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8005
8006 CallBrInst *CBI =
8007 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8008 BundleList);
8009 CBI->setCallingConv(CC);
8010 CBI->setAttributes(PAL);
8011 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8012 Inst = CBI;
8013 return false;
8014}
8015
8016//===----------------------------------------------------------------------===//
8017// Binary Operators.
8018//===----------------------------------------------------------------------===//
8019
8020/// parseArithmetic
8021/// ::= ArithmeticOps TypeAndValue ',' Value
8022///
8023/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8024/// operand is allowed.
8025bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8026 unsigned Opc, bool IsFP) {
8027 LocTy Loc; Value *LHS, *RHS;
8028 if (parseTypeAndValue(LHS, Loc, PFS) ||
8029 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8030 parseValue(LHS->getType(), RHS, PFS))
8031 return true;
8032
8033 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8035
8036 if (!Valid)
8037 return error(Loc, "invalid operand type for instruction");
8038
8040 return false;
8041}
8042
8043/// parseLogical
8044/// ::= ArithmeticOps TypeAndValue ',' Value {
8045bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8046 unsigned Opc) {
8047 LocTy Loc; Value *LHS, *RHS;
8048 if (parseTypeAndValue(LHS, Loc, PFS) ||
8049 parseToken(lltok::comma, "expected ',' in logical operation") ||
8050 parseValue(LHS->getType(), RHS, PFS))
8051 return true;
8052
8053 if (!LHS->getType()->isIntOrIntVectorTy())
8054 return error(Loc,
8055 "instruction requires integer or integer vector operands");
8056
8058 return false;
8059}
8060
8061/// parseCompare
8062/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8063/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8064bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8065 unsigned Opc) {
8066 // parse the integer/fp comparison predicate.
8067 LocTy Loc;
8068 unsigned Pred;
8069 Value *LHS, *RHS;
8070 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8071 parseToken(lltok::comma, "expected ',' after compare value") ||
8072 parseValue(LHS->getType(), RHS, PFS))
8073 return true;
8074
8075 if (Opc == Instruction::FCmp) {
8076 if (!LHS->getType()->isFPOrFPVectorTy())
8077 return error(Loc, "fcmp requires floating point operands");
8078 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8079 } else {
8080 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8081 if (!LHS->getType()->isIntOrIntVectorTy() &&
8083 return error(Loc, "icmp requires integer operands");
8084 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8085 }
8086 return false;
8087}
8088
8089//===----------------------------------------------------------------------===//
8090// Other Instructions.
8091//===----------------------------------------------------------------------===//
8092
8093/// parseCast
8094/// ::= CastOpc TypeAndValue 'to' Type
8095bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8096 unsigned Opc) {
8097 LocTy Loc;
8098 Value *Op;
8099 Type *DestTy = nullptr;
8100 if (parseTypeAndValue(Op, Loc, PFS) ||
8101 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8102 parseType(DestTy))
8103 return true;
8104
8106 return error(Loc, "invalid cast opcode for cast from '" +
8107 getTypeString(Op->getType()) + "' to '" +
8108 getTypeString(DestTy) + "'");
8109 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8110 return false;
8111}
8112
8113/// parseSelect
8114/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8115bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8116 LocTy Loc;
8117 Value *Op0, *Op1, *Op2;
8118 if (parseTypeAndValue(Op0, Loc, PFS) ||
8119 parseToken(lltok::comma, "expected ',' after select condition") ||
8120 parseTypeAndValue(Op1, PFS) ||
8121 parseToken(lltok::comma, "expected ',' after select value") ||
8122 parseTypeAndValue(Op2, PFS))
8123 return true;
8124
8125 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8126 return error(Loc, Reason);
8127
8128 Inst = SelectInst::Create(Op0, Op1, Op2);
8129 return false;
8130}
8131
8132/// parseVAArg
8133/// ::= 'va_arg' TypeAndValue ',' Type
8134bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8135 Value *Op;
8136 Type *EltTy = nullptr;
8137 LocTy TypeLoc;
8138 if (parseTypeAndValue(Op, PFS) ||
8139 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8140 parseType(EltTy, TypeLoc))
8141 return true;
8142
8143 if (!EltTy->isFirstClassType())
8144 return error(TypeLoc, "va_arg requires operand with first class type");
8145
8146 Inst = new VAArgInst(Op, EltTy);
8147 return false;
8148}
8149
8150/// parseExtractElement
8151/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8152bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8153 LocTy Loc;
8154 Value *Op0, *Op1;
8155 if (parseTypeAndValue(Op0, Loc, PFS) ||
8156 parseToken(lltok::comma, "expected ',' after extract value") ||
8157 parseTypeAndValue(Op1, PFS))
8158 return true;
8159
8161 return error(Loc, "invalid extractelement operands");
8162
8163 Inst = ExtractElementInst::Create(Op0, Op1);
8164 return false;
8165}
8166
8167/// parseInsertElement
8168/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8169bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8170 LocTy Loc;
8171 Value *Op0, *Op1, *Op2;
8172 if (parseTypeAndValue(Op0, Loc, PFS) ||
8173 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8174 parseTypeAndValue(Op1, PFS) ||
8175 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8176 parseTypeAndValue(Op2, PFS))
8177 return true;
8178
8179 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8180 return error(Loc, "invalid insertelement operands");
8181
8182 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8183 return false;
8184}
8185
8186/// parseShuffleVector
8187/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8188bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8189 LocTy Loc;
8190 Value *Op0, *Op1, *Op2;
8191 if (parseTypeAndValue(Op0, Loc, PFS) ||
8192 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8193 parseTypeAndValue(Op1, PFS) ||
8194 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8195 parseTypeAndValue(Op2, PFS))
8196 return true;
8197
8198 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8199 return error(Loc, "invalid shufflevector operands");
8200
8201 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8202 return false;
8203}
8204
8205/// parsePHI
8206/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8207int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8208 Type *Ty = nullptr; LocTy TypeLoc;
8209 Value *Op0, *Op1;
8210
8211 if (parseType(Ty, TypeLoc))
8212 return true;
8213
8214 if (!Ty->isFirstClassType())
8215 return error(TypeLoc, "phi node must have first class type");
8216
8217 bool First = true;
8218 bool AteExtraComma = false;
8220
8221 while (true) {
8222 if (First) {
8223 if (Lex.getKind() != lltok::lsquare)
8224 break;
8225 First = false;
8226 } else if (!EatIfPresent(lltok::comma))
8227 break;
8228
8229 if (Lex.getKind() == lltok::MetadataVar) {
8230 AteExtraComma = true;
8231 break;
8232 }
8233
8234 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8235 parseValue(Ty, Op0, PFS) ||
8236 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8237 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8238 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8239 return true;
8240
8241 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8242 }
8243
8244 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8245 for (const auto &[Val, BB] : PHIVals)
8246 PN->addIncoming(Val, BB);
8247 Inst = PN;
8248 return AteExtraComma ? InstExtraComma : InstNormal;
8249}
8250
8251/// parseLandingPad
8252/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8253/// Clause
8254/// ::= 'catch' TypeAndValue
8255/// ::= 'filter'
8256/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8257bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8258 Type *Ty = nullptr; LocTy TyLoc;
8259
8260 if (parseType(Ty, TyLoc))
8261 return true;
8262
8263 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8264 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8265
8266 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8268 if (EatIfPresent(lltok::kw_catch))
8270 else if (EatIfPresent(lltok::kw_filter))
8272 else
8273 return tokError("expected 'catch' or 'filter' clause type");
8274
8275 Value *V;
8276 LocTy VLoc;
8277 if (parseTypeAndValue(V, VLoc, PFS))
8278 return true;
8279
8280 // A 'catch' type expects a non-array constant. A filter clause expects an
8281 // array constant.
8282 if (CT == LandingPadInst::Catch) {
8283 if (isa<ArrayType>(V->getType()))
8284 return error(VLoc, "'catch' clause has an invalid type");
8285 } else {
8286 if (!isa<ArrayType>(V->getType()))
8287 return error(VLoc, "'filter' clause has an invalid type");
8288 }
8289
8291 if (!CV)
8292 return error(VLoc, "clause argument must be a constant");
8293 LP->addClause(CV);
8294 }
8295
8296 Inst = LP.release();
8297 return false;
8298}
8299
8300/// parseFreeze
8301/// ::= 'freeze' Type Value
8302bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8303 LocTy Loc;
8304 Value *Op;
8305 if (parseTypeAndValue(Op, Loc, PFS))
8306 return true;
8307
8308 Inst = new FreezeInst(Op);
8309 return false;
8310}
8311
8312/// parseCall
8313/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8314/// OptionalAttrs Type Value ParameterList OptionalAttrs
8315/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8316/// OptionalAttrs Type Value ParameterList OptionalAttrs
8317/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8318/// OptionalAttrs Type Value ParameterList OptionalAttrs
8319/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8320/// OptionalAttrs Type Value ParameterList OptionalAttrs
8321bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8323 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8324 std::vector<unsigned> FwdRefAttrGrps;
8325 LocTy BuiltinLoc;
8326 unsigned CallAddrSpace;
8327 unsigned CC;
8328 Type *RetType = nullptr;
8329 LocTy RetTypeLoc;
8330 ValID CalleeID;
8333 LocTy CallLoc = Lex.getLoc();
8334
8335 if (TCK != CallInst::TCK_None &&
8336 parseToken(lltok::kw_call,
8337 "expected 'tail call', 'musttail call', or 'notail call'"))
8338 return true;
8339
8340 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8341
8342 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8343 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8344 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8345 parseValID(CalleeID, &PFS) ||
8346 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8347 PFS.getFunction().isVarArg()) ||
8348 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8349 parseOptionalOperandBundles(BundleList, PFS))
8350 return true;
8351
8352 // If RetType is a non-function pointer type, then this is the short syntax
8353 // for the call, which means that RetType is just the return type. Infer the
8354 // rest of the function argument types from the arguments that are present.
8355 FunctionType *Ty;
8356 if (resolveFunctionType(RetType, ArgList, Ty))
8357 return error(RetTypeLoc, "Invalid result type for LLVM function");
8358
8359 CalleeID.FTy = Ty;
8360
8361 // Look up the callee.
8362 Value *Callee;
8363 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8364 Callee, &PFS))
8365 return true;
8366
8367 // Set up the Attribute for the function.
8369
8370 SmallVector<Value*, 8> Args;
8371
8372 // Loop through FunctionType's arguments and ensure they are specified
8373 // correctly. Also, gather any parameter attributes.
8374 FunctionType::param_iterator I = Ty->param_begin();
8375 FunctionType::param_iterator E = Ty->param_end();
8376 for (const ParamInfo &Arg : ArgList) {
8377 Type *ExpectedTy = nullptr;
8378 if (I != E) {
8379 ExpectedTy = *I++;
8380 } else if (!Ty->isVarArg()) {
8381 return error(Arg.Loc, "too many arguments specified");
8382 }
8383
8384 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8385 return error(Arg.Loc, "argument is not of expected type '" +
8386 getTypeString(ExpectedTy) + "'");
8387 Args.push_back(Arg.V);
8388 Attrs.push_back(Arg.Attrs);
8389 }
8390
8391 if (I != E)
8392 return error(CallLoc, "not enough parameters specified for call");
8393
8394 // Finish off the Attribute and check them
8395 AttributeList PAL =
8396 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8397 AttributeSet::get(Context, RetAttrs), Attrs);
8398
8399 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8400 CI->setTailCallKind(TCK);
8401 CI->setCallingConv(CC);
8402 if (FMF.any()) {
8403 if (!isa<FPMathOperator>(CI)) {
8404 CI->deleteValue();
8405 return error(CallLoc, "fast-math-flags specified for call without "
8406 "floating-point scalar or vector return type");
8407 }
8408 CI->setFastMathFlags(FMF);
8409 }
8410
8411 if (CalleeID.Kind == ValID::t_GlobalName &&
8412 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8413 if (SeenNewDbgInfoFormat) {
8414 CI->deleteValue();
8415 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8416 "using non-intrinsic debug info");
8417 }
8418 SeenOldDbgInfoFormat = true;
8419 }
8420 CI->setAttributes(PAL);
8421 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8422 Inst = CI;
8423 return false;
8424}
8425
8426//===----------------------------------------------------------------------===//
8427// Memory Instructions.
8428//===----------------------------------------------------------------------===//
8429
8430/// parseAlloc
8431/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8432/// (',' 'align' i32)? (',', 'addrspace(n))?
8433int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8434 Value *Size = nullptr;
8435 LocTy SizeLoc, TyLoc, ASLoc;
8436 MaybeAlign Alignment;
8437 unsigned AddrSpace = 0;
8438 Type *Ty = nullptr;
8439
8440 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8441 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8442
8443 if (parseType(Ty, TyLoc))
8444 return true;
8445
8447 return error(TyLoc, "invalid type for alloca");
8448
8449 bool AteExtraComma = false;
8450 if (EatIfPresent(lltok::comma)) {
8451 if (Lex.getKind() == lltok::kw_align) {
8452 if (parseOptionalAlignment(Alignment))
8453 return true;
8454 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8455 return true;
8456 } else if (Lex.getKind() == lltok::kw_addrspace) {
8457 ASLoc = Lex.getLoc();
8458 if (parseOptionalAddrSpace(AddrSpace))
8459 return true;
8460 } else if (Lex.getKind() == lltok::MetadataVar) {
8461 AteExtraComma = true;
8462 } else {
8463 if (parseTypeAndValue(Size, SizeLoc, PFS))
8464 return true;
8465 if (EatIfPresent(lltok::comma)) {
8466 if (Lex.getKind() == lltok::kw_align) {
8467 if (parseOptionalAlignment(Alignment))
8468 return true;
8469 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8470 return true;
8471 } else if (Lex.getKind() == lltok::kw_addrspace) {
8472 ASLoc = Lex.getLoc();
8473 if (parseOptionalAddrSpace(AddrSpace))
8474 return true;
8475 } else if (Lex.getKind() == lltok::MetadataVar) {
8476 AteExtraComma = true;
8477 }
8478 }
8479 }
8480 }
8481
8482 if (Size && !Size->getType()->isIntegerTy())
8483 return error(SizeLoc, "element count must have integer type");
8484
8485 SmallPtrSet<Type *, 4> Visited;
8486 if (!Alignment && !Ty->isSized(&Visited))
8487 return error(TyLoc, "Cannot allocate unsized type");
8488 if (!Alignment)
8489 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8490 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8491 AI->setUsedWithInAlloca(IsInAlloca);
8492 AI->setSwiftError(IsSwiftError);
8493 Inst = AI;
8494 return AteExtraComma ? InstExtraComma : InstNormal;
8495}
8496
8497/// parseLoad
8498/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8499/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8500/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8501int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8502 Value *Val; LocTy Loc;
8503 MaybeAlign Alignment;
8504 bool AteExtraComma = false;
8505 bool isAtomic = false;
8508
8509 if (Lex.getKind() == lltok::kw_atomic) {
8510 isAtomic = true;
8511 Lex.Lex();
8512 }
8513
8514 bool isVolatile = false;
8515 if (Lex.getKind() == lltok::kw_volatile) {
8516 isVolatile = true;
8517 Lex.Lex();
8518 }
8519
8520 Type *Ty;
8521 LocTy ExplicitTypeLoc = Lex.getLoc();
8522 if (parseType(Ty) ||
8523 parseToken(lltok::comma, "expected comma after load's type") ||
8524 parseTypeAndValue(Val, Loc, PFS) ||
8525 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8526 parseOptionalCommaAlign(Alignment, AteExtraComma))
8527 return true;
8528
8529 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8530 return error(Loc, "load operand must be a pointer to a first class type");
8531 if (isAtomic && !Alignment)
8532 return error(Loc, "atomic load must have explicit non-zero alignment");
8533 if (Ordering == AtomicOrdering::Release ||
8535 return error(Loc, "atomic load cannot use Release ordering");
8536
8537 SmallPtrSet<Type *, 4> Visited;
8538 if (!Alignment && !Ty->isSized(&Visited))
8539 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8540 if (!Alignment)
8541 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8542 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8543 return AteExtraComma ? InstExtraComma : InstNormal;
8544}
8545
8546/// parseStore
8547
8548/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8549/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8550/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8551int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8552 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8553 MaybeAlign Alignment;
8554 bool AteExtraComma = false;
8555 bool isAtomic = false;
8558
8559 if (Lex.getKind() == lltok::kw_atomic) {
8560 isAtomic = true;
8561 Lex.Lex();
8562 }
8563
8564 bool isVolatile = false;
8565 if (Lex.getKind() == lltok::kw_volatile) {
8566 isVolatile = true;
8567 Lex.Lex();
8568 }
8569
8570 if (parseTypeAndValue(Val, Loc, PFS) ||
8571 parseToken(lltok::comma, "expected ',' after store operand") ||
8572 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8573 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8574 parseOptionalCommaAlign(Alignment, AteExtraComma))
8575 return true;
8576
8577 if (!Ptr->getType()->isPointerTy())
8578 return error(PtrLoc, "store operand must be a pointer");
8579 if (!Val->getType()->isFirstClassType())
8580 return error(Loc, "store operand must be a first class value");
8581 if (isAtomic && !Alignment)
8582 return error(Loc, "atomic store must have explicit non-zero alignment");
8583 if (Ordering == AtomicOrdering::Acquire ||
8585 return error(Loc, "atomic store cannot use Acquire ordering");
8586 SmallPtrSet<Type *, 4> Visited;
8587 if (!Alignment && !Val->getType()->isSized(&Visited))
8588 return error(Loc, "storing unsized types is not allowed");
8589 if (!Alignment)
8590 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8591
8592 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8593 return AteExtraComma ? InstExtraComma : InstNormal;
8594}
8595
8596/// parseCmpXchg
8597/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8598/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8599/// 'Align'?
8600int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8601 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8602 bool AteExtraComma = false;
8603 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8604 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8606 bool isVolatile = false;
8607 bool isWeak = false;
8608 MaybeAlign Alignment;
8609
8610 if (EatIfPresent(lltok::kw_weak))
8611 isWeak = true;
8612
8613 if (EatIfPresent(lltok::kw_volatile))
8614 isVolatile = true;
8615
8616 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8617 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8618 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8619 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8620 parseTypeAndValue(New, NewLoc, PFS) ||
8621 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8622 parseOrdering(FailureOrdering) ||
8623 parseOptionalCommaAlign(Alignment, AteExtraComma))
8624 return true;
8625
8626 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8627 return tokError("invalid cmpxchg success ordering");
8628 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8629 return tokError("invalid cmpxchg failure ordering");
8630 if (!Ptr->getType()->isPointerTy())
8631 return error(PtrLoc, "cmpxchg operand must be a pointer");
8632 if (Cmp->getType() != New->getType())
8633 return error(NewLoc, "compare value and new value type do not match");
8634 if (!New->getType()->isFirstClassType())
8635 return error(NewLoc, "cmpxchg operand must be a first class value");
8636
8637 const Align DefaultAlignment(
8638 PFS.getFunction().getDataLayout().getTypeStoreSize(
8639 Cmp->getType()));
8640
8641 AtomicCmpXchgInst *CXI =
8642 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8643 SuccessOrdering, FailureOrdering, SSID);
8644 CXI->setVolatile(isVolatile);
8645 CXI->setWeak(isWeak);
8646
8647 Inst = CXI;
8648 return AteExtraComma ? InstExtraComma : InstNormal;
8649}
8650
8651/// parseAtomicRMW
8652/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8653/// 'singlethread'? AtomicOrdering
8654int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8655 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8656 bool AteExtraComma = false;
8659 bool isVolatile = false;
8660 bool IsFP = false;
8662 MaybeAlign Alignment;
8663
8664 if (EatIfPresent(lltok::kw_volatile))
8665 isVolatile = true;
8666
8667 switch (Lex.getKind()) {
8668 default:
8669 return tokError("expected binary operation in atomicrmw");
8683 break;
8686 break;
8689 break;
8690 case lltok::kw_usub_sat:
8692 break;
8693 case lltok::kw_fadd:
8695 IsFP = true;
8696 break;
8697 case lltok::kw_fsub:
8699 IsFP = true;
8700 break;
8701 case lltok::kw_fmax:
8703 IsFP = true;
8704 break;
8705 case lltok::kw_fmin:
8707 IsFP = true;
8708 break;
8709 case lltok::kw_fmaximum:
8711 IsFP = true;
8712 break;
8713 case lltok::kw_fminimum:
8715 IsFP = true;
8716 break;
8717 }
8718 Lex.Lex(); // Eat the operation.
8719
8720 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8721 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8722 parseTypeAndValue(Val, ValLoc, PFS) ||
8723 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8724 parseOptionalCommaAlign(Alignment, AteExtraComma))
8725 return true;
8726
8727 if (Ordering == AtomicOrdering::Unordered)
8728 return tokError("atomicrmw cannot be unordered");
8729 if (!Ptr->getType()->isPointerTy())
8730 return error(PtrLoc, "atomicrmw operand must be a pointer");
8731 if (Val->getType()->isScalableTy())
8732 return error(ValLoc, "atomicrmw operand may not be scalable");
8733
8735 if (!Val->getType()->isIntegerTy() &&
8736 !Val->getType()->isFloatingPointTy() &&
8737 !Val->getType()->isPointerTy()) {
8738 return error(
8739 ValLoc,
8741 " operand must be an integer, floating point, or pointer type");
8742 }
8743 } else if (IsFP) {
8744 if (!Val->getType()->isFPOrFPVectorTy()) {
8745 return error(ValLoc, "atomicrmw " +
8747 " operand must be a floating point type");
8748 }
8749 } else {
8750 if (!Val->getType()->isIntegerTy()) {
8751 return error(ValLoc, "atomicrmw " +
8753 " operand must be an integer");
8754 }
8755 }
8756
8757 unsigned Size =
8758 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8759 Val->getType());
8760 if (Size < 8 || (Size & (Size - 1)))
8761 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8762 " integer");
8763 const Align DefaultAlignment(
8764 PFS.getFunction().getDataLayout().getTypeStoreSize(
8765 Val->getType()));
8766 AtomicRMWInst *RMWI =
8767 new AtomicRMWInst(Operation, Ptr, Val,
8768 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8769 RMWI->setVolatile(isVolatile);
8770 Inst = RMWI;
8771 return AteExtraComma ? InstExtraComma : InstNormal;
8772}
8773
8774/// parseFence
8775/// ::= 'fence' 'singlethread'? AtomicOrdering
8776int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8779 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8780 return true;
8781
8782 if (Ordering == AtomicOrdering::Unordered)
8783 return tokError("fence cannot be unordered");
8784 if (Ordering == AtomicOrdering::Monotonic)
8785 return tokError("fence cannot be monotonic");
8786
8787 Inst = new FenceInst(Context, Ordering, SSID);
8788 return InstNormal;
8789}
8790
8791/// parseGetElementPtr
8792/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8793int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8794 Value *Ptr = nullptr;
8795 Value *Val = nullptr;
8796 LocTy Loc, EltLoc;
8797 GEPNoWrapFlags NW;
8798
8799 while (true) {
8800 if (EatIfPresent(lltok::kw_inbounds))
8802 else if (EatIfPresent(lltok::kw_nusw))
8804 else if (EatIfPresent(lltok::kw_nuw))
8806 else
8807 break;
8808 }
8809
8810 Type *Ty = nullptr;
8811 if (parseType(Ty) ||
8812 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8813 parseTypeAndValue(Ptr, Loc, PFS))
8814 return true;
8815
8816 Type *BaseType = Ptr->getType();
8817 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8818 if (!BasePointerType)
8819 return error(Loc, "base of getelementptr must be a pointer");
8820
8821 SmallVector<Value*, 16> Indices;
8822 bool AteExtraComma = false;
8823 // GEP returns a vector of pointers if at least one of parameters is a vector.
8824 // All vector parameters should have the same vector width.
8825 ElementCount GEPWidth = BaseType->isVectorTy()
8826 ? cast<VectorType>(BaseType)->getElementCount()
8828
8829 while (EatIfPresent(lltok::comma)) {
8830 if (Lex.getKind() == lltok::MetadataVar) {
8831 AteExtraComma = true;
8832 break;
8833 }
8834 if (parseTypeAndValue(Val, EltLoc, PFS))
8835 return true;
8836 if (!Val->getType()->isIntOrIntVectorTy())
8837 return error(EltLoc, "getelementptr index must be an integer");
8838
8839 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8840 ElementCount ValNumEl = ValVTy->getElementCount();
8841 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8842 return error(
8843 EltLoc,
8844 "getelementptr vector index has a wrong number of elements");
8845 GEPWidth = ValNumEl;
8846 }
8847 Indices.push_back(Val);
8848 }
8849
8850 SmallPtrSet<Type*, 4> Visited;
8851 if (!Indices.empty() && !Ty->isSized(&Visited))
8852 return error(Loc, "base element of getelementptr must be sized");
8853
8854 auto *STy = dyn_cast<StructType>(Ty);
8855 if (STy && STy->isScalableTy())
8856 return error(Loc, "getelementptr cannot target structure that contains "
8857 "scalable vector type");
8858
8859 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8860 return error(Loc, "invalid getelementptr indices");
8861 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8862 Inst = GEP;
8863 GEP->setNoWrapFlags(NW);
8864 return AteExtraComma ? InstExtraComma : InstNormal;
8865}
8866
8867/// parseExtractValue
8868/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8869int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8870 Value *Val; LocTy Loc;
8871 SmallVector<unsigned, 4> Indices;
8872 bool AteExtraComma;
8873 if (parseTypeAndValue(Val, Loc, PFS) ||
8874 parseIndexList(Indices, AteExtraComma))
8875 return true;
8876
8877 if (!Val->getType()->isAggregateType())
8878 return error(Loc, "extractvalue operand must be aggregate type");
8879
8880 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8881 return error(Loc, "invalid indices for extractvalue");
8882 Inst = ExtractValueInst::Create(Val, Indices);
8883 return AteExtraComma ? InstExtraComma : InstNormal;
8884}
8885
8886/// parseInsertValue
8887/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8888int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8889 Value *Val0, *Val1; LocTy Loc0, Loc1;
8890 SmallVector<unsigned, 4> Indices;
8891 bool AteExtraComma;
8892 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8893 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8894 parseTypeAndValue(Val1, Loc1, PFS) ||
8895 parseIndexList(Indices, AteExtraComma))
8896 return true;
8897
8898 if (!Val0->getType()->isAggregateType())
8899 return error(Loc0, "insertvalue operand must be aggregate type");
8900
8901 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8902 if (!IndexedType)
8903 return error(Loc0, "invalid indices for insertvalue");
8904 if (IndexedType != Val1->getType())
8905 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8906 getTypeString(Val1->getType()) + "' instead of '" +
8907 getTypeString(IndexedType) + "'");
8908 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8909 return AteExtraComma ? InstExtraComma : InstNormal;
8910}
8911
8912//===----------------------------------------------------------------------===//
8913// Embedded metadata.
8914//===----------------------------------------------------------------------===//
8915
8916/// parseMDNodeVector
8917/// ::= { Element (',' Element)* }
8918/// Element
8919/// ::= 'null' | Metadata
8920bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8921 if (parseToken(lltok::lbrace, "expected '{' here"))
8922 return true;
8923
8924 // Check for an empty list.
8925 if (EatIfPresent(lltok::rbrace))
8926 return false;
8927
8928 do {
8929 if (EatIfPresent(lltok::kw_null)) {
8930 Elts.push_back(nullptr);
8931 continue;
8932 }
8933
8934 Metadata *MD;
8935 if (parseMetadata(MD, nullptr))
8936 return true;
8937 Elts.push_back(MD);
8938 } while (EatIfPresent(lltok::comma));
8939
8940 return parseToken(lltok::rbrace, "expected end of metadata node");
8941}
8942
8943//===----------------------------------------------------------------------===//
8944// Use-list order directives.
8945//===----------------------------------------------------------------------===//
8946bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
8947 SMLoc Loc) {
8948 if (!V->hasUseList())
8949 return false;
8950 if (V->use_empty())
8951 return error(Loc, "value has no uses");
8952
8953 unsigned NumUses = 0;
8954 SmallDenseMap<const Use *, unsigned, 16> Order;
8955 for (const Use &U : V->uses()) {
8956 if (++NumUses > Indexes.size())
8957 break;
8958 Order[&U] = Indexes[NumUses - 1];
8959 }
8960 if (NumUses < 2)
8961 return error(Loc, "value only has one use");
8962 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
8963 return error(Loc,
8964 "wrong number of indexes, expected " + Twine(V->getNumUses()));
8965
8966 V->sortUseList([&](const Use &L, const Use &R) {
8967 return Order.lookup(&L) < Order.lookup(&R);
8968 });
8969 return false;
8970}
8971
8972/// parseUseListOrderIndexes
8973/// ::= '{' uint32 (',' uint32)+ '}'
8974bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8975 SMLoc Loc = Lex.getLoc();
8976 if (parseToken(lltok::lbrace, "expected '{' here"))
8977 return true;
8978 if (Lex.getKind() == lltok::rbrace)
8979 return tokError("expected non-empty list of uselistorder indexes");
8980
8981 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8982 // indexes should be distinct numbers in the range [0, size-1], and should
8983 // not be in order.
8984 unsigned Offset = 0;
8985 unsigned Max = 0;
8986 bool IsOrdered = true;
8987 assert(Indexes.empty() && "Expected empty order vector");
8988 do {
8989 unsigned Index;
8990 if (parseUInt32(Index))
8991 return true;
8992
8993 // Update consistency checks.
8994 Offset += Index - Indexes.size();
8995 Max = std::max(Max, Index);
8996 IsOrdered &= Index == Indexes.size();
8997
8998 Indexes.push_back(Index);
8999 } while (EatIfPresent(lltok::comma));
9000
9001 if (parseToken(lltok::rbrace, "expected '}' here"))
9002 return true;
9003
9004 if (Indexes.size() < 2)
9005 return error(Loc, "expected >= 2 uselistorder indexes");
9006 if (Offset != 0 || Max >= Indexes.size())
9007 return error(Loc,
9008 "expected distinct uselistorder indexes in range [0, size)");
9009 if (IsOrdered)
9010 return error(Loc, "expected uselistorder indexes to change the order");
9011
9012 return false;
9013}
9014
9015/// parseUseListOrder
9016/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9017bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9018 SMLoc Loc = Lex.getLoc();
9019 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9020 return true;
9021
9022 Value *V;
9023 SmallVector<unsigned, 16> Indexes;
9024 if (parseTypeAndValue(V, PFS) ||
9025 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9026 parseUseListOrderIndexes(Indexes))
9027 return true;
9028
9029 return sortUseListOrder(V, Indexes, Loc);
9030}
9031
9032/// parseUseListOrderBB
9033/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9034bool LLParser::parseUseListOrderBB() {
9035 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9036 SMLoc Loc = Lex.getLoc();
9037 Lex.Lex();
9038
9039 ValID Fn, Label;
9040 SmallVector<unsigned, 16> Indexes;
9041 if (parseValID(Fn, /*PFS=*/nullptr) ||
9042 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9043 parseValID(Label, /*PFS=*/nullptr) ||
9044 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9045 parseUseListOrderIndexes(Indexes))
9046 return true;
9047
9048 // Check the function.
9049 GlobalValue *GV;
9050 if (Fn.Kind == ValID::t_GlobalName)
9051 GV = M->getNamedValue(Fn.StrVal);
9052 else if (Fn.Kind == ValID::t_GlobalID)
9053 GV = NumberedVals.get(Fn.UIntVal);
9054 else
9055 return error(Fn.Loc, "expected function name in uselistorder_bb");
9056 if (!GV)
9057 return error(Fn.Loc,
9058 "invalid function forward reference in uselistorder_bb");
9059 auto *F = dyn_cast<Function>(GV);
9060 if (!F)
9061 return error(Fn.Loc, "expected function name in uselistorder_bb");
9062 if (F->isDeclaration())
9063 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9064
9065 // Check the basic block.
9066 if (Label.Kind == ValID::t_LocalID)
9067 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9068 if (Label.Kind != ValID::t_LocalName)
9069 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9070 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9071 if (!V)
9072 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9073 if (!isa<BasicBlock>(V))
9074 return error(Label.Loc, "expected basic block in uselistorder_bb");
9075
9076 return sortUseListOrder(V, Indexes, Loc);
9077}
9078
9079/// ModuleEntry
9080/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9081/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9082bool LLParser::parseModuleEntry(unsigned ID) {
9083 assert(Lex.getKind() == lltok::kw_module);
9084 Lex.Lex();
9085
9086 std::string Path;
9087 if (parseToken(lltok::colon, "expected ':' here") ||
9088 parseToken(lltok::lparen, "expected '(' here") ||
9089 parseToken(lltok::kw_path, "expected 'path' here") ||
9090 parseToken(lltok::colon, "expected ':' here") ||
9091 parseStringConstant(Path) ||
9092 parseToken(lltok::comma, "expected ',' here") ||
9093 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9094 parseToken(lltok::colon, "expected ':' here") ||
9095 parseToken(lltok::lparen, "expected '(' here"))
9096 return true;
9097
9098 ModuleHash Hash;
9099 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9100 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9101 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9102 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9103 parseUInt32(Hash[4]))
9104 return true;
9105
9106 if (parseToken(lltok::rparen, "expected ')' here") ||
9107 parseToken(lltok::rparen, "expected ')' here"))
9108 return true;
9109
9110 auto ModuleEntry = Index->addModule(Path, Hash);
9111 ModuleIdMap[ID] = ModuleEntry->first();
9112
9113 return false;
9114}
9115
9116/// TypeIdEntry
9117/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9118bool LLParser::parseTypeIdEntry(unsigned ID) {
9119 assert(Lex.getKind() == lltok::kw_typeid);
9120 Lex.Lex();
9121
9122 std::string Name;
9123 if (parseToken(lltok::colon, "expected ':' here") ||
9124 parseToken(lltok::lparen, "expected '(' here") ||
9125 parseToken(lltok::kw_name, "expected 'name' here") ||
9126 parseToken(lltok::colon, "expected ':' here") ||
9127 parseStringConstant(Name))
9128 return true;
9129
9130 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9131 if (parseToken(lltok::comma, "expected ',' here") ||
9132 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9133 return true;
9134
9135 // Check if this ID was forward referenced, and if so, update the
9136 // corresponding GUIDs.
9137 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9138 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9139 for (auto TIDRef : FwdRefTIDs->second) {
9140 assert(!*TIDRef.first &&
9141 "Forward referenced type id GUID expected to be 0");
9142 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9143 }
9144 ForwardRefTypeIds.erase(FwdRefTIDs);
9145 }
9146
9147 return false;
9148}
9149
9150/// TypeIdSummary
9151/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9152bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9153 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9154 parseToken(lltok::colon, "expected ':' here") ||
9155 parseToken(lltok::lparen, "expected '(' here") ||
9156 parseTypeTestResolution(TIS.TTRes))
9157 return true;
9158
9159 if (EatIfPresent(lltok::comma)) {
9160 // Expect optional wpdResolutions field
9161 if (parseOptionalWpdResolutions(TIS.WPDRes))
9162 return true;
9163 }
9164
9165 if (parseToken(lltok::rparen, "expected ')' here"))
9166 return true;
9167
9168 return false;
9169}
9170
9172 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9173
9174/// TypeIdCompatibleVtableEntry
9175/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9176/// TypeIdCompatibleVtableInfo
9177/// ')'
9178bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9180 Lex.Lex();
9181
9182 std::string Name;
9183 if (parseToken(lltok::colon, "expected ':' here") ||
9184 parseToken(lltok::lparen, "expected '(' here") ||
9185 parseToken(lltok::kw_name, "expected 'name' here") ||
9186 parseToken(lltok::colon, "expected ':' here") ||
9187 parseStringConstant(Name))
9188 return true;
9189
9191 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9192 if (parseToken(lltok::comma, "expected ',' here") ||
9193 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9194 parseToken(lltok::colon, "expected ':' here") ||
9195 parseToken(lltok::lparen, "expected '(' here"))
9196 return true;
9197
9198 IdToIndexMapType IdToIndexMap;
9199 // parse each call edge
9200 do {
9202 if (parseToken(lltok::lparen, "expected '(' here") ||
9203 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9204 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9205 parseToken(lltok::comma, "expected ',' here"))
9206 return true;
9207
9208 LocTy Loc = Lex.getLoc();
9209 unsigned GVId;
9210 ValueInfo VI;
9211 if (parseGVReference(VI, GVId))
9212 return true;
9213
9214 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9215 // forward reference. We will save the location of the ValueInfo needing an
9216 // update, but can only do so once the std::vector is finalized.
9217 if (VI == EmptyVI)
9218 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9219 TI.push_back({Offset, VI});
9220
9221 if (parseToken(lltok::rparen, "expected ')' in call"))
9222 return true;
9223 } while (EatIfPresent(lltok::comma));
9224
9225 // Now that the TI vector is finalized, it is safe to save the locations
9226 // of any forward GV references that need updating later.
9227 for (auto I : IdToIndexMap) {
9228 auto &Infos = ForwardRefValueInfos[I.first];
9229 for (auto P : I.second) {
9230 assert(TI[P.first].VTableVI == EmptyVI &&
9231 "Forward referenced ValueInfo expected to be empty");
9232 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9233 }
9234 }
9235
9236 if (parseToken(lltok::rparen, "expected ')' here") ||
9237 parseToken(lltok::rparen, "expected ')' here"))
9238 return true;
9239
9240 // Check if this ID was forward referenced, and if so, update the
9241 // corresponding GUIDs.
9242 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9243 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9244 for (auto TIDRef : FwdRefTIDs->second) {
9245 assert(!*TIDRef.first &&
9246 "Forward referenced type id GUID expected to be 0");
9247 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9248 }
9249 ForwardRefTypeIds.erase(FwdRefTIDs);
9250 }
9251
9252 return false;
9253}
9254
9255/// TypeTestResolution
9256/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9257/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9258/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9259/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9260/// [',' 'inlinesBits' ':' UInt64]? ')'
9261bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9262 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9263 parseToken(lltok::colon, "expected ':' here") ||
9264 parseToken(lltok::lparen, "expected '(' here") ||
9265 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9266 parseToken(lltok::colon, "expected ':' here"))
9267 return true;
9268
9269 switch (Lex.getKind()) {
9270 case lltok::kw_unknown:
9272 break;
9273 case lltok::kw_unsat:
9275 break;
9278 break;
9279 case lltok::kw_inline:
9281 break;
9282 case lltok::kw_single:
9284 break;
9285 case lltok::kw_allOnes:
9287 break;
9288 default:
9289 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9290 }
9291 Lex.Lex();
9292
9293 if (parseToken(lltok::comma, "expected ',' here") ||
9294 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9295 parseToken(lltok::colon, "expected ':' here") ||
9296 parseUInt32(TTRes.SizeM1BitWidth))
9297 return true;
9298
9299 // parse optional fields
9300 while (EatIfPresent(lltok::comma)) {
9301 switch (Lex.getKind()) {
9303 Lex.Lex();
9304 if (parseToken(lltok::colon, "expected ':'") ||
9305 parseUInt64(TTRes.AlignLog2))
9306 return true;
9307 break;
9308 case lltok::kw_sizeM1:
9309 Lex.Lex();
9310 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9311 return true;
9312 break;
9313 case lltok::kw_bitMask: {
9314 unsigned Val;
9315 Lex.Lex();
9316 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9317 return true;
9318 assert(Val <= 0xff);
9319 TTRes.BitMask = (uint8_t)Val;
9320 break;
9321 }
9323 Lex.Lex();
9324 if (parseToken(lltok::colon, "expected ':'") ||
9325 parseUInt64(TTRes.InlineBits))
9326 return true;
9327 break;
9328 default:
9329 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9330 }
9331 }
9332
9333 if (parseToken(lltok::rparen, "expected ')' here"))
9334 return true;
9335
9336 return false;
9337}
9338
9339/// OptionalWpdResolutions
9340/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9341/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9342bool LLParser::parseOptionalWpdResolutions(
9343 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9344 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9345 parseToken(lltok::colon, "expected ':' here") ||
9346 parseToken(lltok::lparen, "expected '(' here"))
9347 return true;
9348
9349 do {
9350 uint64_t Offset;
9351 WholeProgramDevirtResolution WPDRes;
9352 if (parseToken(lltok::lparen, "expected '(' here") ||
9353 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9354 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9355 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9356 parseToken(lltok::rparen, "expected ')' here"))
9357 return true;
9358 WPDResMap[Offset] = WPDRes;
9359 } while (EatIfPresent(lltok::comma));
9360
9361 if (parseToken(lltok::rparen, "expected ')' here"))
9362 return true;
9363
9364 return false;
9365}
9366
9367/// WpdRes
9368/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9369/// [',' OptionalResByArg]? ')'
9370/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9371/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9372/// [',' OptionalResByArg]? ')'
9373/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9374/// [',' OptionalResByArg]? ')'
9375bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9376 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9377 parseToken(lltok::colon, "expected ':' here") ||
9378 parseToken(lltok::lparen, "expected '(' here") ||
9379 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9380 parseToken(lltok::colon, "expected ':' here"))
9381 return true;
9382
9383 switch (Lex.getKind()) {
9384 case lltok::kw_indir:
9386 break;
9389 break;
9392 break;
9393 default:
9394 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9395 }
9396 Lex.Lex();
9397
9398 // parse optional fields
9399 while (EatIfPresent(lltok::comma)) {
9400 switch (Lex.getKind()) {
9402 Lex.Lex();
9403 if (parseToken(lltok::colon, "expected ':' here") ||
9404 parseStringConstant(WPDRes.SingleImplName))
9405 return true;
9406 break;
9407 case lltok::kw_resByArg:
9408 if (parseOptionalResByArg(WPDRes.ResByArg))
9409 return true;
9410 break;
9411 default:
9412 return error(Lex.getLoc(),
9413 "expected optional WholeProgramDevirtResolution field");
9414 }
9415 }
9416
9417 if (parseToken(lltok::rparen, "expected ')' here"))
9418 return true;
9419
9420 return false;
9421}
9422
9423/// OptionalResByArg
9424/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9425/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9426/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9427/// 'virtualConstProp' )
9428/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9429/// [',' 'bit' ':' UInt32]? ')'
9430bool LLParser::parseOptionalResByArg(
9431 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9432 &ResByArg) {
9433 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9434 parseToken(lltok::colon, "expected ':' here") ||
9435 parseToken(lltok::lparen, "expected '(' here"))
9436 return true;
9437
9438 do {
9439 std::vector<uint64_t> Args;
9440 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9441 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9442 parseToken(lltok::colon, "expected ':' here") ||
9443 parseToken(lltok::lparen, "expected '(' here") ||
9444 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9445 parseToken(lltok::colon, "expected ':' here"))
9446 return true;
9447
9448 WholeProgramDevirtResolution::ByArg ByArg;
9449 switch (Lex.getKind()) {
9450 case lltok::kw_indir:
9452 break;
9455 break;
9458 break;
9461 break;
9462 default:
9463 return error(Lex.getLoc(),
9464 "unexpected WholeProgramDevirtResolution::ByArg kind");
9465 }
9466 Lex.Lex();
9467
9468 // parse optional fields
9469 while (EatIfPresent(lltok::comma)) {
9470 switch (Lex.getKind()) {
9471 case lltok::kw_info:
9472 Lex.Lex();
9473 if (parseToken(lltok::colon, "expected ':' here") ||
9474 parseUInt64(ByArg.Info))
9475 return true;
9476 break;
9477 case lltok::kw_byte:
9478 Lex.Lex();
9479 if (parseToken(lltok::colon, "expected ':' here") ||
9480 parseUInt32(ByArg.Byte))
9481 return true;
9482 break;
9483 case lltok::kw_bit:
9484 Lex.Lex();
9485 if (parseToken(lltok::colon, "expected ':' here") ||
9486 parseUInt32(ByArg.Bit))
9487 return true;
9488 break;
9489 default:
9490 return error(Lex.getLoc(),
9491 "expected optional whole program devirt field");
9492 }
9493 }
9494
9495 if (parseToken(lltok::rparen, "expected ')' here"))
9496 return true;
9497
9498 ResByArg[Args] = ByArg;
9499 } while (EatIfPresent(lltok::comma));
9500
9501 if (parseToken(lltok::rparen, "expected ')' here"))
9502 return true;
9503
9504 return false;
9505}
9506
9507/// OptionalResByArg
9508/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9509bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9510 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9511 parseToken(lltok::colon, "expected ':' here") ||
9512 parseToken(lltok::lparen, "expected '(' here"))
9513 return true;
9514
9515 do {
9516 uint64_t Val;
9517 if (parseUInt64(Val))
9518 return true;
9519 Args.push_back(Val);
9520 } while (EatIfPresent(lltok::comma));
9521
9522 if (parseToken(lltok::rparen, "expected ')' here"))
9523 return true;
9524
9525 return false;
9526}
9527
9528static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9529
9530static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9531 bool ReadOnly = Fwd->isReadOnly();
9532 bool WriteOnly = Fwd->isWriteOnly();
9533 assert(!(ReadOnly && WriteOnly));
9534 *Fwd = Resolved;
9535 if (ReadOnly)
9536 Fwd->setReadOnly();
9537 if (WriteOnly)
9538 Fwd->setWriteOnly();
9539}
9540
9541/// Stores the given Name/GUID and associated summary into the Index.
9542/// Also updates any forward references to the associated entry ID.
9543bool LLParser::addGlobalValueToIndex(
9544 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9545 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9546 // First create the ValueInfo utilizing the Name or GUID.
9547 ValueInfo VI;
9548 if (GUID != 0) {
9549 assert(Name.empty());
9550 VI = Index->getOrInsertValueInfo(GUID);
9551 } else {
9552 assert(!Name.empty());
9553 if (M) {
9554 auto *GV = M->getNamedValue(Name);
9555 if (!GV)
9556 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9557
9558 VI = Index->getOrInsertValueInfo(GV);
9559 } else {
9560 assert(
9561 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9562 "Need a source_filename to compute GUID for local");
9564 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9565 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9566 }
9567 }
9568
9569 // Resolve forward references from calls/refs
9570 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9571 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9572 for (auto VIRef : FwdRefVIs->second) {
9573 assert(VIRef.first->getRef() == FwdVIRef &&
9574 "Forward referenced ValueInfo expected to be empty");
9575 resolveFwdRef(VIRef.first, VI);
9576 }
9577 ForwardRefValueInfos.erase(FwdRefVIs);
9578 }
9579
9580 // Resolve forward references from aliases
9581 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9582 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9583 for (auto AliaseeRef : FwdRefAliasees->second) {
9584 assert(!AliaseeRef.first->hasAliasee() &&
9585 "Forward referencing alias already has aliasee");
9586 assert(Summary && "Aliasee must be a definition");
9587 AliaseeRef.first->setAliasee(VI, Summary.get());
9588 }
9589 ForwardRefAliasees.erase(FwdRefAliasees);
9590 }
9591
9592 // Add the summary if one was provided.
9593 if (Summary)
9594 Index->addGlobalValueSummary(VI, std::move(Summary));
9595
9596 // Save the associated ValueInfo for use in later references by ID.
9597 if (ID == NumberedValueInfos.size())
9598 NumberedValueInfos.push_back(VI);
9599 else {
9600 // Handle non-continuous numbers (to make test simplification easier).
9601 if (ID > NumberedValueInfos.size())
9602 NumberedValueInfos.resize(ID + 1);
9603 NumberedValueInfos[ID] = VI;
9604 }
9605
9606 return false;
9607}
9608
9609/// parseSummaryIndexFlags
9610/// ::= 'flags' ':' UInt64
9611bool LLParser::parseSummaryIndexFlags() {
9612 assert(Lex.getKind() == lltok::kw_flags);
9613 Lex.Lex();
9614
9615 if (parseToken(lltok::colon, "expected ':' here"))
9616 return true;
9617 uint64_t Flags;
9618 if (parseUInt64(Flags))
9619 return true;
9620 if (Index)
9621 Index->setFlags(Flags);
9622 return false;
9623}
9624
9625/// parseBlockCount
9626/// ::= 'blockcount' ':' UInt64
9627bool LLParser::parseBlockCount() {
9628 assert(Lex.getKind() == lltok::kw_blockcount);
9629 Lex.Lex();
9630
9631 if (parseToken(lltok::colon, "expected ':' here"))
9632 return true;
9633 uint64_t BlockCount;
9634 if (parseUInt64(BlockCount))
9635 return true;
9636 if (Index)
9637 Index->setBlockCount(BlockCount);
9638 return false;
9639}
9640
9641/// parseGVEntry
9642/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9643/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9644/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9645bool LLParser::parseGVEntry(unsigned ID) {
9646 assert(Lex.getKind() == lltok::kw_gv);
9647 Lex.Lex();
9648
9649 if (parseToken(lltok::colon, "expected ':' here") ||
9650 parseToken(lltok::lparen, "expected '(' here"))
9651 return true;
9652
9653 LocTy Loc = Lex.getLoc();
9654 std::string Name;
9656 switch (Lex.getKind()) {
9657 case lltok::kw_name:
9658 Lex.Lex();
9659 if (parseToken(lltok::colon, "expected ':' here") ||
9660 parseStringConstant(Name))
9661 return true;
9662 // Can't create GUID/ValueInfo until we have the linkage.
9663 break;
9664 case lltok::kw_guid:
9665 Lex.Lex();
9666 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9667 return true;
9668 break;
9669 default:
9670 return error(Lex.getLoc(), "expected name or guid tag");
9671 }
9672
9673 if (!EatIfPresent(lltok::comma)) {
9674 // No summaries. Wrap up.
9675 if (parseToken(lltok::rparen, "expected ')' here"))
9676 return true;
9677 // This was created for a call to an external or indirect target.
9678 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9679 // created for indirect calls with VP. A Name with no GUID came from
9680 // an external definition. We pass ExternalLinkage since that is only
9681 // used when the GUID must be computed from Name, and in that case
9682 // the symbol must have external linkage.
9683 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9684 nullptr, Loc);
9685 }
9686
9687 // Have a list of summaries
9688 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9689 parseToken(lltok::colon, "expected ':' here") ||
9690 parseToken(lltok::lparen, "expected '(' here"))
9691 return true;
9692 do {
9693 switch (Lex.getKind()) {
9694 case lltok::kw_function:
9695 if (parseFunctionSummary(Name, GUID, ID))
9696 return true;
9697 break;
9698 case lltok::kw_variable:
9699 if (parseVariableSummary(Name, GUID, ID))
9700 return true;
9701 break;
9702 case lltok::kw_alias:
9703 if (parseAliasSummary(Name, GUID, ID))
9704 return true;
9705 break;
9706 default:
9707 return error(Lex.getLoc(), "expected summary type");
9708 }
9709 } while (EatIfPresent(lltok::comma));
9710
9711 if (parseToken(lltok::rparen, "expected ')' here") ||
9712 parseToken(lltok::rparen, "expected ')' here"))
9713 return true;
9714
9715 return false;
9716}
9717
9718/// FunctionSummary
9719/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9720/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9721/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9722/// [',' OptionalRefs]? ')'
9723bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9724 unsigned ID) {
9725 LocTy Loc = Lex.getLoc();
9726 assert(Lex.getKind() == lltok::kw_function);
9727 Lex.Lex();
9728
9729 StringRef ModulePath;
9730 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9732 /*NotEligibleToImport=*/false,
9733 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9735 unsigned InstCount;
9737 FunctionSummary::TypeIdInfo TypeIdInfo;
9738 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9740 std::vector<CallsiteInfo> Callsites;
9741 std::vector<AllocInfo> Allocs;
9742 // Default is all-zeros (conservative values).
9743 FunctionSummary::FFlags FFlags = {};
9744 if (parseToken(lltok::colon, "expected ':' here") ||
9745 parseToken(lltok::lparen, "expected '(' here") ||
9746 parseModuleReference(ModulePath) ||
9747 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9748 parseToken(lltok::comma, "expected ',' here") ||
9749 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9750 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9751 return true;
9752
9753 // parse optional fields
9754 while (EatIfPresent(lltok::comma)) {
9755 switch (Lex.getKind()) {
9757 if (parseOptionalFFlags(FFlags))
9758 return true;
9759 break;
9760 case lltok::kw_calls:
9761 if (parseOptionalCalls(Calls))
9762 return true;
9763 break;
9765 if (parseOptionalTypeIdInfo(TypeIdInfo))
9766 return true;
9767 break;
9768 case lltok::kw_refs:
9769 if (parseOptionalRefs(Refs))
9770 return true;
9771 break;
9772 case lltok::kw_params:
9773 if (parseOptionalParamAccesses(ParamAccesses))
9774 return true;
9775 break;
9776 case lltok::kw_allocs:
9777 if (parseOptionalAllocs(Allocs))
9778 return true;
9779 break;
9781 if (parseOptionalCallsites(Callsites))
9782 return true;
9783 break;
9784 default:
9785 return error(Lex.getLoc(), "expected optional function summary field");
9786 }
9787 }
9788
9789 if (parseToken(lltok::rparen, "expected ')' here"))
9790 return true;
9791
9792 auto FS = std::make_unique<FunctionSummary>(
9793 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9794 std::move(TypeIdInfo.TypeTests),
9795 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9796 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9797 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9798 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9799 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9800
9801 FS->setModulePath(ModulePath);
9802
9803 return addGlobalValueToIndex(Name, GUID,
9805 std::move(FS), Loc);
9806}
9807
9808/// VariableSummary
9809/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9810/// [',' OptionalRefs]? ')'
9811bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9812 unsigned ID) {
9813 LocTy Loc = Lex.getLoc();
9814 assert(Lex.getKind() == lltok::kw_variable);
9815 Lex.Lex();
9816
9817 StringRef ModulePath;
9818 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9820 /*NotEligibleToImport=*/false,
9821 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9823 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9824 /* WriteOnly */ false,
9825 /* Constant */ false,
9828 VTableFuncList VTableFuncs;
9829 if (parseToken(lltok::colon, "expected ':' here") ||
9830 parseToken(lltok::lparen, "expected '(' here") ||
9831 parseModuleReference(ModulePath) ||
9832 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9833 parseToken(lltok::comma, "expected ',' here") ||
9834 parseGVarFlags(GVarFlags))
9835 return true;
9836
9837 // parse optional fields
9838 while (EatIfPresent(lltok::comma)) {
9839 switch (Lex.getKind()) {
9841 if (parseOptionalVTableFuncs(VTableFuncs))
9842 return true;
9843 break;
9844 case lltok::kw_refs:
9845 if (parseOptionalRefs(Refs))
9846 return true;
9847 break;
9848 default:
9849 return error(Lex.getLoc(), "expected optional variable summary field");
9850 }
9851 }
9852
9853 if (parseToken(lltok::rparen, "expected ')' here"))
9854 return true;
9855
9856 auto GS =
9857 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9858
9859 GS->setModulePath(ModulePath);
9860 GS->setVTableFuncs(std::move(VTableFuncs));
9861
9862 return addGlobalValueToIndex(Name, GUID,
9864 std::move(GS), Loc);
9865}
9866
9867/// AliasSummary
9868/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9869/// 'aliasee' ':' GVReference ')'
9870bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9871 unsigned ID) {
9872 assert(Lex.getKind() == lltok::kw_alias);
9873 LocTy Loc = Lex.getLoc();
9874 Lex.Lex();
9875
9876 StringRef ModulePath;
9877 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9879 /*NotEligibleToImport=*/false,
9880 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9882 if (parseToken(lltok::colon, "expected ':' here") ||
9883 parseToken(lltok::lparen, "expected '(' here") ||
9884 parseModuleReference(ModulePath) ||
9885 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9886 parseToken(lltok::comma, "expected ',' here") ||
9887 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9888 parseToken(lltok::colon, "expected ':' here"))
9889 return true;
9890
9891 ValueInfo AliaseeVI;
9892 unsigned GVId;
9893 if (parseGVReference(AliaseeVI, GVId))
9894 return true;
9895
9896 if (parseToken(lltok::rparen, "expected ')' here"))
9897 return true;
9898
9899 auto AS = std::make_unique<AliasSummary>(GVFlags);
9900
9901 AS->setModulePath(ModulePath);
9902
9903 // Record forward reference if the aliasee is not parsed yet.
9904 if (AliaseeVI.getRef() == FwdVIRef) {
9905 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9906 } else {
9907 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9908 assert(Summary && "Aliasee must be a definition");
9909 AS->setAliasee(AliaseeVI, Summary);
9910 }
9911
9912 return addGlobalValueToIndex(Name, GUID,
9914 std::move(AS), Loc);
9915}
9916
9917/// Flag
9918/// ::= [0|1]
9919bool LLParser::parseFlag(unsigned &Val) {
9920 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9921 return tokError("expected integer");
9922 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9923 Lex.Lex();
9924 return false;
9925}
9926
9927/// OptionalFFlags
9928/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9929/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9930/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9931/// [',' 'noInline' ':' Flag]? ')'
9932/// [',' 'alwaysInline' ':' Flag]? ')'
9933/// [',' 'noUnwind' ':' Flag]? ')'
9934/// [',' 'mayThrow' ':' Flag]? ')'
9935/// [',' 'hasUnknownCall' ':' Flag]? ')'
9936/// [',' 'mustBeUnreachable' ':' Flag]? ')'
9937
9938bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9939 assert(Lex.getKind() == lltok::kw_funcFlags);
9940 Lex.Lex();
9941
9942 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
9943 parseToken(lltok::lparen, "expected '(' in funcFlags"))
9944 return true;
9945
9946 do {
9947 unsigned Val = 0;
9948 switch (Lex.getKind()) {
9949 case lltok::kw_readNone:
9950 Lex.Lex();
9951 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9952 return true;
9953 FFlags.ReadNone = Val;
9954 break;
9955 case lltok::kw_readOnly:
9956 Lex.Lex();
9957 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9958 return true;
9959 FFlags.ReadOnly = Val;
9960 break;
9962 Lex.Lex();
9963 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9964 return true;
9965 FFlags.NoRecurse = Val;
9966 break;
9968 Lex.Lex();
9969 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9970 return true;
9971 FFlags.ReturnDoesNotAlias = Val;
9972 break;
9973 case lltok::kw_noInline:
9974 Lex.Lex();
9975 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9976 return true;
9977 FFlags.NoInline = Val;
9978 break;
9980 Lex.Lex();
9981 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9982 return true;
9983 FFlags.AlwaysInline = Val;
9984 break;
9985 case lltok::kw_noUnwind:
9986 Lex.Lex();
9987 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9988 return true;
9989 FFlags.NoUnwind = Val;
9990 break;
9991 case lltok::kw_mayThrow:
9992 Lex.Lex();
9993 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9994 return true;
9995 FFlags.MayThrow = Val;
9996 break;
9998 Lex.Lex();
9999 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10000 return true;
10001 FFlags.HasUnknownCall = Val;
10002 break;
10004 Lex.Lex();
10005 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10006 return true;
10007 FFlags.MustBeUnreachable = Val;
10008 break;
10009 default:
10010 return error(Lex.getLoc(), "expected function flag type");
10011 }
10012 } while (EatIfPresent(lltok::comma));
10013
10014 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10015 return true;
10016
10017 return false;
10018}
10019
10020/// OptionalCalls
10021/// := 'calls' ':' '(' Call [',' Call]* ')'
10022/// Call ::= '(' 'callee' ':' GVReference
10023/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10024/// [ ',' 'tail' ]? ')'
10025bool LLParser::parseOptionalCalls(
10026 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10027 assert(Lex.getKind() == lltok::kw_calls);
10028 Lex.Lex();
10029
10030 if (parseToken(lltok::colon, "expected ':' in calls") ||
10031 parseToken(lltok::lparen, "expected '(' in calls"))
10032 return true;
10033
10034 IdToIndexMapType IdToIndexMap;
10035 // parse each call edge
10036 do {
10037 ValueInfo VI;
10038 if (parseToken(lltok::lparen, "expected '(' in call") ||
10039 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10040 parseToken(lltok::colon, "expected ':'"))
10041 return true;
10042
10043 LocTy Loc = Lex.getLoc();
10044 unsigned GVId;
10045 if (parseGVReference(VI, GVId))
10046 return true;
10047
10049 unsigned RelBF = 0;
10050 unsigned HasTailCall = false;
10051
10052 // parse optional fields
10053 while (EatIfPresent(lltok::comma)) {
10054 switch (Lex.getKind()) {
10055 case lltok::kw_hotness:
10056 Lex.Lex();
10057 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10058 return true;
10059 break;
10060 case lltok::kw_relbf:
10061 Lex.Lex();
10062 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10063 return true;
10064 break;
10065 case lltok::kw_tail:
10066 Lex.Lex();
10067 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10068 return true;
10069 break;
10070 default:
10071 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10072 }
10073 }
10074 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
10075 return tokError("Expected only one of hotness or relbf");
10076 // Keep track of the Call array index needing a forward reference.
10077 // We will save the location of the ValueInfo needing an update, but
10078 // can only do so once the std::vector is finalized.
10079 if (VI.getRef() == FwdVIRef)
10080 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10081 Calls.push_back(
10082 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
10083
10084 if (parseToken(lltok::rparen, "expected ')' in call"))
10085 return true;
10086 } while (EatIfPresent(lltok::comma));
10087
10088 // Now that the Calls vector is finalized, it is safe to save the locations
10089 // of any forward GV references that need updating later.
10090 for (auto I : IdToIndexMap) {
10091 auto &Infos = ForwardRefValueInfos[I.first];
10092 for (auto P : I.second) {
10093 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10094 "Forward referenced ValueInfo expected to be empty");
10095 Infos.emplace_back(&Calls[P.first].first, P.second);
10096 }
10097 }
10098
10099 if (parseToken(lltok::rparen, "expected ')' in calls"))
10100 return true;
10101
10102 return false;
10103}
10104
10105/// Hotness
10106/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10107bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10108 switch (Lex.getKind()) {
10109 case lltok::kw_unknown:
10111 break;
10112 case lltok::kw_cold:
10114 break;
10115 case lltok::kw_none:
10117 break;
10118 case lltok::kw_hot:
10120 break;
10121 case lltok::kw_critical:
10123 break;
10124 default:
10125 return error(Lex.getLoc(), "invalid call edge hotness");
10126 }
10127 Lex.Lex();
10128 return false;
10129}
10130
10131/// OptionalVTableFuncs
10132/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10133/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10134bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10135 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10136 Lex.Lex();
10137
10138 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10139 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10140 return true;
10141
10142 IdToIndexMapType IdToIndexMap;
10143 // parse each virtual function pair
10144 do {
10145 ValueInfo VI;
10146 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10147 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10148 parseToken(lltok::colon, "expected ':'"))
10149 return true;
10150
10151 LocTy Loc = Lex.getLoc();
10152 unsigned GVId;
10153 if (parseGVReference(VI, GVId))
10154 return true;
10155
10156 uint64_t Offset;
10157 if (parseToken(lltok::comma, "expected comma") ||
10158 parseToken(lltok::kw_offset, "expected offset") ||
10159 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10160 return true;
10161
10162 // Keep track of the VTableFuncs array index needing a forward reference.
10163 // We will save the location of the ValueInfo needing an update, but
10164 // can only do so once the std::vector is finalized.
10165 if (VI == EmptyVI)
10166 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10167 VTableFuncs.push_back({VI, Offset});
10168
10169 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10170 return true;
10171 } while (EatIfPresent(lltok::comma));
10172
10173 // Now that the VTableFuncs vector is finalized, it is safe to save the
10174 // locations of any forward GV references that need updating later.
10175 for (auto I : IdToIndexMap) {
10176 auto &Infos = ForwardRefValueInfos[I.first];
10177 for (auto P : I.second) {
10178 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10179 "Forward referenced ValueInfo expected to be empty");
10180 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10181 }
10182 }
10183
10184 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10185 return true;
10186
10187 return false;
10188}
10189
10190/// ParamNo := 'param' ':' UInt64
10191bool LLParser::parseParamNo(uint64_t &ParamNo) {
10192 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10193 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10194 return true;
10195 return false;
10196}
10197
10198/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10199bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10200 APSInt Lower;
10201 APSInt Upper;
10202 auto ParseAPSInt = [&](APSInt &Val) {
10203 if (Lex.getKind() != lltok::APSInt)
10204 return tokError("expected integer");
10205 Val = Lex.getAPSIntVal();
10206 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10207 Val.setIsSigned(true);
10208 Lex.Lex();
10209 return false;
10210 };
10211 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10212 parseToken(lltok::colon, "expected ':' here") ||
10213 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10214 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10215 parseToken(lltok::rsquare, "expected ']' here"))
10216 return true;
10217
10218 ++Upper;
10219 Range =
10220 (Lower == Upper && !Lower.isMaxValue())
10221 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10222 : ConstantRange(Lower, Upper);
10223
10224 return false;
10225}
10226
10227/// ParamAccessCall
10228/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10229bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10230 IdLocListType &IdLocList) {
10231 if (parseToken(lltok::lparen, "expected '(' here") ||
10232 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10233 parseToken(lltok::colon, "expected ':' here"))
10234 return true;
10235
10236 unsigned GVId;
10237 ValueInfo VI;
10238 LocTy Loc = Lex.getLoc();
10239 if (parseGVReference(VI, GVId))
10240 return true;
10241
10242 Call.Callee = VI;
10243 IdLocList.emplace_back(GVId, Loc);
10244
10245 if (parseToken(lltok::comma, "expected ',' here") ||
10246 parseParamNo(Call.ParamNo) ||
10247 parseToken(lltok::comma, "expected ',' here") ||
10248 parseParamAccessOffset(Call.Offsets))
10249 return true;
10250
10251 if (parseToken(lltok::rparen, "expected ')' here"))
10252 return true;
10253
10254 return false;
10255}
10256
10257/// ParamAccess
10258/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10259/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10260bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10261 IdLocListType &IdLocList) {
10262 if (parseToken(lltok::lparen, "expected '(' here") ||
10263 parseParamNo(Param.ParamNo) ||
10264 parseToken(lltok::comma, "expected ',' here") ||
10265 parseParamAccessOffset(Param.Use))
10266 return true;
10267
10268 if (EatIfPresent(lltok::comma)) {
10269 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10270 parseToken(lltok::colon, "expected ':' here") ||
10271 parseToken(lltok::lparen, "expected '(' here"))
10272 return true;
10273 do {
10274 FunctionSummary::ParamAccess::Call Call;
10275 if (parseParamAccessCall(Call, IdLocList))
10276 return true;
10277 Param.Calls.push_back(Call);
10278 } while (EatIfPresent(lltok::comma));
10279
10280 if (parseToken(lltok::rparen, "expected ')' here"))
10281 return true;
10282 }
10283
10284 if (parseToken(lltok::rparen, "expected ')' here"))
10285 return true;
10286
10287 return false;
10288}
10289
10290/// OptionalParamAccesses
10291/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10292bool LLParser::parseOptionalParamAccesses(
10293 std::vector<FunctionSummary::ParamAccess> &Params) {
10294 assert(Lex.getKind() == lltok::kw_params);
10295 Lex.Lex();
10296
10297 if (parseToken(lltok::colon, "expected ':' here") ||
10298 parseToken(lltok::lparen, "expected '(' here"))
10299 return true;
10300
10301 IdLocListType VContexts;
10302 size_t CallsNum = 0;
10303 do {
10304 FunctionSummary::ParamAccess ParamAccess;
10305 if (parseParamAccess(ParamAccess, VContexts))
10306 return true;
10307 CallsNum += ParamAccess.Calls.size();
10308 assert(VContexts.size() == CallsNum);
10309 (void)CallsNum;
10310 Params.emplace_back(std::move(ParamAccess));
10311 } while (EatIfPresent(lltok::comma));
10312
10313 if (parseToken(lltok::rparen, "expected ')' here"))
10314 return true;
10315
10316 // Now that the Params is finalized, it is safe to save the locations
10317 // of any forward GV references that need updating later.
10318 IdLocListType::const_iterator ItContext = VContexts.begin();
10319 for (auto &PA : Params) {
10320 for (auto &C : PA.Calls) {
10321 if (C.Callee.getRef() == FwdVIRef)
10322 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10323 ItContext->second);
10324 ++ItContext;
10325 }
10326 }
10327 assert(ItContext == VContexts.end());
10328
10329 return false;
10330}
10331
10332/// OptionalRefs
10333/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10334bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10335 assert(Lex.getKind() == lltok::kw_refs);
10336 Lex.Lex();
10337
10338 if (parseToken(lltok::colon, "expected ':' in refs") ||
10339 parseToken(lltok::lparen, "expected '(' in refs"))
10340 return true;
10341
10342 struct ValueContext {
10343 ValueInfo VI;
10344 unsigned GVId;
10345 LocTy Loc;
10346 };
10347 std::vector<ValueContext> VContexts;
10348 // parse each ref edge
10349 do {
10350 ValueContext VC;
10351 VC.Loc = Lex.getLoc();
10352 if (parseGVReference(VC.VI, VC.GVId))
10353 return true;
10354 VContexts.push_back(VC);
10355 } while (EatIfPresent(lltok::comma));
10356
10357 // Sort value contexts so that ones with writeonly
10358 // and readonly ValueInfo are at the end of VContexts vector.
10359 // See FunctionSummary::specialRefCounts()
10360 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10361 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10362 });
10363
10364 IdToIndexMapType IdToIndexMap;
10365 for (auto &VC : VContexts) {
10366 // Keep track of the Refs array index needing a forward reference.
10367 // We will save the location of the ValueInfo needing an update, but
10368 // can only do so once the std::vector is finalized.
10369 if (VC.VI.getRef() == FwdVIRef)
10370 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10371 Refs.push_back(VC.VI);
10372 }
10373
10374 // Now that the Refs vector is finalized, it is safe to save the locations
10375 // of any forward GV references that need updating later.
10376 for (auto I : IdToIndexMap) {
10377 auto &Infos = ForwardRefValueInfos[I.first];
10378 for (auto P : I.second) {
10379 assert(Refs[P.first].getRef() == FwdVIRef &&
10380 "Forward referenced ValueInfo expected to be empty");
10381 Infos.emplace_back(&Refs[P.first], P.second);
10382 }
10383 }
10384
10385 if (parseToken(lltok::rparen, "expected ')' in refs"))
10386 return true;
10387
10388 return false;
10389}
10390
10391/// OptionalTypeIdInfo
10392/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10393/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10394/// [',' TypeCheckedLoadConstVCalls]? ')'
10395bool LLParser::parseOptionalTypeIdInfo(
10396 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10397 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10398 Lex.Lex();
10399
10400 if (parseToken(lltok::colon, "expected ':' here") ||
10401 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10402 return true;
10403
10404 do {
10405 switch (Lex.getKind()) {
10407 if (parseTypeTests(TypeIdInfo.TypeTests))
10408 return true;
10409 break;
10411 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10412 TypeIdInfo.TypeTestAssumeVCalls))
10413 return true;
10414 break;
10416 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10417 TypeIdInfo.TypeCheckedLoadVCalls))
10418 return true;
10419 break;
10421 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10422 TypeIdInfo.TypeTestAssumeConstVCalls))
10423 return true;
10424 break;
10426 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10427 TypeIdInfo.TypeCheckedLoadConstVCalls))
10428 return true;
10429 break;
10430 default:
10431 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10432 }
10433 } while (EatIfPresent(lltok::comma));
10434
10435 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10436 return true;
10437
10438 return false;
10439}
10440
10441/// TypeTests
10442/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10443/// [',' (SummaryID | UInt64)]* ')'
10444bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10445 assert(Lex.getKind() == lltok::kw_typeTests);
10446 Lex.Lex();
10447
10448 if (parseToken(lltok::colon, "expected ':' here") ||
10449 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10450 return true;
10451
10452 IdToIndexMapType IdToIndexMap;
10453 do {
10455 if (Lex.getKind() == lltok::SummaryID) {
10456 unsigned ID = Lex.getUIntVal();
10457 LocTy Loc = Lex.getLoc();
10458 // Keep track of the TypeTests array index needing a forward reference.
10459 // We will save the location of the GUID needing an update, but
10460 // can only do so once the std::vector is finalized.
10461 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10462 Lex.Lex();
10463 } else if (parseUInt64(GUID))
10464 return true;
10465 TypeTests.push_back(GUID);
10466 } while (EatIfPresent(lltok::comma));
10467
10468 // Now that the TypeTests vector is finalized, it is safe to save the
10469 // locations of any forward GV references that need updating later.
10470 for (auto I : IdToIndexMap) {
10471 auto &Ids = ForwardRefTypeIds[I.first];
10472 for (auto P : I.second) {
10473 assert(TypeTests[P.first] == 0 &&
10474 "Forward referenced type id GUID expected to be 0");
10475 Ids.emplace_back(&TypeTests[P.first], P.second);
10476 }
10477 }
10478
10479 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10480 return true;
10481
10482 return false;
10483}
10484
10485/// VFuncIdList
10486/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10487bool LLParser::parseVFuncIdList(
10488 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10489 assert(Lex.getKind() == Kind);
10490 Lex.Lex();
10491
10492 if (parseToken(lltok::colon, "expected ':' here") ||
10493 parseToken(lltok::lparen, "expected '(' here"))
10494 return true;
10495
10496 IdToIndexMapType IdToIndexMap;
10497 do {
10498 FunctionSummary::VFuncId VFuncId;
10499 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10500 return true;
10501 VFuncIdList.push_back(VFuncId);
10502 } while (EatIfPresent(lltok::comma));
10503
10504 if (parseToken(lltok::rparen, "expected ')' here"))
10505 return true;
10506
10507 // Now that the VFuncIdList vector is finalized, it is safe to save the
10508 // locations of any forward GV references that need updating later.
10509 for (auto I : IdToIndexMap) {
10510 auto &Ids = ForwardRefTypeIds[I.first];
10511 for (auto P : I.second) {
10512 assert(VFuncIdList[P.first].GUID == 0 &&
10513 "Forward referenced type id GUID expected to be 0");
10514 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10515 }
10516 }
10517
10518 return false;
10519}
10520
10521/// ConstVCallList
10522/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10523bool LLParser::parseConstVCallList(
10524 lltok::Kind Kind,
10525 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10526 assert(Lex.getKind() == Kind);
10527 Lex.Lex();
10528
10529 if (parseToken(lltok::colon, "expected ':' here") ||
10530 parseToken(lltok::lparen, "expected '(' here"))
10531 return true;
10532
10533 IdToIndexMapType IdToIndexMap;
10534 do {
10535 FunctionSummary::ConstVCall ConstVCall;
10536 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10537 return true;
10538 ConstVCallList.push_back(ConstVCall);
10539 } while (EatIfPresent(lltok::comma));
10540
10541 if (parseToken(lltok::rparen, "expected ')' here"))
10542 return true;
10543
10544 // Now that the ConstVCallList vector is finalized, it is safe to save the
10545 // locations of any forward GV references that need updating later.
10546 for (auto I : IdToIndexMap) {
10547 auto &Ids = ForwardRefTypeIds[I.first];
10548 for (auto P : I.second) {
10549 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10550 "Forward referenced type id GUID expected to be 0");
10551 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10552 }
10553 }
10554
10555 return false;
10556}
10557
10558/// ConstVCall
10559/// ::= '(' VFuncId ',' Args ')'
10560bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10561 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10562 if (parseToken(lltok::lparen, "expected '(' here") ||
10563 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10564 return true;
10565
10566 if (EatIfPresent(lltok::comma))
10567 if (parseArgs(ConstVCall.Args))
10568 return true;
10569
10570 if (parseToken(lltok::rparen, "expected ')' here"))
10571 return true;
10572
10573 return false;
10574}
10575
10576/// VFuncId
10577/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10578/// 'offset' ':' UInt64 ')'
10579bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10580 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10581 assert(Lex.getKind() == lltok::kw_vFuncId);
10582 Lex.Lex();
10583
10584 if (parseToken(lltok::colon, "expected ':' here") ||
10585 parseToken(lltok::lparen, "expected '(' here"))
10586 return true;
10587
10588 if (Lex.getKind() == lltok::SummaryID) {
10589 VFuncId.GUID = 0;
10590 unsigned ID = Lex.getUIntVal();
10591 LocTy Loc = Lex.getLoc();
10592 // Keep track of the array index needing a forward reference.
10593 // We will save the location of the GUID needing an update, but
10594 // can only do so once the caller's std::vector is finalized.
10595 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10596 Lex.Lex();
10597 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10598 parseToken(lltok::colon, "expected ':' here") ||
10599 parseUInt64(VFuncId.GUID))
10600 return true;
10601
10602 if (parseToken(lltok::comma, "expected ',' here") ||
10603 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10604 parseToken(lltok::colon, "expected ':' here") ||
10605 parseUInt64(VFuncId.Offset) ||
10606 parseToken(lltok::rparen, "expected ')' here"))
10607 return true;
10608
10609 return false;
10610}
10611
10612/// GVFlags
10613/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10614/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10615/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10616/// 'canAutoHide' ':' Flag ',' ')'
10617bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10618 assert(Lex.getKind() == lltok::kw_flags);
10619 Lex.Lex();
10620
10621 if (parseToken(lltok::colon, "expected ':' here") ||
10622 parseToken(lltok::lparen, "expected '(' here"))
10623 return true;
10624
10625 do {
10626 unsigned Flag = 0;
10627 switch (Lex.getKind()) {
10628 case lltok::kw_linkage:
10629 Lex.Lex();
10630 if (parseToken(lltok::colon, "expected ':'"))
10631 return true;
10632 bool HasLinkage;
10633 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10634 assert(HasLinkage && "Linkage not optional in summary entry");
10635 Lex.Lex();
10636 break;
10638 Lex.Lex();
10639 if (parseToken(lltok::colon, "expected ':'"))
10640 return true;
10641 parseOptionalVisibility(Flag);
10642 GVFlags.Visibility = Flag;
10643 break;
10645 Lex.Lex();
10646 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10647 return true;
10648 GVFlags.NotEligibleToImport = Flag;
10649 break;
10650 case lltok::kw_live:
10651 Lex.Lex();
10652 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10653 return true;
10654 GVFlags.Live = Flag;
10655 break;
10656 case lltok::kw_dsoLocal:
10657 Lex.Lex();
10658 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10659 return true;
10660 GVFlags.DSOLocal = Flag;
10661 break;
10663 Lex.Lex();
10664 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10665 return true;
10666 GVFlags.CanAutoHide = Flag;
10667 break;
10669 Lex.Lex();
10670 if (parseToken(lltok::colon, "expected ':'"))
10671 return true;
10673 if (parseOptionalImportType(Lex.getKind(), IK))
10674 return true;
10675 GVFlags.ImportType = static_cast<unsigned>(IK);
10676 Lex.Lex();
10677 break;
10678 default:
10679 return error(Lex.getLoc(), "expected gv flag type");
10680 }
10681 } while (EatIfPresent(lltok::comma));
10682
10683 if (parseToken(lltok::rparen, "expected ')' here"))
10684 return true;
10685
10686 return false;
10687}
10688
10689/// GVarFlags
10690/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10691/// ',' 'writeonly' ':' Flag
10692/// ',' 'constant' ':' Flag ')'
10693bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10694 assert(Lex.getKind() == lltok::kw_varFlags);
10695 Lex.Lex();
10696
10697 if (parseToken(lltok::colon, "expected ':' here") ||
10698 parseToken(lltok::lparen, "expected '(' here"))
10699 return true;
10700
10701 auto ParseRest = [this](unsigned int &Val) {
10702 Lex.Lex();
10703 if (parseToken(lltok::colon, "expected ':'"))
10704 return true;
10705 return parseFlag(Val);
10706 };
10707
10708 do {
10709 unsigned Flag = 0;
10710 switch (Lex.getKind()) {
10711 case lltok::kw_readonly:
10712 if (ParseRest(Flag))
10713 return true;
10714 GVarFlags.MaybeReadOnly = Flag;
10715 break;
10716 case lltok::kw_writeonly:
10717 if (ParseRest(Flag))
10718 return true;
10719 GVarFlags.MaybeWriteOnly = Flag;
10720 break;
10721 case lltok::kw_constant:
10722 if (ParseRest(Flag))
10723 return true;
10724 GVarFlags.Constant = Flag;
10725 break;
10727 if (ParseRest(Flag))
10728 return true;
10729 GVarFlags.VCallVisibility = Flag;
10730 break;
10731 default:
10732 return error(Lex.getLoc(), "expected gvar flag type");
10733 }
10734 } while (EatIfPresent(lltok::comma));
10735 return parseToken(lltok::rparen, "expected ')' here");
10736}
10737
10738/// ModuleReference
10739/// ::= 'module' ':' UInt
10740bool LLParser::parseModuleReference(StringRef &ModulePath) {
10741 // parse module id.
10742 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10743 parseToken(lltok::colon, "expected ':' here") ||
10744 parseToken(lltok::SummaryID, "expected module ID"))
10745 return true;
10746
10747 unsigned ModuleID = Lex.getUIntVal();
10748 auto I = ModuleIdMap.find(ModuleID);
10749 // We should have already parsed all module IDs
10750 assert(I != ModuleIdMap.end());
10751 ModulePath = I->second;
10752 return false;
10753}
10754
10755/// GVReference
10756/// ::= SummaryID
10757bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10758 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10759 if (!ReadOnly)
10760 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10761 if (parseToken(lltok::SummaryID, "expected GV ID"))
10762 return true;
10763
10764 GVId = Lex.getUIntVal();
10765 // Check if we already have a VI for this GV
10766 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10767 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10768 VI = NumberedValueInfos[GVId];
10769 } else
10770 // We will create a forward reference to the stored location.
10771 VI = ValueInfo(false, FwdVIRef);
10772
10773 if (ReadOnly)
10774 VI.setReadOnly();
10775 if (WriteOnly)
10776 VI.setWriteOnly();
10777 return false;
10778}
10779
10780/// OptionalAllocs
10781/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10782/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10783/// ',' MemProfs ')'
10784/// Version ::= UInt32
10785bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10786 assert(Lex.getKind() == lltok::kw_allocs);
10787 Lex.Lex();
10788
10789 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10790 parseToken(lltok::lparen, "expected '(' in allocs"))
10791 return true;
10792
10793 // parse each alloc
10794 do {
10795 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10796 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10797 parseToken(lltok::colon, "expected ':'") ||
10798 parseToken(lltok::lparen, "expected '(' in versions"))
10799 return true;
10800
10801 SmallVector<uint8_t> Versions;
10802 do {
10803 uint8_t V = 0;
10804 if (parseAllocType(V))
10805 return true;
10806 Versions.push_back(V);
10807 } while (EatIfPresent(lltok::comma));
10808
10809 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10810 parseToken(lltok::comma, "expected ',' in alloc"))
10811 return true;
10812
10813 std::vector<MIBInfo> MIBs;
10814 if (parseMemProfs(MIBs))
10815 return true;
10816
10817 Allocs.push_back({Versions, MIBs});
10818
10819 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10820 return true;
10821 } while (EatIfPresent(lltok::comma));
10822
10823 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10824 return true;
10825
10826 return false;
10827}
10828
10829/// MemProfs
10830/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10831/// MemProf ::= '(' 'type' ':' AllocType
10832/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10833/// StackId ::= UInt64
10834bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10835 assert(Lex.getKind() == lltok::kw_memProf);
10836 Lex.Lex();
10837
10838 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10839 parseToken(lltok::lparen, "expected '(' in memprof"))
10840 return true;
10841
10842 // parse each MIB
10843 do {
10844 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10845 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10846 parseToken(lltok::colon, "expected ':'"))
10847 return true;
10848
10849 uint8_t AllocType;
10850 if (parseAllocType(AllocType))
10851 return true;
10852
10853 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10854 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10855 parseToken(lltok::colon, "expected ':'") ||
10856 parseToken(lltok::lparen, "expected '(' in stackIds"))
10857 return true;
10858
10859 SmallVector<unsigned> StackIdIndices;
10860 // Combined index alloc records may not have a stack id list.
10861 if (Lex.getKind() != lltok::rparen) {
10862 do {
10863 uint64_t StackId = 0;
10864 if (parseUInt64(StackId))
10865 return true;
10866 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10867 } while (EatIfPresent(lltok::comma));
10868 }
10869
10870 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10871 return true;
10872
10873 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10874
10875 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10876 return true;
10877 } while (EatIfPresent(lltok::comma));
10878
10879 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10880 return true;
10881
10882 return false;
10883}
10884
10885/// AllocType
10886/// := ('none'|'notcold'|'cold'|'hot')
10887bool LLParser::parseAllocType(uint8_t &AllocType) {
10888 switch (Lex.getKind()) {
10889 case lltok::kw_none:
10891 break;
10892 case lltok::kw_notcold:
10894 break;
10895 case lltok::kw_cold:
10897 break;
10898 case lltok::kw_hot:
10899 AllocType = (uint8_t)AllocationType::Hot;
10900 break;
10901 default:
10902 return error(Lex.getLoc(), "invalid alloc type");
10903 }
10904 Lex.Lex();
10905 return false;
10906}
10907
10908/// OptionalCallsites
10909/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10910/// Callsite ::= '(' 'callee' ':' GVReference
10911/// ',' 'clones' ':' '(' Version [',' Version]* ')'
10912/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10913/// Version ::= UInt32
10914/// StackId ::= UInt64
10915bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10916 assert(Lex.getKind() == lltok::kw_callsites);
10917 Lex.Lex();
10918
10919 if (parseToken(lltok::colon, "expected ':' in callsites") ||
10920 parseToken(lltok::lparen, "expected '(' in callsites"))
10921 return true;
10922
10923 IdToIndexMapType IdToIndexMap;
10924 // parse each callsite
10925 do {
10926 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10927 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10928 parseToken(lltok::colon, "expected ':'"))
10929 return true;
10930
10931 ValueInfo VI;
10932 unsigned GVId = 0;
10933 LocTy Loc = Lex.getLoc();
10934 if (!EatIfPresent(lltok::kw_null)) {
10935 if (parseGVReference(VI, GVId))
10936 return true;
10937 }
10938
10939 if (parseToken(lltok::comma, "expected ',' in callsite") ||
10940 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10941 parseToken(lltok::colon, "expected ':'") ||
10942 parseToken(lltok::lparen, "expected '(' in clones"))
10943 return true;
10944
10945 SmallVector<unsigned> Clones;
10946 do {
10947 unsigned V = 0;
10948 if (parseUInt32(V))
10949 return true;
10950 Clones.push_back(V);
10951 } while (EatIfPresent(lltok::comma));
10952
10953 if (parseToken(lltok::rparen, "expected ')' in clones") ||
10954 parseToken(lltok::comma, "expected ',' in callsite") ||
10955 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
10956 parseToken(lltok::colon, "expected ':'") ||
10957 parseToken(lltok::lparen, "expected '(' in stackIds"))
10958 return true;
10959
10960 SmallVector<unsigned> StackIdIndices;
10961 // Synthesized callsite records will not have a stack id list.
10962 if (Lex.getKind() != lltok::rparen) {
10963 do {
10964 uint64_t StackId = 0;
10965 if (parseUInt64(StackId))
10966 return true;
10967 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10968 } while (EatIfPresent(lltok::comma));
10969 }
10970
10971 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10972 return true;
10973
10974 // Keep track of the Callsites array index needing a forward reference.
10975 // We will save the location of the ValueInfo needing an update, but
10976 // can only do so once the SmallVector is finalized.
10977 if (VI.getRef() == FwdVIRef)
10978 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10979 Callsites.push_back({VI, Clones, StackIdIndices});
10980
10981 if (parseToken(lltok::rparen, "expected ')' in callsite"))
10982 return true;
10983 } while (EatIfPresent(lltok::comma));
10984
10985 // Now that the Callsites vector is finalized, it is safe to save the
10986 // locations of any forward GV references that need updating later.
10987 for (auto I : IdToIndexMap) {
10988 auto &Infos = ForwardRefValueInfos[I.first];
10989 for (auto P : I.second) {
10990 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
10991 "Forward referenced ValueInfo expected to be empty");
10992 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
10993 }
10994 }
10995
10996 if (parseToken(lltok::rparen, "expected ')' in callsites"))
10997 return true;
10998
10999 return false;
11000}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:244
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:151
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:67
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1128
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1237
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:120
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
iterator begin() const
Definition ArrayRef.h:135
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:766
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:107
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:88
@ None
No attributes have been set.
Definition Attributes.h:90
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:367
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:678
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:681
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:695
@ ICMP_SLT
signed less than
Definition InstrTypes.h:707
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:708
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:684
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:693
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:682
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:683
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:702
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:701
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:705
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:692
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:686
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:689
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:703
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:690
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:685
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:687
@ ICMP_NE
not equal
Definition InstrTypes.h:700
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:706
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:694
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:704
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:691
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:680
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:688
@ 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:535
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1274
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:131
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:157
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:187
unsigned size() const
Definition DenseMap.h:108
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:404
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:399
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:836
void setPersonalityFn(Constant *Fn)
arg_iterator arg_begin()
Definition Function.h:866
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1038
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:274
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:597
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:654
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:245
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:93
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:251
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:228
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:523
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:565
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:65
lltok::Kind getKind() const
Definition LLLexer.h:71
LocTy getLoc() const
Definition LLLexer.h:70
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:123
LLLexer::LocTy LocTy
Definition LLParser.h:109
LLVMContext & getContext()
Definition LLParser.h:210
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:107
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:94
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:75
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1077
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1561
A single uniqued string.
Definition Metadata.h:720
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:607
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1529
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1518
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1538
static MemoryEffectsBase readOnly()
Definition ModRef.h:125
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:193
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:141
static MemoryEffectsBase writeOnly()
Definition ModRef.h:130
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:158
static MemoryEffectsBase none()
Definition ModRef.h:120
static MemoryEffectsBase unknown()
Definition ModRef.h:115
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:182
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:103
Root of the metadata hierarchy.
Definition Metadata.h:63
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:876
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:23
constexpr const char * getPointer() const
Definition SMLoc.h:34
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
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.
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:235
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:151
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:414
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:620
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:704
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition Type.cpp:539
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:441
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:914
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:288
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:62
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:250
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:295
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:198
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:294
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:258
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:502
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
static constexpr uint64_t MaximumAlignment
Definition Value.h:830
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
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:130
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
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:500
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:572
#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).
@ 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).
@ 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.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:758
@ 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:808
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:814
@ 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:361
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:496
@ 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:217
@ kw_mustBeUnreachable
Definition LLToken.h:407
@ kw_internal
Definition LLToken.h:54
@ kw_no_sanitize_hwaddress
Definition LLToken.h:475
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:446
@ kw_canAutoHide
Definition LLToken.h:391
@ kw_alwaysInline
Definition LLToken.h:403
@ kw_insertelement
Definition LLToken.h:358
@ kw_linkonce
Definition LLToken.h:55
@ kw_inaccessiblememonly
Definition LLToken.h:210
@ kw_amdgpu_gfx
Definition LLToken.h:183
@ kw_getelementptr
Definition LLToken.h:355
@ 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:387
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:449
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:139
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:426
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:149
@ kw_amdgpu_kernel
Definition LLToken.h:182
@ kw_uselistorder
Definition LLToken.h:374
@ kw_blockcount
Definition LLToken.h:385
@ kw_notEligibleToImport
Definition LLToken.h:388
@ 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:330
@ DwarfEnumKind
Definition LLToken.h:508
@ kw_declaration
Definition LLToken.h:394
@ DwarfAttEncoding
Definition LLToken.h:495
@ 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:406
@ kw_x86_intrcc
Definition LLToken.h:169
@ kw_addrspacecast
Definition LLToken.h:325
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:493
@ kw_x86_thiscallcc
Definition LLToken.h:142
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:375
@ NameTableKind
Definition LLToken.h:500
@ kw_inlineBits
Definition LLToken.h:444
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:209
@ kw_blockaddress
Definition LLToken.h:363
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:184
@ kw_landingpad
Definition LLToken.h:329
@ kw_aarch64_vector_pcs
Definition LLToken.h:148
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:425
@ FixedPointKind
Definition LLToken.h:501
@ kw_ptx_kernel
Definition LLToken.h:156
@ kw_extractelement
Definition LLToken.h:357
@ kw_branchFunnel
Definition LLToken.h:450
@ kw_typeidCompatibleVTable
Definition LLToken.h:431
@ kw_vTableFuncs
Definition LLToken.h:417
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:424
@ kw_no_sanitize_address
Definition LLToken.h:472
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:211
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:478
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:181
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:343
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:146
@ kw_read_provenance
Definition LLToken.h:218
@ kw_cleanuppad
Definition LLToken.h:346
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:451
@ kw_swifttailcc
Definition LLToken.h:164
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:423
@ kw_attributes
Definition LLToken.h:192
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:454
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:440
@ kw_nodeduplicate
Definition LLToken.h:247
@ kw_avr_signalcc
Definition LLToken.h:155
@ kw_exactmatch
Definition LLToken.h:245
@ kw_unreachable
Definition LLToken.h:341
@ kw_intel_ocl_bicc
Definition LLToken.h:138
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:401
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:150
@ kw_preserve_allcc
Definition LLToken.h:166
@ kw_importType
Definition LLToken.h:392
@ kw_cleanupret
Definition LLToken.h:342
@ kw_shufflevector
Definition LLToken.h:359
@ kw_riscv_vector_cc
Definition LLToken.h:188
@ kw_avr_intrcc
Definition LLToken.h:154
@ kw_definition
Definition LLToken.h:393
@ kw_virtualConstProp
Definition LLToken.h:456
@ kw_vcall_visibility
Definition LLToken.h:445
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:205
@ kw_preserve_mostcc
Definition LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:147
@ kw_typeTestRes
Definition LLToken.h:433
@ kw_x86_regcallcc
Definition LLToken.h:144
@ kw_typeIdInfo
Definition LLToken.h:421
@ kw_amdgpu_cs_chain
Definition LLToken.h:180
@ kw_dso_local_equivalent
Definition LLToken.h:364
@ kw_x86_64_sysvcc
Definition LLToken.h:160
@ DbgRecordType
Definition LLToken.h:507
@ kw_address_is_null
Definition LLToken.h:216
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:152
@ kw_uniqueRetVal
Definition LLToken.h:455
@ kw_insertvalue
Definition LLToken.h:362
@ kw_indirectbr
Definition LLToken.h:338
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:577
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void 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:1657
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:51
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
auto cast_or_null(const Y &Val)
Definition Casting.h:720
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:293
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:296
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:759
UWTableKind
Definition CodeGen.h:148
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:151
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:150
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:288
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1624
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:288
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:198
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:305
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:35
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:1934
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:1847
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:315
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
static LLVM_ABI const fltSemantics & IEEEsingle() LLVM_READNONE
Definition APFloat.cpp:266
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:304
static LLVM_ABI const fltSemantics & IEEEdouble() LLVM_READNONE
Definition APFloat.cpp:267
static LLVM_ABI const fltSemantics & IEEEhalf() LLVM_READNONE
Definition APFloat.cpp:264
static LLVM_ABI const fltSemantics & BFloat() LLVM_READNONE
Definition APFloat.cpp:265
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:117
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:33
std::map< unsigned, Type * > Types
Definition SlotMapping.h:37
StringMap< Type * > NamedTypes
Definition SlotMapping.h:36
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:35
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:34
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:53
@ t_PackedConstantStruct
Definition LLParser.h:71
@ t_ConstantStruct
Definition LLParser.h:70
@ t_ConstantSplat
Definition LLParser.h:68
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:75
FunctionType * FTy
Definition LLParser.h:76
LLLexer::LocTy Loc
Definition LLParser.h:74
std::string StrVal
Definition LLParser.h:77
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.