LLVM 24.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/AutoUpgrade.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Comdat.h"
30#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalIFunc.h"
36#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
63 "allow-incomplete-ir", cl::init(false), cl::Hidden,
65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
67
68static std::string getTypeString(Type *T) {
69 std::string Result;
70 raw_string_ostream Tmp(Result);
71 Tmp << *T;
72 return Tmp.str();
73}
74
75/// Return whether skipped trivia contains a block comment that crosses the
76/// boundary between two metadata definitions.
77static bool blockCommentCrossesBoundary(SMLoc BeginLoc, SMLoc EndLoc,
78 SMLoc BoundaryLoc) {
79 const char *Begin = BeginLoc.getPointer();
80 const char *End = EndLoc.getPointer();
81 const char *Boundary = BoundaryLoc.getPointer();
82 const char *BlockCommentStart = nullptr;
83 bool InLineComment = false;
84
85 for (const char *Ptr = Begin; Ptr < End;) {
86 if (BlockCommentStart) {
87 if (Ptr + 1 < End && Ptr[0] == '*' && Ptr[1] == '/') {
88 Ptr += 2;
89 if (BlockCommentStart < Boundary && Ptr > Boundary)
90 return true;
91 BlockCommentStart = nullptr;
92 continue;
93 }
94 ++Ptr;
95 continue;
96 }
97
98 if (InLineComment) {
99 if (*Ptr == '\n' || *Ptr == '\r')
100 InLineComment = false;
101 ++Ptr;
102 continue;
103 }
104
105 if (*Ptr == ';') {
106 InLineComment = true;
107 ++Ptr;
108 continue;
109 }
110 if (Ptr + 1 < End && Ptr[0] == '/' && Ptr[1] == '*') {
111 BlockCommentStart = Ptr;
112 Ptr += 2;
113 continue;
114 }
115 ++Ptr;
116 }
117
118 return BlockCommentStart && BlockCommentStart < Boundary && End > Boundary;
119}
120
121/// Run: module ::= toplevelentity*
122bool LLParser::Run(bool UpgradeDebugInfo,
123 DataLayoutCallbackTy DataLayoutCallback) {
124 // Prime the lexer.
125 Lex.Lex();
126
127 if (Context.shouldDiscardValueNames())
128 return error(
129 Lex.getLoc(),
130 "Can't read textual IR with a Context that discards named Values");
131
132 if (M) {
133 if (parseTargetDefinitions(DataLayoutCallback))
134 return true;
135 }
136
137 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
138 validateEndOfIndex();
139}
140
142 const SlotMapping *Slots) {
143 restoreParsingState(Slots);
144 Lex.Lex();
145
146 Type *Ty = nullptr;
147 if (parseType(Ty) || parseConstantValue(Ty, C))
148 return true;
149 if (Lex.getKind() != lltok::Eof)
150 return error(Lex.getLoc(), "expected end of string");
151 return false;
152}
153
155 const SlotMapping *Slots) {
156 restoreParsingState(Slots);
157 Lex.Lex();
158
159 Read = 0;
160 SMLoc Start = Lex.getLoc();
161 Ty = nullptr;
162 if (parseType(Ty))
163 return true;
164 SMLoc End = Lex.getLoc();
165 Read = End.getPointer() - Start.getPointer();
166
167 return false;
168}
169
171 const SlotMapping *Slots) {
172 restoreParsingState(Slots);
173 Lex.Lex();
174
175 Read = 0;
176 SMLoc Start = Lex.getLoc();
177 Result = nullptr;
178 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
179 SMLoc End = Lex.getLoc();
180 Read = End.getPointer() - Start.getPointer();
181
182 return Status;
183}
184
186 ArrayRef<SMLoc> DefinitionEnds) {
187 restoreParsingState(&Slots);
188 Lex.Lex();
189
190 for (SMLoc End : DefinitionEnds) {
191 if (Lex.getLoc().getPointer() >= End.getPointer())
192 return error(End, "expected end of metadata definition");
193 if (Lex.getKind() != lltok::exclaim)
194 return tokError("expected a metadata definition");
195 if (parseStandaloneMetadata())
196 return true;
197 if (Lex.getPrevTokEndLoc().getPointer() > End.getPointer() ||
198 (Lex.getKind() != lltok::Eof &&
199 Lex.getLoc().getPointer() < End.getPointer()) ||
200 blockCommentCrossesBoundary(Lex.getPrevTokEndLoc(), Lex.getLoc(), End))
201 return error(End, "expected end of metadata definition");
202 }
203
204 if (Lex.getKind() != lltok::Eof)
205 return tokError("expected end of metadata definitions");
206
207 if (!ForwardRefMDNodes.empty())
208 return error(ForwardRefMDNodes.begin()->second.second,
209 "use of undefined metadata '!" +
210 Twine(ForwardRefMDNodes.begin()->first) + "'");
211
212 for (auto &[_, MD] : NumberedMetadata)
213 if (MD && !MD->isResolved())
214 MD->resolveCycles();
216 NewDistinctSPs.clear();
217
218 Slots.MetadataNodes = std::move(NumberedMetadata);
219 return false;
220}
221
222void LLParser::restoreParsingState(const SlotMapping *Slots) {
223 if (!Slots)
224 return;
225 NumberedVals = Slots->GlobalValues;
226 NumberedMetadata = Slots->MetadataNodes;
227 for (const auto &I : Slots->NamedTypes)
228 NamedTypes.insert(
229 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
230 for (const auto &I : Slots->Types)
231 NumberedTypes.insert(
232 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
233}
234
236 // White-list intrinsics that are safe to drop.
238 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
239 return;
240
242 for (Value *V : II->args())
243 if (auto *MV = dyn_cast<MetadataAsValue>(V))
244 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
245 if (MD->isTemporary())
246 MVs.push_back(MV);
247
248 if (!MVs.empty()) {
249 assert(II->use_empty() && "Cannot have uses");
250 II->eraseFromParent();
251
252 // Also remove no longer used MetadataAsValue wrappers.
253 for (MetadataAsValue *MV : MVs)
254 if (MV->use_empty())
255 delete MV;
256 }
257}
258
259void LLParser::dropUnknownMetadataReferences() {
260 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
261 for (Function &F : *M) {
262 F.eraseMetadataIf(Pred);
263 for (Instruction &I : make_early_inc_range(instructions(F))) {
264 I.eraseMetadataIf(Pred);
265
266 if (auto *II = dyn_cast<IntrinsicInst>(&I))
268 }
269 }
270
271 for (GlobalVariable &GV : M->globals())
272 GV.eraseMetadataIf(Pred);
273
274 llvm::erase_if(PendingDbgRecords,
275 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
276 llvm::erase_if(PendingDbgInsts,
277 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
278
279 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
280 // Check whether there is only a single use left, which would be in our
281 // own NumberedMetadata.
282 if (Info.first->getNumTemporaryUses() == 1) {
283 NumberedMetadata.erase(ID);
284 ForwardRefMDNodes.erase(ID);
285 }
286 }
287}
288
289/// validateEndOfModule - Do final validity and basic correctness checks at the
290/// end of the module.
291bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
292 if (!M)
293 return false;
294
295 // We should have already returned an error if we observed both intrinsics and
296 // records in this IR.
297 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
298 "Mixed debug intrinsics/records seen without a parsing error?");
299
300 // Handle any function attribute group forward references.
301 for (const auto &RAG : ForwardRefAttrGroups) {
302 Value *V = RAG.first;
303 const std::vector<unsigned> &Attrs = RAG.second;
304 AttrBuilder B(Context);
305
306 for (const auto &Attr : Attrs) {
307 auto R = NumberedAttrBuilders.find(Attr);
308 if (R != NumberedAttrBuilders.end())
309 B.merge(R->second);
310 }
311
312 if (Function *Fn = dyn_cast<Function>(V)) {
313 AttributeList AS = Fn->getAttributes();
314 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
315 AS = AS.removeFnAttributes(Context);
316
317 FnAttrs.merge(B);
318
319 // If the alignment was parsed as an attribute, move to the alignment
320 // field.
321 if (MaybeAlign A = FnAttrs.getAlignment()) {
322 Fn->setAlignment(*A);
323 FnAttrs.removeAttribute(Attribute::Alignment);
324 }
325
326 AS = AS.addFnAttributes(Context, FnAttrs);
327 Fn->setAttributes(AS);
328 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
329 AttributeList AS = CI->getAttributes();
330 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
331 AS = AS.removeFnAttributes(Context);
332 FnAttrs.merge(B);
333 AS = AS.addFnAttributes(Context, FnAttrs);
334 CI->setAttributes(AS);
335 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
336 AttributeList AS = II->getAttributes();
337 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
338 AS = AS.removeFnAttributes(Context);
339 FnAttrs.merge(B);
340 AS = AS.addFnAttributes(Context, FnAttrs);
341 II->setAttributes(AS);
342 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
343 AttributeList AS = CBI->getAttributes();
344 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
345 AS = AS.removeFnAttributes(Context);
346 FnAttrs.merge(B);
347 AS = AS.addFnAttributes(Context, FnAttrs);
348 CBI->setAttributes(AS);
349 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
350 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
351 Attrs.merge(B);
352 GV->setAttributes(AttributeSet::get(Context,Attrs));
353 } else {
354 llvm_unreachable("invalid object with forward attribute group reference");
355 }
356 }
357
358 // If there are entries in ForwardRefBlockAddresses at this point, the
359 // function was never defined.
360 if (!ForwardRefBlockAddresses.empty())
361 return error(ForwardRefBlockAddresses.begin()->first.Loc,
362 "expected function name in blockaddress");
363
364 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
365 GlobalValue *FwdRef) {
366 GlobalValue *GV = nullptr;
367 if (GVRef.Kind == ValID::t_GlobalName) {
368 GV = M->getNamedValue(GVRef.StrVal);
369 } else {
370 GV = NumberedVals.get(GVRef.UIntVal);
371 }
372
373 if (!GV)
374 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
375 "' referenced by dso_local_equivalent");
376
377 if (!GV->getValueType()->isFunctionTy())
378 return error(GVRef.Loc,
379 "expected a function, alias to function, or ifunc "
380 "in dso_local_equivalent");
381
382 auto *Equiv = DSOLocalEquivalent::get(GV);
383 FwdRef->replaceAllUsesWith(Equiv);
384 FwdRef->eraseFromParent();
385 return false;
386 };
387
388 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
389 // point, they are references after the function was defined. Resolve those
390 // now.
391 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
392 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
393 return true;
394 }
395 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
396 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
397 return true;
398 }
399 ForwardRefDSOLocalEquivalentIDs.clear();
400 ForwardRefDSOLocalEquivalentNames.clear();
401
402 for (const auto &NT : NumberedTypes)
403 if (NT.second.second.isValid())
404 return error(NT.second.second,
405 "use of undefined type '%" + Twine(NT.first) + "'");
406
407 for (const auto &[Name, TypeInfo] : NamedTypes)
408 if (TypeInfo.second.isValid())
409 return error(TypeInfo.second,
410 "use of undefined type named '" + Name + "'");
411
412 if (!ForwardRefComdats.empty())
413 return error(ForwardRefComdats.begin()->second,
414 "use of undefined comdat '$" +
415 ForwardRefComdats.begin()->first + "'");
416
417 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
418 dropUnknownMetadataReferences();
419
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) + "'");
424
425 // Set debug locations.
426 for (auto [Loc, DR, MD] : PendingDbgRecords) {
427 if (auto *DI = dyn_cast<DILocation>(MD))
428 DR->setDebugLoc(DebugLoc(DI));
429 else
430 return error(Loc, "invalid debug location");
431 }
432 PendingDbgRecords.clear();
433 for (auto [Loc, I, MD] : PendingDbgInsts) {
434 if (auto *DI = dyn_cast<DILocation>(MD))
435 I->setDebugLoc(DebugLoc(DI));
436 else
437 return error(Loc, "invalid !dbg metadata");
438 }
439 PendingDbgInsts.clear();
440
441 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
442 if (StringRef(Name).starts_with("llvm.")) {
444 // Automatically create declarations for intrinsics. Intrinsics can only
445 // be called directly, so the call function type directly determines the
446 // declaration function type.
447 //
448 // Additionally, automatically add the required mangling suffix to the
449 // intrinsic name. This means that we may replace a single forward
450 // declaration with multiple functions here.
451 for (Use &U : make_early_inc_range(Info.first->uses())) {
452 auto *CB = dyn_cast<CallBase>(U.getUser());
453 if (!CB || !CB->isCallee(&U))
454 return error(Info.second, "intrinsic can only be used as callee");
455
456 std::string ErrorMsg;
457 raw_string_ostream ErrorOS(ErrorMsg);
458
459 SmallVector<Type *> OverloadTys;
460 if (IID != Intrinsic::not_intrinsic &&
461 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
462 ErrorOS)) {
463 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
464 } else {
465 // Try to upgrade the intrinsic.
466 Function *TmpF = Function::Create(CB->getFunctionType(),
468 Function *NewF = nullptr;
469 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
470 if (IID == Intrinsic::not_intrinsic)
471 return error(Info.second, "unknown intrinsic '" + Name + "'");
472 return error(Info.second, ErrorMsg);
473 }
474
475 U.set(TmpF);
476 UpgradeIntrinsicCall(CB, NewF);
477 if (TmpF->use_empty())
478 TmpF->eraseFromParent();
479 }
480 }
481
482 Info.first->eraseFromParent();
483 ForwardRefVals.erase(Name);
484 continue;
485 }
486
487 // If incomplete IR is allowed, also add declarations for
488 // non-intrinsics.
490 continue;
491
492 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
493 FunctionType *FTy = nullptr;
494 for (Use &U : V->uses()) {
495 auto *CB = dyn_cast<CallBase>(U.getUser());
496 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
497 return nullptr;
498 FTy = CB->getFunctionType();
499 }
500 return FTy;
501 };
502
503 // First check whether this global is only used in calls with the same
504 // type, in which case we'll insert a function. Otherwise, fall back to
505 // using a dummy i8 type.
506 Type *Ty = GetCommonFunctionType(Info.first);
507 if (!Ty)
508 Ty = Type::getInt8Ty(Context);
509
510 GlobalValue *GV;
511 if (auto *FTy = dyn_cast<FunctionType>(Ty))
513 else
514 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
516 /*Initializer*/ nullptr, Name);
517 Info.first->replaceAllUsesWith(GV);
518 Info.first->eraseFromParent();
519 ForwardRefVals.erase(Name);
520 }
521
522 if (!ForwardRefVals.empty())
523 return error(ForwardRefVals.begin()->second.second,
524 "use of undefined value '@" + ForwardRefVals.begin()->first +
525 "'");
526
527 if (!ForwardRefValIDs.empty())
528 return error(ForwardRefValIDs.begin()->second.second,
529 "use of undefined value '@" +
530 Twine(ForwardRefValIDs.begin()->first) + "'");
531
532 // Resolve metadata cycles.
533 for (auto &N : NumberedMetadata) {
534 if (N.second && !N.second->isResolved())
535 N.second->resolveCycles();
536 }
537
539 NewDistinctSPs.clear();
540
541 // Look for intrinsic functions and CallInst that need to be upgraded. We use
542 // make_early_inc_range here because we may remove some functions.
545
546 if (UpgradeDebugInfo)
548
555
556 if (!Slots)
557 return false;
558 // Initialize the slot mapping.
559 // Because by this point we've parsed and validated everything, we can "steal"
560 // the mapping from LLParser as it doesn't need it anymore.
561 Slots->GlobalValues = std::move(NumberedVals);
562 Slots->MetadataNodes = std::move(NumberedMetadata);
563 for (const auto &I : NamedTypes)
564 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
565 for (const auto &I : NumberedTypes)
566 Slots->Types.insert(std::make_pair(I.first, I.second.first));
567
568 return false;
569}
570
571/// Do final validity and basic correctness checks at the end of the index.
572bool LLParser::validateEndOfIndex() {
573 if (!Index)
574 return false;
575
576 if (!ForwardRefValueInfos.empty())
577 return error(ForwardRefValueInfos.begin()->second.front().second,
578 "use of undefined summary '^" +
579 Twine(ForwardRefValueInfos.begin()->first) + "'");
580
581 if (!ForwardRefAliasees.empty())
582 return error(ForwardRefAliasees.begin()->second.front().second,
583 "use of undefined summary '^" +
584 Twine(ForwardRefAliasees.begin()->first) + "'");
585
586 if (!ForwardRefTypeIds.empty())
587 return error(ForwardRefTypeIds.begin()->second.front().second,
588 "use of undefined type id summary '^" +
589 Twine(ForwardRefTypeIds.begin()->first) + "'");
590
591 return false;
592}
593
594//===----------------------------------------------------------------------===//
595// Top-Level Entities
596//===----------------------------------------------------------------------===//
597
598bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
599 // Delay parsing of the data layout string until the target triple is known.
600 // Then, pass both the the target triple and the tentative data layout string
601 // to DataLayoutCallback, allowing to override the DL string.
602 // This enables importing modules with invalid DL strings.
603 std::string TentativeDLStr = M->getDataLayoutStr();
604 LocTy DLStrLoc;
605
606 bool Done = false;
607 while (!Done) {
608 switch (Lex.getKind()) {
609 case lltok::kw_target:
610 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
611 return true;
612 break;
614 if (parseSourceFileName())
615 return true;
616 break;
617 default:
618 Done = true;
619 }
620 }
621 // Run the override callback to potentially change the data layout string, and
622 // parse the data layout string.
623 if (auto LayoutOverride =
624 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
625 TentativeDLStr = *LayoutOverride;
626 DLStrLoc = {};
627 }
628 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
629 if (!MaybeDL)
630 return error(DLStrLoc, toString(MaybeDL.takeError()));
631 M->setDataLayout(MaybeDL.get());
632 return false;
633}
634
635bool LLParser::parseTopLevelEntities() {
636 // If there is no Module, then parse just the summary index entries.
637 if (!M) {
638 while (true) {
639 switch (Lex.getKind()) {
640 case lltok::Eof:
641 return false;
642 case lltok::SummaryID:
643 if (parseSummaryEntry())
644 return true;
645 break;
647 if (parseSourceFileName())
648 return true;
649 break;
650 default:
651 // Skip everything else
652 Lex.Lex();
653 }
654 }
655 }
656 while (true) {
657 switch (Lex.getKind()) {
658 default:
659 return tokError("expected top-level entity");
660 case lltok::Eof: return false;
662 if (parseDeclare())
663 return true;
664 break;
665 case lltok::kw_define:
666 if (parseDefine())
667 return true;
668 break;
669 case lltok::kw_module:
670 if (parseModuleAsm())
671 return true;
672 break;
674 if (parseUnnamedType())
675 return true;
676 break;
677 case lltok::LocalVar:
678 if (parseNamedType())
679 return true;
680 break;
681 case lltok::GlobalID:
682 if (parseUnnamedGlobal())
683 return true;
684 break;
685 case lltok::GlobalVar:
686 if (parseNamedGlobal())
687 return true;
688 break;
689 case lltok::ComdatVar: if (parseComdat()) return true; break;
690 case lltok::exclaim:
691 if (parseStandaloneMetadata())
692 return true;
693 break;
694 case lltok::SummaryID:
695 if (parseSummaryEntry())
696 return true;
697 break;
699 if (parseNamedMetadata())
700 return true;
701 break;
703 if (parseUnnamedAttrGrp())
704 return true;
705 break;
707 if (parseUseListOrder())
708 return true;
709 break;
710 }
711 }
712}
713
714/// toplevelentity
715/// ::= 'module' 'asm' STRINGCONSTANT
716/// ::= 'module' 'asm' '(' 'property_name1:' STRINGCONSTANT ','
717/// 'property_name2:' STRINGCONSTANT ')'
718/// STRINGCONSTANT
719bool LLParser::parseModuleAsm() {
720 assert(Lex.getKind() == lltok::kw_module);
721 Lex.Lex();
722
723 std::string AsmStr;
724 if (parseToken(lltok::kw_asm, "expected 'module asm'"))
725 return true;
726
727 Module::GlobalAsmProperties Props;
728 if (EatIfPresent(lltok::lparen)) {
729 while (true) {
730 std::string Key, Value;
731 SMLoc Loc = Lex.getLoc();
732 if (Lex.getKind() != lltok::LabelStr)
733 return error(Loc, "expected property name followed by ':'");
734
735 Key = Lex.getStrVal();
736 Lex.Lex();
737
738 if (parseStringConstant(Value))
739 return true;
740
741 if (!Props.set(Key, Value))
742 return error(Loc, "unknown property name");
743
744 if (EatIfPresent(lltok::rparen))
745 break;
746 if (parseToken(lltok::comma, "expected ',' or ')'"))
747 return true;
748 }
749 }
750
751 do {
752 std::string AsmStrPart;
753 if (parseStringConstant(AsmStrPart))
754 return true;
755 AsmStr += AsmStrPart + "\n";
756 } while (Lex.getKind() == lltok::StringConstant);
757
758 M->appendModuleInlineAsm({AsmStr, Props});
759 return false;
760}
761
762/// toplevelentity
763/// ::= 'target' 'triple' '=' STRINGCONSTANT
764/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
765bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
766 LocTy &DLStrLoc) {
767 assert(Lex.getKind() == lltok::kw_target);
768 std::string Str;
769 switch (Lex.Lex()) {
770 default:
771 return tokError("unknown target property");
772 case lltok::kw_triple:
773 Lex.Lex();
774 if (parseToken(lltok::equal, "expected '=' after target triple") ||
775 parseStringConstant(Str))
776 return true;
777 M->setTargetTriple(Triple(std::move(Str)));
778 return false;
780 Lex.Lex();
781 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
782 return true;
783 DLStrLoc = Lex.getLoc();
784 if (parseStringConstant(TentativeDLStr))
785 return true;
786 return false;
787 }
788}
789
790/// toplevelentity
791/// ::= 'source_filename' '=' STRINGCONSTANT
792bool LLParser::parseSourceFileName() {
793 assert(Lex.getKind() == lltok::kw_source_filename);
794 Lex.Lex();
795 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
796 parseStringConstant(SourceFileName))
797 return true;
798 if (M)
799 M->setSourceFileName(SourceFileName);
800 return false;
801}
802
803/// parseUnnamedType:
804/// ::= LocalVarID '=' 'type' type
805bool LLParser::parseUnnamedType() {
806 LocTy TypeLoc = Lex.getLoc();
807 unsigned TypeID = Lex.getUIntVal();
808 Lex.Lex(); // eat LocalVarID;
809
810 if (parseToken(lltok::equal, "expected '=' after name") ||
811 parseToken(lltok::kw_type, "expected 'type' after '='"))
812 return true;
813
814 Type *Result = nullptr;
815 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
816 return true;
817
818 if (!isa<StructType>(Result)) {
819 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
820 if (Entry.first)
821 return error(TypeLoc, "non-struct types may not be recursive");
822 Entry.first = Result;
823 Entry.second = SMLoc();
824 }
825
826 return false;
827}
828
829/// toplevelentity
830/// ::= LocalVar '=' 'type' type
831bool LLParser::parseNamedType() {
832 std::string Name = Lex.getStrVal();
833 LocTy NameLoc = Lex.getLoc();
834 Lex.Lex(); // eat LocalVar.
835
836 if (parseToken(lltok::equal, "expected '=' after name") ||
837 parseToken(lltok::kw_type, "expected 'type' after name"))
838 return true;
839
840 Type *Result = nullptr;
841 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
842 return true;
843
844 if (!isa<StructType>(Result)) {
845 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
846 if (Entry.first)
847 return error(NameLoc, "non-struct types may not be recursive");
848 Entry.first = Result;
849 Entry.second = SMLoc();
850 }
851
852 return false;
853}
854
855/// toplevelentity
856/// ::= 'declare' FunctionHeader
857bool LLParser::parseDeclare() {
858 assert(Lex.getKind() == lltok::kw_declare);
859 Lex.Lex();
860
861 std::vector<std::pair<unsigned, MDNode *>> MDs;
862 while (Lex.getKind() == lltok::MetadataVar) {
863 unsigned MDK;
864 MDNode *N;
865 if (parseMetadataAttachment(MDK, N))
866 return true;
867 MDs.push_back({MDK, N});
868 }
869
870 Function *F;
871 unsigned FunctionNumber = -1;
872 SmallVector<unsigned> UnnamedArgNums;
873 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
874 return true;
875 for (auto &MD : MDs)
876 F->addMetadata(MD.first, *MD.second);
877 return false;
878}
879
880/// toplevelentity
881/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
882bool LLParser::parseDefine() {
883 assert(Lex.getKind() == lltok::kw_define);
884
885 FileLoc FunctionStart = getTokLineColumnPos();
886 Lex.Lex();
887
888 Function *F;
889 unsigned FunctionNumber = -1;
890 SmallVector<unsigned> UnnamedArgNums;
891 bool RetValue =
892 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
893 parseOptionalFunctionMetadata(*F) ||
894 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
895 if (ParserContext)
896 ParserContext->addFunctionLocation(
897 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
898
899 return RetValue;
900}
901
902/// parseGlobalType
903/// ::= 'constant'
904/// ::= 'global'
905bool LLParser::parseGlobalType(bool &IsConstant) {
906 if (Lex.getKind() == lltok::kw_constant)
907 IsConstant = true;
908 else if (Lex.getKind() == lltok::kw_global)
909 IsConstant = false;
910 else {
911 IsConstant = false;
912 return tokError("expected 'global' or 'constant'");
913 }
914 Lex.Lex();
915 return false;
916}
917
918bool LLParser::parseOptionalUnnamedAddr(
919 GlobalVariable::UnnamedAddr &UnnamedAddr) {
920 if (EatIfPresent(lltok::kw_unnamed_addr))
922 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
924 else
925 UnnamedAddr = GlobalValue::UnnamedAddr::None;
926 return false;
927}
928
929/// parseUnnamedGlobal:
930/// OptionalVisibility (ALIAS | IFUNC) ...
931/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
932/// OptionalDLLStorageClass
933/// ... -> global variable
934/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
935/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
936/// OptionalVisibility
937/// OptionalDLLStorageClass
938/// ... -> global variable
939bool LLParser::parseUnnamedGlobal() {
940 unsigned VarID;
941 std::string Name;
942 LocTy NameLoc = Lex.getLoc();
943
944 // Handle the GlobalID form.
945 if (Lex.getKind() == lltok::GlobalID) {
946 VarID = Lex.getUIntVal();
947 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
948 return true;
949
950 Lex.Lex(); // eat GlobalID;
951 if (parseToken(lltok::equal, "expected '=' after name"))
952 return true;
953 } else {
954 VarID = NumberedVals.getNext();
955 }
956
957 bool HasLinkage;
958 unsigned Linkage, Visibility, DLLStorageClass;
959 bool DSOLocal;
961 GlobalVariable::UnnamedAddr UnnamedAddr;
962 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
963 DSOLocal) ||
964 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
965 return true;
966
967 switch (Lex.getKind()) {
968 default:
969 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
970 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
971 case lltok::kw_alias:
972 case lltok::kw_ifunc:
973 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
974 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
975 }
976}
977
978/// parseNamedGlobal:
979/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
980/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
981/// OptionalVisibility OptionalDLLStorageClass
982/// ... -> global variable
983bool LLParser::parseNamedGlobal() {
984 assert(Lex.getKind() == lltok::GlobalVar);
985 LocTy NameLoc = Lex.getLoc();
986 std::string Name = Lex.getStrVal();
987 Lex.Lex();
988
989 bool HasLinkage;
990 unsigned Linkage, Visibility, DLLStorageClass;
991 bool DSOLocal;
993 GlobalVariable::UnnamedAddr UnnamedAddr;
994 if (parseToken(lltok::equal, "expected '=' in global variable") ||
995 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
996 DSOLocal) ||
997 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
998 return true;
999
1000 switch (Lex.getKind()) {
1001 default:
1002 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
1003 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1004 case lltok::kw_alias:
1005 case lltok::kw_ifunc:
1006 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
1007 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1008 }
1009}
1010
1011bool LLParser::parseComdat() {
1012 assert(Lex.getKind() == lltok::ComdatVar);
1013 std::string Name = Lex.getStrVal();
1014 LocTy NameLoc = Lex.getLoc();
1015 Lex.Lex();
1016
1017 if (parseToken(lltok::equal, "expected '=' here"))
1018 return true;
1019
1020 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
1021 return tokError("expected comdat type");
1022
1024 switch (Lex.getKind()) {
1025 default:
1026 return tokError("unknown selection kind");
1027 case lltok::kw_any:
1028 SK = Comdat::Any;
1029 break;
1031 SK = Comdat::ExactMatch;
1032 break;
1033 case lltok::kw_largest:
1034 SK = Comdat::Largest;
1035 break;
1038 break;
1039 case lltok::kw_samesize:
1040 SK = Comdat::SameSize;
1041 break;
1042 }
1043 Lex.Lex();
1044
1045 // See if the comdat was forward referenced, if so, use the comdat.
1046 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1047 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1048 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
1049 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
1050
1051 Comdat *C;
1052 if (I != ComdatSymTab.end())
1053 C = &I->second;
1054 else
1055 C = M->getOrInsertComdat(Name);
1056 C->setSelectionKind(SK);
1057
1058 return false;
1059}
1060
1061// MDString:
1062// ::= '!' STRINGCONSTANT
1063bool LLParser::parseMDString(MDString *&Result) {
1064 std::string Str;
1065 if (parseStringConstant(Str))
1066 return true;
1067 Result = MDString::get(Context, Str);
1068 return false;
1069}
1070
1071// MDNode:
1072// ::= '!' MDNodeNumber
1073bool LLParser::parseMDNodeID(MDNode *&Result) {
1074 // !{ ..., !42, ... }
1075 LocTy IDLoc = Lex.getLoc();
1076 unsigned MID = 0;
1077 if (parseUInt32(MID))
1078 return true;
1079
1080 // If not a forward reference, just return it now.
1081 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
1082 if (!Inserted) {
1083 Result = It->second;
1084 return false;
1085 }
1086
1087 // Otherwise, create MDNode forward reference.
1088 auto &FwdRef = ForwardRefMDNodes[MID];
1089 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
1090
1091 Result = FwdRef.first.get();
1092 It->second.reset(Result);
1093 return false;
1094}
1095
1096/// parseNamedMetadata:
1097/// !foo = !{ !1, !2 }
1098bool LLParser::parseNamedMetadata() {
1099 assert(Lex.getKind() == lltok::MetadataVar);
1100 std::string Name = Lex.getStrVal();
1101 Lex.Lex();
1102
1103 if (parseToken(lltok::equal, "expected '=' here") ||
1104 parseToken(lltok::exclaim, "Expected '!' here") ||
1105 parseToken(lltok::lbrace, "Expected '{' here"))
1106 return true;
1107
1108 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1109 if (Lex.getKind() != lltok::rbrace)
1110 do {
1111 MDNode *N = nullptr;
1112 // parse DIExpressions inline as a special case. They are still MDNodes,
1113 // so they can still appear in named metadata. Remove this logic if they
1114 // become plain Metadata.
1115 if (Lex.getKind() == lltok::MetadataVar &&
1116 Lex.getStrVal() == "DIExpression") {
1117 if (parseDIExpression(N, /*IsDistinct=*/false))
1118 return true;
1119 // DIArgLists should only appear inline in a function, as they may
1120 // contain LocalAsMetadata arguments which require a function context.
1121 } else if (Lex.getKind() == lltok::MetadataVar &&
1122 Lex.getStrVal() == "DIArgList") {
1123 return tokError("found DIArgList outside of function");
1124 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1125 parseMDNodeID(N)) {
1126 return true;
1127 }
1128 NMD->addOperand(N);
1129 } while (EatIfPresent(lltok::comma));
1130
1131 return parseToken(lltok::rbrace, "expected end of metadata node");
1132}
1133
1134/// parseStandaloneMetadata:
1135/// !42 = !{...}
1136bool LLParser::parseStandaloneMetadata() {
1137 assert(Lex.getKind() == lltok::exclaim);
1138 Lex.Lex();
1139 unsigned MetadataID = 0;
1140
1141 MDNode *Init;
1142 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1143 return true;
1144
1145 // Detect common error, from old metadata syntax.
1146 if (Lex.getKind() == lltok::Type)
1147 return tokError("unexpected type in metadata definition");
1148
1149 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1150 if (Lex.getKind() == lltok::MetadataVar) {
1151 if (parseSpecializedMDNode(Init, IsDistinct))
1152 return true;
1153 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1154 parseMDTuple(Init, IsDistinct))
1155 return true;
1156
1157 // See if this was forward referenced, if so, handle it.
1158 auto FI = ForwardRefMDNodes.find(MetadataID);
1159 if (FI != ForwardRefMDNodes.end()) {
1160 auto *ToReplace = FI->second.first.get();
1161 // DIAssignID has its own special forward-reference "replacement" for
1162 // attachments (the temporary attachments are never actually attached).
1163 if (isa<DIAssignID>(Init)) {
1164 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1165 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1166 "Inst unexpectedly already has DIAssignID attachment");
1167 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1168 }
1169 }
1170
1171 ToReplace->replaceAllUsesWith(Init);
1172 ForwardRefMDNodes.erase(FI);
1173
1174 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1175 } else {
1176 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1177 if (!Inserted)
1178 return tokError("Metadata id is already used");
1179 It->second.reset(Init);
1180 }
1181
1182 return false;
1183}
1184
1185// Skips a single module summary entry.
1186bool LLParser::skipModuleSummaryEntry() {
1187 // Each module summary entry consists of a tag for the entry
1188 // type, followed by a colon, then the fields which may be surrounded by
1189 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1190 // support is in place we will look for the tokens corresponding to the
1191 // expected tags.
1192 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1193 Lex.getKind() != lltok::kw_typeid &&
1194 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1195 Lex.getKind() != lltok::kw_flags &&
1196 Lex.getKind() != lltok::kw_blockcount &&
1197 Lex.getKind() != lltok::kw_cfiFunctionDefs &&
1198 Lex.getKind() != lltok::kw_cfiFunctionDecls)
1199 return tokError("Expected 'gv', 'module', 'typeid', "
1200 "'typeidCompatibleVTable', 'flags', 'blockcount', "
1201 "'cfiFunctionDefs' or 'cfiFunctionDecls' at the start of "
1202 "summary entry");
1203 if (Lex.getKind() == lltok::kw_flags)
1204 return parseSummaryIndexFlags();
1205 if (Lex.getKind() == lltok::kw_blockcount)
1206 return parseBlockCount();
1207 Lex.Lex();
1208 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1209 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1210 return true;
1211 // Now walk through the parenthesized entry, until the number of open
1212 // parentheses goes back down to 0 (the first '(' was parsed above).
1213 unsigned NumOpenParen = 1;
1214 do {
1215 switch (Lex.getKind()) {
1216 case lltok::lparen:
1217 NumOpenParen++;
1218 break;
1219 case lltok::rparen:
1220 NumOpenParen--;
1221 break;
1222 case lltok::Eof:
1223 return tokError("found end of file while parsing summary entry");
1224 default:
1225 // Skip everything in between parentheses.
1226 break;
1227 }
1228 Lex.Lex();
1229 } while (NumOpenParen > 0);
1230 return false;
1231}
1232
1233/// SummaryEntry
1234/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1235bool LLParser::parseSummaryEntry() {
1236 assert(Lex.getKind() == lltok::SummaryID);
1237 unsigned SummaryID = Lex.getUIntVal();
1238
1239 // For summary entries, colons should be treated as distinct tokens,
1240 // not an indication of the end of a label token.
1241 Lex.setIgnoreColonInIdentifiers(true);
1242
1243 Lex.Lex();
1244 if (parseToken(lltok::equal, "expected '=' here"))
1245 return true;
1246
1247 // If we don't have an index object, skip the summary entry.
1248 if (!Index)
1249 return skipModuleSummaryEntry();
1250
1251 bool result = false;
1252 switch (Lex.getKind()) {
1253 case lltok::kw_gv:
1254 result = parseGVEntry(SummaryID);
1255 break;
1256 case lltok::kw_module:
1257 result = parseModuleEntry(SummaryID);
1258 break;
1259 case lltok::kw_typeid:
1260 result = parseTypeIdEntry(SummaryID);
1261 break;
1263 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1264 break;
1265 case lltok::kw_flags:
1266 result = parseSummaryIndexFlags();
1267 break;
1269 result = parseBlockCount();
1270 break;
1273 result = parseCfiFunctions();
1274 break;
1275 default:
1276 result = error(Lex.getLoc(), "unexpected summary kind");
1277 break;
1278 }
1279 Lex.setIgnoreColonInIdentifiers(false);
1280 return result;
1281}
1282
1291
1292// If there was an explicit dso_local, update GV. In the absence of an explicit
1293// dso_local we keep the default value.
1294static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1295 if (DSOLocal)
1296 GV.setDSOLocal(true);
1297}
1298
1299/// parseAliasOrIFunc:
1300/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1301/// OptionalVisibility OptionalDLLStorageClass
1302/// OptionalThreadLocal OptionalUnnamedAddr
1303/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1304///
1305/// AliaseeOrResolver
1306/// ::= TypeAndValue
1307///
1308/// SymbolAttrs
1309/// ::= ',' 'partition' StringConstant
1310///
1311/// Everything through OptionalUnnamedAddr has already been parsed.
1312///
1313bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1314 LocTy NameLoc, unsigned L, unsigned Visibility,
1315 unsigned DLLStorageClass, bool DSOLocal,
1317 GlobalVariable::UnnamedAddr UnnamedAddr) {
1318 bool IsAlias;
1319 if (Lex.getKind() == lltok::kw_alias)
1320 IsAlias = true;
1321 else if (Lex.getKind() == lltok::kw_ifunc)
1322 IsAlias = false;
1323 else
1324 llvm_unreachable("Not an alias or ifunc!");
1325 Lex.Lex();
1326
1328
1329 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1330 return error(NameLoc, "invalid linkage type for alias");
1331
1332 if (!isValidVisibilityForLinkage(Visibility, L))
1333 return error(NameLoc,
1334 "symbol with local linkage must have default visibility");
1335
1336 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1337 return error(NameLoc,
1338 "symbol with local linkage cannot have a DLL storage class");
1339
1340 Type *Ty;
1341 LocTy ExplicitTypeLoc = Lex.getLoc();
1342 if (parseType(Ty) ||
1343 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1344 return true;
1345
1346 Constant *Aliasee;
1347 LocTy AliaseeLoc = Lex.getLoc();
1348 if (Lex.getKind() != lltok::kw_bitcast &&
1349 Lex.getKind() != lltok::kw_getelementptr &&
1350 Lex.getKind() != lltok::kw_addrspacecast &&
1351 Lex.getKind() != lltok::kw_inttoptr) {
1352 if (parseGlobalTypeAndValue(Aliasee))
1353 return true;
1354 } else {
1355 // The bitcast dest type is not present, it is implied by the dest type.
1356 ValID ID;
1357 if (parseValID(ID, /*PFS=*/nullptr))
1358 return true;
1359 if (ID.Kind != ValID::t_Constant)
1360 return error(AliaseeLoc, "invalid aliasee");
1361 Aliasee = ID.ConstantVal;
1362 }
1363
1364 Type *AliaseeType = Aliasee->getType();
1365 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1366 if (!PTy)
1367 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1368 unsigned AddrSpace = PTy->getAddressSpace();
1369
1370 GlobalValue *GVal = nullptr;
1371
1372 // See if the alias was forward referenced, if so, prepare to replace the
1373 // forward reference.
1374 if (!Name.empty()) {
1375 auto I = ForwardRefVals.find(Name);
1376 if (I != ForwardRefVals.end()) {
1377 GVal = I->second.first;
1378 ForwardRefVals.erase(Name);
1379 } else if (M->getNamedValue(Name)) {
1380 return error(NameLoc, "redefinition of global '@" + Name + "'");
1381 }
1382 } else {
1383 auto I = ForwardRefValIDs.find(NameID);
1384 if (I != ForwardRefValIDs.end()) {
1385 GVal = I->second.first;
1386 ForwardRefValIDs.erase(I);
1387 }
1388 }
1389
1390 // Okay, create the alias/ifunc but do not insert it into the module yet.
1391 std::unique_ptr<GlobalAlias> GA;
1392 std::unique_ptr<GlobalIFunc> GI;
1393 GlobalValue *GV;
1394 if (IsAlias) {
1395 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1396 /*Parent=*/nullptr));
1397 GV = GA.get();
1398 } else {
1399 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1400 /*Parent=*/nullptr));
1401 GV = GI.get();
1402 }
1403 GV->setThreadLocalMode(TLM);
1406 GV->setUnnamedAddr(UnnamedAddr);
1407 maybeSetDSOLocal(DSOLocal, *GV);
1408
1409 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1410 // Now parse them if there are any.
1411 while (Lex.getKind() == lltok::comma) {
1412 Lex.Lex();
1413
1414 if (Lex.getKind() == lltok::kw_partition) {
1415 Lex.Lex();
1416 GV->setPartition(Lex.getStrVal());
1417 if (parseToken(lltok::StringConstant, "expected partition string"))
1418 return true;
1419 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1420 if (parseGlobalObjectMetadataAttachment(*GI))
1421 return true;
1422 } else {
1423 return tokError("unknown alias or ifunc property!");
1424 }
1425 }
1426
1427 if (Name.empty())
1428 NumberedVals.add(NameID, GV);
1429
1430 if (GVal) {
1431 // Verify that types agree.
1432 if (GVal->getType() != GV->getType())
1433 return error(
1434 ExplicitTypeLoc,
1435 "forward reference and definition of alias have different types");
1436
1437 // If they agree, just RAUW the old value with the alias and remove the
1438 // forward ref info.
1439 GVal->replaceAllUsesWith(GV);
1440 GVal->eraseFromParent();
1441 }
1442
1443 // Insert into the module, we know its name won't collide now.
1444 if (IsAlias)
1445 M->insertAlias(GA.release());
1446 else
1447 M->insertIFunc(GI.release());
1448 assert(GV->getName() == Name && "Should not be a name conflict!");
1449
1450 return false;
1451}
1452
1453static bool isSanitizer(lltok::Kind Kind) {
1454 switch (Kind) {
1457 case lltok::kw_sanitize_memtag:
1459 return true;
1460 default:
1461 return false;
1462 }
1463}
1464
1465bool LLParser::parseSanitizer(GlobalVariable *GV) {
1466 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1468 if (GV->hasSanitizerMetadata())
1469 Meta = GV->getSanitizerMetadata();
1470
1471 switch (Lex.getKind()) {
1473 Meta.NoAddress = true;
1474 break;
1476 Meta.NoHWAddress = true;
1477 break;
1478 case lltok::kw_sanitize_memtag:
1479 Meta.Memtag = true;
1480 break;
1482 Meta.IsDynInit = true;
1483 break;
1484 default:
1485 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1486 }
1487 GV->setSanitizerMetadata(Meta);
1488 Lex.Lex();
1489 return false;
1490}
1491
1492/// parseGlobal
1493/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1494/// OptionalVisibility OptionalDLLStorageClass
1495/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1496/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1497/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1498/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1499/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1500/// Const OptionalAttrs
1501///
1502/// Everything up to and including OptionalUnnamedAddr has been parsed
1503/// already.
1504///
1505bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1506 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1507 unsigned Visibility, unsigned DLLStorageClass,
1508 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1509 GlobalVariable::UnnamedAddr UnnamedAddr) {
1510 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1511 return error(NameLoc,
1512 "symbol with local linkage must have default visibility");
1513
1514 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1515 return error(NameLoc,
1516 "symbol with local linkage cannot have a DLL storage class");
1517
1518 unsigned AddrSpace;
1519 bool IsConstant, IsExternallyInitialized;
1520 LocTy IsExternallyInitializedLoc;
1521 LocTy TyLoc;
1522
1523 Type *Ty = nullptr;
1524 if (parseOptionalAddrSpace(AddrSpace) ||
1525 parseOptionalToken(lltok::kw_externally_initialized,
1526 IsExternallyInitialized,
1527 &IsExternallyInitializedLoc) ||
1528 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1529 return true;
1530
1531 // If the linkage is specified and is external, then no initializer is
1532 // present.
1533 Constant *Init = nullptr;
1534 if (!HasLinkage ||
1537 if (parseGlobalValue(Ty, Init))
1538 return true;
1539 }
1540
1542 return error(TyLoc, "invalid type for global variable");
1543
1544 GlobalValue *GVal = nullptr;
1545
1546 // See if the global was forward referenced, if so, use the global.
1547 if (!Name.empty()) {
1548 auto I = ForwardRefVals.find(Name);
1549 if (I != ForwardRefVals.end()) {
1550 GVal = I->second.first;
1551 ForwardRefVals.erase(I);
1552 } else if (M->getNamedValue(Name)) {
1553 return error(NameLoc, "redefinition of global '@" + Name + "'");
1554 }
1555 } else {
1556 // Handle @"", where a name is syntactically specified, but semantically
1557 // missing.
1558 if (NameID == (unsigned)-1)
1559 NameID = NumberedVals.getNext();
1560
1561 auto I = ForwardRefValIDs.find(NameID);
1562 if (I != ForwardRefValIDs.end()) {
1563 GVal = I->second.first;
1564 ForwardRefValIDs.erase(I);
1565 }
1566 }
1567
1568 GlobalVariable *GV = new GlobalVariable(
1569 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1571
1572 if (Name.empty())
1573 NumberedVals.add(NameID, GV);
1574
1575 // Set the parsed properties on the global.
1576 if (Init)
1577 GV->setInitializer(Init);
1578 GV->setConstant(IsConstant);
1580 maybeSetDSOLocal(DSOLocal, *GV);
1583 GV->setExternallyInitialized(IsExternallyInitialized);
1584 GV->setThreadLocalMode(TLM);
1585 GV->setUnnamedAddr(UnnamedAddr);
1586
1587 if (GVal) {
1588 if (GVal->getAddressSpace() != AddrSpace)
1589 return error(
1590 TyLoc,
1591 "forward reference and definition of global have different types");
1592
1593 GVal->replaceAllUsesWith(GV);
1594 GVal->eraseFromParent();
1595 }
1596
1597 // parse attributes on the global.
1598 while (Lex.getKind() == lltok::comma) {
1599 Lex.Lex();
1600
1601 if (Lex.getKind() == lltok::kw_section) {
1602 Lex.Lex();
1603 GV->setSection(Lex.getStrVal());
1604 if (parseToken(lltok::StringConstant, "expected global section string"))
1605 return true;
1606 } else if (Lex.getKind() == lltok::kw_partition) {
1607 Lex.Lex();
1608 GV->setPartition(Lex.getStrVal());
1609 if (parseToken(lltok::StringConstant, "expected partition string"))
1610 return true;
1611 } else if (Lex.getKind() == lltok::kw_align) {
1612 MaybeAlign Alignment;
1613 if (parseOptionalAlignment(Alignment))
1614 return true;
1615 if (Alignment)
1616 GV->setAlignment(*Alignment);
1617 } else if (Lex.getKind() == lltok::kw_code_model) {
1619 if (parseOptionalCodeModel(CodeModel))
1620 return true;
1621 GV->setCodeModel(CodeModel);
1622 } else if (Lex.getKind() == lltok::MetadataVar) {
1623 if (parseGlobalObjectMetadataAttachment(*GV))
1624 return true;
1625 } else if (isSanitizer(Lex.getKind())) {
1626 if (parseSanitizer(GV))
1627 return true;
1628 } else {
1629 Comdat *C;
1630 if (parseOptionalComdat(Name, C))
1631 return true;
1632 if (C)
1633 GV->setComdat(C);
1634 else
1635 return tokError("unknown global variable property!");
1636 }
1637 }
1638
1639 AttrBuilder Attrs(M->getContext());
1640 LocTy BuiltinLoc;
1641 std::vector<unsigned> FwdRefAttrGrps;
1642 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1643 return true;
1644 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1645 GV->setAttributes(AttributeSet::get(Context, Attrs));
1646 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1647 }
1648
1649 return false;
1650}
1651
1652/// parseUnnamedAttrGrp
1653/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1654bool LLParser::parseUnnamedAttrGrp() {
1655 assert(Lex.getKind() == lltok::kw_attributes);
1656 LocTy AttrGrpLoc = Lex.getLoc();
1657 Lex.Lex();
1658
1659 if (Lex.getKind() != lltok::AttrGrpID)
1660 return tokError("expected attribute group id");
1661
1662 unsigned VarID = Lex.getUIntVal();
1663 std::vector<unsigned> unused;
1664 LocTy BuiltinLoc;
1665 Lex.Lex();
1666
1667 if (parseToken(lltok::equal, "expected '=' here") ||
1668 parseToken(lltok::lbrace, "expected '{' here"))
1669 return true;
1670
1671 auto R = NumberedAttrBuilders.find(VarID);
1672 if (R == NumberedAttrBuilders.end())
1673 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1674
1675 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1676 parseToken(lltok::rbrace, "expected end of attribute group"))
1677 return true;
1678
1679 if (!R->second.hasAttributes())
1680 return error(AttrGrpLoc, "attribute group has no attributes");
1681
1682 return false;
1683}
1684
1686 switch (Kind) {
1687#define GET_ATTR_NAMES
1688#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1689 case lltok::kw_##DISPLAY_NAME: \
1690 return Attribute::ENUM_NAME;
1691#include "llvm/IR/Attributes.inc"
1692 default:
1693 return Attribute::None;
1694 }
1695}
1696
1697bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1698 bool InAttrGroup) {
1699 if (Attribute::isTypeAttrKind(Attr))
1700 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1701
1702 switch (Attr) {
1703 case Attribute::Alignment: {
1704 MaybeAlign Alignment;
1705 if (InAttrGroup) {
1706 uint32_t Value = 0;
1707 Lex.Lex();
1708 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1709 return true;
1711 } else {
1712 if (parseOptionalAlignment(Alignment, true))
1713 return true;
1714 }
1715 B.addAlignmentAttr(Alignment);
1716 return false;
1717 }
1718 case Attribute::StackAlignment: {
1719 unsigned Alignment;
1720 if (InAttrGroup) {
1721 Lex.Lex();
1722 if (parseToken(lltok::equal, "expected '=' here") ||
1723 parseUInt32(Alignment))
1724 return true;
1725 } else {
1726 if (parseOptionalStackAlignment(Alignment))
1727 return true;
1728 }
1729 B.addStackAlignmentAttr(Alignment);
1730 return false;
1731 }
1732 case Attribute::AllocSize: {
1733 unsigned ElemSizeArg;
1734 std::optional<unsigned> NumElemsArg;
1735 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1736 return true;
1737 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1738 return false;
1739 }
1740 case Attribute::VScaleRange: {
1741 unsigned MinValue, MaxValue;
1742 if (parseVScaleRangeArguments(MinValue, MaxValue))
1743 return true;
1744 B.addVScaleRangeAttr(MinValue,
1745 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1746 return false;
1747 }
1748 case Attribute::Dereferenceable: {
1749 std::optional<uint64_t> Bytes;
1750 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1751 return true;
1752 assert(Bytes.has_value());
1753 B.addDereferenceableAttr(Bytes.value());
1754 return false;
1755 }
1756 case Attribute::DeadOnReturn: {
1757 std::optional<uint64_t> Bytes;
1758 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1759 /*ErrorNoBytes=*/false))
1760 return true;
1761 if (Bytes.has_value()) {
1762 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1763 } else {
1764 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1765 }
1766 return false;
1767 }
1768 case Attribute::DereferenceableOrNull: {
1769 std::optional<uint64_t> Bytes;
1770 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1771 return true;
1772 assert(Bytes.has_value());
1773 B.addDereferenceableOrNullAttr(Bytes.value());
1774 return false;
1775 }
1776 case Attribute::UWTable: {
1778 if (parseOptionalUWTableKind(Kind))
1779 return true;
1780 B.addUWTableAttr(Kind);
1781 return false;
1782 }
1783 case Attribute::AllocKind: {
1785 if (parseAllocKind(Kind))
1786 return true;
1787 B.addAllocKindAttr(Kind);
1788 return false;
1789 }
1790 case Attribute::Memory: {
1791 std::optional<MemoryEffects> ME = parseMemoryAttr();
1792 if (!ME)
1793 return true;
1794 B.addMemoryAttr(*ME);
1795 return false;
1796 }
1797 case Attribute::DenormalFPEnv: {
1798 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1799 if (!Mode)
1800 return true;
1801
1802 B.addDenormalFPEnvAttr(*Mode);
1803 return false;
1804 }
1805 case Attribute::NoFPClass: {
1806 if (FPClassTest NoFPClass =
1807 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1808 B.addNoFPClassAttr(NoFPClass);
1809 return false;
1810 }
1811
1812 return true;
1813 }
1814 case Attribute::Range:
1815 return parseRangeAttr(B);
1816 case Attribute::Initializes:
1817 return parseInitializesAttr(B);
1818 case Attribute::Captures:
1819 return parseCapturesAttr(B);
1820 default:
1821 B.addAttribute(Attr);
1822 Lex.Lex();
1823 return false;
1824 }
1825}
1826
1828 switch (Kind) {
1829 case lltok::kw_readnone:
1830 ME &= MemoryEffects::none();
1831 return true;
1832 case lltok::kw_readonly:
1834 return true;
1835 case lltok::kw_writeonly:
1837 return true;
1840 return true;
1843 return true;
1846 return true;
1847 default:
1848 return false;
1849 }
1850}
1851
1852/// parseFnAttributeValuePairs
1853/// ::= <attr> | <attr> '=' <value>
1854bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1855 std::vector<unsigned> &FwdRefAttrGrps,
1856 bool InAttrGrp, LocTy &BuiltinLoc) {
1857 bool HaveError = false;
1858
1859 B.clear();
1860
1862 while (true) {
1863 lltok::Kind Token = Lex.getKind();
1864 if (Token == lltok::rbrace)
1865 break; // Finished.
1866
1867 if (Token == lltok::StringConstant) {
1868 if (parseStringAttribute(B))
1869 return true;
1870 continue;
1871 }
1872
1873 if (Token == lltok::AttrGrpID) {
1874 // Allow a function to reference an attribute group:
1875 //
1876 // define void @foo() #1 { ... }
1877 if (InAttrGrp) {
1878 HaveError |= error(
1879 Lex.getLoc(),
1880 "cannot have an attribute group reference in an attribute group");
1881 } else {
1882 // Save the reference to the attribute group. We'll fill it in later.
1883 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1884 }
1885 Lex.Lex();
1886 continue;
1887 }
1888
1889 SMLoc Loc = Lex.getLoc();
1890 if (Token == lltok::kw_builtin)
1891 BuiltinLoc = Loc;
1892
1893 if (upgradeMemoryAttr(ME, Token)) {
1894 Lex.Lex();
1895 continue;
1896 }
1897
1899 if (Attr == Attribute::None) {
1900 if (!InAttrGrp)
1901 break;
1902 return error(Lex.getLoc(), "unterminated attribute group");
1903 }
1904
1905 if (parseEnumAttribute(Attr, B, InAttrGrp))
1906 return true;
1907
1908 // As a hack, we allow function alignment to be initially parsed as an
1909 // attribute on a function declaration/definition or added to an attribute
1910 // group and later moved to the alignment field.
1911 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1912 HaveError |= error(Loc, "this attribute does not apply to functions");
1913 }
1914
1915 if (ME != MemoryEffects::unknown())
1916 B.addMemoryAttr(ME);
1917 return HaveError;
1918}
1919
1920//===----------------------------------------------------------------------===//
1921// GlobalValue Reference/Resolution Routines.
1922//===----------------------------------------------------------------------===//
1923
1925 // The used global type does not matter. We will later RAUW it with a
1926 // global/function of the correct type.
1927 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1930 PTy->getAddressSpace());
1931}
1932
1933Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1934 Value *Val) {
1935 Type *ValTy = Val->getType();
1936 if (ValTy == Ty)
1937 return Val;
1938 if (Ty->isLabelTy())
1939 error(Loc, "'" + Name + "' is not a basic block");
1940 else
1941 error(Loc, "'" + Name + "' defined with type '" +
1942 getTypeString(Val->getType()) + "' but expected '" +
1943 getTypeString(Ty) + "'");
1944 return nullptr;
1945}
1946
1947/// getGlobalVal - Get a value with the specified name or ID, creating a
1948/// forward reference record if needed. This can return null if the value
1949/// exists but does not have the right type.
1950GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1951 LocTy Loc) {
1953 if (!PTy) {
1954 error(Loc, "global variable reference must have pointer type");
1955 return nullptr;
1956 }
1957
1958 // Look this name up in the normal function symbol table.
1959 GlobalValue *Val =
1960 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1961
1962 // If this is a forward reference for the value, see if we already created a
1963 // forward ref record.
1964 if (!Val) {
1965 auto I = ForwardRefVals.find(Name);
1966 if (I != ForwardRefVals.end())
1967 Val = I->second.first;
1968 }
1969
1970 // If we have the value in the symbol table or fwd-ref table, return it.
1971 if (Val)
1973 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1974
1975 // Otherwise, create a new forward reference for this value and remember it.
1976 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1977 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1978 return FwdVal;
1979}
1980
1981GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1983 if (!PTy) {
1984 error(Loc, "global variable reference must have pointer type");
1985 return nullptr;
1986 }
1987
1988 GlobalValue *Val = NumberedVals.get(ID);
1989
1990 // If this is a forward reference for the value, see if we already created a
1991 // forward ref record.
1992 if (!Val) {
1993 auto I = ForwardRefValIDs.find(ID);
1994 if (I != ForwardRefValIDs.end())
1995 Val = I->second.first;
1996 }
1997
1998 // If we have the value in the symbol table or fwd-ref table, return it.
1999 if (Val)
2001 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
2002
2003 // Otherwise, create a new forward reference for this value and remember it.
2004 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
2005 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2006 return FwdVal;
2007}
2008
2009//===----------------------------------------------------------------------===//
2010// Comdat Reference/Resolution Routines.
2011//===----------------------------------------------------------------------===//
2012
2013Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
2014 // Look this name up in the comdat symbol table.
2015 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
2016 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
2017 if (I != ComdatSymTab.end())
2018 return &I->second;
2019
2020 // Otherwise, create a new forward reference for this value and remember it.
2021 Comdat *C = M->getOrInsertComdat(Name);
2022 ForwardRefComdats[Name] = Loc;
2023 return C;
2024}
2025
2026//===----------------------------------------------------------------------===//
2027// Helper Routines.
2028//===----------------------------------------------------------------------===//
2029
2030/// parseToken - If the current token has the specified kind, eat it and return
2031/// success. Otherwise, emit the specified error and return failure.
2032bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
2033 if (Lex.getKind() != T)
2034 return tokError(ErrMsg);
2035 Lex.Lex();
2036 return false;
2037}
2038
2039/// parseStringConstant
2040/// ::= StringConstant
2041bool LLParser::parseStringConstant(std::string &Result) {
2042 if (Lex.getKind() != lltok::StringConstant)
2043 return tokError("expected string constant");
2044 Result = Lex.getStrVal();
2045 Lex.Lex();
2046 return false;
2047}
2048
2049/// parseUInt32
2050/// ::= uint32
2051bool LLParser::parseUInt32(uint32_t &Val) {
2052 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2053 return tokError("expected integer");
2054 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2055 if (Val64 != unsigned(Val64))
2056 return tokError("expected 32-bit integer (too large)");
2057 Val = Val64;
2058 Lex.Lex();
2059 return false;
2060}
2061
2062/// parseUInt64
2063/// ::= uint64
2064bool LLParser::parseUInt64(uint64_t &Val) {
2065 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2066 return tokError("expected integer");
2067 Val = Lex.getAPSIntVal().getLimitedValue();
2068 Lex.Lex();
2069 return false;
2070}
2071
2072/// parseTLSModel
2073/// := 'localdynamic'
2074/// := 'initialexec'
2075/// := 'localexec'
2076bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
2077 switch (Lex.getKind()) {
2078 default:
2079 return tokError("expected localdynamic, initialexec or localexec");
2082 break;
2085 break;
2088 break;
2089 }
2090
2091 Lex.Lex();
2092 return false;
2093}
2094
2095/// parseOptionalThreadLocal
2096/// := /*empty*/
2097/// := 'thread_local'
2098/// := 'thread_local' '(' tlsmodel ')'
2099bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
2101 if (!EatIfPresent(lltok::kw_thread_local))
2102 return false;
2103
2105 if (Lex.getKind() == lltok::lparen) {
2106 Lex.Lex();
2107 return parseTLSModel(TLM) ||
2108 parseToken(lltok::rparen, "expected ')' after thread local model");
2109 }
2110 return false;
2111}
2112
2113/// parseOptionalAddrSpace
2114/// := /*empty*/
2115/// := 'addrspace' '(' uint32 ')'
2116bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
2117 AddrSpace = DefaultAS;
2118 if (!EatIfPresent(lltok::kw_addrspace))
2119 return false;
2120
2121 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
2122 if (Lex.getKind() == lltok::StringConstant) {
2123 const std::string &AddrSpaceStr = Lex.getStrVal();
2124 if (AddrSpaceStr == "A") {
2125 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2126 } else if (AddrSpaceStr == "G") {
2127 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2128 } else if (AddrSpaceStr == "P") {
2129 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2130 } else if (std::optional<unsigned> AS =
2131 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2132 AddrSpace = *AS;
2133 } else {
2134 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2135 }
2136 Lex.Lex();
2137 return false;
2138 }
2139 if (Lex.getKind() != lltok::APSInt)
2140 return tokError("expected integer or string constant");
2141 SMLoc Loc = Lex.getLoc();
2142 if (parseUInt32(AddrSpace))
2143 return true;
2144 if (!isUInt<24>(AddrSpace))
2145 return error(Loc, "invalid address space, must be a 24-bit integer");
2146 return false;
2147 };
2148
2149 return parseToken(lltok::lparen, "expected '(' in address space") ||
2150 ParseAddrspaceValue(AddrSpace) ||
2151 parseToken(lltok::rparen, "expected ')' in address space");
2152}
2153
2154/// parseStringAttribute
2155/// := StringConstant
2156/// := StringConstant '=' StringConstant
2157bool LLParser::parseStringAttribute(AttrBuilder &B) {
2158 std::string Attr = Lex.getStrVal();
2159 Lex.Lex();
2160 std::string Val;
2161 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2162 return true;
2163 B.addAttribute(Attr, Val);
2164 return false;
2165}
2166
2167/// Parse a potentially empty list of parameter or return attributes.
2168bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2169 bool HaveError = false;
2170
2171 B.clear();
2172
2173 while (true) {
2174 lltok::Kind Token = Lex.getKind();
2175 if (Token == lltok::StringConstant) {
2176 if (parseStringAttribute(B))
2177 return true;
2178 continue;
2179 }
2180
2181 if (Token == lltok::kw_nocapture) {
2182 Lex.Lex();
2183 B.addCapturesAttr(CaptureInfo::none());
2184 continue;
2185 }
2186
2187 SMLoc Loc = Lex.getLoc();
2189 if (Attr == Attribute::None)
2190 return HaveError;
2191
2192 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2193 return true;
2194
2195 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2196 HaveError |= error(Loc, "this attribute does not apply to parameters");
2197 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2198 HaveError |= error(Loc, "this attribute does not apply to return values");
2199 }
2200}
2201
2202static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2203 HasLinkage = true;
2204 switch (Kind) {
2205 default:
2206 HasLinkage = false;
2208 case lltok::kw_private:
2210 case lltok::kw_internal:
2212 case lltok::kw_weak:
2214 case lltok::kw_weak_odr:
2216 case lltok::kw_linkonce:
2224 case lltok::kw_common:
2228 case lltok::kw_external:
2230 }
2231}
2232
2233/// parseOptionalLinkage
2234/// ::= /*empty*/
2235/// ::= 'private'
2236/// ::= 'internal'
2237/// ::= 'weak'
2238/// ::= 'weak_odr'
2239/// ::= 'linkonce'
2240/// ::= 'linkonce_odr'
2241/// ::= 'available_externally'
2242/// ::= 'appending'
2243/// ::= 'common'
2244/// ::= 'extern_weak'
2245/// ::= 'external'
2246bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2247 unsigned &Visibility,
2248 unsigned &DLLStorageClass, bool &DSOLocal) {
2249 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2250 if (HasLinkage)
2251 Lex.Lex();
2252 parseOptionalDSOLocal(DSOLocal);
2253 parseOptionalVisibility(Visibility);
2254 parseOptionalDLLStorageClass(DLLStorageClass);
2255
2256 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2257 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2258 }
2259
2260 return false;
2261}
2262
2263void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2264 switch (Lex.getKind()) {
2265 default:
2266 DSOLocal = false;
2267 break;
2269 DSOLocal = true;
2270 Lex.Lex();
2271 break;
2273 DSOLocal = false;
2274 Lex.Lex();
2275 break;
2276 }
2277}
2278
2279/// parseOptionalVisibility
2280/// ::= /*empty*/
2281/// ::= 'default'
2282/// ::= 'hidden'
2283/// ::= 'protected'
2284///
2285void LLParser::parseOptionalVisibility(unsigned &Res) {
2286 switch (Lex.getKind()) {
2287 default:
2289 return;
2290 case lltok::kw_default:
2292 break;
2293 case lltok::kw_hidden:
2295 break;
2298 break;
2299 }
2300 Lex.Lex();
2301}
2302
2303bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2305 switch (Kind) {
2306 default:
2307 return tokError("unknown import kind. Expect definition or declaration.");
2310 return false;
2313 return false;
2314 }
2315}
2316
2317/// parseOptionalDLLStorageClass
2318/// ::= /*empty*/
2319/// ::= 'dllimport'
2320/// ::= 'dllexport'
2321///
2322void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2323 switch (Lex.getKind()) {
2324 default:
2326 return;
2329 break;
2332 break;
2333 }
2334 Lex.Lex();
2335}
2336
2337/// parseOptionalCallingConv
2338/// ::= /*empty*/
2339/// ::= 'ccc'
2340/// ::= 'fastcc'
2341/// ::= 'intel_ocl_bicc'
2342/// ::= 'coldcc'
2343/// ::= 'cfguard_checkcc'
2344/// ::= 'x86_stdcallcc'
2345/// ::= 'x86_fastcallcc'
2346/// ::= 'x86_thiscallcc'
2347/// ::= 'x86_vectorcallcc'
2348/// ::= 'arm_apcscc'
2349/// ::= 'arm_aapcscc'
2350/// ::= 'arm_aapcs_vfpcc'
2351/// ::= 'aarch64_vector_pcs'
2352/// ::= 'aarch64_sve_vector_pcs'
2353/// ::= 'aarch64_sme_preservemost_from_x0'
2354/// ::= 'aarch64_sme_preservemost_from_x1'
2355/// ::= 'aarch64_sme_preservemost_from_x2'
2356/// ::= 'msp430_intrcc'
2357/// ::= 'avr_intrcc'
2358/// ::= 'avr_signalcc'
2359/// ::= 'ptx_kernel'
2360/// ::= 'ptx_device'
2361/// ::= 'spir_func'
2362/// ::= 'spir_kernel'
2363/// ::= 'x86_64_sysvcc'
2364/// ::= 'win64cc'
2365/// ::= 'anyregcc'
2366/// ::= 'preserve_mostcc'
2367/// ::= 'preserve_allcc'
2368/// ::= 'preserve_nonecc'
2369/// ::= 'ghccc'
2370/// ::= 'swiftcc'
2371/// ::= 'swifttailcc'
2372/// ::= 'x86_intrcc'
2373/// ::= 'hhvmcc'
2374/// ::= 'hhvm_ccc'
2375/// ::= 'cxx_fast_tlscc'
2376/// ::= 'amdgpu_vs'
2377/// ::= 'amdgpu_ls'
2378/// ::= 'amdgpu_hs'
2379/// ::= 'amdgpu_es'
2380/// ::= 'amdgpu_gs'
2381/// ::= 'amdgpu_ps'
2382/// ::= 'amdgpu_cs'
2383/// ::= 'amdgpu_cs_chain'
2384/// ::= 'amdgpu_cs_chain_preserve'
2385/// ::= 'amdgpu_kernel'
2386/// ::= 'tailcc'
2387/// ::= 'm68k_rtdcc'
2388/// ::= 'wasm_emscripten_invokecc'
2389/// ::= 'graalcc'
2390/// ::= 'riscv_vector_cc'
2391/// ::= 'riscv_vls_cc'
2392/// ::= 'cc' UINT
2393///
2394bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2395 switch (Lex.getKind()) {
2396 default: CC = CallingConv::C; return false;
2397 case lltok::kw_ccc: CC = CallingConv::C; break;
2398 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2399 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2412 break;
2415 break;
2418 break;
2421 break;
2436 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2440 case lltok::kw_hhvmcc:
2442 break;
2443 case lltok::kw_hhvm_ccc:
2445 break;
2457 break;
2460 break;
2464 break;
2465 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2469 break;
2473 break;
2475 // Default ABI_VLEN
2477 Lex.Lex();
2478 if (!EatIfPresent(lltok::lparen))
2479 break;
2480 uint32_t ABIVlen;
2481 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2482 return true;
2483 switch (ABIVlen) {
2484 default:
2485 return tokError("unknown RISC-V ABI VLEN");
2486#define CC_VLS_CASE(ABIVlen) \
2487 case ABIVlen: \
2488 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2489 break;
2490 CC_VLS_CASE(32)
2491 CC_VLS_CASE(64)
2492 CC_VLS_CASE(128)
2493 CC_VLS_CASE(256)
2494 CC_VLS_CASE(512)
2495 CC_VLS_CASE(1024)
2496 CC_VLS_CASE(2048)
2497 CC_VLS_CASE(4096)
2498 CC_VLS_CASE(8192)
2499 CC_VLS_CASE(16384)
2500 CC_VLS_CASE(32768)
2501 CC_VLS_CASE(65536)
2502#undef CC_VLS_CASE
2503 }
2504 return false;
2507 break;
2510 break;
2513 break;
2514 case lltok::kw_cc: {
2515 Lex.Lex();
2516 return parseUInt32(CC);
2517 }
2518 }
2519
2520 Lex.Lex();
2521 return false;
2522}
2523
2524/// parseMetadataAttachment
2525/// ::= !dbg !42
2526bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2527 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2528
2529 std::string Name = Lex.getStrVal();
2530 Kind = M->getMDKindID(Name);
2531 Lex.Lex();
2532
2533 return parseMDNode(MD);
2534}
2535
2536/// parseInstructionMetadata
2537/// ::= !dbg !42 (',' !dbg !57)*
2538bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2539 do {
2540 if (Lex.getKind() != lltok::MetadataVar)
2541 return tokError("expected metadata after comma");
2542
2543 unsigned MDK;
2544 MDNode *N;
2545 auto Loc = Lex.getLoc();
2546 if (parseMetadataAttachment(MDK, N))
2547 return true;
2548
2549 if (MDK == LLVMContext::MD_DIAssignID)
2550 TempDIAssignIDAttachments[N].push_back(&Inst);
2551 else if (MDK == LLVMContext::MD_dbg)
2552 PendingDbgInsts.emplace_back(Loc, &Inst, N);
2553 else
2554 Inst.setMetadata(MDK, N);
2555
2556 // If this is the end of the list, we're done.
2557 } while (EatIfPresent(lltok::comma));
2558 return false;
2559}
2560
2561/// parseGlobalObjectMetadataAttachment
2562/// ::= !dbg !57
2563bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2564 unsigned MDK;
2565 MDNode *N;
2566 if (parseMetadataAttachment(MDK, N))
2567 return true;
2568
2569 GO.addMetadata(MDK, *N);
2570 return false;
2571}
2572
2573/// parseOptionalFunctionMetadata
2574/// ::= (!dbg !57)*
2575bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2576 while (Lex.getKind() == lltok::MetadataVar)
2577 if (parseGlobalObjectMetadataAttachment(F))
2578 return true;
2579 return false;
2580}
2581
2582/// parseOptionalAlignment
2583/// ::= /* empty */
2584/// ::= 'align' 4
2585bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2586 Alignment = std::nullopt;
2587 if (!EatIfPresent(lltok::kw_align))
2588 return false;
2589 LocTy AlignLoc = Lex.getLoc();
2590 uint64_t Value = 0;
2591
2592 LocTy ParenLoc = Lex.getLoc();
2593 bool HaveParens = false;
2594 if (AllowParens) {
2595 if (EatIfPresent(lltok::lparen))
2596 HaveParens = true;
2597 }
2598
2599 if (parseUInt64(Value))
2600 return true;
2601
2602 if (HaveParens && !EatIfPresent(lltok::rparen))
2603 return error(ParenLoc, "expected ')'");
2604
2605 if (!isPowerOf2_64(Value))
2606 return error(AlignLoc, "alignment is not a power of two");
2608 return error(AlignLoc, "huge alignments are not supported yet");
2610 return false;
2611}
2612
2613/// parseOptionalPrefAlignment
2614/// ::= /* empty */
2615/// ::= 'prefalign' '(' 4 ')'
2616bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2617 Alignment = std::nullopt;
2618 if (!EatIfPresent(lltok::kw_prefalign))
2619 return false;
2620 LocTy AlignLoc = Lex.getLoc();
2621 uint64_t Value = 0;
2622
2623 LocTy ParenLoc = Lex.getLoc();
2624 if (!EatIfPresent(lltok::lparen))
2625 return error(ParenLoc, "expected '('");
2626
2627 if (parseUInt64(Value))
2628 return true;
2629
2630 ParenLoc = Lex.getLoc();
2631 if (!EatIfPresent(lltok::rparen))
2632 return error(ParenLoc, "expected ')'");
2633
2634 if (!isPowerOf2_64(Value))
2635 return error(AlignLoc, "alignment is not a power of two");
2637 return error(AlignLoc, "huge alignments are not supported yet");
2639 return false;
2640}
2641
2642/// parseOptionalCodeModel
2643/// ::= /* empty */
2644/// ::= 'code_model' "large"
2645bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2646 Lex.Lex();
2647 auto StrVal = Lex.getStrVal();
2648 auto ErrMsg = "expected global code model string";
2649 if (StrVal == "tiny")
2650 model = CodeModel::Tiny;
2651 else if (StrVal == "small")
2652 model = CodeModel::Small;
2653 else if (StrVal == "kernel")
2654 model = CodeModel::Kernel;
2655 else if (StrVal == "medium")
2656 model = CodeModel::Medium;
2657 else if (StrVal == "large")
2658 model = CodeModel::Large;
2659 else
2660 return tokError(ErrMsg);
2661 if (parseToken(lltok::StringConstant, ErrMsg))
2662 return true;
2663 return false;
2664}
2665
2666/// parseOptionalAttrBytes
2667/// ::= /* empty */
2668/// ::= AttrKind '(' 4 ')'
2669///
2670/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2671/// 'dead_on_return'
2672bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2673 std::optional<uint64_t> &Bytes,
2674 bool ErrorNoBytes) {
2675 assert((AttrKind == lltok::kw_dereferenceable ||
2676 AttrKind == lltok::kw_dereferenceable_or_null ||
2677 AttrKind == lltok::kw_dead_on_return) &&
2678 "contract!");
2679
2680 Bytes = 0;
2681 if (!EatIfPresent(AttrKind))
2682 return false;
2683 LocTy ParenLoc = Lex.getLoc();
2684 if (!EatIfPresent(lltok::lparen)) {
2685 if (ErrorNoBytes)
2686 return error(ParenLoc, "expected '('");
2687 Bytes = std::nullopt;
2688 return false;
2689 }
2690 LocTy DerefLoc = Lex.getLoc();
2691 if (parseUInt64(Bytes.value()))
2692 return true;
2693 ParenLoc = Lex.getLoc();
2694 if (!EatIfPresent(lltok::rparen))
2695 return error(ParenLoc, "expected ')'");
2696 if (!Bytes.value())
2697 return error(DerefLoc, "byte count specified must be non-zero");
2698 return false;
2699}
2700
2701bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2702 Lex.Lex();
2704 if (!EatIfPresent(lltok::lparen))
2705 return false;
2706 LocTy KindLoc = Lex.getLoc();
2707 if (Lex.getKind() == lltok::kw_sync)
2709 else if (Lex.getKind() == lltok::kw_async)
2711 else
2712 return error(KindLoc, "expected unwind table kind");
2713 Lex.Lex();
2714 return parseToken(lltok::rparen, "expected ')'");
2715}
2716
2717bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2718 Lex.Lex();
2719 LocTy ParenLoc = Lex.getLoc();
2720 if (!EatIfPresent(lltok::lparen))
2721 return error(ParenLoc, "expected '('");
2722 LocTy KindLoc = Lex.getLoc();
2723 std::string Arg;
2724 if (parseStringConstant(Arg))
2725 return error(KindLoc, "expected allockind value");
2726 for (StringRef A : llvm::split(Arg, ",")) {
2727 if (A == "alloc") {
2729 } else if (A == "realloc") {
2731 } else if (A == "free") {
2733 } else if (A == "uninitialized") {
2735 } else if (A == "zeroed") {
2737 } else if (A == "aligned") {
2739 } else {
2740 return error(KindLoc, Twine("unknown allockind ") + A);
2741 }
2742 }
2743 ParenLoc = Lex.getLoc();
2744 if (!EatIfPresent(lltok::rparen))
2745 return error(ParenLoc, "expected ')'");
2746 if (Kind == AllocFnKind::Unknown)
2747 return error(KindLoc, "expected allockind value");
2748 return false;
2749}
2750
2752 using Loc = IRMemLocation;
2753
2754 switch (Tok) {
2755 case lltok::kw_argmem:
2756 return {Loc::ArgMem};
2758 return {Loc::InaccessibleMem};
2759 case lltok::kw_errnomem:
2760 return {Loc::ErrnoMem};
2762 return {Loc::TargetMem0};
2764 return {Loc::TargetMem1};
2765 case lltok::kw_target_mem: {
2768 Targets.push_back(Loc);
2769 return Targets;
2770 }
2771 default:
2772 return {};
2773 }
2774}
2775
2776static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2777 switch (Tok) {
2778 case lltok::kw_none:
2779 return ModRefInfo::NoModRef;
2780 case lltok::kw_read:
2781 return ModRefInfo::Ref;
2782 case lltok::kw_write:
2783 return ModRefInfo::Mod;
2785 return ModRefInfo::ModRef;
2786 default:
2787 return std::nullopt;
2788 }
2789}
2790
2791static std::optional<DenormalMode::DenormalModeKind>
2793 switch (Tok) {
2794 case lltok::kw_ieee:
2795 return DenormalMode::IEEE;
2800 case lltok::kw_dynamic:
2801 return DenormalMode::Dynamic;
2802 default:
2803 return std::nullopt;
2804 }
2805}
2806
2807std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2809
2810 // We use syntax like memory(argmem: read), so the colon should not be
2811 // interpreted as a label terminator.
2812 Lex.setIgnoreColonInIdentifiers(true);
2813 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2814
2815 Lex.Lex();
2816 if (!EatIfPresent(lltok::lparen)) {
2817 tokError("expected '('");
2818 return std::nullopt;
2819 }
2820
2821 bool SeenLoc = false;
2822 bool SeenTargetLoc = false;
2823 do {
2824 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2825 if (!Locs.empty()) {
2826 Lex.Lex();
2827 if (!EatIfPresent(lltok::colon)) {
2828 tokError("expected ':' after location");
2829 return std::nullopt;
2830 }
2831 }
2832
2833 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2834 if (!MR) {
2835 if (Locs.empty())
2836 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2837 "or access kind (none, read, write, readwrite)");
2838 else
2839 tokError("expected access kind (none, read, write, readwrite)");
2840 return std::nullopt;
2841 }
2842
2843 Lex.Lex();
2844 if (!Locs.empty()) {
2845 SeenLoc = true;
2846 for (IRMemLocation Loc : Locs) {
2847 ME = ME.getWithModRef(Loc, *MR);
2848 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2849 SeenTargetLoc = true;
2850 }
2851 if (Locs.size() > 1 && SeenTargetLoc) {
2852 tokError("target memory default access kind must be specified first");
2853 return std::nullopt;
2854 }
2855
2856 } else {
2857 if (SeenLoc) {
2858 tokError("default access kind must be specified first");
2859 return std::nullopt;
2860 }
2861 ME = MemoryEffects(*MR);
2862 }
2863
2864 if (EatIfPresent(lltok::rparen))
2865 return ME;
2866 } while (EatIfPresent(lltok::comma));
2867
2868 tokError("unterminated memory attribute");
2869 return std::nullopt;
2870}
2871
2872std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2873 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2874 keywordToDenormalModeKind(Lex.getKind());
2875 if (!OutputMode) {
2876 tokError("expected denormal behavior kind (ieee, preservesign, "
2877 "positivezero, dynamic)");
2878 return {};
2879 }
2880
2881 Lex.Lex();
2882
2883 std::optional<DenormalMode::DenormalModeKind> InputMode;
2884 if (EatIfPresent(lltok::bar)) {
2885 InputMode = keywordToDenormalModeKind(Lex.getKind());
2886 if (!InputMode) {
2887 tokError("expected denormal behavior kind (ieee, preservesign, "
2888 "positivezero, dynamic)");
2889 return {};
2890 }
2891
2892 Lex.Lex();
2893 } else {
2894 // Single item, input == output mode
2895 InputMode = OutputMode;
2896 }
2897
2898 return DenormalMode(*OutputMode, *InputMode);
2899}
2900
2901std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2902 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2903 // not be interpreted as a label terminator.
2904 Lex.setIgnoreColonInIdentifiers(true);
2905 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2906
2907 Lex.Lex();
2908
2909 if (parseToken(lltok::lparen, "expected '('"))
2910 return {};
2911
2912 DenormalMode DefaultMode = DenormalMode::getIEEE();
2913 DenormalMode F32Mode = DenormalMode::getInvalid();
2914
2915 bool HasDefaultSection = false;
2916 if (Lex.getKind() != lltok::Type) {
2917 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2918 if (!ParsedDefaultMode)
2919 return {};
2920 DefaultMode = *ParsedDefaultMode;
2921 HasDefaultSection = true;
2922 }
2923
2924 bool HasComma = EatIfPresent(lltok::comma);
2925 if (Lex.getKind() == lltok::Type) {
2926 if (HasDefaultSection && !HasComma) {
2927 tokError("expected ',' before float:");
2928 return {};
2929 }
2930
2931 Type *Ty = nullptr;
2932 if (parseType(Ty) || !Ty->isFloatTy()) {
2933 tokError("expected float:");
2934 return {};
2935 }
2936
2937 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2938 return {};
2939
2940 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2941 if (!ParsedF32Mode)
2942 return {};
2943
2944 F32Mode = *ParsedF32Mode;
2945 }
2946
2947 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2948 return {};
2949
2950 return DenormalFPEnv(DefaultMode, F32Mode);
2951}
2952
2953static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2954 switch (Tok) {
2955 case lltok::kw_all:
2956 return fcAllFlags;
2957 case lltok::kw_nan:
2958 return fcNan;
2959 case lltok::kw_snan:
2960 return fcSNan;
2961 case lltok::kw_qnan:
2962 return fcQNan;
2963 case lltok::kw_inf:
2964 return fcInf;
2965 case lltok::kw_ninf:
2966 return fcNegInf;
2967 case lltok::kw_pinf:
2968 return fcPosInf;
2969 case lltok::kw_norm:
2970 return fcNormal;
2971 case lltok::kw_nnorm:
2972 return fcNegNormal;
2973 case lltok::kw_pnorm:
2974 return fcPosNormal;
2975 case lltok::kw_sub:
2976 return fcSubnormal;
2977 case lltok::kw_nsub:
2978 return fcNegSubnormal;
2979 case lltok::kw_psub:
2980 return fcPosSubnormal;
2981 case lltok::kw_zero:
2982 return fcZero;
2983 case lltok::kw_nzero:
2984 return fcNegZero;
2985 case lltok::kw_pzero:
2986 return fcPosZero;
2987 default:
2988 return 0;
2989 }
2990}
2991
2992unsigned LLParser::parseNoFPClassAttr() {
2993 unsigned Mask = fcNone;
2994
2995 Lex.Lex();
2996 if (!EatIfPresent(lltok::lparen)) {
2997 tokError("expected '('");
2998 return 0;
2999 }
3000
3001 do {
3002 uint64_t Value = 0;
3003 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
3004 if (TestMask != 0) {
3005 Mask |= TestMask;
3006 // TODO: Disallow overlapping masks to avoid copy paste errors
3007 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
3008 !parseUInt64(Value)) {
3009 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
3010 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
3011 return 0;
3012 }
3013
3014 if (!EatIfPresent(lltok::rparen)) {
3015 error(Lex.getLoc(), "expected ')'");
3016 return 0;
3017 }
3018
3019 return Value;
3020 } else {
3021 error(Lex.getLoc(), "expected nofpclass test mask");
3022 return 0;
3023 }
3024
3025 Lex.Lex();
3026 if (EatIfPresent(lltok::rparen))
3027 return Mask;
3028 } while (1);
3029
3030 llvm_unreachable("unterminated nofpclass attribute");
3031}
3032
3033/// parseOptionalCommaAlign
3034/// ::=
3035/// ::= ',' align 4
3036///
3037/// This returns with AteExtraComma set to true if it ate an excess comma at the
3038/// end.
3039bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
3040 bool &AteExtraComma) {
3041 AteExtraComma = false;
3042 while (EatIfPresent(lltok::comma)) {
3043 // Metadata at the end is an early exit.
3044 if (Lex.getKind() == lltok::MetadataVar) {
3045 AteExtraComma = true;
3046 return false;
3047 }
3048
3049 if (Lex.getKind() != lltok::kw_align)
3050 return error(Lex.getLoc(), "expected metadata or 'align'");
3051
3052 if (parseOptionalAlignment(Alignment))
3053 return true;
3054 }
3055
3056 return false;
3057}
3058
3059/// parseOptionalCommaAddrSpace
3060/// ::=
3061/// ::= ',' addrspace(1)
3062///
3063/// This returns with AteExtraComma set to true if it ate an excess comma at the
3064/// end.
3065bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
3066 bool &AteExtraComma) {
3067 AteExtraComma = false;
3068 while (EatIfPresent(lltok::comma)) {
3069 // Metadata at the end is an early exit.
3070 if (Lex.getKind() == lltok::MetadataVar) {
3071 AteExtraComma = true;
3072 return false;
3073 }
3074
3075 Loc = Lex.getLoc();
3076 if (Lex.getKind() != lltok::kw_addrspace)
3077 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
3078
3079 if (parseOptionalAddrSpace(AddrSpace))
3080 return true;
3081 }
3082
3083 return false;
3084}
3085
3086bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
3087 std::optional<unsigned> &HowManyArg) {
3088 Lex.Lex();
3089
3090 auto StartParen = Lex.getLoc();
3091 if (!EatIfPresent(lltok::lparen))
3092 return error(StartParen, "expected '('");
3093
3094 if (parseUInt32(BaseSizeArg))
3095 return true;
3096
3097 if (EatIfPresent(lltok::comma)) {
3098 auto HowManyAt = Lex.getLoc();
3099 unsigned HowMany;
3100 if (parseUInt32(HowMany))
3101 return true;
3102 if (HowMany == BaseSizeArg)
3103 return error(HowManyAt,
3104 "'allocsize' indices can't refer to the same parameter");
3105 HowManyArg = HowMany;
3106 } else
3107 HowManyArg = std::nullopt;
3108
3109 auto EndParen = Lex.getLoc();
3110 if (!EatIfPresent(lltok::rparen))
3111 return error(EndParen, "expected ')'");
3112 return false;
3113}
3114
3115bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
3116 unsigned &MaxValue) {
3117 Lex.Lex();
3118
3119 auto StartParen = Lex.getLoc();
3120 if (!EatIfPresent(lltok::lparen))
3121 return error(StartParen, "expected '('");
3122
3123 if (parseUInt32(MinValue))
3124 return true;
3125
3126 if (EatIfPresent(lltok::comma)) {
3127 if (parseUInt32(MaxValue))
3128 return true;
3129 } else
3130 MaxValue = MinValue;
3131
3132 auto EndParen = Lex.getLoc();
3133 if (!EatIfPresent(lltok::rparen))
3134 return error(EndParen, "expected ')'");
3135 return false;
3136}
3137
3138/// parseScopeAndOrdering
3139/// if isAtomic: ::= SyncScope? AtomicOrdering
3140/// else: ::=
3141///
3142/// This sets Scope and Ordering to the parsed values.
3143bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3144 AtomicOrdering &Ordering) {
3145 if (!IsAtomic)
3146 return false;
3147
3148 return parseScope(SSID) || parseOrdering(Ordering);
3149}
3150
3151/// parseScope
3152/// ::= syncscope("singlethread" | "<target scope>")?
3153///
3154/// This sets synchronization scope ID to the ID of the parsed value.
3155bool LLParser::parseScope(SyncScope::ID &SSID) {
3156 SSID = SyncScope::System;
3157 if (EatIfPresent(lltok::kw_syncscope)) {
3158 auto StartParenAt = Lex.getLoc();
3159 if (!EatIfPresent(lltok::lparen))
3160 return error(StartParenAt, "Expected '(' in syncscope");
3161
3162 std::string SSN;
3163 auto SSNAt = Lex.getLoc();
3164 if (parseStringConstant(SSN))
3165 return error(SSNAt, "Expected synchronization scope name");
3166
3167 auto EndParenAt = Lex.getLoc();
3168 if (!EatIfPresent(lltok::rparen))
3169 return error(EndParenAt, "Expected ')' in syncscope");
3170
3171 SSID = Context.getOrInsertSyncScopeID(SSN);
3172 }
3173
3174 return false;
3175}
3176
3177/// parseOrdering
3178/// ::= AtomicOrdering
3179///
3180/// This sets Ordering to the parsed value.
3181bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3182 switch (Lex.getKind()) {
3183 default:
3184 return tokError("Expected ordering on atomic instruction");
3187 // Not specified yet:
3188 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3192 case lltok::kw_seq_cst:
3194 break;
3195 }
3196 Lex.Lex();
3197 return false;
3198}
3199
3200/// parseOptionalStackAlignment
3201/// ::= /* empty */
3202/// ::= 'alignstack' '(' 4 ')'
3203bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3204 Alignment = 0;
3205 if (!EatIfPresent(lltok::kw_alignstack))
3206 return false;
3207 LocTy ParenLoc = Lex.getLoc();
3208 if (!EatIfPresent(lltok::lparen))
3209 return error(ParenLoc, "expected '('");
3210 LocTy AlignLoc = Lex.getLoc();
3211 if (parseUInt32(Alignment))
3212 return true;
3213 ParenLoc = Lex.getLoc();
3214 if (!EatIfPresent(lltok::rparen))
3215 return error(ParenLoc, "expected ')'");
3216 if (!isPowerOf2_32(Alignment))
3217 return error(AlignLoc, "stack alignment is not a power of two");
3218 return false;
3219}
3220
3221/// parseIndexList - This parses the index list for an insert/extractvalue
3222/// instruction. This sets AteExtraComma in the case where we eat an extra
3223/// comma at the end of the line and find that it is followed by metadata.
3224/// Clients that don't allow metadata can call the version of this function that
3225/// only takes one argument.
3226///
3227/// parseIndexList
3228/// ::= (',' uint32)+
3229///
3230bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3231 bool &AteExtraComma) {
3232 AteExtraComma = false;
3233
3234 if (Lex.getKind() != lltok::comma)
3235 return tokError("expected ',' as start of index list");
3236
3237 while (EatIfPresent(lltok::comma)) {
3238 if (Lex.getKind() == lltok::MetadataVar) {
3239 if (Indices.empty())
3240 return tokError("expected index");
3241 AteExtraComma = true;
3242 return false;
3243 }
3244 unsigned Idx = 0;
3245 if (parseUInt32(Idx))
3246 return true;
3247 Indices.push_back(Idx);
3248 }
3249
3250 return false;
3251}
3252
3253//===----------------------------------------------------------------------===//
3254// Type Parsing.
3255//===----------------------------------------------------------------------===//
3256
3257/// parseType - parse a type.
3258bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3259 SMLoc TypeLoc = Lex.getLoc();
3260 switch (Lex.getKind()) {
3261 default:
3262 return tokError(Msg);
3263 case lltok::Type:
3264 // Type ::= 'float' | 'void' (etc)
3265 Result = Lex.getTyVal();
3266 Lex.Lex();
3267
3268 // Handle "ptr" opaque pointer type.
3269 //
3270 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3271 if (Result->isPointerTy()) {
3272 unsigned AddrSpace;
3273 if (parseOptionalAddrSpace(AddrSpace))
3274 return true;
3275 Result = PointerType::get(getContext(), AddrSpace);
3276
3277 // Give a nice error for 'ptr*'.
3278 if (Lex.getKind() == lltok::star)
3279 return tokError("ptr* is invalid - use ptr instead");
3280
3281 // Fall through to parsing the type suffixes only if this 'ptr' is a
3282 // function return. Otherwise, return success, implicitly rejecting other
3283 // suffixes.
3284 if (Lex.getKind() != lltok::lparen)
3285 return false;
3286 }
3287 break;
3288 case lltok::kw_target: {
3289 // Type ::= TargetExtType
3290 if (parseTargetExtType(Result))
3291 return true;
3292 break;
3293 }
3294 case lltok::lbrace:
3295 // Type ::= StructType
3296 if (parseAnonStructType(Result, false))
3297 return true;
3298 break;
3299 case lltok::lsquare:
3300 // Type ::= '[' ... ']'
3301 Lex.Lex(); // eat the lsquare.
3302 if (parseArrayVectorType(Result, false))
3303 return true;
3304 break;
3305 case lltok::less: // Either vector or packed struct.
3306 // Type ::= '<' ... '>'
3307 Lex.Lex();
3308 if (Lex.getKind() == lltok::lbrace) {
3309 if (parseAnonStructType(Result, true) ||
3310 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3311 return true;
3312 } else if (parseArrayVectorType(Result, true))
3313 return true;
3314 break;
3315 case lltok::LocalVar: {
3316 // Type ::= %foo
3317 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3318
3319 // If the type hasn't been defined yet, create a forward definition and
3320 // remember where that forward def'n was seen (in case it never is defined).
3321 if (!Entry.first) {
3322 Entry.first = StructType::create(Context, Lex.getStrVal());
3323 Entry.second = Lex.getLoc();
3324 }
3325 Result = Entry.first;
3326 Lex.Lex();
3327 break;
3328 }
3329
3330 case lltok::LocalVarID: {
3331 // Type ::= %4
3332 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3333
3334 // If the type hasn't been defined yet, create a forward definition and
3335 // remember where that forward def'n was seen (in case it never is defined).
3336 if (!Entry.first) {
3337 Entry.first = StructType::create(Context);
3338 Entry.second = Lex.getLoc();
3339 }
3340 Result = Entry.first;
3341 Lex.Lex();
3342 break;
3343 }
3344 }
3345
3346 // parse the type suffixes.
3347 while (true) {
3348 switch (Lex.getKind()) {
3349 // End of type.
3350 default:
3351 if (!AllowVoid && Result->isVoidTy())
3352 return error(TypeLoc, "void type only allowed for function results");
3353 return false;
3354
3355 // Type ::= Type '*'
3356 case lltok::star:
3357 if (Result->isLabelTy())
3358 return tokError("basic block pointers are invalid");
3359 if (Result->isVoidTy())
3360 return tokError("pointers to void are invalid - use i8* instead");
3362 return tokError("pointer to this type is invalid");
3363 Result = PointerType::getUnqual(Context);
3364 Lex.Lex();
3365 break;
3366
3367 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3368 case lltok::kw_addrspace: {
3369 if (Result->isLabelTy())
3370 return tokError("basic block pointers are invalid");
3371 if (Result->isVoidTy())
3372 return tokError("pointers to void are invalid; use i8* instead");
3374 return tokError("pointer to this type is invalid");
3375 unsigned AddrSpace;
3376 if (parseOptionalAddrSpace(AddrSpace) ||
3377 parseToken(lltok::star, "expected '*' in address space"))
3378 return true;
3379
3380 Result = PointerType::get(Context, AddrSpace);
3381 break;
3382 }
3383
3384 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3385 case lltok::lparen:
3386 if (parseFunctionType(Result))
3387 return true;
3388 break;
3389 }
3390 }
3391}
3392
3393/// parseParameterList
3394/// ::= '(' ')'
3395/// ::= '(' Arg (',' Arg)* ')'
3396/// Arg
3397/// ::= Type OptionalAttributes Value OptionalAttributes
3398bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3399 PerFunctionState &PFS, bool IsMustTailCall,
3400 bool InVarArgsFunc) {
3401 if (parseToken(lltok::lparen, "expected '(' in call"))
3402 return true;
3403
3404 while (Lex.getKind() != lltok::rparen) {
3405 // If this isn't the first argument, we need a comma.
3406 if (!ArgList.empty() &&
3407 parseToken(lltok::comma, "expected ',' in argument list"))
3408 return true;
3409
3410 // parse an ellipsis if this is a musttail call in a variadic function.
3411 if (Lex.getKind() == lltok::dotdotdot) {
3412 const char *Msg = "unexpected ellipsis in argument list for ";
3413 if (!IsMustTailCall)
3414 return tokError(Twine(Msg) + "non-musttail call");
3415 if (!InVarArgsFunc)
3416 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3417 Lex.Lex(); // Lex the '...', it is purely for readability.
3418 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3419 }
3420
3421 // parse the argument.
3422 LocTy ArgLoc;
3423 Type *ArgTy = nullptr;
3424 Value *V;
3425 if (parseType(ArgTy, ArgLoc))
3426 return true;
3428 return error(ArgLoc, "invalid type for function argument");
3429
3430 AttrBuilder ArgAttrs(M->getContext());
3431
3432 if (ArgTy->isMetadataTy()) {
3433 if (parseMetadataAsValue(V, PFS))
3434 return true;
3435 } else {
3436 // Otherwise, handle normal operands.
3437 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3438 return true;
3439 }
3440 ArgList.push_back(ParamInfo(
3441 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3442 }
3443
3444 if (IsMustTailCall && InVarArgsFunc)
3445 return tokError("expected '...' at end of argument list for musttail call "
3446 "in varargs function");
3447
3448 Lex.Lex(); // Lex the ')'.
3449 return false;
3450}
3451
3452/// parseRequiredTypeAttr
3453/// ::= attrname(<ty>)
3454bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3455 Attribute::AttrKind AttrKind) {
3456 Type *Ty = nullptr;
3457 if (!EatIfPresent(AttrToken))
3458 return true;
3459 if (!EatIfPresent(lltok::lparen))
3460 return error(Lex.getLoc(), "expected '('");
3461 if (parseType(Ty))
3462 return true;
3463 if (!EatIfPresent(lltok::rparen))
3464 return error(Lex.getLoc(), "expected ')'");
3465
3466 B.addTypeAttr(AttrKind, Ty);
3467 return false;
3468}
3469
3470/// parseRangeAttr
3471/// ::= range(<ty> <n>,<n>)
3472bool LLParser::parseRangeAttr(AttrBuilder &B) {
3473 Lex.Lex();
3474
3475 APInt Lower;
3476 APInt Upper;
3477 Type *Ty = nullptr;
3478 LocTy TyLoc;
3479
3480 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3481 if (Lex.getKind() != lltok::APSInt)
3482 return tokError("expected integer");
3483 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3484 return tokError(
3485 "integer is too large for the bit width of specified type");
3486 Val = Lex.getAPSIntVal().extend(BitWidth);
3487 Lex.Lex();
3488 return false;
3489 };
3490
3491 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3492 return true;
3493 if (!Ty->isIntegerTy())
3494 return error(TyLoc, "the range must have integer type!");
3495
3496 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3497
3498 if (ParseAPSInt(BitWidth, Lower) ||
3499 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3500 return true;
3501 if (Lower == Upper && !Lower.isZero())
3502 return tokError("the range represent the empty set but limits aren't 0!");
3503
3504 if (parseToken(lltok::rparen, "expected ')'"))
3505 return true;
3506
3507 B.addRangeAttr(ConstantRange(Lower, Upper));
3508 return false;
3509}
3510
3511/// parseInitializesAttr
3512/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3513bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3514 Lex.Lex();
3515
3516 auto ParseAPSInt = [&](APInt &Val) {
3517 if (Lex.getKind() != lltok::APSInt)
3518 return tokError("expected integer");
3519 Val = Lex.getAPSIntVal().extend(64);
3520 Lex.Lex();
3521 return false;
3522 };
3523
3524 if (parseToken(lltok::lparen, "expected '('"))
3525 return true;
3526
3528 // Parse each constant range.
3529 do {
3530 APInt Lower, Upper;
3531 if (parseToken(lltok::lparen, "expected '('"))
3532 return true;
3533
3534 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3535 ParseAPSInt(Upper))
3536 return true;
3537
3538 if (Lower == Upper)
3539 return tokError("the range should not represent the full or empty set!");
3540
3541 if (parseToken(lltok::rparen, "expected ')'"))
3542 return true;
3543
3544 RangeList.push_back(ConstantRange(Lower, Upper));
3545 } while (EatIfPresent(lltok::comma));
3546
3547 if (parseToken(lltok::rparen, "expected ')'"))
3548 return true;
3549
3550 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3551 if (!CRLOrNull.has_value())
3552 return tokError("Invalid (unordered or overlapping) range list");
3553 B.addInitializesAttr(*CRLOrNull);
3554 return false;
3555}
3556
3557bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3559 std::optional<CaptureComponents> Ret;
3560
3561 // We use syntax like captures(ret: address, provenance), so the colon
3562 // should not be interpreted as a label terminator.
3563 Lex.setIgnoreColonInIdentifiers(true);
3564 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3565
3566 Lex.Lex();
3567 if (parseToken(lltok::lparen, "expected '('"))
3568 return true;
3569
3570 CaptureComponents *Current = &Other;
3571 bool SeenComponent = false;
3572 while (true) {
3573 if (EatIfPresent(lltok::kw_ret)) {
3574 if (parseToken(lltok::colon, "expected ':'"))
3575 return true;
3576 if (Ret)
3577 return tokError("duplicate 'ret' location");
3579 Current = &*Ret;
3580 SeenComponent = false;
3581 }
3582
3583 if (EatIfPresent(lltok::kw_none)) {
3584 if (SeenComponent)
3585 return tokError("cannot use 'none' with other component");
3586 *Current = CaptureComponents::None;
3587 } else {
3588 if (SeenComponent && capturesNothing(*Current))
3589 return tokError("cannot use 'none' with other component");
3590
3591 if (EatIfPresent(lltok::kw_address_is_null))
3593 else if (EatIfPresent(lltok::kw_address))
3594 *Current |= CaptureComponents::Address;
3595 else if (EatIfPresent(lltok::kw_provenance))
3597 else if (EatIfPresent(lltok::kw_read_provenance))
3599 else
3600 return tokError("expected one of 'none', 'address', 'address_is_null', "
3601 "'provenance' or 'read_provenance'");
3602 }
3603
3604 SeenComponent = true;
3605 if (EatIfPresent(lltok::rparen))
3606 break;
3607
3608 if (parseToken(lltok::comma, "expected ',' or ')'"))
3609 return true;
3610 }
3611
3612 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3613 return false;
3614}
3615
3616/// parseOptionalOperandBundles
3617/// ::= /*empty*/
3618/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3619///
3620/// OperandBundle
3621/// ::= bundle-tag '(' ')'
3622/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3623///
3624/// bundle-tag ::= String Constant
3625bool LLParser::parseOptionalOperandBundles(
3626 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3627 LocTy BeginLoc = Lex.getLoc();
3628 if (!EatIfPresent(lltok::lsquare))
3629 return false;
3630
3631 while (Lex.getKind() != lltok::rsquare) {
3632 // If this isn't the first operand bundle, we need a comma.
3633 if (!BundleList.empty() &&
3634 parseToken(lltok::comma, "expected ',' in input list"))
3635 return true;
3636
3637 std::string Tag;
3638 if (parseStringConstant(Tag))
3639 return true;
3640
3641 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3642 return true;
3643
3644 std::vector<Value *> Inputs;
3645 while (Lex.getKind() != lltok::rparen) {
3646 // If this isn't the first input, we need a comma.
3647 if (!Inputs.empty() &&
3648 parseToken(lltok::comma, "expected ',' in input list"))
3649 return true;
3650
3651 Type *Ty = nullptr;
3652 Value *Input = nullptr;
3653 if (parseType(Ty))
3654 return true;
3655 if (Ty->isMetadataTy()) {
3656 if (parseMetadataAsValue(Input, PFS))
3657 return true;
3658 } else if (parseValue(Ty, Input, PFS)) {
3659 return true;
3660 }
3661 Inputs.push_back(Input);
3662 }
3663
3664 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3665
3666 Lex.Lex(); // Lex the ')'.
3667 }
3668
3669 if (BundleList.empty())
3670 return error(BeginLoc, "operand bundle set must not be empty");
3671
3672 Lex.Lex(); // Lex the ']'.
3673 return false;
3674}
3675
3676bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3677 unsigned NextID, unsigned ID) {
3678 if (ID < NextID)
3679 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3680 Twine(NextID) + "' or greater");
3681
3682 return false;
3683}
3684
3685/// parseArgumentList - parse the argument list for a function type or function
3686/// prototype.
3687/// ::= '(' ArgTypeListI ')'
3688/// ArgTypeListI
3689/// ::= /*empty*/
3690/// ::= '...'
3691/// ::= ArgTypeList ',' '...'
3692/// ::= ArgType (',' ArgType)*
3693///
3694bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3695 SmallVectorImpl<unsigned> &UnnamedArgNums,
3696 bool &IsVarArg) {
3697 unsigned CurValID = 0;
3698 IsVarArg = false;
3699 assert(Lex.getKind() == lltok::lparen);
3700 Lex.Lex(); // eat the (.
3701
3702 if (Lex.getKind() != lltok::rparen) {
3703 do {
3704 // Handle ... at end of arg list.
3705 if (EatIfPresent(lltok::dotdotdot)) {
3706 IsVarArg = true;
3707 break;
3708 }
3709
3710 // Otherwise must be an argument type.
3711 LocTy TypeLoc = Lex.getLoc();
3712 Type *ArgTy = nullptr;
3713 AttrBuilder Attrs(M->getContext());
3714 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3715 return true;
3716
3717 if (ArgTy->isVoidTy())
3718 return error(TypeLoc, "argument can not have void type");
3719
3720 std::string Name;
3721 FileLoc IdentStart;
3722 FileLoc IdentEnd;
3723 bool Unnamed = false;
3724 if (Lex.getKind() == lltok::LocalVar) {
3725 Name = Lex.getStrVal();
3726 IdentStart = getTokLineColumnPos();
3727 Lex.Lex();
3728 IdentEnd = getPrevTokEndLineColumnPos();
3729 } else {
3730 unsigned ArgID;
3731 if (Lex.getKind() == lltok::LocalVarID) {
3732 ArgID = Lex.getUIntVal();
3733 IdentStart = getTokLineColumnPos();
3734 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3735 return true;
3736 Lex.Lex();
3737 IdentEnd = getPrevTokEndLineColumnPos();
3738 } else {
3739 ArgID = CurValID;
3740 Unnamed = true;
3741 }
3742 UnnamedArgNums.push_back(ArgID);
3743 CurValID = ArgID + 1;
3744 }
3745
3747 return error(TypeLoc, "invalid type for function argument");
3748
3749 ArgList.emplace_back(
3750 TypeLoc, ArgTy,
3751 Unnamed ? std::nullopt
3752 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3753 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3754 } while (EatIfPresent(lltok::comma));
3755 }
3756
3757 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3758}
3759
3760/// parseFunctionType
3761/// ::= Type ArgumentList OptionalAttrs
3762bool LLParser::parseFunctionType(Type *&Result) {
3763 assert(Lex.getKind() == lltok::lparen);
3764
3766 return tokError("invalid function return type");
3767
3769 bool IsVarArg;
3770 SmallVector<unsigned> UnnamedArgNums;
3771 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3772 return true;
3773
3774 // Reject names on the arguments lists.
3775 for (const ArgInfo &Arg : ArgList) {
3776 if (!Arg.Name.empty())
3777 return error(Arg.Loc, "argument name invalid in function type");
3778 if (Arg.Attrs.hasAttributes())
3779 return error(Arg.Loc, "argument attributes invalid in function type");
3780 }
3781
3782 SmallVector<Type*, 16> ArgListTy;
3783 for (const ArgInfo &Arg : ArgList)
3784 ArgListTy.push_back(Arg.Ty);
3785
3786 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3787 return false;
3788}
3789
3790/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3791/// other structs.
3792bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3794 if (parseStructBody(Elts))
3795 return true;
3796
3797 Result = StructType::get(Context, Elts, Packed);
3798 return false;
3799}
3800
3801/// parseStructDefinition - parse a struct in a 'type' definition.
3802bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3803 std::pair<Type *, LocTy> &Entry,
3804 Type *&ResultTy) {
3805 // If the type was already defined, diagnose the redefinition.
3806 if (Entry.first && !Entry.second.isValid())
3807 return error(TypeLoc, "redefinition of type");
3808
3809 // If we have opaque, just return without filling in the definition for the
3810 // struct. This counts as a definition as far as the .ll file goes.
3811 if (EatIfPresent(lltok::kw_opaque)) {
3812 // This type is being defined, so clear the location to indicate this.
3813 Entry.second = SMLoc();
3814
3815 // If this type number has never been uttered, create it.
3816 if (!Entry.first)
3817 Entry.first = StructType::create(Context, Name);
3818 ResultTy = Entry.first;
3819 return false;
3820 }
3821
3822 // If the type starts with '<', then it is either a packed struct or a vector.
3823 bool isPacked = EatIfPresent(lltok::less);
3824
3825 // If we don't have a struct, then we have a random type alias, which we
3826 // accept for compatibility with old files. These types are not allowed to be
3827 // forward referenced and not allowed to be recursive.
3828 if (Lex.getKind() != lltok::lbrace) {
3829 if (Entry.first)
3830 return error(TypeLoc, "forward references to non-struct type");
3831
3832 ResultTy = nullptr;
3833 if (isPacked)
3834 return parseArrayVectorType(ResultTy, true);
3835 return parseType(ResultTy);
3836 }
3837
3838 // This type is being defined, so clear the location to indicate this.
3839 Entry.second = SMLoc();
3840
3841 // If this type number has never been uttered, create it.
3842 if (!Entry.first)
3843 Entry.first = StructType::create(Context, Name);
3844
3845 StructType *STy = cast<StructType>(Entry.first);
3846
3848 if (parseStructBody(Body) ||
3849 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3850 return true;
3851
3852 if (auto E = STy->setBodyOrError(Body, isPacked))
3853 return tokError(toString(std::move(E)));
3854
3855 ResultTy = STy;
3856 return false;
3857}
3858
3859/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3860/// StructType
3861/// ::= '{' '}'
3862/// ::= '{' Type (',' Type)* '}'
3863/// ::= '<' '{' '}' '>'
3864/// ::= '<' '{' Type (',' Type)* '}' '>'
3865bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3866 assert(Lex.getKind() == lltok::lbrace);
3867 Lex.Lex(); // Consume the '{'
3868
3869 // Handle the empty struct.
3870 if (EatIfPresent(lltok::rbrace))
3871 return false;
3872
3873 LocTy EltTyLoc = Lex.getLoc();
3874 Type *Ty = nullptr;
3875 if (parseType(Ty))
3876 return true;
3877 Body.push_back(Ty);
3878
3880 return error(EltTyLoc, "invalid element type for struct");
3881
3882 while (EatIfPresent(lltok::comma)) {
3883 EltTyLoc = Lex.getLoc();
3884 if (parseType(Ty))
3885 return true;
3886
3888 return error(EltTyLoc, "invalid element type for struct");
3889
3890 Body.push_back(Ty);
3891 }
3892
3893 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3894}
3895
3896/// parseArrayVectorType - parse an array or vector type, assuming the first
3897/// token has already been consumed.
3898/// Type
3899/// ::= '[' APSINTVAL 'x' Types ']'
3900/// ::= '<' APSINTVAL 'x' Types '>'
3901/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3902bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3903 bool Scalable = false;
3904
3905 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3906 Lex.Lex(); // consume the 'vscale'
3907 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3908 return true;
3909
3910 Scalable = true;
3911 }
3912
3913 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3914 Lex.getAPSIntVal().getBitWidth() > 64)
3915 return tokError("expected number in address space");
3916
3917 LocTy SizeLoc = Lex.getLoc();
3918 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3919 Lex.Lex();
3920
3921 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3922 return true;
3923
3924 LocTy TypeLoc = Lex.getLoc();
3925 Type *EltTy = nullptr;
3926 if (parseType(EltTy))
3927 return true;
3928
3929 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3930 "expected end of sequential type"))
3931 return true;
3932
3933 if (IsVector) {
3934 if (Size == 0)
3935 return error(SizeLoc, "zero element vector is illegal");
3936 if ((unsigned)Size != Size)
3937 return error(SizeLoc, "size too large for vector");
3939 return error(TypeLoc, "invalid vector element type");
3940 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3941 } else {
3943 return error(TypeLoc, "invalid array element type");
3944 Result = ArrayType::get(EltTy, Size);
3945 }
3946 return false;
3947}
3948
3949/// parseTargetExtType - handle target extension type syntax
3950/// TargetExtType
3951/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3952///
3953/// TargetExtTypeParams
3954/// ::= /*empty*/
3955/// ::= ',' Type TargetExtTypeParams
3956///
3957/// TargetExtIntParams
3958/// ::= /*empty*/
3959/// ::= ',' uint32 TargetExtIntParams
3960bool LLParser::parseTargetExtType(Type *&Result) {
3961 Lex.Lex(); // Eat the 'target' keyword.
3962
3963 // Get the mandatory type name.
3964 std::string TypeName;
3965 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3966 parseStringConstant(TypeName))
3967 return true;
3968
3969 // Parse all of the integer and type parameters at the same time; the use of
3970 // SeenInt will allow us to catch cases where type parameters follow integer
3971 // parameters.
3972 SmallVector<Type *> TypeParams;
3973 SmallVector<unsigned> IntParams;
3974 bool SeenInt = false;
3975 while (Lex.getKind() == lltok::comma) {
3976 Lex.Lex(); // Eat the comma.
3977
3978 if (Lex.getKind() == lltok::APSInt) {
3979 SeenInt = true;
3980 unsigned IntVal;
3981 if (parseUInt32(IntVal))
3982 return true;
3983 IntParams.push_back(IntVal);
3984 } else if (SeenInt) {
3985 // The only other kind of parameter we support is type parameters, which
3986 // must precede the integer parameters. This is therefore an error.
3987 return tokError("expected uint32 param");
3988 } else {
3989 Type *TypeParam;
3990 if (parseType(TypeParam, /*AllowVoid=*/true))
3991 return true;
3992 TypeParams.push_back(TypeParam);
3993 }
3994 }
3995
3996 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3997 return true;
3998
3999 auto TTy =
4000 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
4001 if (auto E = TTy.takeError())
4002 return tokError(toString(std::move(E)));
4003
4004 Result = *TTy;
4005 return false;
4006}
4007
4008//===----------------------------------------------------------------------===//
4009// Function Semantic Analysis.
4010//===----------------------------------------------------------------------===//
4011
4012LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
4013 int functionNumber,
4014 ArrayRef<unsigned> UnnamedArgNums)
4015 : P(p), F(f), FunctionNumber(functionNumber) {
4016
4017 // Insert unnamed arguments into the NumberedVals list.
4018 auto It = UnnamedArgNums.begin();
4019 for (Argument &A : F.args()) {
4020 if (!A.hasName()) {
4021 unsigned ArgNum = *It++;
4022 NumberedVals.add(ArgNum, &A);
4023 }
4024 }
4025}
4026
4027LLParser::PerFunctionState::~PerFunctionState() {
4028 // If there were any forward referenced non-basicblock values, delete them.
4029
4030 for (const auto &P : ForwardRefVals) {
4031 if (isa<BasicBlock>(P.second.first))
4032 continue;
4033 P.second.first->replaceAllUsesWith(
4034 PoisonValue::get(P.second.first->getType()));
4035 P.second.first->deleteValue();
4036 }
4037
4038 for (const auto &P : ForwardRefValIDs) {
4039 if (isa<BasicBlock>(P.second.first))
4040 continue;
4041 P.second.first->replaceAllUsesWith(
4042 PoisonValue::get(P.second.first->getType()));
4043 P.second.first->deleteValue();
4044 }
4045}
4046
4047bool LLParser::PerFunctionState::finishFunction() {
4048 if (!ForwardRefVals.empty())
4049 return P.error(ForwardRefVals.begin()->second.second,
4050 "use of undefined value '%" + ForwardRefVals.begin()->first +
4051 "'");
4052 if (!ForwardRefValIDs.empty())
4053 return P.error(ForwardRefValIDs.begin()->second.second,
4054 "use of undefined value '%" +
4055 Twine(ForwardRefValIDs.begin()->first) + "'");
4056 return false;
4057}
4058
4059/// getVal - Get a value with the specified name or ID, creating a
4060/// forward reference record if needed. This can return null if the value
4061/// exists but does not have the right type.
4062Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
4063 LocTy Loc) {
4064 // Look this name up in the normal function symbol table.
4065 Value *Val = F.getValueSymbolTable()->lookup(Name);
4066
4067 // If this is a forward reference for the value, see if we already created a
4068 // forward ref record.
4069 if (!Val) {
4070 auto I = ForwardRefVals.find(Name);
4071 if (I != ForwardRefVals.end())
4072 Val = I->second.first;
4073 }
4074
4075 // If we have the value in the symbol table or fwd-ref table, return it.
4076 if (Val)
4077 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
4078
4079 // Don't make placeholders with invalid type.
4080 if (!Ty->isFirstClassType()) {
4081 P.error(Loc, "invalid use of a non-first-class type");
4082 return nullptr;
4083 }
4084
4085 // Otherwise, create a new forward reference for this value and remember it.
4086 Value *FwdVal;
4087 if (Ty->isLabelTy()) {
4088 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
4089 } else {
4090 FwdVal = new Argument(Ty, Name);
4091 }
4092 if (FwdVal->getName() != Name) {
4093 P.error(Loc, "name is too long which can result in name collisions, "
4094 "consider making the name shorter or "
4095 "increasing -non-global-value-max-name-size");
4096 return nullptr;
4097 }
4098
4099 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
4100 return FwdVal;
4101}
4102
4103Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
4104 // Look this name up in the normal function symbol table.
4105 Value *Val = NumberedVals.get(ID);
4106
4107 // If this is a forward reference for the value, see if we already created a
4108 // forward ref record.
4109 if (!Val) {
4110 auto I = ForwardRefValIDs.find(ID);
4111 if (I != ForwardRefValIDs.end())
4112 Val = I->second.first;
4113 }
4114
4115 // If we have the value in the symbol table or fwd-ref table, return it.
4116 if (Val)
4117 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
4118
4119 if (!Ty->isFirstClassType()) {
4120 P.error(Loc, "invalid use of a non-first-class type");
4121 return nullptr;
4122 }
4123
4124 // Otherwise, create a new forward reference for this value and remember it.
4125 Value *FwdVal;
4126 if (Ty->isLabelTy()) {
4127 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
4128 } else {
4129 FwdVal = new Argument(Ty);
4130 }
4131
4132 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
4133 return FwdVal;
4134}
4135
4136/// setInstName - After an instruction is parsed and inserted into its
4137/// basic block, this installs its name.
4138bool LLParser::PerFunctionState::setInstName(int NameID,
4139 const std::string &NameStr,
4140 LocTy NameLoc, Instruction *Inst) {
4141 // If this instruction has void type, it cannot have a name or ID specified.
4142 if (Inst->getType()->isVoidTy()) {
4143 if (NameID != -1 || !NameStr.empty())
4144 return P.error(NameLoc, "instructions returning void cannot have a name");
4145 return false;
4146 }
4147
4148 // If this was a numbered instruction, verify that the instruction is the
4149 // expected value and resolve any forward references.
4150 if (NameStr.empty()) {
4151 // If neither a name nor an ID was specified, just use the next ID.
4152 if (NameID == -1)
4153 NameID = NumberedVals.getNext();
4154
4155 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4156 NameID))
4157 return true;
4158
4159 auto FI = ForwardRefValIDs.find(NameID);
4160 if (FI != ForwardRefValIDs.end()) {
4161 Value *Sentinel = FI->second.first;
4162 if (Sentinel->getType() != Inst->getType())
4163 return P.error(NameLoc, "instruction forward referenced with type '" +
4164 getTypeString(FI->second.first->getType()) +
4165 "'");
4166
4167 Sentinel->replaceAllUsesWith(Inst);
4168 Sentinel->deleteValue();
4169 ForwardRefValIDs.erase(FI);
4170 }
4171
4172 NumberedVals.add(NameID, Inst);
4173 return false;
4174 }
4175
4176 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4177 auto FI = ForwardRefVals.find(NameStr);
4178 if (FI != ForwardRefVals.end()) {
4179 Value *Sentinel = FI->second.first;
4180 if (Sentinel->getType() != Inst->getType())
4181 return P.error(NameLoc, "instruction forward referenced with type '" +
4182 getTypeString(FI->second.first->getType()) +
4183 "'");
4184
4185 Sentinel->replaceAllUsesWith(Inst);
4186 Sentinel->deleteValue();
4187 ForwardRefVals.erase(FI);
4188 }
4189
4190 // Set the name on the instruction.
4191 Inst->setName(NameStr);
4192
4193 if (Inst->getName() != NameStr)
4194 return P.error(NameLoc, "multiple definition of local value named '" +
4195 NameStr + "'");
4196 return false;
4197}
4198
4199/// getBB - Get a basic block with the specified name or ID, creating a
4200/// forward reference record if needed.
4201BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4202 LocTy Loc) {
4204 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4205}
4206
4207BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4209 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4210}
4211
4212/// defineBB - Define the specified basic block, which is either named or
4213/// unnamed. If there is an error, this returns null otherwise it returns
4214/// the block being defined.
4215BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4216 int NameID, LocTy Loc) {
4217 BasicBlock *BB;
4218 if (Name.empty()) {
4219 if (NameID != -1) {
4220 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4221 return nullptr;
4222 } else {
4223 NameID = NumberedVals.getNext();
4224 }
4225 BB = getBB(NameID, Loc);
4226 if (!BB) {
4227 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4228 return nullptr;
4229 }
4230 } else {
4231 BB = getBB(Name, Loc);
4232 if (!BB) {
4233 P.error(Loc, "unable to create block named '" + Name + "'");
4234 return nullptr;
4235 }
4236 }
4237
4238 // Move the block to the end of the function. Forward ref'd blocks are
4239 // inserted wherever they happen to be referenced.
4240 F.splice(F.end(), &F, BB->getIterator());
4241
4242 // Remove the block from forward ref sets.
4243 if (Name.empty()) {
4244 ForwardRefValIDs.erase(NameID);
4245 NumberedVals.add(NameID, BB);
4246 } else {
4247 // BB forward references are already in the function symbol table.
4248 ForwardRefVals.erase(Name);
4249 }
4250
4251 return BB;
4252}
4253
4254//===----------------------------------------------------------------------===//
4255// Constants.
4256//===----------------------------------------------------------------------===//
4257
4258/// parseValID - parse an abstract value that doesn't necessarily have a
4259/// type implied. For example, if we parse "4" we don't know what integer type
4260/// it has. The value will later be combined with its type and checked for
4261/// basic correctness. PFS is used to convert function-local operands of
4262/// metadata (since metadata operands are not just parsed here but also
4263/// converted to values). PFS can be null when we are not parsing metadata
4264/// values inside a function.
4265bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4266 ID.Loc = Lex.getLoc();
4267 switch (Lex.getKind()) {
4268 default:
4269 return tokError("expected value token");
4270 case lltok::GlobalID: // @42
4271 ID.UIntVal = Lex.getUIntVal();
4272 ID.Kind = ValID::t_GlobalID;
4273 break;
4274 case lltok::GlobalVar: // @foo
4275 ID.StrVal = Lex.getStrVal();
4276 ID.Kind = ValID::t_GlobalName;
4277 break;
4278 case lltok::LocalVarID: // %42
4279 ID.UIntVal = Lex.getUIntVal();
4280 ID.Kind = ValID::t_LocalID;
4281 break;
4282 case lltok::LocalVar: // %foo
4283 ID.StrVal = Lex.getStrVal();
4284 ID.Kind = ValID::t_LocalName;
4285 break;
4286 case lltok::APSInt:
4287 ID.APSIntVal = Lex.getAPSIntVal();
4288 ID.Kind = ValID::t_APSInt;
4289 break;
4290 case lltok::APFloat: {
4291 ID.APFloatVal = Lex.getAPFloatVal();
4292 ID.Kind = ValID::t_APFloat;
4293 break;
4294 }
4295 case lltok::FloatLiteral: {
4296 if (!ExpectedTy)
4297 return error(ID.Loc, "unexpected floating-point literal");
4298 if (!ExpectedTy->isFloatingPointTy())
4299 return error(ID.Loc, "floating-point constant invalid for type");
4300 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4301 APFloat::opStatus Except =
4302 cantFail(ID.APFloatVal.convertFromString(
4303 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4304 "Invalid float strings should be caught by the lexer");
4305 // Forbid overflowing and underflowing literals, but permit inexact
4306 // literals. Underflow is thrown when the result is denormal, so to allow
4307 // denormals, only reject underflowing literals that resulted in a zero.
4308 if (Except & APFloat::opOverflow)
4309 return error(ID.Loc, "floating-point constant overflowed type");
4310 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4311 return error(ID.Loc, "floating-point constant underflowed type");
4312 ID.Kind = ValID::t_APFloat;
4313 break;
4314 }
4316 if (!ExpectedTy)
4317 return error(ID.Loc, "unexpected floating-point literal");
4318 const auto &Semantics = ExpectedTy->getFltSemantics();
4319 const APInt &Bits = Lex.getAPSIntVal();
4320 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4321 return error(ID.Loc, "float hex literal has incorrect number of bits");
4322 ID.APFloatVal = APFloat(Semantics, Bits);
4323 ID.Kind = ValID::t_APFloat;
4324 break;
4325 }
4326 case lltok::kw_true:
4327 ID.ConstantVal = ConstantInt::getTrue(Context);
4328 ID.Kind = ValID::t_Constant;
4329 break;
4330 case lltok::kw_false:
4331 ID.ConstantVal = ConstantInt::getFalse(Context);
4332 ID.Kind = ValID::t_Constant;
4333 break;
4334 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4335 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4336 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4337 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4338 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4339
4340 case lltok::lbrace: {
4341 // ValID ::= '{' ConstVector '}'
4342 Lex.Lex();
4344 if (parseGlobalValueVector(Elts) ||
4345 parseToken(lltok::rbrace, "expected end of struct constant"))
4346 return true;
4347
4348 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4349 ID.UIntVal = Elts.size();
4350 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4351 Elts.size() * sizeof(Elts[0]));
4353 return false;
4354 }
4355 case lltok::less: {
4356 // ValID ::= '<' ConstVector '>' --> Vector.
4357 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4358 Lex.Lex();
4359 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4360
4362 LocTy FirstEltLoc = Lex.getLoc();
4363 if (parseGlobalValueVector(Elts) ||
4364 (isPackedStruct &&
4365 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4366 parseToken(lltok::greater, "expected end of constant"))
4367 return true;
4368
4369 if (isPackedStruct) {
4370 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4371 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4372 Elts.size() * sizeof(Elts[0]));
4373 ID.UIntVal = Elts.size();
4375 return false;
4376 }
4377
4378 if (Elts.empty())
4379 return error(ID.Loc, "constant vector must not be empty");
4380
4381 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4382 !Elts[0]->getType()->isFloatingPointTy() &&
4383 !Elts[0]->getType()->isPointerTy())
4384 return error(
4385 FirstEltLoc,
4386 "vector elements must have integer, byte, pointer or floating point "
4387 "type");
4388
4389 // Verify that all the vector elements have the same type.
4390 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4391 if (Elts[i]->getType() != Elts[0]->getType())
4392 return error(FirstEltLoc, "vector element #" + Twine(i) +
4393 " is not of type '" +
4394 getTypeString(Elts[0]->getType()));
4395
4396 ID.ConstantVal = ConstantVector::get(Elts);
4397 ID.Kind = ValID::t_Constant;
4398 return false;
4399 }
4400 case lltok::lsquare: { // Array Constant
4401 Lex.Lex();
4403 LocTy FirstEltLoc = Lex.getLoc();
4404 if (parseGlobalValueVector(Elts) ||
4405 parseToken(lltok::rsquare, "expected end of array constant"))
4406 return true;
4407
4408 // Handle empty element.
4409 if (Elts.empty()) {
4410 // Use undef instead of an array because it's inconvenient to determine
4411 // the element type at this point, there being no elements to examine.
4412 ID.Kind = ValID::t_EmptyArray;
4413 return false;
4414 }
4415
4416 if (!Elts[0]->getType()->isFirstClassType())
4417 return error(FirstEltLoc, "invalid array element type: " +
4418 getTypeString(Elts[0]->getType()));
4419
4420 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4421
4422 // Verify all elements are correct type!
4423 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4424 if (Elts[i]->getType() != Elts[0]->getType())
4425 return error(FirstEltLoc, "array element #" + Twine(i) +
4426 " is not of type '" +
4427 getTypeString(Elts[0]->getType()));
4428 }
4429
4430 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4431 ID.Kind = ValID::t_Constant;
4432 return false;
4433 }
4434 case lltok::kw_c: { // c "foo"
4435 Lex.Lex();
4436 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4437 ID.ConstantVal = ConstantDataArray::getString(
4438 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4439 if (parseToken(lltok::StringConstant, "expected string"))
4440 return true;
4441 ID.Kind = ValID::t_Constant;
4442 return false;
4443 }
4444 case lltok::kw_asm: {
4445 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4446 // STRINGCONSTANT
4447 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4448 Lex.Lex();
4449 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4450 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4451 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4452 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4453 parseStringConstant(ID.StrVal) ||
4454 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4455 parseToken(lltok::StringConstant, "expected constraint string"))
4456 return true;
4457 ID.StrVal2 = Lex.getStrVal();
4458 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4459 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4460 ID.Kind = ValID::t_InlineAsm;
4461 return false;
4462 }
4463
4465 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4466 Lex.Lex();
4467
4468 ValID Fn, Label;
4469
4470 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4471 parseValID(Fn, PFS) ||
4472 parseToken(lltok::comma,
4473 "expected comma in block address expression") ||
4474 parseValID(Label, PFS) ||
4475 parseToken(lltok::rparen, "expected ')' in block address expression"))
4476 return true;
4477
4479 return error(Fn.Loc, "expected function name in blockaddress");
4480 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4481 return error(Label.Loc, "expected basic block name in blockaddress");
4482
4483 // Try to find the function (but skip it if it's forward-referenced).
4484 GlobalValue *GV = nullptr;
4485 if (Fn.Kind == ValID::t_GlobalID) {
4486 GV = NumberedVals.get(Fn.UIntVal);
4487 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4488 GV = M->getNamedValue(Fn.StrVal);
4489 }
4490 Function *F = nullptr;
4491 if (GV) {
4492 // Confirm that it's actually a function with a definition.
4493 if (!isa<Function>(GV))
4494 return error(Fn.Loc, "expected function name in blockaddress");
4495 F = cast<Function>(GV);
4496 if (F->isDeclaration())
4497 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4498 }
4499
4500 if (!F) {
4501 // Make a global variable as a placeholder for this reference.
4502 GlobalValue *&FwdRef =
4503 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4504 if (!FwdRef) {
4505 unsigned FwdDeclAS;
4506 if (ExpectedTy) {
4507 // If we know the type that the blockaddress is being assigned to,
4508 // we can use the address space of that type.
4509 if (!ExpectedTy->isPointerTy())
4510 return error(ID.Loc,
4511 "type of blockaddress must be a pointer and not '" +
4512 getTypeString(ExpectedTy) + "'");
4513 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4514 } else if (PFS) {
4515 // Otherwise, we default the address space of the current function.
4516 FwdDeclAS = PFS->getFunction().getAddressSpace();
4517 } else {
4518 llvm_unreachable("Unknown address space for blockaddress");
4519 }
4520 FwdRef = new GlobalVariable(
4521 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4522 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4523 }
4524
4525 ID.ConstantVal = FwdRef;
4526 ID.Kind = ValID::t_Constant;
4527 return false;
4528 }
4529
4530 // We found the function; now find the basic block. Don't use PFS, since we
4531 // might be inside a constant expression.
4532 BasicBlock *BB;
4533 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4534 if (Label.Kind == ValID::t_LocalID)
4535 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4536 else
4537 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4538 if (!BB)
4539 return error(Label.Loc, "referenced value is not a basic block");
4540 } else {
4541 if (Label.Kind == ValID::t_LocalID)
4542 return error(Label.Loc, "cannot take address of numeric label after "
4543 "the function is defined");
4545 F->getValueSymbolTable()->lookup(Label.StrVal));
4546 if (!BB)
4547 return error(Label.Loc, "referenced value is not a basic block");
4548 }
4549
4550 ID.ConstantVal = BlockAddress::get(F, BB);
4551 ID.Kind = ValID::t_Constant;
4552 return false;
4553 }
4554
4556 // ValID ::= 'dso_local_equivalent' @foo
4557 Lex.Lex();
4558
4559 ValID Fn;
4560
4561 if (parseValID(Fn, PFS))
4562 return true;
4563
4565 return error(Fn.Loc,
4566 "expected global value name in dso_local_equivalent");
4567
4568 // Try to find the function (but skip it if it's forward-referenced).
4569 GlobalValue *GV = nullptr;
4570 if (Fn.Kind == ValID::t_GlobalID) {
4571 GV = NumberedVals.get(Fn.UIntVal);
4572 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4573 GV = M->getNamedValue(Fn.StrVal);
4574 }
4575
4576 if (!GV) {
4577 // Make a placeholder global variable as a placeholder for this reference.
4578 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4579 ? ForwardRefDSOLocalEquivalentIDs
4580 : ForwardRefDSOLocalEquivalentNames;
4581 GlobalValue *&FwdRef = FwdRefMap[Fn];
4582 if (!FwdRef) {
4583 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4584 GlobalValue::InternalLinkage, nullptr, "",
4586 }
4587
4588 ID.ConstantVal = FwdRef;
4589 ID.Kind = ValID::t_Constant;
4590 return false;
4591 }
4592
4593 if (!GV->getValueType()->isFunctionTy())
4594 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4595 "in dso_local_equivalent");
4596
4597 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4598 ID.Kind = ValID::t_Constant;
4599 return false;
4600 }
4601
4602 case lltok::kw_no_cfi: {
4603 // ValID ::= 'no_cfi' @foo
4604 Lex.Lex();
4605
4606 if (parseValID(ID, PFS))
4607 return true;
4608
4609 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4610 return error(ID.Loc, "expected global value name in no_cfi");
4611
4612 ID.NoCFI = true;
4613 return false;
4614 }
4615 case lltok::kw_ptrauth: {
4616 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4617 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4618 // )? )? ')'
4619 Lex.Lex();
4620
4621 Constant *Ptr, *Key;
4622 Constant *Disc = nullptr, *AddrDisc = nullptr,
4623 *DeactivationSymbol = nullptr;
4624
4625 if (parseToken(lltok::lparen,
4626 "expected '(' in constant ptrauth expression") ||
4627 parseGlobalTypeAndValue(Ptr) ||
4628 parseToken(lltok::comma,
4629 "expected comma in constant ptrauth expression") ||
4630 parseGlobalTypeAndValue(Key))
4631 return true;
4632 // If present, parse the optional disc/addrdisc/ds.
4633 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4634 return true;
4635 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4636 return true;
4637 if (EatIfPresent(lltok::comma) &&
4638 parseGlobalTypeAndValue(DeactivationSymbol))
4639 return true;
4640 if (parseToken(lltok::rparen,
4641 "expected ')' in constant ptrauth expression"))
4642 return true;
4643
4644 if (!Ptr->getType()->isPointerTy())
4645 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4646
4647 auto *KeyC = dyn_cast<ConstantInt>(Key);
4648 if (!KeyC || KeyC->getBitWidth() != 32)
4649 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4650
4651 ConstantInt *DiscC = nullptr;
4652 if (Disc) {
4653 DiscC = dyn_cast<ConstantInt>(Disc);
4654 if (!DiscC || DiscC->getBitWidth() != 64)
4655 return error(
4656 ID.Loc,
4657 "constant ptrauth integer discriminator must be i64 constant");
4658 } else {
4659 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4660 }
4661
4662 if (AddrDisc) {
4663 if (!AddrDisc->getType()->isPointerTy())
4664 return error(
4665 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4666 } else {
4667 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4668 }
4669
4670 if (!DeactivationSymbol)
4671 DeactivationSymbol =
4673 if (!DeactivationSymbol->getType()->isPointerTy())
4674 return error(ID.Loc,
4675 "constant ptrauth deactivation symbol must be a pointer");
4676
4677 ID.ConstantVal =
4678 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4679 ID.Kind = ValID::t_Constant;
4680 return false;
4681 }
4682
4683 case lltok::kw_trunc:
4684 case lltok::kw_bitcast:
4686 case lltok::kw_inttoptr:
4688 case lltok::kw_ptrtoint: {
4689 unsigned Opc = Lex.getUIntVal();
4690 Type *DestTy = nullptr;
4691 Constant *SrcVal;
4692 Lex.Lex();
4693 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4694 parseGlobalTypeAndValue(SrcVal) ||
4695 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4696 parseType(DestTy) ||
4697 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4698 return true;
4699 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4700 return error(ID.Loc, "invalid cast opcode for cast from '" +
4701 getTypeString(SrcVal->getType()) + "' to '" +
4702 getTypeString(DestTy) + "'");
4704 SrcVal, DestTy);
4705 ID.Kind = ValID::t_Constant;
4706 return false;
4707 }
4709 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4711 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4712 case lltok::kw_udiv:
4713 return error(ID.Loc, "udiv constexprs are no longer supported");
4714 case lltok::kw_sdiv:
4715 return error(ID.Loc, "sdiv constexprs are no longer supported");
4716 case lltok::kw_urem:
4717 return error(ID.Loc, "urem constexprs are no longer supported");
4718 case lltok::kw_srem:
4719 return error(ID.Loc, "srem constexprs are no longer supported");
4720 case lltok::kw_fadd:
4721 return error(ID.Loc, "fadd constexprs are no longer supported");
4722 case lltok::kw_fsub:
4723 return error(ID.Loc, "fsub constexprs are no longer supported");
4724 case lltok::kw_fmul:
4725 return error(ID.Loc, "fmul constexprs are no longer supported");
4726 case lltok::kw_fdiv:
4727 return error(ID.Loc, "fdiv constexprs are no longer supported");
4728 case lltok::kw_frem:
4729 return error(ID.Loc, "frem constexprs are no longer supported");
4730 case lltok::kw_and:
4731 return error(ID.Loc, "and constexprs are no longer supported");
4732 case lltok::kw_or:
4733 return error(ID.Loc, "or constexprs are no longer supported");
4734 case lltok::kw_lshr:
4735 return error(ID.Loc, "lshr constexprs are no longer supported");
4736 case lltok::kw_ashr:
4737 return error(ID.Loc, "ashr constexprs are no longer supported");
4738 case lltok::kw_shl:
4739 return error(ID.Loc, "shl constexprs are no longer supported");
4740 case lltok::kw_mul:
4741 return error(ID.Loc, "mul constexprs are no longer supported");
4742 case lltok::kw_fneg:
4743 return error(ID.Loc, "fneg constexprs are no longer supported");
4744 case lltok::kw_select:
4745 return error(ID.Loc, "select constexprs are no longer supported");
4746 case lltok::kw_zext:
4747 return error(ID.Loc, "zext constexprs are no longer supported");
4748 case lltok::kw_sext:
4749 return error(ID.Loc, "sext constexprs are no longer supported");
4750 case lltok::kw_fptrunc:
4751 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4752 case lltok::kw_fpext:
4753 return error(ID.Loc, "fpext constexprs are no longer supported");
4754 case lltok::kw_uitofp:
4755 return error(ID.Loc, "uitofp constexprs are no longer supported");
4756 case lltok::kw_sitofp:
4757 return error(ID.Loc, "sitofp constexprs are no longer supported");
4758 case lltok::kw_fptoui:
4759 return error(ID.Loc, "fptoui constexprs are no longer supported");
4760 case lltok::kw_fptosi:
4761 return error(ID.Loc, "fptosi constexprs are no longer supported");
4762 case lltok::kw_icmp:
4763 return error(ID.Loc, "icmp constexprs are no longer supported");
4764 case lltok::kw_fcmp:
4765 return error(ID.Loc, "fcmp constexprs are no longer supported");
4766
4767 // Binary Operators.
4768 case lltok::kw_add:
4769 case lltok::kw_sub:
4770 case lltok::kw_xor: {
4771 bool NUW = false;
4772 bool NSW = false;
4773 unsigned Opc = Lex.getUIntVal();
4774 Constant *Val0, *Val1;
4775 Lex.Lex();
4776 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4777 Opc == Instruction::Mul) {
4778 if (EatIfPresent(lltok::kw_nuw))
4779 NUW = true;
4780 if (EatIfPresent(lltok::kw_nsw)) {
4781 NSW = true;
4782 if (EatIfPresent(lltok::kw_nuw))
4783 NUW = true;
4784 }
4785 }
4786 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4787 parseGlobalTypeAndValue(Val0) ||
4788 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4789 parseGlobalTypeAndValue(Val1) ||
4790 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4791 return true;
4792 if (Val0->getType() != Val1->getType())
4793 return error(ID.Loc, "operands of constexpr must have same type");
4794 // Check that the type is valid for the operator.
4795 if (!Val0->getType()->isIntOrIntVectorTy())
4796 return error(ID.Loc,
4797 "constexpr requires integer or integer vector operands");
4798 unsigned Flags = 0;
4801 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4802 ID.Kind = ValID::t_Constant;
4803 return false;
4804 }
4805
4806 case lltok::kw_splat: {
4807 Lex.Lex();
4808 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4809 return true;
4810 Constant *C;
4811 if (parseGlobalTypeAndValue(C))
4812 return true;
4813 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4814 return true;
4815
4816 ID.ConstantVal = C;
4818 return false;
4819 }
4820
4825 unsigned Opc = Lex.getUIntVal();
4827 GEPNoWrapFlags NW;
4828 bool HasInRange = false;
4829 APSInt InRangeStart;
4830 APSInt InRangeEnd;
4831 Type *Ty;
4832 Lex.Lex();
4833
4834 if (Opc == Instruction::GetElementPtr) {
4835 while (true) {
4836 if (EatIfPresent(lltok::kw_inbounds))
4838 else if (EatIfPresent(lltok::kw_nusw))
4840 else if (EatIfPresent(lltok::kw_nuw))
4842 else
4843 break;
4844 }
4845
4846 if (EatIfPresent(lltok::kw_inrange)) {
4847 if (parseToken(lltok::lparen, "expected '('"))
4848 return true;
4849 if (Lex.getKind() != lltok::APSInt)
4850 return tokError("expected integer");
4851 InRangeStart = Lex.getAPSIntVal();
4852 Lex.Lex();
4853 if (parseToken(lltok::comma, "expected ','"))
4854 return true;
4855 if (Lex.getKind() != lltok::APSInt)
4856 return tokError("expected integer");
4857 InRangeEnd = Lex.getAPSIntVal();
4858 Lex.Lex();
4859 if (parseToken(lltok::rparen, "expected ')'"))
4860 return true;
4861 HasInRange = true;
4862 }
4863 }
4864
4865 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4866 return true;
4867
4868 if (Opc == Instruction::GetElementPtr) {
4869 if (parseType(Ty) ||
4870 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4871 return true;
4872 }
4873
4874 if (parseGlobalValueVector(Elts) ||
4875 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4876 return true;
4877
4878 if (Opc == Instruction::GetElementPtr) {
4879 if (Elts.size() == 0 ||
4880 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4881 return error(ID.Loc, "base of getelementptr must be a pointer");
4882
4883 Type *BaseType = Elts[0]->getType();
4884 std::optional<ConstantRange> InRange;
4885 if (HasInRange) {
4886 unsigned IndexWidth =
4887 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4888 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4889 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4890 if (InRangeStart.sge(InRangeEnd))
4891 return error(ID.Loc, "expected end to be larger than start");
4892 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4893 }
4894
4895 unsigned GEPWidth =
4896 BaseType->isVectorTy()
4897 ? cast<FixedVectorType>(BaseType)->getNumElements()
4898 : 0;
4899
4900 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4901 for (Constant *Val : Indices) {
4902 Type *ValTy = Val->getType();
4903 if (!ValTy->isIntOrIntVectorTy())
4904 return error(ID.Loc, "getelementptr index must be an integer");
4905 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4906 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4907 if (GEPWidth && (ValNumEl != GEPWidth))
4908 return error(
4909 ID.Loc,
4910 "getelementptr vector index has a wrong number of elements");
4911 // GEPWidth may have been unknown because the base is a scalar,
4912 // but it is known now.
4913 GEPWidth = ValNumEl;
4914 }
4915 }
4916
4917 if (!Indices.empty() && !Ty->isSized())
4918 return error(ID.Loc, "base element of getelementptr must be sized");
4919
4921 return error(ID.Loc, "invalid base element for constant getelementptr");
4922
4923 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4924 return error(ID.Loc, "invalid getelementptr indices");
4925
4927 ID.ConstantVal =
4928 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4930 } else if (Opc == Instruction::ShuffleVector) {
4931 if (Elts.size() != 3)
4932 return error(ID.Loc, "expected three operands to shufflevector");
4933 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4934 return error(ID.Loc, "invalid operands to shufflevector");
4935 SmallVector<int, 16> Mask;
4937 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4938 } else if (Opc == Instruction::ExtractElement) {
4939 if (Elts.size() != 2)
4940 return error(ID.Loc, "expected two operands to extractelement");
4941 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4942 return error(ID.Loc, "invalid extractelement operands");
4943 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4944 } else {
4945 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4946 if (Elts.size() != 3)
4947 return error(ID.Loc, "expected three operands to insertelement");
4948 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4949 return error(ID.Loc, "invalid insertelement operands");
4950 ID.ConstantVal =
4951 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4952 }
4953
4954 ID.Kind = ValID::t_Constant;
4955 return false;
4956 }
4957 }
4958
4959 Lex.Lex();
4960 return false;
4961}
4962
4963/// parseGlobalValue - parse a global value with the specified type.
4964bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4965 C = nullptr;
4966 ValID ID;
4967 Value *V = nullptr;
4968 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4969 convertValIDToValue(Ty, ID, V, nullptr);
4970 if (V && !(C = dyn_cast<Constant>(V)))
4971 return error(ID.Loc, "global values must be constants");
4972 return Parsed;
4973}
4974
4975bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4976 Type *Ty = nullptr;
4977 return parseType(Ty) || parseGlobalValue(Ty, V);
4978}
4979
4980bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4981 C = nullptr;
4982
4983 LocTy KwLoc = Lex.getLoc();
4984 if (!EatIfPresent(lltok::kw_comdat))
4985 return false;
4986
4987 if (EatIfPresent(lltok::lparen)) {
4988 if (Lex.getKind() != lltok::ComdatVar)
4989 return tokError("expected comdat variable");
4990 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4991 Lex.Lex();
4992 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4993 return true;
4994 } else {
4995 if (GlobalName.empty())
4996 return tokError("comdat cannot be unnamed");
4997 C = getComdat(std::string(GlobalName), KwLoc);
4998 }
4999
5000 return false;
5001}
5002
5003/// parseGlobalValueVector
5004/// ::= /*empty*/
5005/// ::= TypeAndValue (',' TypeAndValue)*
5006bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5007 // Empty list.
5008 if (Lex.getKind() == lltok::rbrace ||
5009 Lex.getKind() == lltok::rsquare ||
5010 Lex.getKind() == lltok::greater ||
5011 Lex.getKind() == lltok::rparen)
5012 return false;
5013
5014 do {
5015 // Let the caller deal with inrange.
5016 if (Lex.getKind() == lltok::kw_inrange)
5017 return false;
5018
5019 Constant *C;
5020 if (parseGlobalTypeAndValue(C))
5021 return true;
5022 Elts.push_back(C);
5023 } while (EatIfPresent(lltok::comma));
5024
5025 return false;
5026}
5027
5028bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
5030 if (parseMDNodeVector(Elts))
5031 return true;
5032
5033 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
5034 return false;
5035}
5036
5037/// MDNode:
5038/// ::= !{ ... }
5039/// ::= !7
5040/// ::= !DILocation(...)
5041bool LLParser::parseMDNode(MDNode *&N) {
5042 if (Lex.getKind() == lltok::MetadataVar)
5043 return parseSpecializedMDNode(N);
5044
5045 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
5046}
5047
5048bool LLParser::parseMDNodeTail(MDNode *&N) {
5049 // !{ ... }
5050 if (Lex.getKind() == lltok::lbrace)
5051 return parseMDTuple(N);
5052
5053 // !42
5054 return parseMDNodeID(N);
5055}
5056
5057namespace {
5058
5059/// Structure to represent an optional metadata field.
5060template <class FieldTy> struct MDFieldImpl {
5061 typedef MDFieldImpl ImplTy;
5062 FieldTy Val;
5063 bool Seen;
5064
5065 void assign(FieldTy Val) {
5066 Seen = true;
5067 this->Val = std::move(Val);
5068 }
5069
5070 explicit MDFieldImpl(FieldTy Default)
5071 : Val(std::move(Default)), Seen(false) {}
5072};
5073
5074/// Structure to represent an optional metadata field that
5075/// can be of either type (A or B) and encapsulates the
5076/// MD<typeofA>Field and MD<typeofB>Field structs, so not
5077/// to reimplement the specifics for representing each Field.
5078template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
5079 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5080 FieldTypeA A;
5081 FieldTypeB B;
5082 bool Seen;
5083
5084 enum {
5085 IsInvalid = 0,
5086 IsTypeA = 1,
5087 IsTypeB = 2
5088 } WhatIs;
5089
5090 void assign(FieldTypeA A) {
5091 Seen = true;
5092 this->A = std::move(A);
5093 WhatIs = IsTypeA;
5094 }
5095
5096 void assign(FieldTypeB B) {
5097 Seen = true;
5098 this->B = std::move(B);
5099 WhatIs = IsTypeB;
5100 }
5101
5102 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5103 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
5104 WhatIs(IsInvalid) {}
5105};
5106
5107struct MDUnsignedField : public MDFieldImpl<uint64_t> {
5108 uint64_t Max;
5109
5110 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
5111 : ImplTy(Default), Max(Max) {}
5112};
5113
5114struct LineField : public MDUnsignedField {
5115 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5116};
5117
5118struct ColumnField : public MDUnsignedField {
5119 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5120};
5121
5122struct DwarfTagField : public MDUnsignedField {
5123 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
5124 DwarfTagField(dwarf::Tag DefaultTag)
5125 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
5126};
5127
5128struct DwarfMacinfoTypeField : public MDUnsignedField {
5129 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
5130 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
5131 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
5132};
5133
5134struct DwarfAttEncodingField : public MDUnsignedField {
5135 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5136};
5137
5138struct DwarfVirtualityField : public MDUnsignedField {
5139 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5140};
5141
5142struct DwarfLangField : public MDUnsignedField {
5143 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5144};
5145
5146struct DwarfSourceLangNameField : public MDUnsignedField {
5147 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5148};
5149
5150struct DwarfLangDialectField : public MDUnsignedField {
5151 DwarfLangDialectField()
5152 : MDUnsignedField(0, dwarf::DW_LLVM_LANG_DIALECT_max) {}
5153};
5154
5155struct DwarfCCField : public MDUnsignedField {
5156 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5157};
5158
5159struct DwarfEnumKindField : public MDUnsignedField {
5160 DwarfEnumKindField()
5161 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5162 dwarf::DW_APPLE_ENUM_KIND_max) {}
5163};
5164
5165struct EmissionKindField : public MDUnsignedField {
5166 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5167};
5168
5169struct FixedPointKindField : public MDUnsignedField {
5170 FixedPointKindField()
5171 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5172};
5173
5174struct NameTableKindField : public MDUnsignedField {
5175 NameTableKindField()
5176 : MDUnsignedField(
5177 0, (unsigned)
5178 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5179};
5180
5181struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5182 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5183};
5184
5185struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5186 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5187};
5188
5189struct MDAPSIntField : public MDFieldImpl<APSInt> {
5190 MDAPSIntField() : ImplTy(APSInt()) {}
5191};
5192
5193struct MDSignedField : public MDFieldImpl<int64_t> {
5194 int64_t Min = INT64_MIN;
5195 int64_t Max = INT64_MAX;
5196
5197 MDSignedField(int64_t Default = 0)
5198 : ImplTy(Default) {}
5199 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5200 : ImplTy(Default), Min(Min), Max(Max) {}
5201};
5202
5203struct MDBoolField : public MDFieldImpl<bool> {
5204 MDBoolField(bool Default = false) : ImplTy(Default) {}
5205};
5206
5207struct MDField : public MDFieldImpl<Metadata *> {
5208 bool AllowNull;
5209
5210 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5211};
5212
5213struct MDStringField : public MDFieldImpl<MDString *> {
5214 enum class EmptyIs {
5215 Null, //< Allow empty input string, map to nullptr
5216 Empty, //< Allow empty input string, map to an empty MDString
5217 Error, //< Disallow empty string, map to an error
5218 } EmptyIs;
5219 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5220 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5221};
5222
5223struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5224 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5225};
5226
5227struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5228 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5229};
5230
5231struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5232 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5233 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5234
5235 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5236 bool AllowNull = true)
5237 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5238
5239 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5240 bool isMDField() const { return WhatIs == IsTypeB; }
5241 int64_t getMDSignedValue() const {
5242 assert(isMDSignedField() && "Wrong field type");
5243 return A.Val;
5244 }
5245 Metadata *getMDFieldValue() const {
5246 assert(isMDField() && "Wrong field type");
5247 return B.Val;
5248 }
5249};
5250
5251struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5252 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5253 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5254
5255 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5256 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5257
5258 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5259 bool isMDField() const { return WhatIs == IsTypeB; }
5260 uint64_t getMDUnsignedValue() const {
5261 assert(isMDUnsignedField() && "Wrong field type");
5262 return A.Val;
5263 }
5264 Metadata *getMDFieldValue() const {
5265 assert(isMDField() && "Wrong field type");
5266 return B.Val;
5267 }
5268
5269 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5270 if (isMDUnsignedField())
5272 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5273 if (isMDField())
5274 return getMDFieldValue();
5275 return nullptr;
5276 }
5277};
5278
5279} // end anonymous namespace
5280
5281namespace llvm {
5282
5283template <>
5284bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5285 if (Lex.getKind() != lltok::APSInt)
5286 return tokError("expected integer");
5287
5288 Result.assign(Lex.getAPSIntVal());
5289 Lex.Lex();
5290 return false;
5291}
5292
5293template <>
5294bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5295 MDUnsignedField &Result) {
5296 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5297 return tokError("expected unsigned integer");
5298
5299 auto &U = Lex.getAPSIntVal();
5300 if (U.ugt(Result.Max))
5301 return tokError("value for '" + Name + "' too large, limit is " +
5302 Twine(Result.Max));
5303 Result.assign(U.getZExtValue());
5304 assert(Result.Val <= Result.Max && "Expected value in range");
5305 Lex.Lex();
5306 return false;
5307}
5308
5309template <>
5310bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5311 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5312}
5313template <>
5314bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5315 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5316}
5317
5318template <>
5319bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5320 if (Lex.getKind() == lltok::APSInt)
5321 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5322
5323 if (Lex.getKind() != lltok::DwarfTag)
5324 return tokError("expected DWARF tag");
5325
5326 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5328 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5329 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5330
5331 Result.assign(Tag);
5332 Lex.Lex();
5333 return false;
5334}
5335
5336template <>
5337bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5338 DwarfMacinfoTypeField &Result) {
5339 if (Lex.getKind() == lltok::APSInt)
5340 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5341
5342 if (Lex.getKind() != lltok::DwarfMacinfo)
5343 return tokError("expected DWARF macinfo type");
5344
5345 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5346 if (Macinfo == dwarf::DW_MACINFO_invalid)
5347 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5348 Lex.getStrVal() + "'");
5349 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5350
5351 Result.assign(Macinfo);
5352 Lex.Lex();
5353 return false;
5354}
5355
5356template <>
5357bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5358 DwarfVirtualityField &Result) {
5359 if (Lex.getKind() == lltok::APSInt)
5360 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5361
5362 if (Lex.getKind() != lltok::DwarfVirtuality)
5363 return tokError("expected DWARF virtuality code");
5364
5365 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5366 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5367 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5368 Lex.getStrVal() + "'");
5369 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5370 Result.assign(Virtuality);
5371 Lex.Lex();
5372 return false;
5373}
5374
5375template <>
5376bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5377 DwarfEnumKindField &Result) {
5378 if (Lex.getKind() == lltok::APSInt)
5379 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5380
5381 if (Lex.getKind() != lltok::DwarfEnumKind)
5382 return tokError("expected DWARF enum kind code");
5383
5384 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5385 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5386 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5387 Lex.getStrVal() + "'");
5388 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5389 Result.assign(EnumKind);
5390 Lex.Lex();
5391 return false;
5392}
5393
5394template <>
5395bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5396 if (Lex.getKind() == lltok::APSInt)
5397 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5398
5399 if (Lex.getKind() != lltok::DwarfLang)
5400 return tokError("expected DWARF language");
5401
5402 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5403 if (!Lang)
5404 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5405 "'");
5406 assert(Lang <= Result.Max && "Expected valid DWARF language");
5407 Result.assign(Lang);
5408 Lex.Lex();
5409 return false;
5410}
5411
5412template <>
5413bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5414 DwarfSourceLangNameField &Result) {
5415 if (Lex.getKind() == lltok::APSInt)
5416 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5417
5418 if (Lex.getKind() != lltok::DwarfSourceLangName)
5419 return tokError("expected DWARF source language name");
5420
5421 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5422 if (!Lang)
5423 return tokError("invalid DWARF source language name" + Twine(" '") +
5424 Lex.getStrVal() + "'");
5425 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5426 Result.assign(Lang);
5427 Lex.Lex();
5428 return false;
5429}
5430
5431template <>
5432bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5433 DwarfLangDialectField &Result) {
5434 // Specifying the dialect field requires a recognized dialect: simt or
5435 // tile (numerically 1 or 2). Omitting the field is the only way to
5436 // express "no dialect specified".
5437 if (Lex.getKind() == lltok::APSInt) {
5438 if (Lex.getAPSIntVal() == 0)
5439 return tokError("value for 'dialect' must be a known DWARF language "
5440 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5441 "DW_LLVM_LANG_DIALECT_tile)");
5442 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5443 }
5444
5445 if (Lex.getKind() != lltok::DwarfLangDialect)
5446 return tokError("expected DWARF language dialect");
5447
5448 StringRef DialectString = Lex.getStrVal();
5449 // getLanguageDialect returns a sentinel above Result.Max for unknown
5450 // spellings; only simt and tile are registered, so any unrecognized
5451 // DW_LLVM_LANG_DIALECT_* token is rejected here.
5452 unsigned Dialect = dwarf::getLanguageDialect(DialectString);
5453 if (Dialect > Result.Max)
5454 return tokError("invalid DWARF language dialect" + Twine(" '") +
5455 DialectString + "'");
5456 Result.assign(Dialect);
5457 Lex.Lex();
5458 return false;
5459}
5460
5461template <>
5462bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5463 if (Lex.getKind() == lltok::APSInt)
5464 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5465
5466 if (Lex.getKind() != lltok::DwarfCC)
5467 return tokError("expected DWARF calling convention");
5468
5469 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5470 if (!CC)
5471 return tokError("invalid DWARF calling convention" + Twine(" '") +
5472 Lex.getStrVal() + "'");
5473 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5474 Result.assign(CC);
5475 Lex.Lex();
5476 return false;
5477}
5478
5479template <>
5480bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5481 EmissionKindField &Result) {
5482 if (Lex.getKind() == lltok::APSInt)
5483 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5484
5485 if (Lex.getKind() != lltok::EmissionKind)
5486 return tokError("expected emission kind");
5487
5488 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5489 if (!Kind)
5490 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5491 "'");
5492 assert(*Kind <= Result.Max && "Expected valid emission kind");
5493 Result.assign(*Kind);
5494 Lex.Lex();
5495 return false;
5496}
5497
5498template <>
5499bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5500 FixedPointKindField &Result) {
5501 if (Lex.getKind() == lltok::APSInt)
5502 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5503
5504 if (Lex.getKind() != lltok::FixedPointKind)
5505 return tokError("expected fixed-point kind");
5506
5507 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5508 if (!Kind)
5509 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5510 "'");
5511 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5512 Result.assign(*Kind);
5513 Lex.Lex();
5514 return false;
5515}
5516
5517template <>
5518bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5519 NameTableKindField &Result) {
5520 if (Lex.getKind() == lltok::APSInt)
5521 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5522
5523 if (Lex.getKind() != lltok::NameTableKind)
5524 return tokError("expected nameTable kind");
5525
5526 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5527 if (!Kind)
5528 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5529 "'");
5530 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5531 Result.assign((unsigned)*Kind);
5532 Lex.Lex();
5533 return false;
5534}
5535
5536template <>
5537bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5538 DwarfAttEncodingField &Result) {
5539 if (Lex.getKind() == lltok::APSInt)
5540 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5541
5542 if (Lex.getKind() != lltok::DwarfAttEncoding)
5543 return tokError("expected DWARF type attribute encoding");
5544
5545 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5546 if (!Encoding)
5547 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5548 Lex.getStrVal() + "'");
5549 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5550 Result.assign(Encoding);
5551 Lex.Lex();
5552 return false;
5553}
5554
5555/// DIFlagField
5556/// ::= uint32
5557/// ::= DIFlagVector
5558/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5559template <>
5560bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5561
5562 // parser for a single flag.
5563 auto parseFlag = [&](DINode::DIFlags &Val) {
5564 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5565 uint32_t TempVal = static_cast<uint32_t>(Val);
5566 bool Res = parseUInt32(TempVal);
5567 Val = static_cast<DINode::DIFlags>(TempVal);
5568 return Res;
5569 }
5570
5571 if (Lex.getKind() != lltok::DIFlag)
5572 return tokError("expected debug info flag");
5573
5574 Val = DINode::getFlag(Lex.getStrVal());
5575 if (!Val)
5576 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5577 "'");
5578 Lex.Lex();
5579 return false;
5580 };
5581
5582 // parse the flags and combine them together.
5583 DINode::DIFlags Combined = DINode::FlagZero;
5584 do {
5585 DINode::DIFlags Val;
5586 if (parseFlag(Val))
5587 return true;
5588 Combined |= Val;
5589 } while (EatIfPresent(lltok::bar));
5590
5591 Result.assign(Combined);
5592 return false;
5593}
5594
5595/// DISPFlagField
5596/// ::= uint32
5597/// ::= DISPFlagVector
5598/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5599template <>
5600bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5601
5602 // parser for a single flag.
5603 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5604 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5605 uint32_t TempVal = static_cast<uint32_t>(Val);
5606 bool Res = parseUInt32(TempVal);
5607 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5608 return Res;
5609 }
5610
5611 if (Lex.getKind() != lltok::DISPFlag)
5612 return tokError("expected debug info flag");
5613
5614 Val = DISubprogram::getFlag(Lex.getStrVal());
5615 if (!Val)
5616 return tokError(Twine("invalid subprogram debug info flag '") +
5617 Lex.getStrVal() + "'");
5618 Lex.Lex();
5619 return false;
5620 };
5621
5622 // parse the flags and combine them together.
5623 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5624 do {
5626 if (parseFlag(Val))
5627 return true;
5628 Combined |= Val;
5629 } while (EatIfPresent(lltok::bar));
5630
5631 Result.assign(Combined);
5632 return false;
5633}
5634
5635template <>
5636bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5637 if (Lex.getKind() != lltok::APSInt)
5638 return tokError("expected signed integer");
5639
5640 auto &S = Lex.getAPSIntVal();
5641 if (S < Result.Min)
5642 return tokError("value for '" + Name + "' too small, limit is " +
5643 Twine(Result.Min));
5644 if (S > Result.Max)
5645 return tokError("value for '" + Name + "' too large, limit is " +
5646 Twine(Result.Max));
5647 Result.assign(S.getExtValue());
5648 assert(Result.Val >= Result.Min && "Expected value in range");
5649 assert(Result.Val <= Result.Max && "Expected value in range");
5650 Lex.Lex();
5651 return false;
5652}
5653
5654template <>
5655bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5656 switch (Lex.getKind()) {
5657 default:
5658 return tokError("expected 'true' or 'false'");
5659 case lltok::kw_true:
5660 Result.assign(true);
5661 break;
5662 case lltok::kw_false:
5663 Result.assign(false);
5664 break;
5665 }
5666 Lex.Lex();
5667 return false;
5668}
5669
5670template <>
5671bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5672 if (Lex.getKind() == lltok::kw_null) {
5673 if (!Result.AllowNull)
5674 return tokError("'" + Name + "' cannot be null");
5675 Lex.Lex();
5676 Result.assign(nullptr);
5677 return false;
5678 }
5679
5680 Metadata *MD;
5681 if (parseMetadata(MD, nullptr))
5682 return true;
5683
5684 Result.assign(MD);
5685 return false;
5686}
5687
5688template <>
5689bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5690 MDSignedOrMDField &Result) {
5691 // Try to parse a signed int.
5692 if (Lex.getKind() == lltok::APSInt) {
5693 MDSignedField Res = Result.A;
5694 if (!parseMDField(Loc, Name, Res)) {
5695 Result.assign(Res);
5696 return false;
5697 }
5698 return true;
5699 }
5700
5701 // Otherwise, try to parse as an MDField.
5702 MDField Res = Result.B;
5703 if (!parseMDField(Loc, Name, Res)) {
5704 Result.assign(Res);
5705 return false;
5706 }
5707
5708 return true;
5709}
5710
5711template <>
5712bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5713 MDUnsignedOrMDField &Result) {
5714 // Try to parse an unsigned int.
5715 if (Lex.getKind() == lltok::APSInt) {
5716 MDUnsignedField Res = Result.A;
5717 if (!parseMDField(Loc, Name, Res)) {
5718 Result.assign(Res);
5719 return false;
5720 }
5721 return true;
5722 }
5723
5724 // Otherwise, try to parse as an MDField.
5725 MDField Res = Result.B;
5726 if (!parseMDField(Loc, Name, Res)) {
5727 Result.assign(Res);
5728 return false;
5729 }
5730
5731 return true;
5732}
5733
5734template <>
5735bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5736 LocTy ValueLoc = Lex.getLoc();
5737 std::string S;
5738 if (parseStringConstant(S))
5739 return true;
5740
5741 if (S.empty()) {
5742 switch (Result.EmptyIs) {
5743 case MDStringField::EmptyIs::Null:
5744 Result.assign(nullptr);
5745 return false;
5746 case MDStringField::EmptyIs::Empty:
5747 break;
5748 case MDStringField::EmptyIs::Error:
5749 return error(ValueLoc, "'" + Name + "' cannot be empty");
5750 }
5751 }
5752
5753 Result.assign(MDString::get(Context, S));
5754 return false;
5755}
5756
5757template <>
5758bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5760 if (parseMDNodeVector(MDs))
5761 return true;
5762
5763 Result.assign(std::move(MDs));
5764 return false;
5765}
5766
5767template <>
5768bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5769 ChecksumKindField &Result) {
5770 std::optional<DIFile::ChecksumKind> CSKind =
5771 DIFile::getChecksumKind(Lex.getStrVal());
5772
5773 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5774 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5775 "'");
5776
5777 Result.assign(*CSKind);
5778 Lex.Lex();
5779 return false;
5780}
5781
5782} // end namespace llvm
5783
5784template <class ParserTy>
5785bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5786 do {
5787 if (Lex.getKind() != lltok::LabelStr)
5788 return tokError("expected field label here");
5789
5790 if (ParseField())
5791 return true;
5792 } while (EatIfPresent(lltok::comma));
5793
5794 return false;
5795}
5796
5797template <class ParserTy>
5798bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5799 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5800 Lex.Lex();
5801
5802 if (parseToken(lltok::lparen, "expected '(' here"))
5803 return true;
5804 if (Lex.getKind() != lltok::rparen)
5805 if (parseMDFieldsImplBody(ParseField))
5806 return true;
5807
5808 ClosingLoc = Lex.getLoc();
5809 return parseToken(lltok::rparen, "expected ')' here");
5810}
5811
5812template <class FieldTy>
5813bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5814 if (Result.Seen)
5815 return tokError("field '" + Name + "' cannot be specified more than once");
5816
5817 LocTy Loc = Lex.getLoc();
5818 Lex.Lex();
5819 return parseMDField(Loc, Name, Result);
5820}
5821
5822bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5823 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5824
5825#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5826 if (Lex.getStrVal() == #CLASS) \
5827 return parse##CLASS(N, IsDistinct);
5828#include "llvm/IR/Metadata.def"
5829
5830 return tokError("expected metadata type");
5831}
5832
5833#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5834#define NOP_FIELD(NAME, TYPE, INIT)
5835#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5836 if (!NAME.Seen) \
5837 return error(ClosingLoc, "missing required field '" #NAME "'");
5838#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5839 if (Lex.getStrVal() == #NAME) \
5840 return parseMDField(#NAME, NAME);
5841#define PARSE_MD_FIELDS() \
5842 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5843 do { \
5844 LocTy ClosingLoc; \
5845 if (parseMDFieldsImpl( \
5846 [&]() -> bool { \
5847 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5848 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5849 "'"); \
5850 }, \
5851 ClosingLoc)) \
5852 return true; \
5853 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5854 } while (false)
5855#define GET_OR_DISTINCT(CLASS, ARGS) \
5856 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5857
5858/// parseDILocationFields:
5859/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5860/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5861bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5862#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5863 OPTIONAL(line, LineField, ); \
5864 OPTIONAL(column, ColumnField, ); \
5865 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5866 OPTIONAL(inlinedAt, MDField, ); \
5867 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5868 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5869 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
5870 OPTIONAL(irlayers, MDField, );
5872#undef VISIT_MD_FIELDS
5873
5874 Result =
5875 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5876 inlinedAt.Val, isImplicitCode.Val,
5877 atomGroup.Val, atomRank.Val, irlayers.Val));
5878 return false;
5879}
5880
5881bool LLParser::parseDILayerLoc(MDNode *&Result, bool IsDistinct) {
5882#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5883 OPTIONAL(line, LineField, ); \
5884 OPTIONAL(column, ColumnField, ); \
5885 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5886 REQUIRED(kind, MDStringField, );
5888#undef VISIT_MD_FIELDS
5889
5890 Result = GET_OR_DISTINCT(DILayerLoc,
5891 (Context, kind.Val, file.Val, line.Val, column.Val));
5892 return false;
5893}
5894
5895bool LLParser::parseDILayerLocList(MDNode *&Result, bool IsDistinct) {
5896 // ::= !DILayerLocList(!a, !b, ...)
5897 Lex.Lex(); // eat the '!DILayerLocList' type name
5898 if (parseToken(lltok::lparen, "expected '(' here"))
5899 return true;
5901 if (!EatIfPresent(lltok::rparen)) {
5902 do {
5903 Metadata *MD;
5904 if (parseMetadata(MD, nullptr))
5905 return true;
5906 Layers.push_back(MD);
5907 } while (EatIfPresent(lltok::comma));
5908 if (parseToken(lltok::rparen, "expected ')' here"))
5909 return true;
5910 }
5911 Result = GET_OR_DISTINCT(DILayerLocList, (Context, Layers));
5912 return false;
5913}
5914
5915/// parseDIAssignID:
5916/// ::= distinct !DIAssignID()
5917bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5918 if (!IsDistinct)
5919 return tokError("missing 'distinct', required for !DIAssignID()");
5920
5921 Lex.Lex();
5922
5923 // Now eat the parens.
5924 if (parseToken(lltok::lparen, "expected '(' here"))
5925 return true;
5926 if (parseToken(lltok::rparen, "expected ')' here"))
5927 return true;
5928
5930 return false;
5931}
5932
5933/// parseGenericDINode:
5934/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5935bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5937 REQUIRED(tag, DwarfTagField, ); \
5938 OPTIONAL(header, MDStringField, ); \
5939 OPTIONAL(operands, MDFieldList, );
5941#undef VISIT_MD_FIELDS
5942
5943 Result = GET_OR_DISTINCT(GenericDINode,
5944 (Context, tag.Val, header.Val, operands.Val));
5945 return false;
5946}
5947
5948/// parseDISubrangeType:
5949/// ::= !DISubrangeType(name: "whatever", file: !0,
5950/// line: 7, scope: !1, baseType: !2, size: 32,
5951/// align: 32, flags: 0, lowerBound: !3
5952/// upperBound: !4, stride: !5, bias: !6)
5953bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5954#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5955 OPTIONAL(name, MDStringField, ); \
5956 OPTIONAL(file, MDField, ); \
5957 OPTIONAL(line, LineField, ); \
5958 OPTIONAL(scope, MDField, ); \
5959 OPTIONAL(baseType, MDField, ); \
5960 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5961 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5962 OPTIONAL(flags, DIFlagField, ); \
5963 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5964 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5965 OPTIONAL(stride, MDSignedOrMDField, ); \
5966 OPTIONAL(bias, MDSignedOrMDField, );
5968#undef VISIT_MD_FIELDS
5969
5970 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5971 if (Bound.isMDSignedField())
5973 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5974 if (Bound.isMDField())
5975 return Bound.getMDFieldValue();
5976 return nullptr;
5977 };
5978
5979 Metadata *LowerBound = convToMetadata(lowerBound);
5980 Metadata *UpperBound = convToMetadata(upperBound);
5981 Metadata *Stride = convToMetadata(stride);
5982 Metadata *Bias = convToMetadata(bias);
5983
5985 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5986 size.getValueAsMetadata(Context), align.Val, flags.Val,
5987 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5988
5989 return false;
5990}
5991
5992/// parseDISubrange:
5993/// ::= !DISubrange(count: 30, lowerBound: 2)
5994/// ::= !DISubrange(count: !node, lowerBound: 2)
5995/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5996bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5997#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5998 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5999 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6000 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6001 OPTIONAL(stride, MDSignedOrMDField, );
6003#undef VISIT_MD_FIELDS
6004
6005 Metadata *Count = nullptr;
6006 Metadata *LowerBound = nullptr;
6007 Metadata *UpperBound = nullptr;
6008 Metadata *Stride = nullptr;
6009
6010 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6011 if (Bound.isMDSignedField())
6013 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
6014 if (Bound.isMDField())
6015 return Bound.getMDFieldValue();
6016 return nullptr;
6017 };
6018
6019 Count = convToMetadata(count);
6020 LowerBound = convToMetadata(lowerBound);
6021 UpperBound = convToMetadata(upperBound);
6022 Stride = convToMetadata(stride);
6023
6024 Result = GET_OR_DISTINCT(DISubrange,
6025 (Context, Count, LowerBound, UpperBound, Stride));
6026
6027 return false;
6028}
6029
6030/// parseDIGenericSubrange:
6031/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
6032/// !node3)
6033bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
6034#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6035 OPTIONAL(count, MDSignedOrMDField, ); \
6036 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6037 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6038 OPTIONAL(stride, MDSignedOrMDField, );
6040#undef VISIT_MD_FIELDS
6041
6042 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6043 if (Bound.isMDSignedField())
6044 return DIExpression::get(
6045 Context, {dwarf::DW_OP_consts,
6046 static_cast<uint64_t>(Bound.getMDSignedValue())});
6047 if (Bound.isMDField())
6048 return Bound.getMDFieldValue();
6049 return nullptr;
6050 };
6051
6052 Metadata *Count = ConvToMetadata(count);
6053 Metadata *LowerBound = ConvToMetadata(lowerBound);
6054 Metadata *UpperBound = ConvToMetadata(upperBound);
6055 Metadata *Stride = ConvToMetadata(stride);
6056
6057 Result = GET_OR_DISTINCT(DIGenericSubrange,
6058 (Context, Count, LowerBound, UpperBound, Stride));
6059
6060 return false;
6061}
6062
6063/// parseDIEnumerator:
6064/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
6065bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
6066#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6067 REQUIRED(name, MDStringField, ); \
6068 REQUIRED(value, MDAPSIntField, ); \
6069 OPTIONAL(isUnsigned, MDBoolField, (false));
6071#undef VISIT_MD_FIELDS
6072
6073 if (isUnsigned.Val && value.Val.isNegative())
6074 return tokError("unsigned enumerator with negative value");
6075
6076 APSInt Value(value.Val);
6077 // Add a leading zero so that unsigned values with the msb set are not
6078 // mistaken for negative values when used for signed enumerators.
6079 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6080 Value = Value.zext(Value.getBitWidth() + 1);
6081
6082 Result =
6083 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
6084
6085 return false;
6086}
6087
6088/// parseDIBasicType:
6089/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
6090/// encoding: DW_ATE_encoding, flags: 0)
6091bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
6092#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6093 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6094 OPTIONAL(name, MDStringField, ); \
6095 OPTIONAL(file, MDField, ); \
6096 OPTIONAL(line, LineField, ); \
6097 OPTIONAL(scope, MDField, ); \
6098 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6099 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6100 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6101 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6102 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6103 OPTIONAL(flags, DIFlagField, );
6105#undef VISIT_MD_FIELDS
6106
6108 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6109 size.getValueAsMetadata(Context), align.Val, encoding.Val,
6110 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6111 return false;
6112}
6113
6114/// parseDIFixedPointType:
6115/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
6116/// align: 32, encoding: DW_ATE_signed_fixed,
6117/// flags: 0, kind: Rational, factor: 3, numerator: 1,
6118/// denominator: 8)
6119bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
6120#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6121 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6122 OPTIONAL(name, MDStringField, ); \
6123 OPTIONAL(file, MDField, ); \
6124 OPTIONAL(line, LineField, ); \
6125 OPTIONAL(scope, MDField, ); \
6126 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6127 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6128 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6129 OPTIONAL(flags, DIFlagField, ); \
6130 OPTIONAL(kind, FixedPointKindField, ); \
6131 OPTIONAL(factor, MDSignedField, ); \
6132 OPTIONAL(numerator, MDAPSIntField, ); \
6133 OPTIONAL(denominator, MDAPSIntField, );
6135#undef VISIT_MD_FIELDS
6136
6137 Result = GET_OR_DISTINCT(DIFixedPointType,
6138 (Context, tag.Val, name.Val, file.Val, line.Val,
6139 scope.Val, size.getValueAsMetadata(Context),
6140 align.Val, encoding.Val, flags.Val, kind.Val,
6141 factor.Val, numerator.Val, denominator.Val));
6142 return false;
6143}
6144
6145/// parseDIStringType:
6146/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
6147bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
6148#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6149 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6150 OPTIONAL(name, MDStringField, ); \
6151 OPTIONAL(stringLength, MDField, ); \
6152 OPTIONAL(stringLengthExpression, MDField, ); \
6153 OPTIONAL(stringLocationExpression, MDField, ); \
6154 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6155 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6156 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6157 OPTIONAL(charType, MDField, );
6159#undef VISIT_MD_FIELDS
6160
6162 DIStringType,
6163 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
6164 stringLocationExpression.Val, size.getValueAsMetadata(Context),
6165 align.Val, encoding.Val, charType.Val));
6166 return false;
6167}
6168
6169/// parseDIDerivedType:
6170/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
6171/// line: 7, scope: !1, baseType: !2, size: 32,
6172/// align: 32, offset: 0, flags: 0, extraData: !3,
6173/// dwarfAddressSpace: 3, ptrAuthKey: 1,
6174/// ptrAuthIsAddressDiscriminated: true,
6175/// ptrAuthExtraDiscriminator: 0x1234,
6176/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
6177/// )
6178bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
6179#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6180 REQUIRED(tag, DwarfTagField, ); \
6181 OPTIONAL(name, MDStringField, ); \
6182 OPTIONAL(file, MDField, ); \
6183 OPTIONAL(line, LineField, ); \
6184 OPTIONAL(scope, MDField, ); \
6185 REQUIRED(baseType, MDField, ); \
6186 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6187 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6188 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6189 OPTIONAL(flags, DIFlagField, ); \
6190 OPTIONAL(extraData, MDField, ); \
6191 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6192 OPTIONAL(annotations, MDField, ); \
6193 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6194 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6195 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6196 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6197 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6199#undef VISIT_MD_FIELDS
6200
6201 std::optional<unsigned> DWARFAddressSpace;
6202 if (dwarfAddressSpace.Val != UINT32_MAX)
6203 DWARFAddressSpace = dwarfAddressSpace.Val;
6204 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6205 if (ptrAuthKey.Val)
6206 PtrAuthData.emplace(
6207 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6208 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6209 ptrAuthAuthenticatesNullValues.Val);
6210
6212 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6213 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6214 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6215 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6216 return false;
6217}
6218
6219bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6220#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6221 REQUIRED(tag, DwarfTagField, ); \
6222 OPTIONAL(name, MDStringField, ); \
6223 OPTIONAL(file, MDField, ); \
6224 OPTIONAL(line, LineField, ); \
6225 OPTIONAL(scope, MDField, ); \
6226 OPTIONAL(baseType, MDField, ); \
6227 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6228 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6229 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6230 OPTIONAL(flags, DIFlagField, ); \
6231 OPTIONAL(elements, MDField, ); \
6232 OPTIONAL(runtimeLang, DwarfLangField, ); \
6233 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6234 OPTIONAL(vtableHolder, MDField, ); \
6235 OPTIONAL(templateParams, MDField, ); \
6236 OPTIONAL(identifier, MDStringField, ); \
6237 OPTIONAL(discriminator, MDField, ); \
6238 OPTIONAL(dataLocation, MDField, ); \
6239 OPTIONAL(associated, MDField, ); \
6240 OPTIONAL(allocated, MDField, ); \
6241 OPTIONAL(rank, MDSignedOrMDField, ); \
6242 OPTIONAL(annotations, MDField, ); \
6243 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6244 OPTIONAL(specification, MDField, ); \
6245 OPTIONAL(bitStride, MDField, );
6247#undef VISIT_MD_FIELDS
6248
6249 Metadata *Rank = nullptr;
6250 if (rank.isMDSignedField())
6252 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6253 else if (rank.isMDField())
6254 Rank = rank.getMDFieldValue();
6255
6256 std::optional<unsigned> EnumKind;
6257 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6258 EnumKind = enumKind.Val;
6259
6260 // If this has an identifier try to build an ODR type.
6261 if (identifier.Val)
6262 if (auto *CT = DICompositeType::buildODRType(
6263 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6264 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6265 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6266 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6267 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6268 dataLocation.Val, associated.Val, allocated.Val, Rank,
6269 annotations.Val, bitStride.Val)) {
6270 Result = CT;
6271 return false;
6272 }
6273
6274 // Create a new node, and save it in the context if it belongs in the type
6275 // map.
6277 DICompositeType,
6278 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6279 size.getValueAsMetadata(Context), align.Val,
6280 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6281 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6282 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6283 allocated.Val, Rank, annotations.Val, specification.Val,
6284 num_extra_inhabitants.Val, bitStride.Val));
6285 return false;
6286}
6287
6288bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6289#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6290 OPTIONAL(flags, DIFlagField, ); \
6291 OPTIONAL(cc, DwarfCCField, ); \
6292 REQUIRED(types, MDField, );
6294#undef VISIT_MD_FIELDS
6295
6296 Result = GET_OR_DISTINCT(DISubroutineType,
6297 (Context, flags.Val, cc.Val, types.Val));
6298 return false;
6299}
6300
6301/// parseDIFileType:
6302/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6303/// checksumkind: CSK_MD5,
6304/// checksum: "000102030405060708090a0b0c0d0e0f",
6305/// source: "source file contents")
6306bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6307 // The default constructed value for checksumkind is required, but will never
6308 // be used, as the parser checks if the field was actually Seen before using
6309 // the Val.
6310#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6311 REQUIRED(filename, MDStringField, ); \
6312 REQUIRED(directory, MDStringField, ); \
6313 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6314 OPTIONAL(checksum, MDStringField, ); \
6315 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6317#undef VISIT_MD_FIELDS
6318
6319 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6320 if (checksumkind.Seen && checksum.Seen)
6321 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6322 else if (checksumkind.Seen || checksum.Seen)
6323 return tokError("'checksumkind' and 'checksum' must be provided together");
6324
6325 MDString *Source = nullptr;
6326 if (source.Seen)
6327 Source = source.Val;
6329 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6330 return false;
6331}
6332
6333/// parseDICompileUnit:
6334/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6335/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6336/// splitDebugFilename: "abc.debug",
6337/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6338/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6339/// sysroot: "/", sdk: "MacOSX.sdk",
6340/// dialect: DW_LLVM_LANG_DIALECT_simt)
6341bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6342 if (!IsDistinct)
6343 return tokError("missing 'distinct', required for !DICompileUnit");
6344
6345 LocTy Loc = Lex.getLoc();
6346
6347#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6348 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6349 OPTIONAL(language, DwarfLangField, ); \
6350 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6351 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6352 OPTIONAL(producer, MDStringField, ); \
6353 OPTIONAL(isOptimized, MDBoolField, ); \
6354 OPTIONAL(flags, MDStringField, ); \
6355 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6356 OPTIONAL(splitDebugFilename, MDStringField, ); \
6357 OPTIONAL(emissionKind, EmissionKindField, ); \
6358 OPTIONAL(enums, MDField, ); \
6359 OPTIONAL(retainedTypes, MDField, ); \
6360 OPTIONAL(globals, MDField, ); \
6361 OPTIONAL(imports, MDField, ); \
6362 OPTIONAL(macros, MDField, ); \
6363 OPTIONAL(dwoId, MDUnsignedField, ); \
6364 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6365 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6366 OPTIONAL(nameTableKind, NameTableKindField, ); \
6367 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6368 OPTIONAL(sysroot, MDStringField, ); \
6369 OPTIONAL(sdk, MDStringField, ); \
6370 OPTIONAL(dialect, DwarfLangDialectField, );
6372#undef VISIT_MD_FIELDS
6373
6374 if (!language.Seen && !sourceLanguageName.Seen)
6375 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6376 "required for !DICompileUnit");
6377
6378 if (language.Seen && sourceLanguageName.Seen)
6379 return error(Loc, "can only specify one of 'language' and "
6380 "'sourceLanguageName' on !DICompileUnit");
6381
6382 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6383 return error(Loc, "'sourceLanguageVersion' requires an associated "
6384 "'sourceLanguageName' on !DICompileUnit");
6385
6386 uint16_t Dialect = static_cast<uint16_t>(dialect.Val);
6387 DISourceLanguageName SourceLanguage =
6388 language.Seen
6389 ? DISourceLanguageName(static_cast<uint16_t>(language.Val), Dialect)
6390 : DISourceLanguageName(
6391 static_cast<uint16_t>(sourceLanguageName.Val),
6392 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6393
6395 Context, SourceLanguage, file.Val, producer.Val, isOptimized.Val,
6396 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6397 enums.Val, retainedTypes.Val, globals.Val, imports.Val, macros.Val,
6398 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6399 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6400 return false;
6401}
6402
6403/// parseDISubprogram:
6404/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6405/// file: !1, line: 7, type: !2, isLocal: false,
6406/// isDefinition: true, scopeLine: 8, containingType: !3,
6407/// virtuality: DW_VIRTUALTIY_pure_virtual,
6408/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6409/// spFlags: 10, isOptimized: false, templateParams: !4,
6410/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6411/// annotations: !8)
6412bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6413 auto Loc = Lex.getLoc();
6414#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6415 OPTIONAL(scope, MDField, ); \
6416 OPTIONAL(name, MDStringField, ); \
6417 OPTIONAL(linkageName, MDStringField, ); \
6418 OPTIONAL(file, MDField, ); \
6419 OPTIONAL(line, LineField, ); \
6420 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6421 OPTIONAL(isLocal, MDBoolField, ); \
6422 OPTIONAL(isDefinition, MDBoolField, (true)); \
6423 OPTIONAL(scopeLine, LineField, ); \
6424 OPTIONAL(containingType, MDField, ); \
6425 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6426 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6427 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6428 OPTIONAL(flags, DIFlagField, ); \
6429 OPTIONAL(spFlags, DISPFlagField, ); \
6430 OPTIONAL(isOptimized, MDBoolField, ); \
6431 OPTIONAL(unit, MDField, ); \
6432 OPTIONAL(templateParams, MDField, ); \
6433 OPTIONAL(declaration, MDField, ); \
6434 OPTIONAL(retainedNodes, MDField, ); \
6435 OPTIONAL(thrownTypes, MDField, ); \
6436 OPTIONAL(annotations, MDField, ); \
6437 OPTIONAL(targetFuncName, MDStringField, ); \
6438 OPTIONAL(keyInstructions, MDBoolField, );
6440#undef VISIT_MD_FIELDS
6441
6442 // An explicit spFlags field takes precedence over individual fields in
6443 // older IR versions.
6444 DISubprogram::DISPFlags SPFlags =
6445 spFlags.Seen ? spFlags.Val
6446 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6447 isOptimized.Val, virtuality.Val);
6448 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6449 return error(
6450 Loc,
6451 "missing 'distinct', required for !DISubprogram that is a Definition");
6453 DISubprogram,
6454 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6455 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6456 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6457 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6458 targetFuncName.Val, keyInstructions.Val));
6459
6460 if (IsDistinct)
6461 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6462
6463 return false;
6464}
6465
6466/// parseDILexicalBlock:
6467/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6468bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6469#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6470 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6471 OPTIONAL(file, MDField, ); \
6472 OPTIONAL(line, LineField, ); \
6473 OPTIONAL(column, ColumnField, );
6475#undef VISIT_MD_FIELDS
6476
6478 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6479 return false;
6480}
6481
6482/// parseDILexicalBlockFile:
6483/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6484bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6485#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6486 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6487 OPTIONAL(file, MDField, ); \
6488 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6490#undef VISIT_MD_FIELDS
6491
6492 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6493 (Context, scope.Val, file.Val, discriminator.Val));
6494 return false;
6495}
6496
6497/// parseDICommonBlock:
6498/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6499bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6500#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6501 REQUIRED(scope, MDField, ); \
6502 OPTIONAL(declaration, MDField, ); \
6503 OPTIONAL(name, MDStringField, ); \
6504 OPTIONAL(file, MDField, ); \
6505 OPTIONAL(line, LineField, );
6507#undef VISIT_MD_FIELDS
6508
6509 Result = GET_OR_DISTINCT(DICommonBlock,
6510 (Context, scope.Val, declaration.Val, name.Val,
6511 file.Val, line.Val));
6512 return false;
6513}
6514
6515/// parseDINamespace:
6516/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6517bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6518#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6519 REQUIRED(scope, MDField, ); \
6520 OPTIONAL(name, MDStringField, ); \
6521 OPTIONAL(exportSymbols, MDBoolField, );
6523#undef VISIT_MD_FIELDS
6524
6525 Result = GET_OR_DISTINCT(DINamespace,
6526 (Context, scope.Val, name.Val, exportSymbols.Val));
6527 return false;
6528}
6529
6530/// parseDIMacro:
6531/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6532/// "SomeValue")
6533bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6534#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6535 REQUIRED(type, DwarfMacinfoTypeField, ); \
6536 OPTIONAL(line, LineField, ); \
6537 REQUIRED(name, MDStringField, ); \
6538 OPTIONAL(value, MDStringField, );
6540#undef VISIT_MD_FIELDS
6541
6542 Result = GET_OR_DISTINCT(DIMacro,
6543 (Context, type.Val, line.Val, name.Val, value.Val));
6544 return false;
6545}
6546
6547/// parseDIMacroFile:
6548/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6549bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6550#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6551 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6552 OPTIONAL(line, LineField, ); \
6553 REQUIRED(file, MDField, ); \
6554 OPTIONAL(nodes, MDField, );
6556#undef VISIT_MD_FIELDS
6557
6558 Result = GET_OR_DISTINCT(DIMacroFile,
6559 (Context, type.Val, line.Val, file.Val, nodes.Val));
6560 return false;
6561}
6562
6563/// parseDIModule:
6564/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6565/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6566/// file: !1, line: 4, isDecl: false)
6567bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6568#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6569 REQUIRED(scope, MDField, ); \
6570 REQUIRED(name, MDStringField, ); \
6571 OPTIONAL(configMacros, MDStringField, ); \
6572 OPTIONAL(includePath, MDStringField, ); \
6573 OPTIONAL(apinotes, MDStringField, ); \
6574 OPTIONAL(file, MDField, ); \
6575 OPTIONAL(line, LineField, ); \
6576 OPTIONAL(isDecl, MDBoolField, );
6578#undef VISIT_MD_FIELDS
6579
6580 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6581 configMacros.Val, includePath.Val,
6582 apinotes.Val, line.Val, isDecl.Val));
6583 return false;
6584}
6585
6586/// parseDITemplateTypeParameter:
6587/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6588bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6589#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6590 OPTIONAL(name, MDStringField, ); \
6591 REQUIRED(type, MDField, ); \
6592 OPTIONAL(defaulted, MDBoolField, );
6594#undef VISIT_MD_FIELDS
6595
6596 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6597 (Context, name.Val, type.Val, defaulted.Val));
6598 return false;
6599}
6600
6601/// parseDITemplateValueParameter:
6602/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6603/// name: "V", type: !1, defaulted: false,
6604/// value: i32 7)
6605bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6606#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6607 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6608 OPTIONAL(name, MDStringField, ); \
6609 OPTIONAL(type, MDField, ); \
6610 OPTIONAL(defaulted, MDBoolField, ); \
6611 REQUIRED(value, MDField, );
6612
6614#undef VISIT_MD_FIELDS
6615
6617 DITemplateValueParameter,
6618 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6619 return false;
6620}
6621
6622/// parseDIGlobalVariable:
6623/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6624/// file: !1, line: 7, type: !2, isLocal: false,
6625/// isDefinition: true, templateParams: !3,
6626/// declaration: !4, align: 8)
6627bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6628#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6629 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6630 OPTIONAL(scope, MDField, ); \
6631 OPTIONAL(linkageName, MDStringField, ); \
6632 OPTIONAL(file, MDField, ); \
6633 OPTIONAL(line, LineField, ); \
6634 OPTIONAL(type, MDField, ); \
6635 OPTIONAL(isLocal, MDBoolField, ); \
6636 OPTIONAL(isDefinition, MDBoolField, (true)); \
6637 OPTIONAL(templateParams, MDField, ); \
6638 OPTIONAL(declaration, MDField, ); \
6639 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6640 OPTIONAL(annotations, MDField, );
6642#undef VISIT_MD_FIELDS
6643
6644 Result =
6645 GET_OR_DISTINCT(DIGlobalVariable,
6646 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6647 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6648 declaration.Val, templateParams.Val, align.Val,
6649 annotations.Val));
6650 return false;
6651}
6652
6653/// parseDILocalVariable:
6654/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6655/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6656/// align: 8)
6657/// ::= !DILocalVariable(scope: !0, name: "foo",
6658/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6659/// align: 8)
6660bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6661#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6662 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6663 OPTIONAL(name, MDStringField, ); \
6664 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6665 OPTIONAL(file, MDField, ); \
6666 OPTIONAL(line, LineField, ); \
6667 OPTIONAL(type, MDField, ); \
6668 OPTIONAL(flags, DIFlagField, ); \
6669 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6670 OPTIONAL(annotations, MDField, );
6672#undef VISIT_MD_FIELDS
6673
6674 Result = GET_OR_DISTINCT(DILocalVariable,
6675 (Context, scope.Val, name.Val, file.Val, line.Val,
6676 type.Val, arg.Val, flags.Val, align.Val,
6677 annotations.Val));
6678 return false;
6679}
6680
6681/// parseDILabel:
6682/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6683bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6684#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6685 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6686 REQUIRED(name, MDStringField, ); \
6687 REQUIRED(file, MDField, ); \
6688 REQUIRED(line, LineField, ); \
6689 OPTIONAL(column, ColumnField, ); \
6690 OPTIONAL(isArtificial, MDBoolField, ); \
6691 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6693#undef VISIT_MD_FIELDS
6694
6695 std::optional<unsigned> CoroSuspendIdx =
6696 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6697 : std::nullopt;
6698
6699 Result = GET_OR_DISTINCT(DILabel,
6700 (Context, scope.Val, name.Val, file.Val, line.Val,
6701 column.Val, isArtificial.Val, CoroSuspendIdx));
6702 return false;
6703}
6704
6705/// parseDIExpressionBody:
6706/// ::= (0, 7, -1)
6707bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6708 if (parseToken(lltok::lparen, "expected '(' here"))
6709 return true;
6710
6711 SmallVector<uint64_t, 8> Elements;
6712 if (Lex.getKind() != lltok::rparen)
6713 do {
6714 if (Lex.getKind() == lltok::DwarfOp) {
6715 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6716 Lex.Lex();
6717 Elements.push_back(Op);
6718 continue;
6719 }
6720 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6721 }
6722
6723 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6724 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6725 Lex.Lex();
6726 Elements.push_back(Op);
6727 continue;
6728 }
6729 return tokError(Twine("invalid DWARF attribute encoding '") +
6730 Lex.getStrVal() + "'");
6731 }
6732
6733 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6734 return tokError("expected unsigned integer");
6735
6736 auto &U = Lex.getAPSIntVal();
6737 if (U.ugt(UINT64_MAX))
6738 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6739 Elements.push_back(U.getZExtValue());
6740 Lex.Lex();
6741 } while (EatIfPresent(lltok::comma));
6742
6743 if (parseToken(lltok::rparen, "expected ')' here"))
6744 return true;
6745
6746 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6747 return false;
6748}
6749
6750/// parseDIExpression:
6751/// ::= !DIExpression(0, 7, -1)
6752bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6753 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6754 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6755 Lex.Lex();
6756
6757 return parseDIExpressionBody(Result, IsDistinct);
6758}
6759
6760/// ParseDIArgList:
6761/// ::= !DIArgList(i32 7, i64 %0)
6762bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6763 assert(PFS && "Expected valid function state");
6764 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6765 Lex.Lex();
6766
6767 if (parseToken(lltok::lparen, "expected '(' here"))
6768 return true;
6769
6771 if (Lex.getKind() != lltok::rparen)
6772 do {
6773 Metadata *MD;
6774 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6775 return true;
6776 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6777 } while (EatIfPresent(lltok::comma));
6778
6779 if (parseToken(lltok::rparen, "expected ')' here"))
6780 return true;
6781
6782 MD = DIArgList::get(Context, Args);
6783 return false;
6784}
6785
6786/// parseDIGlobalVariableExpression:
6787/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6788bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6789 bool IsDistinct) {
6790#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6791 REQUIRED(var, MDField, ); \
6792 REQUIRED(expr, MDField, );
6794#undef VISIT_MD_FIELDS
6795
6796 Result =
6797 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6798 return false;
6799}
6800
6801/// parseDIObjCProperty:
6802/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6803/// getter: "getFoo", attributes: 7, type: !2)
6804bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6805#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6806 OPTIONAL(name, MDStringField, ); \
6807 OPTIONAL(file, MDField, ); \
6808 OPTIONAL(line, LineField, ); \
6809 OPTIONAL(setter, MDStringField, ); \
6810 OPTIONAL(getter, MDStringField, ); \
6811 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6812 OPTIONAL(type, MDField, );
6814#undef VISIT_MD_FIELDS
6815
6816 Result = GET_OR_DISTINCT(DIObjCProperty,
6817 (Context, name.Val, file.Val, line.Val, getter.Val,
6818 setter.Val, attributes.Val, type.Val));
6819 return false;
6820}
6821
6822/// parseDIProperty:
6823/// ::= !DIProperty(name: "x", file: !1, line: 7, type: !2,
6824/// backing_storage: !3)
6825bool LLParser::parseDIProperty(MDNode *&Result, bool IsDistinct) {
6826#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6827 OPTIONAL(name, MDStringField, ); \
6828 OPTIONAL(file, MDField, ); \
6829 OPTIONAL(line, LineField, ); \
6830 OPTIONAL(type, MDField, ); \
6831 OPTIONAL(backing_storage, MDField, );
6833#undef VISIT_MD_FIELDS
6834
6835 Result = GET_OR_DISTINCT(DIProperty, (Context, name.Val, file.Val, line.Val,
6836 type.Val, backing_storage.Val));
6837 return false;
6838}
6839
6840/// parseDIImportedEntity:
6841/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6842/// line: 7, name: "foo", elements: !2)
6843bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6844#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6845 REQUIRED(tag, DwarfTagField, ); \
6846 REQUIRED(scope, MDField, ); \
6847 OPTIONAL(entity, MDField, ); \
6848 OPTIONAL(file, MDField, ); \
6849 OPTIONAL(line, LineField, ); \
6850 OPTIONAL(name, MDStringField, ); \
6851 OPTIONAL(elements, MDField, );
6853#undef VISIT_MD_FIELDS
6854
6855 Result = GET_OR_DISTINCT(DIImportedEntity,
6856 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6857 line.Val, name.Val, elements.Val));
6858 return false;
6859}
6860
6861#undef PARSE_MD_FIELD
6862#undef NOP_FIELD
6863#undef REQUIRE_FIELD
6864#undef DECLARE_FIELD
6865
6866/// parseMetadataAsValue
6867/// ::= metadata i32 %local
6868/// ::= metadata i32 @global
6869/// ::= metadata i32 7
6870/// ::= metadata !0
6871/// ::= metadata !{...}
6872/// ::= metadata !"string"
6873bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6874 // Note: the type 'metadata' has already been parsed.
6875 Metadata *MD;
6876 if (parseMetadata(MD, &PFS))
6877 return true;
6878
6879 V = MetadataAsValue::get(Context, MD);
6880 return false;
6881}
6882
6883/// parseValueAsMetadata
6884/// ::= i32 %local
6885/// ::= i32 @global
6886/// ::= i32 7
6887bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6888 PerFunctionState *PFS) {
6889 Type *Ty;
6890 LocTy Loc;
6891 if (parseType(Ty, TypeMsg, Loc))
6892 return true;
6893 if (Ty->isMetadataTy())
6894 return error(Loc, "invalid metadata-value-metadata roundtrip");
6895
6896 Value *V;
6897 if (parseValue(Ty, V, PFS))
6898 return true;
6899
6900 MD = ValueAsMetadata::get(V);
6901 return false;
6902}
6903
6904/// parseMetadata
6905/// ::= i32 %local
6906/// ::= i32 @global
6907/// ::= i32 7
6908/// ::= !42
6909/// ::= !{...}
6910/// ::= !"string"
6911/// ::= !DILocation(...)
6912bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6913 if (Lex.getKind() == lltok::MetadataVar) {
6914 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6915 // so parsing this requires a Function State.
6916 if (Lex.getStrVal() == "DIArgList") {
6917 Metadata *AL;
6918 if (parseDIArgList(AL, PFS))
6919 return true;
6920 MD = AL;
6921 return false;
6922 }
6923 MDNode *N;
6924 if (parseSpecializedMDNode(N)) {
6925 return true;
6926 }
6927 MD = N;
6928 return false;
6929 }
6930
6931 // ValueAsMetadata:
6932 // <type> <value>
6933 if (Lex.getKind() != lltok::exclaim)
6934 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6935
6936 // '!'.
6937 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6938 Lex.Lex();
6939
6940 // MDString:
6941 // ::= '!' STRINGCONSTANT
6942 if (Lex.getKind() == lltok::StringConstant) {
6943 MDString *S;
6944 if (parseMDString(S))
6945 return true;
6946 MD = S;
6947 return false;
6948 }
6949
6950 // MDNode:
6951 // !{ ... }
6952 // !7
6953 MDNode *N;
6954 if (parseMDNodeTail(N))
6955 return true;
6956 MD = N;
6957 return false;
6958}
6959
6960//===----------------------------------------------------------------------===//
6961// Function Parsing.
6962//===----------------------------------------------------------------------===//
6963
6964bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6965 PerFunctionState *PFS) {
6966 if (Ty->isFunctionTy())
6967 return error(ID.Loc, "functions are not values, refer to them as pointers");
6968
6969 switch (ID.Kind) {
6970 case ValID::t_LocalID:
6971 if (!PFS)
6972 return error(ID.Loc, "invalid use of function-local name");
6973 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6974 return V == nullptr;
6975 case ValID::t_LocalName:
6976 if (!PFS)
6977 return error(ID.Loc, "invalid use of function-local name");
6978 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6979 return V == nullptr;
6980 case ValID::t_InlineAsm: {
6981 if (!ID.FTy)
6982 return error(ID.Loc, "invalid type for inline asm constraint string");
6983 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6984 return error(ID.Loc, toString(std::move(Err)));
6985 V = InlineAsm::get(
6986 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6987 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6988 return false;
6989 }
6991 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6992 if (V && ID.NoCFI)
6994 return V == nullptr;
6995 case ValID::t_GlobalID:
6996 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6997 if (V && ID.NoCFI)
6999 return V == nullptr;
7000 case ValID::t_APSInt:
7001 if (!Ty->isIntegerTy() && !Ty->isByteTy())
7002 return error(ID.Loc, "integer/byte constant must have integer/byte type");
7003 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
7004 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
7005 : V = ConstantByte::get(Context, ID.APSIntVal);
7006 return false;
7007 case ValID::t_APFloat:
7008 if (!Ty->isFloatingPointTy() ||
7009 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
7010 return error(ID.Loc, "floating point constant invalid for type");
7011
7012 // The lexer has no type info, so builds all half, bfloat, float, and double
7013 // FP constants as double. Fix this here. Long double does not need this.
7014 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
7015 // Check for signaling before potentially converting and losing that info.
7016 bool IsSNAN = ID.APFloatVal.isSignaling();
7017 bool Ignored;
7018 if (Ty->isHalfTy())
7019 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7020 &Ignored);
7021 else if (Ty->isBFloatTy())
7022 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7023 &Ignored);
7024 else if (Ty->isFloatTy())
7025 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7026 &Ignored);
7027 if (IsSNAN) {
7028 // The convert call above may quiet an SNaN, so manufacture another
7029 // SNaN. The bitcast works because the payload (significand) parameter
7030 // is truncated to fit.
7031 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7032 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7033 ID.APFloatVal.isNegative(), &Payload);
7034 }
7035 }
7036 V = ConstantFP::get(Context, ID.APFloatVal);
7037
7038 if (V->getType() != Ty)
7039 return error(ID.Loc, "floating point constant does not have type '" +
7040 getTypeString(Ty) + "'");
7041
7042 return false;
7043 case ValID::t_Null:
7044 if (!Ty->isPointerTy())
7045 return error(ID.Loc, "null must be a pointer type");
7047 return false;
7048 case ValID::t_Undef:
7049 // FIXME: LabelTy should not be a first-class type.
7050 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7051 return error(ID.Loc, "invalid type for undef constant");
7052 V = UndefValue::get(Ty);
7053 return false;
7055 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
7056 return error(ID.Loc, "invalid empty array initializer");
7057 V = PoisonValue::get(Ty);
7058 return false;
7059 case ValID::t_Zero:
7060 // FIXME: LabelTy should not be a first-class type.
7061 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7062 return error(ID.Loc, "invalid type for null constant");
7063 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
7064 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
7065 return error(ID.Loc, "invalid type for null constant");
7067 return false;
7068 case ValID::t_None:
7069 if (!Ty->isTokenTy())
7070 return error(ID.Loc, "invalid type for none constant");
7072 return false;
7073 case ValID::t_Poison:
7074 // FIXME: LabelTy should not be a first-class type.
7075 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7076 return error(ID.Loc, "invalid type for poison constant");
7077 V = PoisonValue::get(Ty);
7078 return false;
7079 case ValID::t_Constant:
7080 if (ID.ConstantVal->getType() != Ty)
7081 return error(ID.Loc, "constant expression type mismatch: got type '" +
7082 getTypeString(ID.ConstantVal->getType()) +
7083 "' but expected '" + getTypeString(Ty) + "'");
7084 V = ID.ConstantVal;
7085 return false;
7087 if (!Ty->isVectorTy())
7088 return error(ID.Loc, "vector constant must have vector type");
7089 if (ID.ConstantVal->getType() != Ty->getScalarType())
7090 return error(ID.Loc, "constant expression type mismatch: got type '" +
7091 getTypeString(ID.ConstantVal->getType()) +
7092 "' but expected '" +
7093 getTypeString(Ty->getScalarType()) + "'");
7094 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
7095 ID.ConstantVal);
7096 return false;
7099 if (StructType *ST = dyn_cast<StructType>(Ty)) {
7100 if (ST->getNumElements() != ID.UIntVal)
7101 return error(ID.Loc,
7102 "initializer with struct type has wrong # elements");
7103 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
7104 return error(ID.Loc, "packed'ness of initializer and type don't match");
7105
7106 // Verify that the elements are compatible with the structtype.
7107 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
7108 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
7109 return error(
7110 ID.Loc,
7111 "element " + Twine(i) +
7112 " of struct initializer doesn't match struct element type");
7113
7115 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
7116 } else
7117 return error(ID.Loc, "constant expression type mismatch");
7118 return false;
7119 }
7120 llvm_unreachable("Invalid ValID");
7121}
7122
7123bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
7124 C = nullptr;
7125 ValID ID;
7126 auto Loc = Lex.getLoc();
7127 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
7128 return true;
7129 switch (ID.Kind) {
7130 case ValID::t_APSInt:
7131 case ValID::t_APFloat:
7132 case ValID::t_Undef:
7133 case ValID::t_Poison:
7134 case ValID::t_Zero:
7135 case ValID::t_Constant:
7139 Value *V;
7140 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
7141 return true;
7142 assert(isa<Constant>(V) && "Expected a constant value");
7143 C = cast<Constant>(V);
7144 return false;
7145 }
7146 case ValID::t_Null:
7148 return false;
7149 default:
7150 return error(Loc, "expected a constant value");
7151 }
7152}
7153
7154bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
7155 V = nullptr;
7156 ValID ID;
7157
7158 FileLoc Start = getTokLineColumnPos();
7159 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7160 if (!Ret && ParserContext) {
7161 FileLoc End = getPrevTokEndLineColumnPos();
7162 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7163 }
7164 return Ret;
7165}
7166
7167bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
7168 Type *Ty = nullptr;
7169 return parseType(Ty) || parseValue(Ty, V, PFS);
7170}
7171
7172bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
7173 PerFunctionState &PFS) {
7174 Value *V;
7175 Loc = Lex.getLoc();
7176 if (parseTypeAndValue(V, PFS))
7177 return true;
7178 if (!isa<BasicBlock>(V))
7179 return error(Loc, "expected a basic block");
7180 BB = cast<BasicBlock>(V);
7181 return false;
7182}
7183
7185 // Exit early for the common (non-debug-intrinsic) case.
7186 // We can make this the only check when we begin supporting all "llvm.dbg"
7187 // intrinsics in the new debug info format.
7188 if (!Name.starts_with("llvm.dbg."))
7189 return false;
7191 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7192 FnID == Intrinsic::dbg_assign;
7193}
7194
7195/// FunctionHeader
7196/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7197/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7198/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7199/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7200bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7201 unsigned &FunctionNumber,
7202 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7203 // parse the linkage.
7204 LocTy LinkageLoc = Lex.getLoc();
7205 unsigned Linkage;
7206 unsigned Visibility;
7207 unsigned DLLStorageClass;
7208 bool DSOLocal;
7209 AttrBuilder RetAttrs(M->getContext());
7210 unsigned CC;
7211 bool HasLinkage;
7212 Type *RetType = nullptr;
7213 LocTy RetTypeLoc = Lex.getLoc();
7214 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7215 DSOLocal) ||
7216 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7217 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7218 return true;
7219
7220 // Verify that the linkage is ok.
7223 break; // always ok.
7225 if (IsDefine)
7226 return error(LinkageLoc, "invalid linkage for function definition");
7227 break;
7235 if (!IsDefine)
7236 return error(LinkageLoc, "invalid linkage for function declaration");
7237 break;
7240 return error(LinkageLoc, "invalid function linkage type");
7241 }
7242
7243 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7244 return error(LinkageLoc,
7245 "symbol with local linkage must have default visibility");
7246
7247 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7248 return error(LinkageLoc,
7249 "symbol with local linkage cannot have a DLL storage class");
7250
7251 if (!FunctionType::isValidReturnType(RetType))
7252 return error(RetTypeLoc, "invalid function return type");
7253
7254 LocTy NameLoc = Lex.getLoc();
7255
7256 std::string FunctionName;
7257 if (Lex.getKind() == lltok::GlobalVar) {
7258 FunctionName = Lex.getStrVal();
7259 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7260 FunctionNumber = Lex.getUIntVal();
7261 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7262 FunctionNumber))
7263 return true;
7264 } else {
7265 return tokError("expected function name");
7266 }
7267
7268 Lex.Lex();
7269
7270 if (Lex.getKind() != lltok::lparen)
7271 return tokError("expected '(' in function argument list");
7272
7274 bool IsVarArg;
7275 AttrBuilder FuncAttrs(M->getContext());
7276 std::vector<unsigned> FwdRefAttrGrps;
7277 LocTy BuiltinLoc;
7278 std::string Section;
7279 std::string Partition;
7280 MaybeAlign Alignment, PrefAlignment;
7281 std::string GC;
7283 unsigned AddrSpace = 0;
7284 Constant *Prefix = nullptr;
7285 Constant *Prologue = nullptr;
7286 Constant *PersonalityFn = nullptr;
7287 Comdat *C;
7288
7289 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7290 parseOptionalUnnamedAddr(UnnamedAddr) ||
7291 parseOptionalProgramAddrSpace(AddrSpace) ||
7292 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7293 BuiltinLoc) ||
7294 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7295 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7296 parseOptionalComdat(FunctionName, C) ||
7297 parseOptionalAlignment(Alignment) ||
7298 parseOptionalPrefAlignment(PrefAlignment) ||
7299 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7300 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7301 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7302 (EatIfPresent(lltok::kw_personality) &&
7303 parseGlobalTypeAndValue(PersonalityFn)))
7304 return true;
7305
7306 if (FuncAttrs.contains(Attribute::Builtin))
7307 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7308
7309 // If the alignment was parsed as an attribute, move to the alignment field.
7310 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7311 Alignment = A;
7312 FuncAttrs.removeAttribute(Attribute::Alignment);
7313 }
7314
7315 // Okay, if we got here, the function is syntactically valid. Convert types
7316 // and do semantic checks.
7317 std::vector<Type*> ParamTypeList;
7319
7320 for (const ArgInfo &Arg : ArgList) {
7321 ParamTypeList.push_back(Arg.Ty);
7322 Attrs.push_back(Arg.Attrs);
7323 }
7324
7325 AttributeList PAL =
7326 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7327 AttributeSet::get(Context, RetAttrs), Attrs);
7328
7329 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7330 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7331
7332 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7333 PointerType *PFT = PointerType::get(Context, AddrSpace);
7334
7335 Fn = nullptr;
7336 GlobalValue *FwdFn = nullptr;
7337 if (!FunctionName.empty()) {
7338 // If this was a definition of a forward reference, remove the definition
7339 // from the forward reference table and fill in the forward ref.
7340 auto FRVI = ForwardRefVals.find(FunctionName);
7341 if (FRVI != ForwardRefVals.end()) {
7342 FwdFn = FRVI->second.first;
7343 if (FwdFn->getType() != PFT)
7344 return error(FRVI->second.second,
7345 "invalid forward reference to "
7346 "function '" +
7347 FunctionName +
7348 "' with wrong type: "
7349 "expected '" +
7350 getTypeString(PFT) + "' but was '" +
7351 getTypeString(FwdFn->getType()) + "'");
7352 ForwardRefVals.erase(FRVI);
7353 } else if ((Fn = M->getFunction(FunctionName))) {
7354 // Reject redefinitions.
7355 return error(NameLoc,
7356 "invalid redefinition of function '" + FunctionName + "'");
7357 } else if (M->getNamedValue(FunctionName)) {
7358 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7359 }
7360
7361 } else {
7362 // Handle @"", where a name is syntactically specified, but semantically
7363 // missing.
7364 if (FunctionNumber == (unsigned)-1)
7365 FunctionNumber = NumberedVals.getNext();
7366
7367 // If this is a definition of a forward referenced function, make sure the
7368 // types agree.
7369 auto I = ForwardRefValIDs.find(FunctionNumber);
7370 if (I != ForwardRefValIDs.end()) {
7371 FwdFn = I->second.first;
7372 if (FwdFn->getType() != PFT)
7373 return error(NameLoc, "type of definition and forward reference of '@" +
7374 Twine(FunctionNumber) +
7375 "' disagree: "
7376 "expected '" +
7377 getTypeString(PFT) + "' but was '" +
7378 getTypeString(FwdFn->getType()) + "'");
7379 ForwardRefValIDs.erase(I);
7380 }
7381 }
7382
7384 FunctionName, M);
7385
7386 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7387
7388 if (FunctionName.empty())
7389 NumberedVals.add(FunctionNumber, Fn);
7390
7392 maybeSetDSOLocal(DSOLocal, *Fn);
7395 Fn->setCallingConv(CC);
7396 Fn->setAttributes(PAL);
7397 Fn->setUnnamedAddr(UnnamedAddr);
7398 if (Alignment)
7399 Fn->setAlignment(*Alignment);
7400 Fn->setPreferredAlignment(PrefAlignment);
7401 Fn->setSection(Section);
7402 Fn->setPartition(Partition);
7403 Fn->setComdat(C);
7404 Fn->setPersonalityFn(PersonalityFn);
7405 if (!GC.empty()) Fn->setGC(GC);
7406 Fn->setPrefixData(Prefix);
7407 Fn->setPrologueData(Prologue);
7408 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7409
7410 // Add all of the arguments we parsed to the function.
7411 Function::arg_iterator ArgIt = Fn->arg_begin();
7412 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7413 if (ParserContext && ArgList[i].IdentLoc)
7414 ParserContext->addInstructionOrArgumentLocation(
7415 &*ArgIt, ArgList[i].IdentLoc.value());
7416 // If the argument has a name, insert it into the argument symbol table.
7417 if (ArgList[i].Name.empty()) continue;
7418
7419 // Set the name, if it conflicted, it will be auto-renamed.
7420 ArgIt->setName(ArgList[i].Name);
7421
7422 if (ArgIt->getName() != ArgList[i].Name)
7423 return error(ArgList[i].Loc,
7424 "redefinition of argument '%" + ArgList[i].Name + "'");
7425 }
7426
7427 if (FwdFn) {
7428 FwdFn->replaceAllUsesWith(Fn);
7429 FwdFn->eraseFromParent();
7430 }
7431
7432 if (IsDefine)
7433 return false;
7434
7435 // Check the declaration has no block address forward references.
7436 ValID ID;
7437 if (FunctionName.empty()) {
7438 ID.Kind = ValID::t_GlobalID;
7439 ID.UIntVal = FunctionNumber;
7440 } else {
7441 ID.Kind = ValID::t_GlobalName;
7442 ID.StrVal = FunctionName;
7443 }
7444 auto Blocks = ForwardRefBlockAddresses.find(ID);
7445 if (Blocks != ForwardRefBlockAddresses.end())
7446 return error(Blocks->first.Loc,
7447 "cannot take blockaddress inside a declaration");
7448 return false;
7449}
7450
7451bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7452 ValID ID;
7453 if (FunctionNumber == -1) {
7454 ID.Kind = ValID::t_GlobalName;
7455 ID.StrVal = std::string(F.getName());
7456 } else {
7457 ID.Kind = ValID::t_GlobalID;
7458 ID.UIntVal = FunctionNumber;
7459 }
7460
7461 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7462 if (Blocks == P.ForwardRefBlockAddresses.end())
7463 return false;
7464
7465 for (const auto &I : Blocks->second) {
7466 const ValID &BBID = I.first;
7467 GlobalValue *GV = I.second;
7468
7469 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7470 "Expected local id or name");
7471 BasicBlock *BB;
7472 if (BBID.Kind == ValID::t_LocalName)
7473 BB = getBB(BBID.StrVal, BBID.Loc);
7474 else
7475 BB = getBB(BBID.UIntVal, BBID.Loc);
7476 if (!BB)
7477 return P.error(BBID.Loc, "referenced value is not a basic block");
7478
7479 Value *ResolvedVal = BlockAddress::get(&F, BB);
7480 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7481 ResolvedVal);
7482 if (!ResolvedVal)
7483 return true;
7484 GV->replaceAllUsesWith(ResolvedVal);
7485 GV->eraseFromParent();
7486 }
7487
7488 P.ForwardRefBlockAddresses.erase(Blocks);
7489 return false;
7490}
7491
7492/// parseFunctionBody
7493/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7494bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7495 ArrayRef<unsigned> UnnamedArgNums) {
7496 if (Lex.getKind() != lltok::lbrace)
7497 return tokError("expected '{' in function body");
7498 Lex.Lex(); // eat the {.
7499
7500 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7501
7502 // Resolve block addresses and allow basic blocks to be forward-declared
7503 // within this function.
7504 if (PFS.resolveForwardRefBlockAddresses())
7505 return true;
7506 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7507
7508 // We need at least one basic block.
7509 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7510 return tokError("function body requires at least one basic block");
7511
7512 while (Lex.getKind() != lltok::rbrace &&
7513 Lex.getKind() != lltok::kw_uselistorder)
7514 if (parseBasicBlock(PFS))
7515 return true;
7516
7517 while (Lex.getKind() != lltok::rbrace)
7518 if (parseUseListOrder(&PFS))
7519 return true;
7520
7521 // Eat the }.
7522 Lex.Lex();
7523
7524 // Verify function is ok.
7525 return PFS.finishFunction();
7526}
7527
7528/// parseBasicBlock
7529/// ::= (LabelStr|LabelID)? Instruction*
7530bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7531 FileLoc BBStart = getTokLineColumnPos();
7532
7533 // If this basic block starts out with a name, remember it.
7534 std::string Name;
7535 int NameID = -1;
7536 LocTy NameLoc = Lex.getLoc();
7537 if (Lex.getKind() == lltok::LabelStr) {
7538 Name = Lex.getStrVal();
7539 Lex.Lex();
7540 } else if (Lex.getKind() == lltok::LabelID) {
7541 NameID = Lex.getUIntVal();
7542 Lex.Lex();
7543 }
7544
7545 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7546 if (!BB)
7547 return true;
7548
7549 std::string NameStr;
7550
7551 // Parse the instructions and debug values in this block until we get a
7552 // terminator.
7553 Instruction *Inst;
7554 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7555 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7556 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7557 do {
7558 // Handle debug records first - there should always be an instruction
7559 // following the debug records, i.e. they cannot appear after the block
7560 // terminator.
7561 while (Lex.getKind() == lltok::hash) {
7562 if (SeenOldDbgInfoFormat)
7563 return error(Lex.getLoc(), "debug record should not appear in a module "
7564 "containing debug info intrinsics");
7565 SeenNewDbgInfoFormat = true;
7566 Lex.Lex();
7567
7568 DbgRecord *DR;
7569 if (parseDebugRecord(DR, PFS))
7570 return true;
7571 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7572 }
7573
7574 FileLoc InstStart = getTokLineColumnPos();
7575 // This instruction may have three possibilities for a name: a) none
7576 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7577 LocTy NameLoc = Lex.getLoc();
7578 int NameID = -1;
7579 NameStr = "";
7580
7581 if (Lex.getKind() == lltok::LocalVarID) {
7582 NameID = Lex.getUIntVal();
7583 Lex.Lex();
7584 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7585 return true;
7586 } else if (Lex.getKind() == lltok::LocalVar) {
7587 NameStr = Lex.getStrVal();
7588 Lex.Lex();
7589 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7590 return true;
7591 }
7592
7593 switch (parseInstruction(Inst, BB, PFS)) {
7594 default:
7595 llvm_unreachable("Unknown parseInstruction result!");
7596 case InstError: return true;
7597 case InstNormal:
7598 Inst->insertInto(BB, BB->end());
7599
7600 // With a normal result, we check to see if the instruction is followed by
7601 // a comma and metadata.
7602 if (EatIfPresent(lltok::comma))
7603 if (parseInstructionMetadata(*Inst))
7604 return true;
7605 break;
7606 case InstExtraComma:
7607 Inst->insertInto(BB, BB->end());
7608
7609 // If the instruction parser ate an extra comma at the end of it, it
7610 // *must* be followed by metadata.
7611 if (parseInstructionMetadata(*Inst))
7612 return true;
7613 break;
7614 }
7615
7616 // Set the name on the instruction.
7617 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7618 return true;
7619
7620 // Attach any preceding debug values to this instruction.
7621 for (DbgRecordPtr &DR : TrailingDbgRecord)
7622 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7623 TrailingDbgRecord.clear();
7624 if (ParserContext) {
7625 ParserContext->addInstructionOrArgumentLocation(
7626 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7627 }
7628 } while (!Inst->isTerminator());
7629
7630 if (ParserContext)
7631 ParserContext->addBlockLocation(
7632 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7633
7634 assert(TrailingDbgRecord.empty() &&
7635 "All debug values should have been attached to an instruction.");
7636
7637 return false;
7638}
7639
7640/// parseDebugRecord
7641/// ::= #dbg_label '(' MDNode ')'
7642/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7643/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7644bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7645 using RecordKind = DbgRecord::Kind;
7646 using LocType = DbgVariableRecord::LocationType;
7647 LocTy DVRLoc = Lex.getLoc();
7648 if (Lex.getKind() != lltok::DbgRecordType)
7649 return error(DVRLoc, "expected debug record type here");
7650 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7651 .Case("declare", RecordKind::ValueKind)
7652 .Case("value", RecordKind::ValueKind)
7653 .Case("assign", RecordKind::ValueKind)
7654 .Case("label", RecordKind::LabelKind)
7655 .Case("declare_value", RecordKind::ValueKind);
7656
7657 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7658 // full DbgVariableRecord processing stage.
7659 if (RecordType == RecordKind::LabelKind) {
7660 Lex.Lex();
7661 if (parseToken(lltok::lparen, "Expected '(' here"))
7662 return true;
7663 MDNode *Label;
7664 if (parseMDNode(Label))
7665 return true;
7666 if (parseToken(lltok::comma, "Expected ',' here"))
7667 return true;
7668 MDNode *DbgLoc;
7669 if (parseMDNode(DbgLoc))
7670 return true;
7671 if (parseToken(lltok::rparen, "Expected ')' here"))
7672 return true;
7674 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7675 return false;
7676 }
7677
7678 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7679 .Case("declare", LocType::Declare)
7680 .Case("value", LocType::Value)
7681 .Case("assign", LocType::Assign)
7682 .Case("declare_value", LocType::DeclareValue);
7683
7684 Lex.Lex();
7685 if (parseToken(lltok::lparen, "Expected '(' here"))
7686 return true;
7687
7688 // Parse Value field.
7689 Metadata *ValLocMD;
7690 if (parseMetadata(ValLocMD, &PFS))
7691 return true;
7692 if (parseToken(lltok::comma, "Expected ',' here"))
7693 return true;
7694
7695 // Parse Variable field.
7696 MDNode *Variable;
7697 if (parseMDNode(Variable))
7698 return true;
7699 if (parseToken(lltok::comma, "Expected ',' here"))
7700 return true;
7701
7702 // Parse Expression field.
7703 MDNode *Expression;
7704 if (parseMDNode(Expression))
7705 return true;
7706 if (parseToken(lltok::comma, "Expected ',' here"))
7707 return true;
7708
7709 // Parse additional fields for #dbg_assign.
7710 MDNode *AssignID = nullptr;
7711 Metadata *AddressLocation = nullptr;
7712 MDNode *AddressExpression = nullptr;
7713 if (ValueType == LocType::Assign) {
7714 // Parse DIAssignID.
7715 if (parseMDNode(AssignID))
7716 return true;
7717 if (parseToken(lltok::comma, "Expected ',' here"))
7718 return true;
7719
7720 // Parse address ValueAsMetadata.
7721 if (parseMetadata(AddressLocation, &PFS))
7722 return true;
7723 if (parseToken(lltok::comma, "Expected ',' here"))
7724 return true;
7725
7726 // Parse address DIExpression.
7727 if (parseMDNode(AddressExpression))
7728 return true;
7729 if (parseToken(lltok::comma, "Expected ',' here"))
7730 return true;
7731 }
7732
7733 /// Parse DILocation.
7734 MDNode *DebugLoc;
7735 if (parseMDNode(DebugLoc))
7736 return true;
7737
7738 if (parseToken(lltok::rparen, "Expected ')' here"))
7739 return true;
7741 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7742 AddressExpression);
7743 PendingDbgRecords.emplace_back(DVRLoc, DR, DebugLoc);
7744 return false;
7745}
7746//===----------------------------------------------------------------------===//
7747// Instruction Parsing.
7748//===----------------------------------------------------------------------===//
7749
7750/// parseInstruction - parse one of the many different instructions.
7751///
7752int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7753 PerFunctionState &PFS) {
7754 lltok::Kind Token = Lex.getKind();
7755 if (Token == lltok::Eof)
7756 return tokError("found end of file when expecting more instructions");
7757 LocTy Loc = Lex.getLoc();
7758 unsigned KeywordVal = Lex.getUIntVal();
7759 Lex.Lex(); // Eat the keyword.
7760
7761 switch (Token) {
7762 default:
7763 return error(Loc, "expected instruction opcode");
7764 // Terminator Instructions.
7765 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7766 case lltok::kw_ret:
7767 return parseRet(Inst, BB, PFS);
7768 case lltok::kw_br:
7769 return parseBr(Inst, PFS);
7770 case lltok::kw_switch:
7771 return parseSwitch(Inst, PFS);
7773 return parseIndirectBr(Inst, PFS);
7774 case lltok::kw_invoke:
7775 return parseInvoke(Inst, PFS);
7776 case lltok::kw_resume:
7777 return parseResume(Inst, PFS);
7779 return parseCleanupRet(Inst, PFS);
7780 case lltok::kw_catchret:
7781 return parseCatchRet(Inst, PFS);
7783 return parseCatchSwitch(Inst, PFS);
7784 case lltok::kw_catchpad:
7785 return parseCatchPad(Inst, PFS);
7787 return parseCleanupPad(Inst, PFS);
7788 case lltok::kw_callbr:
7789 return parseCallBr(Inst, PFS);
7790 // Unary Operators.
7791 case lltok::kw_fneg: {
7792 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7793 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7794 if (Res != 0)
7795 return Res;
7796 if (FMF.any())
7797 Inst->setFastMathFlags(FMF);
7798 return false;
7799 }
7800 // Binary Operators.
7801 case lltok::kw_add:
7802 case lltok::kw_sub:
7803 case lltok::kw_mul:
7804 case lltok::kw_shl: {
7805 bool NUW = EatIfPresent(lltok::kw_nuw);
7806 bool NSW = EatIfPresent(lltok::kw_nsw);
7807 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7808
7809 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7810 return true;
7811
7812 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7813 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7814 return false;
7815 }
7816 case lltok::kw_fadd:
7817 case lltok::kw_fsub:
7818 case lltok::kw_fmul:
7819 case lltok::kw_fdiv:
7820 case lltok::kw_frem: {
7821 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7822 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7823 if (Res != 0)
7824 return Res;
7825 if (FMF.any())
7826 Inst->setFastMathFlags(FMF);
7827 return 0;
7828 }
7829
7830 case lltok::kw_sdiv:
7831 case lltok::kw_udiv:
7832 case lltok::kw_lshr:
7833 case lltok::kw_ashr: {
7834 bool Exact = EatIfPresent(lltok::kw_exact);
7835
7836 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7837 return true;
7838 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7839 return false;
7840 }
7841
7842 case lltok::kw_urem:
7843 case lltok::kw_srem:
7844 return parseArithmetic(Inst, PFS, KeywordVal,
7845 /*IsFP*/ false);
7846 case lltok::kw_or: {
7847 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7848 if (parseLogical(Inst, PFS, KeywordVal))
7849 return true;
7850 if (Disjoint)
7851 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7852 return false;
7853 }
7854 case lltok::kw_and:
7855 case lltok::kw_xor:
7856 return parseLogical(Inst, PFS, KeywordVal);
7857 case lltok::kw_icmp: {
7858 bool SameSign = EatIfPresent(lltok::kw_samesign);
7859 if (parseCompare(Inst, PFS, KeywordVal))
7860 return true;
7861 if (SameSign)
7862 cast<ICmpInst>(Inst)->setSameSign();
7863 return false;
7864 }
7865 case lltok::kw_fcmp: {
7866 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7867 int Res = parseCompare(Inst, PFS, KeywordVal);
7868 if (Res != 0)
7869 return Res;
7870 if (FMF.any())
7871 Inst->setFastMathFlags(FMF);
7872 return 0;
7873 }
7874
7875 // Casts.
7876 case lltok::kw_uitofp: {
7877 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7878 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7879 bool Res = parseCast(Inst, PFS, KeywordVal);
7880 if (Res != 0)
7881 return Res;
7882 if (NonNeg)
7883 Inst->setNonNeg();
7884 Inst->setFastMathFlags(FMF);
7885 return 0;
7886 }
7887 case lltok::kw_zext: {
7888 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7889 bool Res = parseCast(Inst, PFS, KeywordVal);
7890 if (Res != 0)
7891 return Res;
7892 if (NonNeg)
7893 Inst->setNonNeg();
7894 return 0;
7895 }
7896 case lltok::kw_trunc: {
7897 bool NUW = EatIfPresent(lltok::kw_nuw);
7898 bool NSW = EatIfPresent(lltok::kw_nsw);
7899 if (!NUW)
7900 NUW = EatIfPresent(lltok::kw_nuw);
7901 if (parseCast(Inst, PFS, KeywordVal))
7902 return true;
7903 if (NUW)
7904 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7905 if (NSW)
7906 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7907 return false;
7908 }
7910 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7911 if (parseCast(Inst, PFS, KeywordVal))
7912 return true;
7913 if (NonNull)
7914 cast<AddrSpaceCastInst>(Inst)->setNonNull();
7915 return false;
7916 }
7917 case lltok::kw_sext:
7918 case lltok::kw_bitcast:
7919 case lltok::kw_fptoui:
7920 case lltok::kw_fptosi:
7921 case lltok::kw_inttoptr:
7923 case lltok::kw_ptrtoint:
7924 return parseCast(Inst, PFS, KeywordVal);
7925 case lltok::kw_fptrunc:
7926 case lltok::kw_fpext:
7927 case lltok::kw_sitofp: {
7928 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7929 if (parseCast(Inst, PFS, KeywordVal))
7930 return true;
7931 if (FMF.any())
7932 Inst->setFastMathFlags(FMF);
7933 return false;
7934 }
7935
7936 // Other.
7937 case lltok::kw_select: {
7938 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7939 int Res = parseSelect(Inst, PFS);
7940 if (Res != 0)
7941 return Res;
7942 if (FMF.any()) {
7943 if (!isa<FPMathOperator>(Inst)) {
7944 Inst->deleteValue();
7945 return error(Loc, "fast-math-flags specified for select without "
7946 "floating-point scalar or vector return type");
7947 }
7948 Inst->setFastMathFlags(FMF);
7949 }
7950 return 0;
7951 }
7952 case lltok::kw_va_arg:
7953 return parseVAArg(Inst, PFS);
7955 return parseExtractElement(Inst, PFS);
7957 return parseInsertElement(Inst, PFS);
7959 return parseShuffleVector(Inst, PFS);
7960 case lltok::kw_phi: {
7961 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7962 int Res = parsePHI(Inst, PFS);
7963 if (Res != 0)
7964 return Res;
7965 if (FMF.any()) {
7966 if (!isa<FPMathOperator>(Inst)) {
7967 Inst->deleteValue();
7968 return error(Loc, "fast-math-flags specified for phi without "
7969 "floating-point scalar or vector return type");
7970 }
7971 Inst->setFastMathFlags(FMF);
7972 }
7973 return 0;
7974 }
7976 return parseLandingPad(Inst, PFS);
7977 case lltok::kw_freeze:
7978 return parseFreeze(Inst, PFS);
7980 return parseBitInsert(Inst, PFS);
7982 return parseBitExtract(Inst, PFS);
7983 // Call.
7984 case lltok::kw_call:
7985 return parseCall(Inst, PFS, CallInst::TCK_None);
7986 case lltok::kw_tail:
7987 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7988 case lltok::kw_musttail:
7989 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7990 case lltok::kw_notail:
7991 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7992 // Memory.
7993 case lltok::kw_alloca:
7994 return parseAlloc(Inst, PFS);
7995 case lltok::kw_load:
7996 return parseLoad(Inst, PFS);
7997 case lltok::kw_store:
7998 return parseStore(Inst, PFS);
7999 case lltok::kw_cmpxchg:
8000 return parseCmpXchg(Inst, PFS);
8002 return parseAtomicRMW(Inst, PFS);
8003 case lltok::kw_fence:
8004 return parseFence(Inst, PFS);
8006 return parseGetElementPtr(Inst, PFS);
8008 return parseExtractValue(Inst, PFS);
8010 return parseInsertValue(Inst, PFS);
8011 }
8012}
8013
8014/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
8015bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
8016 if (Opc == Instruction::FCmp) {
8017 switch (Lex.getKind()) {
8018 default:
8019 return tokError("expected fcmp predicate (e.g. 'oeq')");
8020 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
8021 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
8022 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
8023 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
8024 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
8025 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
8026 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
8027 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
8028 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
8029 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
8030 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
8031 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
8032 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
8033 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
8034 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
8035 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
8036 }
8037 } else {
8038 switch (Lex.getKind()) {
8039 default:
8040 return tokError("expected icmp predicate (e.g. 'eq')");
8041 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
8042 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
8043 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
8044 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
8045 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
8046 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
8047 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
8048 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
8049 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
8050 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
8051 }
8052 }
8053 Lex.Lex();
8054 return false;
8055}
8056
8057//===----------------------------------------------------------------------===//
8058// Terminator Instructions.
8059//===----------------------------------------------------------------------===//
8060
8061/// parseRet - parse a return instruction.
8062/// ::= 'ret' void (',' !dbg, !1)*
8063/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
8064bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8065 PerFunctionState &PFS) {
8066 SMLoc TypeLoc = Lex.getLoc();
8067 Type *Ty = nullptr;
8068 if (parseType(Ty, true /*void allowed*/))
8069 return true;
8070
8071 Type *ResType = PFS.getFunction().getReturnType();
8072
8073 if (Ty->isVoidTy()) {
8074 if (!ResType->isVoidTy())
8075 return error(TypeLoc, "value doesn't match function result type '" +
8076 getTypeString(ResType) + "'");
8077
8078 Inst = ReturnInst::Create(Context);
8079 return false;
8080 }
8081
8082 Value *RV;
8083 if (parseValue(Ty, RV, PFS))
8084 return true;
8085
8086 if (ResType != RV->getType())
8087 return error(TypeLoc, "value doesn't match function result type '" +
8088 getTypeString(ResType) + "'");
8089
8090 Inst = ReturnInst::Create(Context, RV);
8091 return false;
8092}
8093
8094/// parseBr
8095/// ::= 'br' TypeAndValue
8096/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8097bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8098 LocTy Loc, Loc2;
8099 Value *Op0;
8100 BasicBlock *Op1, *Op2;
8101 if (parseTypeAndValue(Op0, Loc, PFS))
8102 return true;
8103
8104 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
8105 Inst = UncondBrInst::Create(BB);
8106 return false;
8107 }
8108
8109 if (Op0->getType() != Type::getInt1Ty(Context))
8110 return error(Loc, "branch condition must have 'i1' type");
8111
8112 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
8113 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8114 parseToken(lltok::comma, "expected ',' after true destination") ||
8115 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8116 return true;
8117
8118 Inst = CondBrInst::Create(Op0, Op1, Op2);
8119 return false;
8120}
8121
8122/// parseSwitch
8123/// Instruction
8124/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
8125/// JumpTable
8126/// ::= (TypeAndValue ',' TypeAndValue)*
8127bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8128 LocTy CondLoc, BBLoc;
8129 Value *Cond;
8130 BasicBlock *DefaultBB;
8131 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
8132 parseToken(lltok::comma, "expected ',' after switch condition") ||
8133 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8134 parseToken(lltok::lsquare, "expected '[' with switch table"))
8135 return true;
8136
8137 if (!Cond->getType()->isIntegerTy())
8138 return error(CondLoc, "switch condition must have integer type");
8139
8140 // parse the jump table pairs.
8141 SmallPtrSet<Value*, 32> SeenCases;
8143 while (Lex.getKind() != lltok::rsquare) {
8144 Value *Constant;
8145 BasicBlock *DestBB;
8146
8147 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8148 parseToken(lltok::comma, "expected ',' after case value") ||
8149 parseTypeAndBasicBlock(DestBB, PFS))
8150 return true;
8151
8152 if (!SeenCases.insert(Constant).second)
8153 return error(CondLoc, "duplicate case value in switch");
8154 if (!isa<ConstantInt>(Constant))
8155 return error(CondLoc, "case value is not a constant integer");
8156
8157 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
8158 }
8159
8160 Lex.Lex(); // Eat the ']'.
8161
8162 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
8163 for (const auto &[OnVal, Dest] : Table)
8164 SI->addCase(OnVal, Dest);
8165 Inst = SI;
8166 return false;
8167}
8168
8169/// parseIndirectBr
8170/// Instruction
8171/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
8172bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8173 LocTy AddrLoc;
8174 Value *Address;
8175 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
8176 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
8177 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
8178 return true;
8179
8180 if (!Address->getType()->isPointerTy())
8181 return error(AddrLoc, "indirectbr address must have pointer type");
8182
8183 // parse the destination list.
8184 SmallVector<BasicBlock*, 16> DestList;
8185
8186 if (Lex.getKind() != lltok::rsquare) {
8187 BasicBlock *DestBB;
8188 if (parseTypeAndBasicBlock(DestBB, PFS))
8189 return true;
8190 DestList.push_back(DestBB);
8191
8192 while (EatIfPresent(lltok::comma)) {
8193 if (parseTypeAndBasicBlock(DestBB, PFS))
8194 return true;
8195 DestList.push_back(DestBB);
8196 }
8197 }
8198
8199 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8200 return true;
8201
8202 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
8203 for (BasicBlock *Dest : DestList)
8204 IBI->addDestination(Dest);
8205 Inst = IBI;
8206 return false;
8207}
8208
8209// If RetType is a non-function pointer type, then this is the short syntax
8210// for the call, which means that RetType is just the return type. Infer the
8211// rest of the function argument types from the arguments that are present.
8212bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
8213 FunctionType *&FuncTy) {
8214 FuncTy = dyn_cast<FunctionType>(RetType);
8215 if (!FuncTy) {
8216 // Pull out the types of all of the arguments...
8217 SmallVector<Type *, 8> ParamTypes;
8218 ParamTypes.reserve(ArgList.size());
8219 for (const ParamInfo &Arg : ArgList)
8220 ParamTypes.push_back(Arg.V->getType());
8221
8222 if (!FunctionType::isValidReturnType(RetType))
8223 return true;
8224
8225 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8226 }
8227 return false;
8228}
8229
8230/// parseInvoke
8231/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8232/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8233bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8234 LocTy CallLoc = Lex.getLoc();
8235 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8236 std::vector<unsigned> FwdRefAttrGrps;
8237 LocTy NoBuiltinLoc;
8238 unsigned CC;
8239 unsigned InvokeAddrSpace;
8240 Type *RetType = nullptr;
8241 LocTy RetTypeLoc;
8242 ValID CalleeID;
8245
8246 BasicBlock *NormalBB, *UnwindBB;
8247 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8248 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8249 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8250 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8251 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8252 NoBuiltinLoc) ||
8253 parseOptionalOperandBundles(BundleList, PFS) ||
8254 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8255 parseTypeAndBasicBlock(NormalBB, PFS) ||
8256 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8257 parseTypeAndBasicBlock(UnwindBB, PFS))
8258 return true;
8259
8260 // If RetType is a non-function pointer type, then this is the short syntax
8261 // for the call, which means that RetType is just the return type. Infer the
8262 // rest of the function argument types from the arguments that are present.
8263 FunctionType *Ty;
8264 if (resolveFunctionType(RetType, ArgList, Ty))
8265 return error(RetTypeLoc, "Invalid result type for LLVM function");
8266
8267 CalleeID.FTy = Ty;
8268
8269 // Look up the callee.
8270 Value *Callee;
8271 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8272 Callee, &PFS))
8273 return true;
8274
8275 // Set up the Attribute for the function.
8276 SmallVector<Value *, 8> Args;
8278
8279 // Loop through FunctionType's arguments and ensure they are specified
8280 // correctly. Also, gather any parameter attributes.
8281 FunctionType::param_iterator I = Ty->param_begin();
8282 FunctionType::param_iterator E = Ty->param_end();
8283 for (const ParamInfo &Arg : ArgList) {
8284 Type *ExpectedTy = nullptr;
8285 if (I != E) {
8286 ExpectedTy = *I++;
8287 } else if (!Ty->isVarArg()) {
8288 return error(Arg.Loc, "too many arguments specified");
8289 }
8290
8291 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8292 return error(Arg.Loc, "argument is not of expected type '" +
8293 getTypeString(ExpectedTy) + "'");
8294 Args.push_back(Arg.V);
8295 ArgAttrs.push_back(Arg.Attrs);
8296 }
8297
8298 if (I != E)
8299 return error(CallLoc, "not enough parameters specified for call");
8300
8301 // Finish off the Attribute and check them
8302 AttributeList PAL =
8303 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8304 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8305
8306 InvokeInst *II =
8307 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8308 II->setCallingConv(CC);
8309 II->setAttributes(PAL);
8310 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8311 Inst = II;
8312 return false;
8313}
8314
8315/// parseResume
8316/// ::= 'resume' TypeAndValue
8317bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8318 Value *Exn; LocTy ExnLoc;
8319 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8320 return true;
8321
8322 ResumeInst *RI = ResumeInst::Create(Exn);
8323 Inst = RI;
8324 return false;
8325}
8326
8327bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8328 PerFunctionState &PFS) {
8329 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8330 return true;
8331
8332 while (Lex.getKind() != lltok::rsquare) {
8333 // If this isn't the first argument, we need a comma.
8334 if (!Args.empty() &&
8335 parseToken(lltok::comma, "expected ',' in argument list"))
8336 return true;
8337
8338 // parse the argument.
8339 LocTy ArgLoc;
8340 Type *ArgTy = nullptr;
8341 if (parseType(ArgTy, ArgLoc))
8342 return true;
8343
8344 Value *V;
8345 if (ArgTy->isMetadataTy()) {
8346 if (parseMetadataAsValue(V, PFS))
8347 return true;
8348 } else {
8349 if (parseValue(ArgTy, V, PFS))
8350 return true;
8351 }
8352 Args.push_back(V);
8353 }
8354
8355 Lex.Lex(); // Lex the ']'.
8356 return false;
8357}
8358
8359/// parseCleanupRet
8360/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8361bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8362 Value *CleanupPad = nullptr;
8363
8364 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8365 return true;
8366
8367 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8368 return true;
8369
8370 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8371 return true;
8372
8373 BasicBlock *UnwindBB = nullptr;
8374 if (Lex.getKind() == lltok::kw_to) {
8375 Lex.Lex();
8376 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8377 return true;
8378 } else {
8379 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8380 return true;
8381 }
8382 }
8383
8384 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8385 return false;
8386}
8387
8388/// parseCatchRet
8389/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8390bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8391 Value *CatchPad = nullptr;
8392
8393 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8394 return true;
8395
8396 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8397 return true;
8398
8399 BasicBlock *BB;
8400 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8401 parseTypeAndBasicBlock(BB, PFS))
8402 return true;
8403
8404 Inst = CatchReturnInst::Create(CatchPad, BB);
8405 return false;
8406}
8407
8408/// parseCatchSwitch
8409/// ::= 'catchswitch' within Parent
8410bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8411 Value *ParentPad;
8412
8413 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8414 return true;
8415
8416 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8417 Lex.getKind() != lltok::LocalVarID)
8418 return tokError("expected scope value for catchswitch");
8419
8420 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8421 return true;
8422
8423 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8424 return true;
8425
8427 do {
8428 BasicBlock *DestBB;
8429 if (parseTypeAndBasicBlock(DestBB, PFS))
8430 return true;
8431 Table.push_back(DestBB);
8432 } while (EatIfPresent(lltok::comma));
8433
8434 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8435 return true;
8436
8437 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8438 return true;
8439
8440 BasicBlock *UnwindBB = nullptr;
8441 if (EatIfPresent(lltok::kw_to)) {
8442 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8443 return true;
8444 } else {
8445 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8446 return true;
8447 }
8448
8449 auto *CatchSwitch =
8450 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8451 for (BasicBlock *DestBB : Table)
8452 CatchSwitch->addHandler(DestBB);
8453 Inst = CatchSwitch;
8454 return false;
8455}
8456
8457/// parseCatchPad
8458/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8459bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8460 Value *CatchSwitch = nullptr;
8461
8462 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8463 return true;
8464
8465 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8466 return tokError("expected scope value for catchpad");
8467
8468 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8469 return true;
8470
8471 SmallVector<Value *, 8> Args;
8472 if (parseExceptionArgs(Args, PFS))
8473 return true;
8474
8475 Inst = CatchPadInst::Create(CatchSwitch, Args);
8476 return false;
8477}
8478
8479/// parseCleanupPad
8480/// ::= 'cleanuppad' within Parent ParamList
8481bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8482 Value *ParentPad = nullptr;
8483
8484 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8485 return true;
8486
8487 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8488 Lex.getKind() != lltok::LocalVarID)
8489 return tokError("expected scope value for cleanuppad");
8490
8491 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8492 return true;
8493
8494 SmallVector<Value *, 8> Args;
8495 if (parseExceptionArgs(Args, PFS))
8496 return true;
8497
8498 Inst = CleanupPadInst::Create(ParentPad, Args);
8499 return false;
8500}
8501
8502//===----------------------------------------------------------------------===//
8503// Unary Operators.
8504//===----------------------------------------------------------------------===//
8505
8506/// parseUnaryOp
8507/// ::= UnaryOp TypeAndValue ',' Value
8508///
8509/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8510/// operand is allowed.
8511bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8512 unsigned Opc, bool IsFP) {
8513 LocTy Loc; Value *LHS;
8514 if (parseTypeAndValue(LHS, Loc, PFS))
8515 return true;
8516
8517 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8519
8520 if (!Valid)
8521 return error(Loc, "invalid operand type for instruction");
8522
8524 return false;
8525}
8526
8527/// parseCallBr
8528/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8529/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8530/// '[' LabelList ']'
8531bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8532 LocTy CallLoc = Lex.getLoc();
8533 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8534 std::vector<unsigned> FwdRefAttrGrps;
8535 LocTy NoBuiltinLoc;
8536 unsigned CC;
8537 Type *RetType = nullptr;
8538 LocTy RetTypeLoc;
8539 ValID CalleeID;
8542
8543 BasicBlock *DefaultDest;
8544 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8545 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8546 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8547 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8548 NoBuiltinLoc) ||
8549 parseOptionalOperandBundles(BundleList, PFS) ||
8550 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8551 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8552 parseToken(lltok::lsquare, "expected '[' in callbr"))
8553 return true;
8554
8555 // parse the destination list.
8556 SmallVector<BasicBlock *, 16> IndirectDests;
8557
8558 if (Lex.getKind() != lltok::rsquare) {
8559 BasicBlock *DestBB;
8560 if (parseTypeAndBasicBlock(DestBB, PFS))
8561 return true;
8562 IndirectDests.push_back(DestBB);
8563
8564 while (EatIfPresent(lltok::comma)) {
8565 if (parseTypeAndBasicBlock(DestBB, PFS))
8566 return true;
8567 IndirectDests.push_back(DestBB);
8568 }
8569 }
8570
8571 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8572 return true;
8573
8574 // If RetType is a non-function pointer type, then this is the short syntax
8575 // for the call, which means that RetType is just the return type. Infer the
8576 // rest of the function argument types from the arguments that are present.
8577 FunctionType *Ty;
8578 if (resolveFunctionType(RetType, ArgList, Ty))
8579 return error(RetTypeLoc, "Invalid result type for LLVM function");
8580
8581 CalleeID.FTy = Ty;
8582
8583 // Look up the callee.
8584 Value *Callee;
8585 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8586 &PFS))
8587 return true;
8588
8589 // Set up the Attribute for the function.
8590 SmallVector<Value *, 8> Args;
8592
8593 // Loop through FunctionType's arguments and ensure they are specified
8594 // correctly. Also, gather any parameter attributes.
8595 FunctionType::param_iterator I = Ty->param_begin();
8596 FunctionType::param_iterator E = Ty->param_end();
8597 for (const ParamInfo &Arg : ArgList) {
8598 Type *ExpectedTy = nullptr;
8599 if (I != E) {
8600 ExpectedTy = *I++;
8601 } else if (!Ty->isVarArg()) {
8602 return error(Arg.Loc, "too many arguments specified");
8603 }
8604
8605 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8606 return error(Arg.Loc, "argument is not of expected type '" +
8607 getTypeString(ExpectedTy) + "'");
8608 Args.push_back(Arg.V);
8609 ArgAttrs.push_back(Arg.Attrs);
8610 }
8611
8612 if (I != E)
8613 return error(CallLoc, "not enough parameters specified for call");
8614
8615 // Finish off the Attribute and check them
8616 AttributeList PAL =
8617 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8618 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8619
8620 CallBrInst *CBI =
8621 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8622 BundleList);
8623 CBI->setCallingConv(CC);
8624 CBI->setAttributes(PAL);
8625 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8626 Inst = CBI;
8627 return false;
8628}
8629
8630//===----------------------------------------------------------------------===//
8631// Binary Operators.
8632//===----------------------------------------------------------------------===//
8633
8634/// parseArithmetic
8635/// ::= ArithmeticOps TypeAndValue ',' Value
8636///
8637/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8638/// operand is allowed.
8639bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8640 unsigned Opc, bool IsFP) {
8641 LocTy Loc; Value *LHS, *RHS;
8642 if (parseTypeAndValue(LHS, Loc, PFS) ||
8643 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8644 parseValue(LHS->getType(), RHS, PFS))
8645 return true;
8646
8647 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8649
8650 if (!Valid)
8651 return error(Loc, "invalid operand type for instruction");
8652
8654 return false;
8655}
8656
8657/// parseLogical
8658/// ::= ArithmeticOps TypeAndValue ',' Value {
8659bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8660 unsigned Opc) {
8661 LocTy Loc; Value *LHS, *RHS;
8662 if (parseTypeAndValue(LHS, Loc, PFS) ||
8663 parseToken(lltok::comma, "expected ',' in logical operation") ||
8664 parseValue(LHS->getType(), RHS, PFS))
8665 return true;
8666
8667 if (!LHS->getType()->isIntOrIntVectorTy())
8668 return error(Loc,
8669 "instruction requires integer or integer vector operands");
8670
8672 return false;
8673}
8674
8675/// parseCompare
8676/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8677/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8678bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8679 unsigned Opc) {
8680 // parse the integer/fp comparison predicate.
8681 LocTy Loc;
8682 unsigned Pred;
8683 Value *LHS, *RHS;
8684 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8685 parseToken(lltok::comma, "expected ',' after compare value") ||
8686 parseValue(LHS->getType(), RHS, PFS))
8687 return true;
8688
8689 if (Opc == Instruction::FCmp) {
8690 if (!LHS->getType()->isFPOrFPVectorTy())
8691 return error(Loc, "fcmp requires floating point operands");
8692 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8693 } else {
8694 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8695 if (!LHS->getType()->isIntOrIntVectorTy() &&
8697 return error(Loc, "icmp requires integer operands");
8698 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8699 }
8700 return false;
8701}
8702
8703//===----------------------------------------------------------------------===//
8704// Other Instructions.
8705//===----------------------------------------------------------------------===//
8706
8707/// parseCast
8708/// ::= CastOpc TypeAndValue 'to' Type
8709bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8710 unsigned Opc) {
8711 LocTy Loc;
8712 Value *Op;
8713 Type *DestTy = nullptr;
8714 if (parseTypeAndValue(Op, Loc, PFS) ||
8715 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8716 parseType(DestTy))
8717 return true;
8718
8720 return error(Loc, "invalid cast opcode for cast from '" +
8721 getTypeString(Op->getType()) + "' to '" +
8722 getTypeString(DestTy) + "'");
8723 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8724 return false;
8725}
8726
8727/// parseSelect
8728/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8729bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8730 LocTy Loc;
8731 Value *Op0, *Op1, *Op2;
8732 if (parseTypeAndValue(Op0, Loc, PFS) ||
8733 parseToken(lltok::comma, "expected ',' after select condition") ||
8734 parseTypeAndValue(Op1, PFS) ||
8735 parseToken(lltok::comma, "expected ',' after select value") ||
8736 parseTypeAndValue(Op2, PFS))
8737 return true;
8738
8739 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8740 return error(Loc, Reason);
8741
8742 Inst = SelectInst::Create(Op0, Op1, Op2);
8743 return false;
8744}
8745
8746/// parseVAArg
8747/// ::= 'va_arg' TypeAndValue ',' Type
8748bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8749 Value *Op;
8750 Type *EltTy = nullptr;
8751 LocTy TypeLoc;
8752 if (parseTypeAndValue(Op, PFS) ||
8753 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8754 parseType(EltTy, TypeLoc))
8755 return true;
8756
8757 if (!EltTy->isFirstClassType())
8758 return error(TypeLoc, "va_arg requires operand with first class type");
8759
8760 Inst = new VAArgInst(Op, EltTy);
8761 return false;
8762}
8763
8764/// parseExtractElement
8765/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8766bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8767 LocTy Loc;
8768 Value *Op0, *Op1;
8769 if (parseTypeAndValue(Op0, Loc, PFS) ||
8770 parseToken(lltok::comma, "expected ',' after extract value") ||
8771 parseTypeAndValue(Op1, PFS))
8772 return true;
8773
8775 return error(Loc, "invalid extractelement operands");
8776
8777 Inst = ExtractElementInst::Create(Op0, Op1);
8778 return false;
8779}
8780
8781/// parseInsertElement
8782/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8783bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8784 LocTy Loc;
8785 Value *Op0, *Op1, *Op2;
8786 if (parseTypeAndValue(Op0, Loc, PFS) ||
8787 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8788 parseTypeAndValue(Op1, PFS) ||
8789 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8790 parseTypeAndValue(Op2, PFS))
8791 return true;
8792
8793 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8794 return error(Loc, "invalid insertelement operands");
8795
8796 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8797 return false;
8798}
8799
8800// parseBitExtract
8801// ::= 'bitextract' Type ',' TypeAndValue ',' TypeAndValue
8802bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
8803 LocTy Loc;
8804 Type *Ty = nullptr;
8805 Value *Op0, *Op1;
8806 if (parseType(Ty, Loc) ||
8807 parseToken(lltok::comma, "expected ',' after bitextract type") ||
8808 parseTypeAndValue(Op0, Loc, PFS) ||
8809 parseToken(lltok::comma, "expected ',' after bitextract source value") ||
8810 parseTypeAndValue(Op1, PFS))
8811 return true;
8812
8813 if (const char *Reason = BitExtractInst::areInvalidOperands(Ty, Op0, Op1))
8814 return error(Loc, Reason);
8815
8816 Inst = BitExtractInst::Create(Ty, Op0, Op1);
8817 return false;
8818}
8819
8820// parseBitInsert
8821// ::= 'bitinsert' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8822bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
8823 LocTy Loc;
8824 Value *Op0, *Op1, *Op2;
8825 if (parseTypeAndValue(Op0, Loc, PFS) ||
8826 parseToken(lltok::comma, "expected ',' after bitinsert source value") ||
8827 parseTypeAndValue(Op1, PFS) ||
8828 parseToken(lltok::comma, "expected ',' after bitinsert insert value") ||
8829 parseTypeAndValue(Op2, PFS))
8830 return true;
8831
8832 if (const char *Reason = BitInsertInst::areInvalidOperands(Op0, Op1, Op2))
8833 return error(Loc, Reason);
8834
8835 Inst = BitInsertInst::Create(Op0, Op1, Op2);
8836 return false;
8837}
8838
8839/// parseShuffleVector
8840/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8841bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8842 LocTy Loc;
8843 Value *Op0, *Op1, *Op2;
8844 if (parseTypeAndValue(Op0, Loc, PFS) ||
8845 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8846 parseTypeAndValue(Op1, PFS) ||
8847 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8848 parseTypeAndValue(Op2, PFS))
8849 return true;
8850
8851 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8852 return error(Loc, "invalid shufflevector operands");
8853
8854 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8855 return false;
8856}
8857
8858/// parsePHI
8859/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8860int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8861 Type *Ty = nullptr; LocTy TypeLoc;
8862 Value *Op0, *Op1;
8863
8864 if (parseType(Ty, TypeLoc))
8865 return true;
8866
8867 if (!Ty->isFirstClassType())
8868 return error(TypeLoc, "phi node must have first class type");
8869
8870 bool First = true;
8871 bool AteExtraComma = false;
8873
8874 while (true) {
8875 if (First) {
8876 if (Lex.getKind() != lltok::lsquare)
8877 break;
8878 First = false;
8879 } else if (!EatIfPresent(lltok::comma))
8880 break;
8881
8882 if (Lex.getKind() == lltok::MetadataVar) {
8883 AteExtraComma = true;
8884 break;
8885 }
8886
8887 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8888 parseValue(Ty, Op0, PFS) ||
8889 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8890 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8891 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8892 return true;
8893
8894 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8895 }
8896
8897 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8898 for (const auto &[Val, BB] : PHIVals)
8899 PN->addIncoming(Val, BB);
8900 Inst = PN;
8901 return AteExtraComma ? InstExtraComma : InstNormal;
8902}
8903
8904/// parseLandingPad
8905/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8906/// Clause
8907/// ::= 'catch' TypeAndValue
8908/// ::= 'filter'
8909/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8910bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8911 Type *Ty = nullptr; LocTy TyLoc;
8912
8913 if (parseType(Ty, TyLoc))
8914 return true;
8915
8916 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8917 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8918
8919 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8921 if (EatIfPresent(lltok::kw_catch))
8923 else if (EatIfPresent(lltok::kw_filter))
8925 else
8926 return tokError("expected 'catch' or 'filter' clause type");
8927
8928 Value *V;
8929 LocTy VLoc;
8930 if (parseTypeAndValue(V, VLoc, PFS))
8931 return true;
8932
8933 // A 'catch' type expects a non-array constant. A filter clause expects an
8934 // array constant.
8935 if (CT == LandingPadInst::Catch) {
8936 if (isa<ArrayType>(V->getType()))
8937 return error(VLoc, "'catch' clause has an invalid type");
8938 } else {
8939 if (!isa<ArrayType>(V->getType()))
8940 return error(VLoc, "'filter' clause has an invalid type");
8941 }
8942
8944 if (!CV)
8945 return error(VLoc, "clause argument must be a constant");
8946 LP->addClause(CV);
8947 }
8948
8949 Inst = LP.release();
8950 return false;
8951}
8952
8953/// parseFreeze
8954/// ::= 'freeze' Type Value
8955bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8956 LocTy Loc;
8957 Value *Op;
8958 if (parseTypeAndValue(Op, Loc, PFS))
8959 return true;
8960
8961 Inst = new FreezeInst(Op);
8962 return false;
8963}
8964
8965/// parseCall
8966/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8967/// OptionalAttrs Type Value ParameterList OptionalAttrs
8968/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8969/// OptionalAttrs Type Value ParameterList OptionalAttrs
8970/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8971/// OptionalAttrs Type Value ParameterList OptionalAttrs
8972/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8973/// OptionalAttrs Type Value ParameterList OptionalAttrs
8974bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8976 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8977 std::vector<unsigned> FwdRefAttrGrps;
8978 LocTy BuiltinLoc;
8979 unsigned CallAddrSpace;
8980 unsigned CC;
8981 Type *RetType = nullptr;
8982 LocTy RetTypeLoc;
8983 ValID CalleeID;
8986 LocTy CallLoc = Lex.getLoc();
8987
8988 if (TCK != CallInst::TCK_None &&
8989 parseToken(lltok::kw_call,
8990 "expected 'tail call', 'musttail call', or 'notail call'"))
8991 return true;
8992
8993 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8994
8995 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8996 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8997 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8998 parseValID(CalleeID, &PFS) ||
8999 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
9000 PFS.getFunction().isVarArg()) ||
9001 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
9002 parseOptionalOperandBundles(BundleList, PFS))
9003 return true;
9004
9005 // If RetType is a non-function pointer type, then this is the short syntax
9006 // for the call, which means that RetType is just the return type. Infer the
9007 // rest of the function argument types from the arguments that are present.
9008 FunctionType *Ty;
9009 if (resolveFunctionType(RetType, ArgList, Ty))
9010 return error(RetTypeLoc, "Invalid result type for LLVM function");
9011
9012 CalleeID.FTy = Ty;
9013
9014 // Look up the callee.
9015 Value *Callee;
9016 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
9017 Callee, &PFS))
9018 return true;
9019
9020 // Set up the Attribute for the function.
9022
9023 SmallVector<Value*, 8> Args;
9024
9025 // Loop through FunctionType's arguments and ensure they are specified
9026 // correctly. Also, gather any parameter attributes.
9027 FunctionType::param_iterator I = Ty->param_begin();
9028 FunctionType::param_iterator E = Ty->param_end();
9029 for (const ParamInfo &Arg : ArgList) {
9030 Type *ExpectedTy = nullptr;
9031 if (I != E) {
9032 ExpectedTy = *I++;
9033 } else if (!Ty->isVarArg()) {
9034 return error(Arg.Loc, "too many arguments specified");
9035 }
9036
9037 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9038 return error(Arg.Loc, "argument is not of expected type '" +
9039 getTypeString(ExpectedTy) + "'");
9040 Args.push_back(Arg.V);
9041 Attrs.push_back(Arg.Attrs);
9042 }
9043
9044 if (I != E)
9045 return error(CallLoc, "not enough parameters specified for call");
9046
9047 // Finish off the Attribute and check them
9048 AttributeList PAL =
9049 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
9050 AttributeSet::get(Context, RetAttrs), Attrs);
9051
9052 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
9053 CI->setTailCallKind(TCK);
9054 CI->setCallingConv(CC);
9055 if (FMF.any()) {
9056 if (!isa<FPMathOperator>(CI)) {
9057 CI->deleteValue();
9058 return error(CallLoc, "fast-math-flags specified for call without "
9059 "floating-point scalar or vector return type");
9060 }
9061 CI->setFastMathFlags(FMF);
9062 }
9063
9064 if (CalleeID.Kind == ValID::t_GlobalName &&
9065 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
9066 if (SeenNewDbgInfoFormat) {
9067 CI->deleteValue();
9068 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
9069 "using non-intrinsic debug info");
9070 }
9071 SeenOldDbgInfoFormat = true;
9072 }
9073 CI->setAttributes(PAL);
9074 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9075 Inst = CI;
9076 return false;
9077}
9078
9079//===----------------------------------------------------------------------===//
9080// Memory Instructions.
9081//===----------------------------------------------------------------------===//
9082
9083/// parseAlloc
9084/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
9085/// (',' 'align' i32)? (',', 'addrspace(n))?
9086int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9087 Value *Size = nullptr;
9088 LocTy SizeLoc, TyLoc, ASLoc;
9089 MaybeAlign Alignment;
9090 unsigned AddrSpace = 0;
9091 Type *Ty = nullptr;
9092
9093 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9094 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9095
9096 if (parseType(Ty, TyLoc))
9097 return true;
9098
9100 return error(TyLoc, "invalid type for alloca");
9101
9102 bool AteExtraComma = false;
9103 if (EatIfPresent(lltok::comma)) {
9104 if (Lex.getKind() == lltok::kw_align) {
9105 if (parseOptionalAlignment(Alignment))
9106 return true;
9107 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9108 return true;
9109 } else if (Lex.getKind() == lltok::kw_addrspace) {
9110 ASLoc = Lex.getLoc();
9111 if (parseOptionalAddrSpace(AddrSpace))
9112 return true;
9113 } else if (Lex.getKind() == lltok::MetadataVar) {
9114 AteExtraComma = true;
9115 } else {
9116 if (parseTypeAndValue(Size, SizeLoc, PFS))
9117 return true;
9118 if (EatIfPresent(lltok::comma)) {
9119 if (Lex.getKind() == lltok::kw_align) {
9120 if (parseOptionalAlignment(Alignment))
9121 return true;
9122 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9123 return true;
9124 } else if (Lex.getKind() == lltok::kw_addrspace) {
9125 ASLoc = Lex.getLoc();
9126 if (parseOptionalAddrSpace(AddrSpace))
9127 return true;
9128 } else if (Lex.getKind() == lltok::MetadataVar) {
9129 AteExtraComma = true;
9130 }
9131 }
9132 }
9133 }
9134
9135 if (Size && !Size->getType()->isIntegerTy())
9136 return error(SizeLoc, "element count must have integer type");
9137
9138 if (!Alignment && !Ty->isSized())
9139 return error(TyLoc, "Cannot allocate unsized type");
9140 if (!Alignment)
9141 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9142 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
9143 AI->setUsedWithInAlloca(IsInAlloca);
9144 AI->setSwiftError(IsSwiftError);
9145 Inst = AI;
9146 return AteExtraComma ? InstExtraComma : InstNormal;
9147}
9148
9149/// parseLoad
9150/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
9151/// ::= 'load' 'atomic' 'volatile'? 'elementwise'? TypeAndValue
9152/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
9153int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9154 Value *Val; LocTy Loc;
9155 MaybeAlign Alignment;
9156 bool AteExtraComma = false;
9157 bool isAtomic = false;
9160
9161 if (Lex.getKind() == lltok::kw_atomic) {
9162 isAtomic = true;
9163 Lex.Lex();
9164 }
9165
9166 bool isVolatile = false;
9167 if (Lex.getKind() == lltok::kw_volatile) {
9168 isVolatile = true;
9169 Lex.Lex();
9170 }
9171
9172 bool IsElementwise = false;
9173 if (Lex.getKind() == lltok::kw_elementwise) {
9174 IsElementwise = true;
9175 Lex.Lex();
9176 }
9177
9178 Type *Ty;
9179 LocTy ExplicitTypeLoc = Lex.getLoc();
9180 if (parseType(Ty) ||
9181 parseToken(lltok::comma, "expected comma after load's type") ||
9182 parseTypeAndValue(Val, Loc, PFS) ||
9183 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9184 parseOptionalCommaAlign(Alignment, AteExtraComma))
9185 return true;
9186
9187 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
9188 return error(Loc, "load operand must be a pointer to a first class type");
9189
9190 if (IsElementwise && !isAtomic)
9191 return error(Loc, "elementwise load must be atomic");
9192
9193 if (IsElementwise && !isa<FixedVectorType>(Ty))
9194 return error(ExplicitTypeLoc,
9195 "atomic elementwise load operand must have fixed vector type");
9196
9197 if (isAtomic && !Alignment)
9198 return error(Loc, "atomic load must have explicit non-zero alignment");
9199
9200 if (Ordering == AtomicOrdering::Release ||
9202 return error(Loc, "atomic load cannot use Release ordering");
9203 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9204 return error(Loc,
9205 "atomic elementwise load cannot be sequentially consistent");
9206
9207 if (!Alignment && !Ty->isSized())
9208 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
9209 if (!Alignment)
9210 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9211 Inst = new LoadInst(Ty, Val, "",
9212 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9213 SSID, IsElementwise},
9214 /*InsertBefore=*/nullptr);
9215 return AteExtraComma ? InstExtraComma : InstNormal;
9216}
9217
9218/// parseStore
9219
9220/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
9221/// ::= 'store' 'atomic' 'volatile'? 'elementwise'? TypeAndValue ','
9222/// TypeAndValue 'singlethread'? AtomicOrdering (',' 'align' i32)?
9223int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9224 Value *Val, *Ptr;
9225 LocTy Loc, PtrLoc;
9226 MaybeAlign Alignment;
9227 bool AteExtraComma = false;
9228 bool isAtomic = false;
9231
9232 if (Lex.getKind() == lltok::kw_atomic) {
9233 isAtomic = true;
9234 Lex.Lex();
9235 }
9236
9237 bool isVolatile = false;
9238 if (Lex.getKind() == lltok::kw_volatile) {
9239 isVolatile = true;
9240 Lex.Lex();
9241 }
9242
9243 bool IsElementwise = false;
9244 if (Lex.getKind() == lltok::kw_elementwise) {
9245 IsElementwise = true;
9246 Lex.Lex();
9247 }
9248
9249 if (parseTypeAndValue(Val, Loc, PFS) ||
9250 parseToken(lltok::comma, "expected ',' after store operand") ||
9251 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9252 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9253 parseOptionalCommaAlign(Alignment, AteExtraComma))
9254 return true;
9255
9256 if (!Ptr->getType()->isPointerTy())
9257 return error(PtrLoc, "store operand must be a pointer");
9258 if (!Val->getType()->isFirstClassType())
9259 return error(Loc, "store operand must be a first class value");
9260 if (isAtomic && !Alignment)
9261 return error(Loc, "atomic store must have explicit non-zero alignment");
9262 if (Ordering == AtomicOrdering::Acquire ||
9264 return error(Loc, "atomic store cannot use Acquire ordering");
9265
9266 if (IsElementwise && !isAtomic)
9267 return error(Loc, "elementwise store must be atomic");
9268
9269 if (IsElementwise && !isa<FixedVectorType>(Val->getType()))
9270 return error(
9271 Loc, "atomic elementwise store operand must have fixed vector type");
9272
9273 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9274 return error(Loc,
9275 "atomic elementwise store cannot be sequentially consistent");
9276
9277 if (!Alignment && !Val->getType()->isSized())
9278 return error(Loc, "storing unsized types is not allowed");
9279 if (!Alignment)
9280 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9281
9282 Inst = new StoreInst(Val, Ptr,
9283 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9284 SSID, IsElementwise},
9285 /*InsertBefore=*/nullptr);
9286 return AteExtraComma ? InstExtraComma : InstNormal;
9287}
9288
9289/// parseCmpXchg
9290/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9291/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9292/// 'Align'?
9293int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9294 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9295 bool AteExtraComma = false;
9296 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9297 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9299 bool isVolatile = false;
9300 bool isWeak = false;
9301 MaybeAlign Alignment;
9302
9303 if (EatIfPresent(lltok::kw_weak))
9304 isWeak = true;
9305
9306 if (EatIfPresent(lltok::kw_volatile))
9307 isVolatile = true;
9308
9309 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9310 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9311 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9312 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9313 parseTypeAndValue(New, NewLoc, PFS) ||
9314 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9315 parseOrdering(FailureOrdering) ||
9316 parseOptionalCommaAlign(Alignment, AteExtraComma))
9317 return true;
9318
9319 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9320 return tokError("invalid cmpxchg success ordering");
9321 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9322 return tokError("invalid cmpxchg failure ordering");
9323 if (!Ptr->getType()->isPointerTy())
9324 return error(PtrLoc, "cmpxchg operand must be a pointer");
9325 if (Cmp->getType() != New->getType())
9326 return error(NewLoc, "compare value and new value type do not match");
9327 if (!New->getType()->isFirstClassType())
9328 return error(NewLoc, "cmpxchg operand must be a first class value");
9329
9330 const Align DefaultAlignment(
9331 PFS.getFunction().getDataLayout().getTypeStoreSize(
9332 Cmp->getType()));
9333
9334 AtomicCmpXchgInst *CXI =
9335 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9336 SuccessOrdering, FailureOrdering, SSID);
9337 CXI->setVolatile(isVolatile);
9338 CXI->setWeak(isWeak);
9339
9340 Inst = CXI;
9341 return AteExtraComma ? InstExtraComma : InstNormal;
9342}
9343
9344/// parseAtomicRMW
9345/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9346/// TypeAndValue
9347/// 'singlethread'? AtomicOrdering
9348int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9349 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9350 bool AteExtraComma = false;
9353 bool IsVolatile = false;
9354 bool IsElementwise = false;
9355 bool IsFP = false;
9357 MaybeAlign Alignment;
9358
9359 if (EatIfPresent(lltok::kw_volatile))
9360 IsVolatile = true;
9361 if (EatIfPresent(lltok::kw_elementwise))
9362 IsElementwise = true;
9363
9364 switch (Lex.getKind()) {
9365 default:
9366 return tokError("expected binary operation in atomicrmw");
9380 break;
9383 break;
9386 break;
9387 case lltok::kw_usub_sat:
9389 break;
9390 case lltok::kw_fadd:
9392 IsFP = true;
9393 break;
9394 case lltok::kw_fsub:
9396 IsFP = true;
9397 break;
9398 case lltok::kw_fmax:
9400 IsFP = true;
9401 break;
9402 case lltok::kw_fmin:
9404 IsFP = true;
9405 break;
9406 case lltok::kw_fmaximum:
9408 IsFP = true;
9409 break;
9410 case lltok::kw_fminimum:
9412 IsFP = true;
9413 break;
9416 IsFP = true;
9417 break;
9420 IsFP = true;
9421 break;
9422 }
9423 Lex.Lex(); // Eat the operation.
9424
9425 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9426 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9427 parseTypeAndValue(Val, ValLoc, PFS) ||
9428 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9429 parseOptionalCommaAlign(Alignment, AteExtraComma))
9430 return true;
9431
9432 if (Ordering == AtomicOrdering::Unordered)
9433 return tokError("atomicrmw cannot be unordered");
9434 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9435 return tokError("atomicrmw elementwise cannot be sequentially consistent");
9436 if (!Ptr->getType()->isPointerTy())
9437 return error(PtrLoc, "atomicrmw operand must be a pointer");
9438 if (Val->getType()->isScalableTy())
9439 return error(ValLoc, "atomicrmw operand may not be scalable");
9440
9441 Type *ValTy = Val->getType();
9442 if (IsElementwise) {
9443 if (!isa<FixedVectorType>(Val->getType()))
9444 return error(ValLoc,
9445 "atomicrmw elementwise operand must be a fixed vector type");
9446 }
9447
9449 if (!ValTy->isIntOrIntVectorTy() && !ValTy->isFPOrFPVectorTy() &&
9450 !ValTy->isPtrOrPtrVectorTy()) {
9451 return error(
9452 ValLoc,
9454 " operand must be an integer type, a floating-point type, a "
9455 "pointer type, or a fixed vector of any of these types");
9456 }
9457 } else if (IsFP) {
9458 if (!ValTy->isFPOrFPVectorTy()) {
9459 return error(ValLoc, "atomicrmw " +
9461 " operand must be a floating point or fixed "
9462 "vector of floating point type");
9463 }
9464 } else {
9465 if (!ValTy->isIntOrIntVectorTy()) {
9466 return error(
9467 ValLoc,
9469 " operand must be an integer or fixed vector of integer type");
9470 }
9471 }
9472
9473 unsigned Size =
9474 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9475 if (Size < 8 || (Size & (Size - 1)))
9476 return error(ValLoc,
9477 "atomicrmw operand must have a power-of-two byte size");
9478 const Align DefaultAlignment(
9479 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9480 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9481 Alignment.value_or(DefaultAlignment),
9482 Ordering, SSID, IsElementwise);
9483 RMWI->setVolatile(IsVolatile);
9484 Inst = RMWI;
9485 return AteExtraComma ? InstExtraComma : InstNormal;
9486}
9487
9488/// parseFence
9489/// ::= 'fence' 'singlethread'? AtomicOrdering
9490int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9493 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9494 return true;
9495
9496 if (Ordering == AtomicOrdering::Unordered)
9497 return tokError("fence cannot be unordered");
9498 if (Ordering == AtomicOrdering::Monotonic)
9499 return tokError("fence cannot be monotonic");
9500
9501 Inst = new FenceInst(Context, Ordering, SSID);
9502 return InstNormal;
9503}
9504
9505/// parseGetElementPtr
9506/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9507int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9508 Value *Ptr = nullptr;
9509 Value *Val = nullptr;
9510 LocTy Loc, EltLoc;
9511 GEPNoWrapFlags NW;
9512
9513 while (true) {
9514 if (EatIfPresent(lltok::kw_inbounds))
9516 else if (EatIfPresent(lltok::kw_nusw))
9518 else if (EatIfPresent(lltok::kw_nuw))
9520 else
9521 break;
9522 }
9523
9524 Type *Ty = nullptr;
9525 if (parseType(Ty) ||
9526 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9527 parseTypeAndValue(Ptr, Loc, PFS))
9528 return true;
9529
9530 Type *BaseType = Ptr->getType();
9531 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9532 if (!BasePointerType)
9533 return error(Loc, "base of getelementptr must be a pointer");
9534
9535 SmallVector<Value*, 16> Indices;
9536 bool AteExtraComma = false;
9537 // GEP returns a vector of pointers if at least one of parameters is a vector.
9538 // All vector parameters should have the same vector width.
9539 ElementCount GEPWidth = BaseType->isVectorTy()
9540 ? cast<VectorType>(BaseType)->getElementCount()
9542
9543 while (EatIfPresent(lltok::comma)) {
9544 if (Lex.getKind() == lltok::MetadataVar) {
9545 AteExtraComma = true;
9546 break;
9547 }
9548 if (parseTypeAndValue(Val, EltLoc, PFS))
9549 return true;
9550 if (!Val->getType()->isIntOrIntVectorTy())
9551 return error(EltLoc, "getelementptr index must be an integer");
9552
9553 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9554 ElementCount ValNumEl = ValVTy->getElementCount();
9555 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9556 return error(
9557 EltLoc,
9558 "getelementptr vector index has a wrong number of elements");
9559 GEPWidth = ValNumEl;
9560 }
9561 Indices.push_back(Val);
9562 }
9563
9564 if (!Indices.empty() && !Ty->isSized())
9565 return error(Loc, "base element of getelementptr must be sized");
9566
9567 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9568 return error(Loc, "invalid getelementptr indices");
9569 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9570 Inst = GEP;
9571 GEP->setNoWrapFlags(NW);
9572 return AteExtraComma ? InstExtraComma : InstNormal;
9573}
9574
9575/// parseExtractValue
9576/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9577int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9578 Value *Val; LocTy Loc;
9579 SmallVector<unsigned, 4> Indices;
9580 bool AteExtraComma;
9581 if (parseTypeAndValue(Val, Loc, PFS) ||
9582 parseIndexList(Indices, AteExtraComma))
9583 return true;
9584
9585 if (!Val->getType()->isAggregateType())
9586 return error(Loc, "extractvalue operand must be aggregate type");
9587
9588 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9589 return error(Loc, "invalid indices for extractvalue");
9590 Inst = ExtractValueInst::Create(Val, Indices);
9591 return AteExtraComma ? InstExtraComma : InstNormal;
9592}
9593
9594/// parseInsertValue
9595/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9596int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9597 Value *Val0, *Val1; LocTy Loc0, Loc1;
9598 SmallVector<unsigned, 4> Indices;
9599 bool AteExtraComma;
9600 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9601 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9602 parseTypeAndValue(Val1, Loc1, PFS) ||
9603 parseIndexList(Indices, AteExtraComma))
9604 return true;
9605
9606 if (!Val0->getType()->isAggregateType())
9607 return error(Loc0, "insertvalue operand must be aggregate type");
9608
9609 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9610 if (!IndexedType)
9611 return error(Loc0, "invalid indices for insertvalue");
9612 if (IndexedType != Val1->getType())
9613 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9614 getTypeString(Val1->getType()) + "' instead of '" +
9615 getTypeString(IndexedType) + "'");
9616 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9617 return AteExtraComma ? InstExtraComma : InstNormal;
9618}
9619
9620//===----------------------------------------------------------------------===//
9621// Embedded metadata.
9622//===----------------------------------------------------------------------===//
9623
9624/// parseMDNodeVector
9625/// ::= { Element (',' Element)* }
9626/// Element
9627/// ::= 'null' | Metadata
9628bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9629 if (parseToken(lltok::lbrace, "expected '{' here"))
9630 return true;
9631
9632 // Check for an empty list.
9633 if (EatIfPresent(lltok::rbrace))
9634 return false;
9635
9636 do {
9637 if (EatIfPresent(lltok::kw_null)) {
9638 Elts.push_back(nullptr);
9639 continue;
9640 }
9641
9642 Metadata *MD;
9643 if (parseMetadata(MD, nullptr))
9644 return true;
9645 Elts.push_back(MD);
9646 } while (EatIfPresent(lltok::comma));
9647
9648 return parseToken(lltok::rbrace, "expected end of metadata node");
9649}
9650
9651//===----------------------------------------------------------------------===//
9652// Use-list order directives.
9653//===----------------------------------------------------------------------===//
9654bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9655 SMLoc Loc) {
9656 if (!V->hasUseList())
9657 return false;
9658 if (V->use_empty())
9659 return error(Loc, "value has no uses");
9660
9661 unsigned NumUses = 0;
9662 SmallDenseMap<const Use *, unsigned, 16> Order;
9663 for (const Use &U : V->uses()) {
9664 if (++NumUses > Indexes.size())
9665 break;
9666 Order[&U] = Indexes[NumUses - 1];
9667 }
9668 if (NumUses < 2)
9669 return error(Loc, "value only has one use");
9670 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9671 return error(Loc,
9672 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9673
9674 V->sortUseList([&](const Use &L, const Use &R) {
9675 return Order.lookup(&L) < Order.lookup(&R);
9676 });
9677 return false;
9678}
9679
9680/// parseUseListOrderIndexes
9681/// ::= '{' uint32 (',' uint32)+ '}'
9682bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9683 SMLoc Loc = Lex.getLoc();
9684 if (parseToken(lltok::lbrace, "expected '{' here"))
9685 return true;
9686 if (Lex.getKind() == lltok::rbrace)
9687 return tokError("expected non-empty list of uselistorder indexes");
9688
9689 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9690 // indexes should be distinct numbers in the range [0, size-1], and should
9691 // not be in order.
9692 unsigned Offset = 0;
9693 unsigned Max = 0;
9694 bool IsOrdered = true;
9695 assert(Indexes.empty() && "Expected empty order vector");
9696 do {
9697 unsigned Index;
9698 if (parseUInt32(Index))
9699 return true;
9700
9701 // Update consistency checks.
9702 Offset += Index - Indexes.size();
9703 Max = std::max(Max, Index);
9704 IsOrdered &= Index == Indexes.size();
9705
9706 Indexes.push_back(Index);
9707 } while (EatIfPresent(lltok::comma));
9708
9709 if (parseToken(lltok::rbrace, "expected '}' here"))
9710 return true;
9711
9712 if (Indexes.size() < 2)
9713 return error(Loc, "expected >= 2 uselistorder indexes");
9714 if (Offset != 0 || Max >= Indexes.size())
9715 return error(Loc,
9716 "expected distinct uselistorder indexes in range [0, size)");
9717 if (IsOrdered)
9718 return error(Loc, "expected uselistorder indexes to change the order");
9719
9720 return false;
9721}
9722
9723/// parseUseListOrder
9724/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9725bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9726 SMLoc Loc = Lex.getLoc();
9727 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9728 return true;
9729
9730 Value *V;
9731 SmallVector<unsigned, 16> Indexes;
9732 if (parseTypeAndValue(V, PFS) ||
9733 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9734 parseUseListOrderIndexes(Indexes))
9735 return true;
9736
9737 return sortUseListOrder(V, Indexes, Loc);
9738}
9739
9740/// ModuleEntry
9741/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9742/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9743bool LLParser::parseModuleEntry(unsigned ID) {
9744 assert(Lex.getKind() == lltok::kw_module);
9745 Lex.Lex();
9746
9747 std::string Path;
9748 if (parseToken(lltok::colon, "expected ':' here") ||
9749 parseToken(lltok::lparen, "expected '(' here") ||
9750 parseToken(lltok::kw_path, "expected 'path' here") ||
9751 parseToken(lltok::colon, "expected ':' here") ||
9752 parseStringConstant(Path) ||
9753 parseToken(lltok::comma, "expected ',' here") ||
9754 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9755 parseToken(lltok::colon, "expected ':' here") ||
9756 parseToken(lltok::lparen, "expected '(' here"))
9757 return true;
9758
9759 ModuleHash Hash;
9760 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9761 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9762 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9763 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9764 parseUInt32(Hash[4]))
9765 return true;
9766
9767 if (parseToken(lltok::rparen, "expected ')' here") ||
9768 parseToken(lltok::rparen, "expected ')' here"))
9769 return true;
9770
9771 auto ModuleEntry = Index->addModule(Path, Hash);
9772 ModuleIdMap[ID] = ModuleEntry->first();
9773
9774 return false;
9775}
9776
9777/// TypeIdEntry
9778/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9779bool LLParser::parseTypeIdEntry(unsigned ID) {
9780 assert(Lex.getKind() == lltok::kw_typeid);
9781 Lex.Lex();
9782
9783 std::string Name;
9784 if (parseToken(lltok::colon, "expected ':' here") ||
9785 parseToken(lltok::lparen, "expected '(' here") ||
9786 parseToken(lltok::kw_name, "expected 'name' here") ||
9787 parseToken(lltok::colon, "expected ':' here") ||
9788 parseStringConstant(Name))
9789 return true;
9790
9791 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9792 if (parseToken(lltok::comma, "expected ',' here") ||
9793 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9794 return true;
9795
9796 // Check if this ID was forward referenced, and if so, update the
9797 // corresponding GUIDs.
9798 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9799 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9800 for (auto TIDRef : FwdRefTIDs->second) {
9801 assert(!*TIDRef.first &&
9802 "Forward referenced type id GUID expected to be 0");
9803 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9804 }
9805 ForwardRefTypeIds.erase(FwdRefTIDs);
9806 }
9807
9808 return false;
9809}
9810
9811/// TypeIdSummary
9812/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9813bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9814 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9815 parseToken(lltok::colon, "expected ':' here") ||
9816 parseToken(lltok::lparen, "expected '(' here") ||
9817 parseTypeTestResolution(TIS.TTRes))
9818 return true;
9819
9820 if (EatIfPresent(lltok::comma)) {
9821 // Expect optional wpdResolutions field
9822 if (parseOptionalWpdResolutions(TIS.WPDRes))
9823 return true;
9824 }
9825
9826 if (parseToken(lltok::rparen, "expected ')' here"))
9827 return true;
9828
9829 return false;
9830}
9831
9834
9835/// TypeIdCompatibleVtableEntry
9836/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9837/// TypeIdCompatibleVtableInfo
9838/// ')'
9839bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9841 Lex.Lex();
9842
9843 std::string Name;
9844 if (parseToken(lltok::colon, "expected ':' here") ||
9845 parseToken(lltok::lparen, "expected '(' here") ||
9846 parseToken(lltok::kw_name, "expected 'name' here") ||
9847 parseToken(lltok::colon, "expected ':' here") ||
9848 parseStringConstant(Name))
9849 return true;
9850
9852 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9853 if (parseToken(lltok::comma, "expected ',' here") ||
9854 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9855 parseToken(lltok::colon, "expected ':' here") ||
9856 parseToken(lltok::lparen, "expected '(' here"))
9857 return true;
9858
9859 IdToIndexMapType IdToIndexMap;
9860 // parse each call edge
9861 do {
9863 if (parseToken(lltok::lparen, "expected '(' here") ||
9864 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9865 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9866 parseToken(lltok::comma, "expected ',' here"))
9867 return true;
9868
9869 LocTy Loc = Lex.getLoc();
9870 unsigned GVId;
9871 ValueInfo VI;
9872 if (parseGVReference(VI, GVId))
9873 return true;
9874
9875 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9876 // forward reference. We will save the location of the ValueInfo needing an
9877 // update, but can only do so once the std::vector is finalized.
9878 if (VI == EmptyVI)
9879 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9880 TI.push_back({Offset, VI});
9881
9882 if (parseToken(lltok::rparen, "expected ')' in call"))
9883 return true;
9884 } while (EatIfPresent(lltok::comma));
9885
9886 // Now that the TI vector is finalized, it is safe to save the locations
9887 // of any forward GV references that need updating later.
9888 for (auto I : IdToIndexMap) {
9889 auto &Infos = ForwardRefValueInfos[I.first];
9890 for (auto P : I.second) {
9891 assert(TI[P.first].VTableVI == EmptyVI &&
9892 "Forward referenced ValueInfo expected to be empty");
9893 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9894 }
9895 }
9896
9897 if (parseToken(lltok::rparen, "expected ')' here") ||
9898 parseToken(lltok::rparen, "expected ')' here"))
9899 return true;
9900
9901 // Check if this ID was forward referenced, and if so, update the
9902 // corresponding GUIDs.
9903 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9904 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9905 for (auto TIDRef : FwdRefTIDs->second) {
9906 assert(!*TIDRef.first &&
9907 "Forward referenced type id GUID expected to be 0");
9908 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9909 }
9910 ForwardRefTypeIds.erase(FwdRefTIDs);
9911 }
9912
9913 return false;
9914}
9915
9916/// TypeTestResolution
9917/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9918/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9919/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9920/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9921/// [',' 'inlinesBits' ':' UInt64]? ')'
9922bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9923 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9924 parseToken(lltok::colon, "expected ':' here") ||
9925 parseToken(lltok::lparen, "expected '(' here") ||
9926 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9927 parseToken(lltok::colon, "expected ':' here"))
9928 return true;
9929
9930 switch (Lex.getKind()) {
9931 case lltok::kw_unknown:
9933 break;
9934 case lltok::kw_unsat:
9936 break;
9939 break;
9940 case lltok::kw_inline:
9942 break;
9943 case lltok::kw_single:
9945 break;
9946 case lltok::kw_allOnes:
9948 break;
9949 default:
9950 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9951 }
9952 Lex.Lex();
9953
9954 if (parseToken(lltok::comma, "expected ',' here") ||
9955 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9956 parseToken(lltok::colon, "expected ':' here") ||
9957 parseUInt32(TTRes.SizeM1BitWidth))
9958 return true;
9959
9960 // parse optional fields
9961 while (EatIfPresent(lltok::comma)) {
9962 switch (Lex.getKind()) {
9964 Lex.Lex();
9965 if (parseToken(lltok::colon, "expected ':'") ||
9966 parseUInt64(TTRes.AlignLog2))
9967 return true;
9968 break;
9969 case lltok::kw_sizeM1:
9970 Lex.Lex();
9971 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9972 return true;
9973 break;
9974 case lltok::kw_bitMask: {
9975 unsigned Val;
9976 Lex.Lex();
9977 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9978 return true;
9979 assert(Val <= 0xff);
9980 TTRes.BitMask = (uint8_t)Val;
9981 break;
9982 }
9984 Lex.Lex();
9985 if (parseToken(lltok::colon, "expected ':'") ||
9986 parseUInt64(TTRes.InlineBits))
9987 return true;
9988 break;
9989 default:
9990 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9991 }
9992 }
9993
9994 if (parseToken(lltok::rparen, "expected ')' here"))
9995 return true;
9996
9997 return false;
9998}
9999
10000/// OptionalWpdResolutions
10001/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
10002/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
10003bool LLParser::parseOptionalWpdResolutions(
10004 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10005 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
10006 parseToken(lltok::colon, "expected ':' here") ||
10007 parseToken(lltok::lparen, "expected '(' here"))
10008 return true;
10009
10010 do {
10012 WholeProgramDevirtResolution WPDRes;
10013 if (parseToken(lltok::lparen, "expected '(' here") ||
10014 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10015 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
10016 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
10017 parseToken(lltok::rparen, "expected ')' here"))
10018 return true;
10019 WPDResMap[Offset] = WPDRes;
10020 } while (EatIfPresent(lltok::comma));
10021
10022 if (parseToken(lltok::rparen, "expected ')' here"))
10023 return true;
10024
10025 return false;
10026}
10027
10028/// WpdRes
10029/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
10030/// [',' OptionalResByArg]? ')'
10031/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
10032/// ',' 'singleImplName' ':' STRINGCONSTANT ','
10033/// [',' OptionalResByArg]? ')'
10034/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
10035/// [',' OptionalResByArg]? ')'
10036bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10037 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
10038 parseToken(lltok::colon, "expected ':' here") ||
10039 parseToken(lltok::lparen, "expected '(' here") ||
10040 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10041 parseToken(lltok::colon, "expected ':' here"))
10042 return true;
10043
10044 switch (Lex.getKind()) {
10045 case lltok::kw_indir:
10047 break;
10050 break;
10053 break;
10056 break;
10057 default:
10058 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
10059 }
10060 Lex.Lex();
10061
10062 // parse optional fields
10063 while (EatIfPresent(lltok::comma)) {
10064 switch (Lex.getKind()) {
10066 Lex.Lex();
10067 if (parseToken(lltok::colon, "expected ':' here") ||
10068 parseStringConstant(WPDRes.SingleImplName))
10069 return true;
10070 break;
10071 case lltok::kw_resByArg:
10072 if (parseOptionalResByArg(WPDRes.ResByArg))
10073 return true;
10074 break;
10075 default:
10076 return error(Lex.getLoc(),
10077 "expected optional WholeProgramDevirtResolution field");
10078 }
10079 }
10080
10081 if (parseToken(lltok::rparen, "expected ')' here"))
10082 return true;
10083
10084 return false;
10085}
10086
10087/// OptionalResByArg
10088/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
10089/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
10090/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
10091/// 'virtualConstProp' )
10092/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
10093/// [',' 'bit' ':' UInt32]? ')'
10094bool LLParser::parseOptionalResByArg(
10095 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10096 &ResByArg) {
10097 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
10098 parseToken(lltok::colon, "expected ':' here") ||
10099 parseToken(lltok::lparen, "expected '(' here"))
10100 return true;
10101
10102 do {
10103 std::vector<uint64_t> Args;
10104 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
10105 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
10106 parseToken(lltok::colon, "expected ':' here") ||
10107 parseToken(lltok::lparen, "expected '(' here") ||
10108 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10109 parseToken(lltok::colon, "expected ':' here"))
10110 return true;
10111
10112 WholeProgramDevirtResolution::ByArg ByArg;
10113 switch (Lex.getKind()) {
10114 case lltok::kw_indir:
10116 break;
10119 break;
10122 break;
10125 break;
10126 default:
10127 return error(Lex.getLoc(),
10128 "unexpected WholeProgramDevirtResolution::ByArg kind");
10129 }
10130 Lex.Lex();
10131
10132 // parse optional fields
10133 while (EatIfPresent(lltok::comma)) {
10134 switch (Lex.getKind()) {
10135 case lltok::kw_info:
10136 Lex.Lex();
10137 if (parseToken(lltok::colon, "expected ':' here") ||
10138 parseUInt64(ByArg.Info))
10139 return true;
10140 break;
10141 case lltok::kw_byte:
10142 Lex.Lex();
10143 if (parseToken(lltok::colon, "expected ':' here") ||
10144 parseUInt32(ByArg.Byte))
10145 return true;
10146 break;
10147 case lltok::kw_bit:
10148 Lex.Lex();
10149 if (parseToken(lltok::colon, "expected ':' here") ||
10150 parseUInt32(ByArg.Bit))
10151 return true;
10152 break;
10153 default:
10154 return error(Lex.getLoc(),
10155 "expected optional whole program devirt field");
10156 }
10157 }
10158
10159 if (parseToken(lltok::rparen, "expected ')' here"))
10160 return true;
10161
10162 ResByArg[Args] = ByArg;
10163 } while (EatIfPresent(lltok::comma));
10164
10165 if (parseToken(lltok::rparen, "expected ')' here"))
10166 return true;
10167
10168 return false;
10169}
10170
10171/// OptionalResByArg
10172/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
10173bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10174 if (parseToken(lltok::kw_args, "expected 'args' here") ||
10175 parseToken(lltok::colon, "expected ':' here") ||
10176 parseToken(lltok::lparen, "expected '(' here"))
10177 return true;
10178
10179 do {
10180 uint64_t Val;
10181 if (parseUInt64(Val))
10182 return true;
10183 Args.push_back(Val);
10184 } while (EatIfPresent(lltok::comma));
10185
10186 if (parseToken(lltok::rparen, "expected ')' here"))
10187 return true;
10188
10189 return false;
10190}
10191
10193
10194static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
10195 bool ReadOnly = Fwd->isReadOnly();
10196 bool WriteOnly = Fwd->isWriteOnly();
10197 assert(!(ReadOnly && WriteOnly));
10198 *Fwd = Resolved;
10199 if (ReadOnly)
10200 Fwd->setReadOnly();
10201 if (WriteOnly)
10202 Fwd->setWriteOnly();
10203}
10204
10205/// Stores the given Name/GUID and associated summary into the Index.
10206/// Also updates any forward references to the associated entry ID.
10207bool LLParser::addGlobalValueToIndex(
10208 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
10209 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
10210 // First create the ValueInfo utilizing the Name or GUID.
10211 ValueInfo VI;
10212 if (GUID != 0) {
10213 assert(Name.empty());
10214 VI = Index->getOrInsertValueInfo(GUID);
10215 } else {
10216 assert(!Name.empty());
10217 if (M) {
10218 auto *GV = M->getNamedValue(Name);
10219 if (!GV)
10220 return error(Loc, "Reference to undefined global \"" + Name + "\"");
10221
10222 // Be a little lenient here, to accomodate older files without GUIDs
10223 // already computed and assigned as metadata.
10224 GUID = GV->getGUIDOrFallback();
10225
10226 VI = Index->getOrInsertValueInfo(GV, GUID);
10227 } else {
10228 assert(
10229 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
10230 "Need a source_filename to compute GUID for local");
10232 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
10233 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10234 }
10235 }
10236
10237 // Resolve forward references from calls/refs
10238 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10239 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10240 for (auto VIRef : FwdRefVIs->second) {
10241 assert(VIRef.first->getRef() == FwdVIRef &&
10242 "Forward referenced ValueInfo expected to be empty");
10243 resolveFwdRef(VIRef.first, VI);
10244 }
10245 ForwardRefValueInfos.erase(FwdRefVIs);
10246 }
10247
10248 // Resolve forward references from aliases
10249 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10250 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10251 for (auto AliaseeRef : FwdRefAliasees->second) {
10252 assert(!AliaseeRef.first->hasAliasee() &&
10253 "Forward referencing alias already has aliasee");
10254 assert(Summary && "Aliasee must be a definition");
10255 AliaseeRef.first->setAliasee(VI, Summary.get());
10256 }
10257 ForwardRefAliasees.erase(FwdRefAliasees);
10258 }
10259
10260 // Add the summary if one was provided.
10261 if (Summary)
10262 Index->addGlobalValueSummary(VI, std::move(Summary));
10263
10264 // Save the associated ValueInfo for use in later references by ID.
10265 if (ID == NumberedValueInfos.size())
10266 NumberedValueInfos.push_back(VI);
10267 else {
10268 // Handle non-continuous numbers (to make test simplification easier).
10269 if (ID > NumberedValueInfos.size())
10270 NumberedValueInfos.resize(ID + 1);
10271 NumberedValueInfos[ID] = VI;
10272 }
10273
10274 return false;
10275}
10276
10277/// parseSummaryIndexFlags
10278/// ::= 'flags' ':' UInt64
10279bool LLParser::parseSummaryIndexFlags() {
10280 assert(Lex.getKind() == lltok::kw_flags);
10281 Lex.Lex();
10282
10283 if (parseToken(lltok::colon, "expected ':' here"))
10284 return true;
10286 if (parseUInt64(Flags))
10287 return true;
10288 if (Index)
10289 Index->setFlags(Flags);
10290 return false;
10291}
10292
10293/// parseBlockCount
10294/// ::= 'blockcount' ':' UInt64
10295bool LLParser::parseBlockCount() {
10296 assert(Lex.getKind() == lltok::kw_blockcount);
10297 Lex.Lex();
10298
10299 if (parseToken(lltok::colon, "expected ':' here"))
10300 return true;
10301 uint64_t BlockCount;
10302 if (parseUInt64(BlockCount))
10303 return true;
10304 if (Index)
10305 Index->setBlockCount(BlockCount);
10306 return false;
10307}
10308
10309/// parseCfiFunctions
10310/// ::= ('cfiFunctionDefs' | 'cfiFunctionDecls') ':' '(' CfiFunction
10311/// [',' CfiFunction]* ')'
10312/// CfiFunction ::= '(' 'guid' ':' UInt64 ',' 'name' ':' STRINGCONSTANT ')'
10313bool LLParser::parseCfiFunctions() {
10314 assert(Lex.getKind() == lltok::kw_cfiFunctionDefs ||
10315 Lex.getKind() == lltok::kw_cfiFunctionDecls);
10316 CfiFunctionIndex &CfiIndex = Lex.getKind() == lltok::kw_cfiFunctionDefs
10317 ? Index->cfiFunctionDefs()
10318 : Index->cfiFunctionDecls();
10319 Lex.Lex();
10320
10321 if (parseToken(lltok::colon, "expected ':' here") ||
10322 parseToken(lltok::lparen, "expected '(' here"))
10323 return true;
10324
10325 do {
10327 std::string Name;
10328 if (parseToken(lltok::lparen, "expected '(' here") ||
10329 parseToken(lltok::kw_guid, "expected 'guid' here") ||
10330 parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID) ||
10331 parseToken(lltok::comma, "expected ',' here") ||
10332 parseToken(lltok::kw_name, "expected 'name' here") ||
10333 parseToken(lltok::colon, "expected ':' here") ||
10334 parseStringConstant(Name) ||
10335 parseToken(lltok::rparen, "expected ')' here"))
10336 return true;
10337 CfiIndex.addSymbolWithThinLTOGUID(Name, GUID);
10338 } while (EatIfPresent(lltok::comma));
10339
10340 return parseToken(lltok::rparen, "expected ')' here");
10341}
10342
10343/// parseGVEntry
10344/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10345/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10346/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10347bool LLParser::parseGVEntry(unsigned ID) {
10348 assert(Lex.getKind() == lltok::kw_gv);
10349 Lex.Lex();
10350
10351 if (parseToken(lltok::colon, "expected ':' here") ||
10352 parseToken(lltok::lparen, "expected '(' here"))
10353 return true;
10354
10355 LocTy Loc = Lex.getLoc();
10356 std::string Name;
10358 switch (Lex.getKind()) {
10359 case lltok::kw_name:
10360 Lex.Lex();
10361 if (parseToken(lltok::colon, "expected ':' here") ||
10362 parseStringConstant(Name))
10363 return true;
10364 // Can't create GUID/ValueInfo until we have the linkage.
10365 break;
10366 case lltok::kw_guid:
10367 Lex.Lex();
10368 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10369 return true;
10370 break;
10371 default:
10372 return error(Lex.getLoc(), "expected name or guid tag");
10373 }
10374
10375 if (!EatIfPresent(lltok::comma)) {
10376 // No summaries. Wrap up.
10377 if (parseToken(lltok::rparen, "expected ')' here"))
10378 return true;
10379 // This was created for a call to an external or indirect target.
10380 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10381 // created for indirect calls with VP. A Name with no GUID came from
10382 // an external definition. We pass ExternalLinkage since that is only
10383 // used when the GUID must be computed from Name, and in that case
10384 // the symbol must have external linkage.
10385 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10386 nullptr, Loc);
10387 }
10388
10389 // Have a list of summaries
10390 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10391 parseToken(lltok::colon, "expected ':' here") ||
10392 parseToken(lltok::lparen, "expected '(' here"))
10393 return true;
10394 do {
10395 switch (Lex.getKind()) {
10396 case lltok::kw_function:
10397 if (parseFunctionSummary(Name, GUID, ID))
10398 return true;
10399 break;
10400 case lltok::kw_variable:
10401 if (parseVariableSummary(Name, GUID, ID))
10402 return true;
10403 break;
10404 case lltok::kw_alias:
10405 if (parseAliasSummary(Name, GUID, ID))
10406 return true;
10407 break;
10408 default:
10409 return error(Lex.getLoc(), "expected summary type");
10410 }
10411 } while (EatIfPresent(lltok::comma));
10412
10413 if (parseToken(lltok::rparen, "expected ')' here") ||
10414 parseToken(lltok::rparen, "expected ')' here"))
10415 return true;
10416
10417 return false;
10418}
10419
10420/// FunctionSummary
10421/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10422/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10423/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10424/// [',' OptionalRefs]? ')'
10425bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10426 unsigned ID) {
10427 LocTy Loc = Lex.getLoc();
10428 assert(Lex.getKind() == lltok::kw_function);
10429 Lex.Lex();
10430
10431 StringRef ModulePath;
10432 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10434 /*NotEligibleToImport=*/false,
10435 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10436 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10437 unsigned InstCount;
10439 FunctionSummary::TypeIdInfo TypeIdInfo;
10440 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10442 std::vector<CallsiteInfo> Callsites;
10443 std::vector<AllocInfo> Allocs;
10444 // Default is all-zeros (conservative values).
10445 FunctionSummary::FFlags FFlags = {};
10446 if (parseToken(lltok::colon, "expected ':' here") ||
10447 parseToken(lltok::lparen, "expected '(' here") ||
10448 parseModuleReference(ModulePath) ||
10449 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10450 parseToken(lltok::comma, "expected ',' here") ||
10451 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10452 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10453 return true;
10454
10455 // parse optional fields
10456 while (EatIfPresent(lltok::comma)) {
10457 switch (Lex.getKind()) {
10459 if (parseOptionalFFlags(FFlags))
10460 return true;
10461 break;
10462 case lltok::kw_calls:
10463 if (parseOptionalCalls(Calls))
10464 return true;
10465 break;
10467 if (parseOptionalTypeIdInfo(TypeIdInfo))
10468 return true;
10469 break;
10470 case lltok::kw_refs:
10471 if (parseOptionalRefs(Refs))
10472 return true;
10473 break;
10474 case lltok::kw_params:
10475 if (parseOptionalParamAccesses(ParamAccesses))
10476 return true;
10477 break;
10478 case lltok::kw_allocs:
10479 if (parseOptionalAllocs(Allocs))
10480 return true;
10481 break;
10483 if (parseOptionalCallsites(Callsites))
10484 return true;
10485 break;
10486 default:
10487 return error(Lex.getLoc(), "expected optional function summary field");
10488 }
10489 }
10490
10491 if (parseToken(lltok::rparen, "expected ')' here"))
10492 return true;
10493
10494 auto FS = std::make_unique<FunctionSummary>(
10495 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10496 std::move(TypeIdInfo.TypeTests),
10497 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10498 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10499 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10500 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10501 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10502
10503 FS->setModulePath(ModulePath);
10504
10505 return addGlobalValueToIndex(Name, GUID,
10507 std::move(FS), Loc);
10508}
10509
10510/// VariableSummary
10511/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10512/// [',' OptionalRefs]? ')'
10513bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10514 unsigned ID) {
10515 LocTy Loc = Lex.getLoc();
10516 assert(Lex.getKind() == lltok::kw_variable);
10517 Lex.Lex();
10518
10519 StringRef ModulePath;
10520 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10522 /*NotEligibleToImport=*/false,
10523 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10524 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10525 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10526 /* WriteOnly */ false,
10527 /* Constant */ false,
10530 VTableFuncList VTableFuncs;
10531 if (parseToken(lltok::colon, "expected ':' here") ||
10532 parseToken(lltok::lparen, "expected '(' here") ||
10533 parseModuleReference(ModulePath) ||
10534 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10535 parseToken(lltok::comma, "expected ',' here") ||
10536 parseGVarFlags(GVarFlags))
10537 return true;
10538
10539 // parse optional fields
10540 while (EatIfPresent(lltok::comma)) {
10541 switch (Lex.getKind()) {
10543 if (parseOptionalVTableFuncs(VTableFuncs))
10544 return true;
10545 break;
10546 case lltok::kw_refs:
10547 if (parseOptionalRefs(Refs))
10548 return true;
10549 break;
10550 default:
10551 return error(Lex.getLoc(), "expected optional variable summary field");
10552 }
10553 }
10554
10555 if (parseToken(lltok::rparen, "expected ')' here"))
10556 return true;
10557
10558 auto GS =
10559 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10560
10561 GS->setModulePath(ModulePath);
10562 GS->setVTableFuncs(std::move(VTableFuncs));
10563
10564 return addGlobalValueToIndex(Name, GUID,
10566 std::move(GS), Loc);
10567}
10568
10569/// AliasSummary
10570/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10571/// 'aliasee' ':' GVReference ')'
10572bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10573 unsigned ID) {
10574 assert(Lex.getKind() == lltok::kw_alias);
10575 LocTy Loc = Lex.getLoc();
10576 Lex.Lex();
10577
10578 StringRef ModulePath;
10579 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10581 /*NotEligibleToImport=*/false,
10582 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10583 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10584 if (parseToken(lltok::colon, "expected ':' here") ||
10585 parseToken(lltok::lparen, "expected '(' here") ||
10586 parseModuleReference(ModulePath) ||
10587 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10588 parseToken(lltok::comma, "expected ',' here") ||
10589 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10590 parseToken(lltok::colon, "expected ':' here"))
10591 return true;
10592
10593 ValueInfo AliaseeVI;
10594 unsigned GVId;
10595 auto AS = std::make_unique<AliasSummary>(GVFlags);
10596 AS->setModulePath(ModulePath);
10597
10598 if (!EatIfPresent(lltok::kw_null)) {
10599 if (parseGVReference(AliaseeVI, GVId))
10600 return true;
10601
10602 // Record forward reference if the aliasee is not parsed yet.
10603 if (AliaseeVI.getRef() == FwdVIRef) {
10604 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10605 } else {
10606 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10607 assert(Summary && "Aliasee must be a definition");
10608 AS->setAliasee(AliaseeVI, Summary);
10609 }
10610 }
10611
10612 if (parseToken(lltok::rparen, "expected ')' here"))
10613 return true;
10614
10615 return addGlobalValueToIndex(Name, GUID,
10617 std::move(AS), Loc);
10618}
10619
10620/// Flag
10621/// ::= [0|1]
10622bool LLParser::parseFlag(unsigned &Val) {
10623 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10624 return tokError("expected integer");
10625 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10626 Lex.Lex();
10627 return false;
10628}
10629
10630/// OptionalFFlags
10631/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10632/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10633/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10634/// [',' 'noInline' ':' Flag]? ')'
10635/// [',' 'alwaysInline' ':' Flag]? ')'
10636/// [',' 'noUnwind' ':' Flag]? ')'
10637/// [',' 'mayThrow' ':' Flag]? ')'
10638/// [',' 'hasUnknownCall' ':' Flag]? ')'
10639/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10640
10641bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10642 assert(Lex.getKind() == lltok::kw_funcFlags);
10643 Lex.Lex();
10644
10645 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10646 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10647 return true;
10648
10649 do {
10650 unsigned Val = 0;
10651 switch (Lex.getKind()) {
10652 case lltok::kw_readNone:
10653 Lex.Lex();
10654 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10655 return true;
10656 FFlags.ReadNone = Val;
10657 break;
10658 case lltok::kw_readOnly:
10659 Lex.Lex();
10660 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10661 return true;
10662 FFlags.ReadOnly = Val;
10663 break;
10665 Lex.Lex();
10666 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10667 return true;
10668 FFlags.NoRecurse = Val;
10669 break;
10671 Lex.Lex();
10672 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10673 return true;
10674 FFlags.ReturnDoesNotAlias = Val;
10675 break;
10676 case lltok::kw_noInline:
10677 Lex.Lex();
10678 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10679 return true;
10680 FFlags.NoInline = Val;
10681 break;
10683 Lex.Lex();
10684 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10685 return true;
10686 FFlags.AlwaysInline = Val;
10687 break;
10688 case lltok::kw_noUnwind:
10689 Lex.Lex();
10690 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10691 return true;
10692 FFlags.NoUnwind = Val;
10693 break;
10694 case lltok::kw_mayThrow:
10695 Lex.Lex();
10696 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10697 return true;
10698 FFlags.MayThrow = Val;
10699 break;
10701 Lex.Lex();
10702 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10703 return true;
10704 FFlags.HasUnknownCall = Val;
10705 break;
10707 Lex.Lex();
10708 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10709 return true;
10710 FFlags.MustBeUnreachable = Val;
10711 break;
10712 default:
10713 return error(Lex.getLoc(), "expected function flag type");
10714 }
10715 } while (EatIfPresent(lltok::comma));
10716
10717 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10718 return true;
10719
10720 return false;
10721}
10722
10723/// OptionalCalls
10724/// := 'calls' ':' '(' Call [',' Call]* ')'
10725/// Call ::= '(' 'callee' ':' GVReference
10726/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10727/// [ ',' 'tail' ]? ')'
10728bool LLParser::parseOptionalCalls(
10729 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10730 assert(Lex.getKind() == lltok::kw_calls);
10731 Lex.Lex();
10732
10733 if (parseToken(lltok::colon, "expected ':' in calls") ||
10734 parseToken(lltok::lparen, "expected '(' in calls"))
10735 return true;
10736
10737 IdToIndexMapType IdToIndexMap;
10738 // parse each call edge
10739 do {
10740 ValueInfo VI;
10741 if (parseToken(lltok::lparen, "expected '(' in call") ||
10742 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10743 parseToken(lltok::colon, "expected ':'"))
10744 return true;
10745
10746 LocTy Loc = Lex.getLoc();
10747 unsigned GVId;
10748 if (parseGVReference(VI, GVId))
10749 return true;
10750
10752 unsigned RelBF = 0;
10753 unsigned HasTailCall = false;
10754 unsigned HasIndirectCall = false;
10755
10756 // parse optional fields
10757 while (EatIfPresent(lltok::comma)) {
10758 switch (Lex.getKind()) {
10759 case lltok::kw_hotness:
10760 Lex.Lex();
10761 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10762 return true;
10763 break;
10764 // Deprecated, keep in order to support old files.
10765 case lltok::kw_relbf:
10766 Lex.Lex();
10767 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10768 return true;
10769 break;
10770 case lltok::kw_tail:
10771 Lex.Lex();
10772 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10773 return true;
10774 break;
10775 case lltok::kw_indirect:
10776 Lex.Lex();
10777 if (parseToken(lltok::colon, "expected ':'") ||
10778 parseFlag(HasIndirectCall))
10779 return true;
10780 break;
10781 default:
10782 return error(Lex.getLoc(),
10783 "expected hotness, relbf, tail, or indirect");
10784 }
10785 }
10786 // Keep track of the Call array index needing a forward reference.
10787 // We will save the location of the ValueInfo needing an update, but
10788 // can only do so once the std::vector is finalized.
10789 if (VI.getRef() == FwdVIRef)
10790 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10792 VI, CalleeInfo(Hotness, HasTailCall, HasIndirectCall)});
10793
10794 if (parseToken(lltok::rparen, "expected ')' in call"))
10795 return true;
10796 } while (EatIfPresent(lltok::comma));
10797
10798 // Now that the Calls vector is finalized, it is safe to save the locations
10799 // of any forward GV references that need updating later.
10800 for (auto I : IdToIndexMap) {
10801 auto &Infos = ForwardRefValueInfos[I.first];
10802 for (auto P : I.second) {
10803 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10804 "Forward referenced ValueInfo expected to be empty");
10805 Infos.emplace_back(&Calls[P.first].first, P.second);
10806 }
10807 }
10808
10809 if (parseToken(lltok::rparen, "expected ')' in calls"))
10810 return true;
10811
10812 return false;
10813}
10814
10815/// Hotness
10816/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10817bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10818 switch (Lex.getKind()) {
10819 case lltok::kw_unknown:
10821 break;
10822 case lltok::kw_cold:
10824 break;
10825 case lltok::kw_none:
10827 break;
10828 case lltok::kw_hot:
10830 break;
10831 case lltok::kw_critical:
10833 break;
10834 default:
10835 return error(Lex.getLoc(), "invalid call edge hotness");
10836 }
10837 Lex.Lex();
10838 return false;
10839}
10840
10841/// OptionalVTableFuncs
10842/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10843/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10844bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10845 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10846 Lex.Lex();
10847
10848 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10849 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10850 return true;
10851
10852 IdToIndexMapType IdToIndexMap;
10853 // parse each virtual function pair
10854 do {
10855 ValueInfo VI;
10856 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10857 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10858 parseToken(lltok::colon, "expected ':'"))
10859 return true;
10860
10861 LocTy Loc = Lex.getLoc();
10862 unsigned GVId;
10863 if (parseGVReference(VI, GVId))
10864 return true;
10865
10867 if (parseToken(lltok::comma, "expected comma") ||
10868 parseToken(lltok::kw_offset, "expected offset") ||
10869 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10870 return true;
10871
10872 // Keep track of the VTableFuncs array index needing a forward reference.
10873 // We will save the location of the ValueInfo needing an update, but
10874 // can only do so once the std::vector is finalized.
10875 if (VI == EmptyVI)
10876 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10877 VTableFuncs.push_back({VI, Offset});
10878
10879 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10880 return true;
10881 } while (EatIfPresent(lltok::comma));
10882
10883 // Now that the VTableFuncs vector is finalized, it is safe to save the
10884 // locations of any forward GV references that need updating later.
10885 for (auto I : IdToIndexMap) {
10886 auto &Infos = ForwardRefValueInfos[I.first];
10887 for (auto P : I.second) {
10888 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10889 "Forward referenced ValueInfo expected to be empty");
10890 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10891 }
10892 }
10893
10894 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10895 return true;
10896
10897 return false;
10898}
10899
10900/// ParamNo := 'param' ':' UInt64
10901bool LLParser::parseParamNo(uint64_t &ParamNo) {
10902 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10903 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10904 return true;
10905 return false;
10906}
10907
10908/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10909bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10910 APSInt Lower;
10911 APSInt Upper;
10912 auto ParseAPSInt = [&](APSInt &Val) {
10913 if (Lex.getKind() != lltok::APSInt)
10914 return tokError("expected integer");
10915 Val = Lex.getAPSIntVal();
10916 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10917 Val.setIsSigned(true);
10918 Lex.Lex();
10919 return false;
10920 };
10921 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10922 parseToken(lltok::colon, "expected ':' here") ||
10923 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10924 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10925 parseToken(lltok::rsquare, "expected ']' here"))
10926 return true;
10927
10928 ++Upper;
10929 Range =
10930 (Lower == Upper && !Lower.isMaxValue())
10931 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10932 : ConstantRange(Lower, Upper);
10933
10934 return false;
10935}
10936
10937/// ParamAccessCall
10938/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10939bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10940 IdLocListType &IdLocList) {
10941 if (parseToken(lltok::lparen, "expected '(' here") ||
10942 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10943 parseToken(lltok::colon, "expected ':' here"))
10944 return true;
10945
10946 unsigned GVId;
10947 ValueInfo VI;
10948 LocTy Loc = Lex.getLoc();
10949 if (parseGVReference(VI, GVId))
10950 return true;
10951
10952 Call.Callee = VI;
10953 IdLocList.emplace_back(GVId, Loc);
10954
10955 if (parseToken(lltok::comma, "expected ',' here") ||
10956 parseParamNo(Call.ParamNo) ||
10957 parseToken(lltok::comma, "expected ',' here") ||
10958 parseParamAccessOffset(Call.Offsets))
10959 return true;
10960
10961 if (parseToken(lltok::rparen, "expected ')' here"))
10962 return true;
10963
10964 return false;
10965}
10966
10967/// ParamAccess
10968/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10969/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10970bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10971 IdLocListType &IdLocList) {
10972 if (parseToken(lltok::lparen, "expected '(' here") ||
10973 parseParamNo(Param.ParamNo) ||
10974 parseToken(lltok::comma, "expected ',' here") ||
10975 parseParamAccessOffset(Param.Use))
10976 return true;
10977
10978 if (EatIfPresent(lltok::comma)) {
10979 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10980 parseToken(lltok::colon, "expected ':' here") ||
10981 parseToken(lltok::lparen, "expected '(' here"))
10982 return true;
10983 do {
10984 FunctionSummary::ParamAccess::Call Call;
10985 if (parseParamAccessCall(Call, IdLocList))
10986 return true;
10987 Param.Calls.push_back(Call);
10988 } while (EatIfPresent(lltok::comma));
10989
10990 if (parseToken(lltok::rparen, "expected ')' here"))
10991 return true;
10992 }
10993
10994 if (parseToken(lltok::rparen, "expected ')' here"))
10995 return true;
10996
10997 return false;
10998}
10999
11000/// OptionalParamAccesses
11001/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
11002bool LLParser::parseOptionalParamAccesses(
11003 std::vector<FunctionSummary::ParamAccess> &Params) {
11004 assert(Lex.getKind() == lltok::kw_params);
11005 Lex.Lex();
11006
11007 if (parseToken(lltok::colon, "expected ':' here") ||
11008 parseToken(lltok::lparen, "expected '(' here"))
11009 return true;
11010
11011 IdLocListType VContexts;
11012 size_t CallsNum = 0;
11013 do {
11014 FunctionSummary::ParamAccess ParamAccess;
11015 if (parseParamAccess(ParamAccess, VContexts))
11016 return true;
11017 CallsNum += ParamAccess.Calls.size();
11018 assert(VContexts.size() == CallsNum);
11019 (void)CallsNum;
11020 Params.emplace_back(std::move(ParamAccess));
11021 } while (EatIfPresent(lltok::comma));
11022
11023 if (parseToken(lltok::rparen, "expected ')' here"))
11024 return true;
11025
11026 // Now that the Params is finalized, it is safe to save the locations
11027 // of any forward GV references that need updating later.
11028 IdLocListType::const_iterator ItContext = VContexts.begin();
11029 for (auto &PA : Params) {
11030 for (auto &C : PA.Calls) {
11031 if (C.Callee.getRef() == FwdVIRef)
11032 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
11033 ItContext->second);
11034 ++ItContext;
11035 }
11036 }
11037 assert(ItContext == VContexts.end());
11038
11039 return false;
11040}
11041
11042/// OptionalRefs
11043/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
11044bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
11045 assert(Lex.getKind() == lltok::kw_refs);
11046 Lex.Lex();
11047
11048 if (parseToken(lltok::colon, "expected ':' in refs") ||
11049 parseToken(lltok::lparen, "expected '(' in refs"))
11050 return true;
11051
11052 struct ValueContext {
11053 ValueInfo VI;
11054 unsigned GVId;
11055 LocTy Loc;
11056 };
11057 std::vector<ValueContext> VContexts;
11058 // parse each ref edge
11059 do {
11060 ValueContext VC;
11061 VC.Loc = Lex.getLoc();
11062 if (parseGVReference(VC.VI, VC.GVId))
11063 return true;
11064 VContexts.push_back(VC);
11065 } while (EatIfPresent(lltok::comma));
11066
11067 // Sort value contexts so that ones with writeonly
11068 // and readonly ValueInfo are at the end of VContexts vector.
11069 // See FunctionSummary::specialRefCounts()
11070 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
11071 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11072 });
11073
11074 IdToIndexMapType IdToIndexMap;
11075 for (auto &VC : VContexts) {
11076 // Keep track of the Refs array index needing a forward reference.
11077 // We will save the location of the ValueInfo needing an update, but
11078 // can only do so once the std::vector is finalized.
11079 if (VC.VI.getRef() == FwdVIRef)
11080 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
11081 Refs.push_back(VC.VI);
11082 }
11083
11084 // Now that the Refs vector is finalized, it is safe to save the locations
11085 // of any forward GV references that need updating later.
11086 for (auto I : IdToIndexMap) {
11087 auto &Infos = ForwardRefValueInfos[I.first];
11088 for (auto P : I.second) {
11089 assert(Refs[P.first].getRef() == FwdVIRef &&
11090 "Forward referenced ValueInfo expected to be empty");
11091 Infos.emplace_back(&Refs[P.first], P.second);
11092 }
11093 }
11094
11095 if (parseToken(lltok::rparen, "expected ')' in refs"))
11096 return true;
11097
11098 return false;
11099}
11100
11101/// OptionalTypeIdInfo
11102/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
11103/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
11104/// [',' TypeCheckedLoadConstVCalls]? ')'
11105bool LLParser::parseOptionalTypeIdInfo(
11106 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11107 assert(Lex.getKind() == lltok::kw_typeIdInfo);
11108 Lex.Lex();
11109
11110 if (parseToken(lltok::colon, "expected ':' here") ||
11111 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11112 return true;
11113
11114 do {
11115 switch (Lex.getKind()) {
11117 if (parseTypeTests(TypeIdInfo.TypeTests))
11118 return true;
11119 break;
11121 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
11122 TypeIdInfo.TypeTestAssumeVCalls))
11123 return true;
11124 break;
11126 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
11127 TypeIdInfo.TypeCheckedLoadVCalls))
11128 return true;
11129 break;
11131 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
11132 TypeIdInfo.TypeTestAssumeConstVCalls))
11133 return true;
11134 break;
11136 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
11137 TypeIdInfo.TypeCheckedLoadConstVCalls))
11138 return true;
11139 break;
11140 default:
11141 return error(Lex.getLoc(), "invalid typeIdInfo list type");
11142 }
11143 } while (EatIfPresent(lltok::comma));
11144
11145 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11146 return true;
11147
11148 return false;
11149}
11150
11151/// TypeTests
11152/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
11153/// [',' (SummaryID | UInt64)]* ')'
11154bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11155 assert(Lex.getKind() == lltok::kw_typeTests);
11156 Lex.Lex();
11157
11158 if (parseToken(lltok::colon, "expected ':' here") ||
11159 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11160 return true;
11161
11162 IdToIndexMapType IdToIndexMap;
11163 do {
11165 if (Lex.getKind() == lltok::SummaryID) {
11166 unsigned ID = Lex.getUIntVal();
11167 LocTy Loc = Lex.getLoc();
11168 // Keep track of the TypeTests array index needing a forward reference.
11169 // We will save the location of the GUID needing an update, but
11170 // can only do so once the std::vector is finalized.
11171 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
11172 Lex.Lex();
11173 } else if (parseUInt64(GUID))
11174 return true;
11175 TypeTests.push_back(GUID);
11176 } while (EatIfPresent(lltok::comma));
11177
11178 // Now that the TypeTests vector is finalized, it is safe to save the
11179 // locations of any forward GV references that need updating later.
11180 for (auto I : IdToIndexMap) {
11181 auto &Ids = ForwardRefTypeIds[I.first];
11182 for (auto P : I.second) {
11183 assert(TypeTests[P.first] == 0 &&
11184 "Forward referenced type id GUID expected to be 0");
11185 Ids.emplace_back(&TypeTests[P.first], P.second);
11186 }
11187 }
11188
11189 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11190 return true;
11191
11192 return false;
11193}
11194
11195/// VFuncIdList
11196/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
11197bool LLParser::parseVFuncIdList(
11198 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11199 assert(Lex.getKind() == Kind);
11200 Lex.Lex();
11201
11202 if (parseToken(lltok::colon, "expected ':' here") ||
11203 parseToken(lltok::lparen, "expected '(' here"))
11204 return true;
11205
11206 IdToIndexMapType IdToIndexMap;
11207 do {
11208 FunctionSummary::VFuncId VFuncId;
11209 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11210 return true;
11211 VFuncIdList.push_back(VFuncId);
11212 } while (EatIfPresent(lltok::comma));
11213
11214 if (parseToken(lltok::rparen, "expected ')' here"))
11215 return true;
11216
11217 // Now that the VFuncIdList vector is finalized, it is safe to save the
11218 // locations of any forward GV references that need updating later.
11219 for (auto I : IdToIndexMap) {
11220 auto &Ids = ForwardRefTypeIds[I.first];
11221 for (auto P : I.second) {
11222 assert(VFuncIdList[P.first].GUID == 0 &&
11223 "Forward referenced type id GUID expected to be 0");
11224 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
11225 }
11226 }
11227
11228 return false;
11229}
11230
11231/// ConstVCallList
11232/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
11233bool LLParser::parseConstVCallList(
11234 lltok::Kind Kind,
11235 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11236 assert(Lex.getKind() == Kind);
11237 Lex.Lex();
11238
11239 if (parseToken(lltok::colon, "expected ':' here") ||
11240 parseToken(lltok::lparen, "expected '(' here"))
11241 return true;
11242
11243 IdToIndexMapType IdToIndexMap;
11244 do {
11245 FunctionSummary::ConstVCall ConstVCall;
11246 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11247 return true;
11248 ConstVCallList.push_back(ConstVCall);
11249 } while (EatIfPresent(lltok::comma));
11250
11251 if (parseToken(lltok::rparen, "expected ')' here"))
11252 return true;
11253
11254 // Now that the ConstVCallList vector is finalized, it is safe to save the
11255 // locations of any forward GV references that need updating later.
11256 for (auto I : IdToIndexMap) {
11257 auto &Ids = ForwardRefTypeIds[I.first];
11258 for (auto P : I.second) {
11259 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
11260 "Forward referenced type id GUID expected to be 0");
11261 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
11262 }
11263 }
11264
11265 return false;
11266}
11267
11268/// ConstVCall
11269/// ::= '(' VFuncId ',' Args ')'
11270bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11271 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11272 if (parseToken(lltok::lparen, "expected '(' here") ||
11273 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
11274 return true;
11275
11276 if (EatIfPresent(lltok::comma))
11277 if (parseArgs(ConstVCall.Args))
11278 return true;
11279
11280 if (parseToken(lltok::rparen, "expected ')' here"))
11281 return true;
11282
11283 return false;
11284}
11285
11286/// VFuncId
11287/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
11288/// 'offset' ':' UInt64 ')'
11289bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11290 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11291 assert(Lex.getKind() == lltok::kw_vFuncId);
11292 Lex.Lex();
11293
11294 if (parseToken(lltok::colon, "expected ':' here") ||
11295 parseToken(lltok::lparen, "expected '(' here"))
11296 return true;
11297
11298 if (Lex.getKind() == lltok::SummaryID) {
11299 VFuncId.GUID = 0;
11300 unsigned ID = Lex.getUIntVal();
11301 LocTy Loc = Lex.getLoc();
11302 // Keep track of the array index needing a forward reference.
11303 // We will save the location of the GUID needing an update, but
11304 // can only do so once the caller's std::vector is finalized.
11305 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11306 Lex.Lex();
11307 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11308 parseToken(lltok::colon, "expected ':' here") ||
11309 parseUInt64(VFuncId.GUID))
11310 return true;
11311
11312 if (parseToken(lltok::comma, "expected ',' here") ||
11313 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11314 parseToken(lltok::colon, "expected ':' here") ||
11315 parseUInt64(VFuncId.Offset) ||
11316 parseToken(lltok::rparen, "expected ')' here"))
11317 return true;
11318
11319 return false;
11320}
11321
11322/// GVFlags
11323/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11324/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11325/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11326/// 'canAutoHide' ':' Flag ',' ')'
11327bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11328 assert(Lex.getKind() == lltok::kw_flags);
11329 Lex.Lex();
11330
11331 if (parseToken(lltok::colon, "expected ':' here") ||
11332 parseToken(lltok::lparen, "expected '(' here"))
11333 return true;
11334
11335 do {
11336 unsigned Flag = 0;
11337 switch (Lex.getKind()) {
11338 case lltok::kw_linkage:
11339 Lex.Lex();
11340 if (parseToken(lltok::colon, "expected ':'"))
11341 return true;
11342 bool HasLinkage;
11343 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11344 assert(HasLinkage && "Linkage not optional in summary entry");
11345 Lex.Lex();
11346 break;
11348 Lex.Lex();
11349 if (parseToken(lltok::colon, "expected ':'"))
11350 return true;
11351 parseOptionalVisibility(Flag);
11352 GVFlags.Visibility = Flag;
11353 break;
11355 Lex.Lex();
11356 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11357 return true;
11358 GVFlags.NotEligibleToImport = Flag;
11359 break;
11360 case lltok::kw_live:
11361 Lex.Lex();
11362 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11363 return true;
11364 GVFlags.Live = Flag;
11365 break;
11366 case lltok::kw_dsoLocal:
11367 Lex.Lex();
11368 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11369 return true;
11370 GVFlags.DSOLocal = Flag;
11371 break;
11373 Lex.Lex();
11374 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11375 return true;
11376 GVFlags.CanAutoHide = Flag;
11377 break;
11379 Lex.Lex();
11380 if (parseToken(lltok::colon, "expected ':'"))
11381 return true;
11383 if (parseOptionalImportType(Lex.getKind(), IK))
11384 return true;
11385 GVFlags.ImportType = static_cast<unsigned>(IK);
11386 Lex.Lex();
11387 break;
11389 Lex.Lex();
11390 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11391 return true;
11392 GVFlags.NoRenameOnPromotion = Flag;
11393 break;
11394 default:
11395 return error(Lex.getLoc(), "expected gv flag type");
11396 }
11397 } while (EatIfPresent(lltok::comma));
11398
11399 if (parseToken(lltok::rparen, "expected ')' here"))
11400 return true;
11401
11402 return false;
11403}
11404
11405/// GVarFlags
11406/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11407/// ',' 'writeonly' ':' Flag
11408/// ',' 'constant' ':' Flag ')'
11409bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11410 assert(Lex.getKind() == lltok::kw_varFlags);
11411 Lex.Lex();
11412
11413 if (parseToken(lltok::colon, "expected ':' here") ||
11414 parseToken(lltok::lparen, "expected '(' here"))
11415 return true;
11416
11417 auto ParseRest = [this](unsigned int &Val) {
11418 Lex.Lex();
11419 if (parseToken(lltok::colon, "expected ':'"))
11420 return true;
11421 return parseFlag(Val);
11422 };
11423
11424 do {
11425 unsigned Flag = 0;
11426 switch (Lex.getKind()) {
11427 case lltok::kw_readonly:
11428 if (ParseRest(Flag))
11429 return true;
11430 GVarFlags.MaybeReadOnly = Flag;
11431 break;
11432 case lltok::kw_writeonly:
11433 if (ParseRest(Flag))
11434 return true;
11435 GVarFlags.MaybeWriteOnly = Flag;
11436 break;
11437 case lltok::kw_constant:
11438 if (ParseRest(Flag))
11439 return true;
11440 GVarFlags.Constant = Flag;
11441 break;
11443 if (ParseRest(Flag))
11444 return true;
11445 GVarFlags.VCallVisibility = Flag;
11446 break;
11447 default:
11448 return error(Lex.getLoc(), "expected gvar flag type");
11449 }
11450 } while (EatIfPresent(lltok::comma));
11451 return parseToken(lltok::rparen, "expected ')' here");
11452}
11453
11454/// ModuleReference
11455/// ::= 'module' ':' UInt
11456bool LLParser::parseModuleReference(StringRef &ModulePath) {
11457 // parse module id.
11458 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11459 parseToken(lltok::colon, "expected ':' here") ||
11460 parseToken(lltok::SummaryID, "expected module ID"))
11461 return true;
11462
11463 unsigned ModuleID = Lex.getUIntVal();
11464 auto I = ModuleIdMap.find(ModuleID);
11465 // We should have already parsed all module IDs
11466 assert(I != ModuleIdMap.end());
11467 ModulePath = I->second;
11468 return false;
11469}
11470
11471/// GVReference
11472/// ::= SummaryID
11473bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11474 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11475 if (!ReadOnly)
11476 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11477 if (parseToken(lltok::SummaryID, "expected GV ID"))
11478 return true;
11479
11480 GVId = Lex.getUIntVal();
11481 // Check if we already have a VI for this GV
11482 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11483 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11484 VI = NumberedValueInfos[GVId];
11485 } else
11486 // We will create a forward reference to the stored location.
11487 VI = ValueInfo(false, FwdVIRef);
11488
11489 if (ReadOnly)
11490 VI.setReadOnly();
11491 if (WriteOnly)
11492 VI.setWriteOnly();
11493 return false;
11494}
11495
11496/// OptionalAllocs
11497/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11498/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11499/// ',' MemProfs ')'
11500/// Version ::= UInt32
11501bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11502 assert(Lex.getKind() == lltok::kw_allocs);
11503 Lex.Lex();
11504
11505 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11506 parseToken(lltok::lparen, "expected '(' in allocs"))
11507 return true;
11508
11509 // parse each alloc
11510 do {
11511 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11512 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11513 parseToken(lltok::colon, "expected ':'") ||
11514 parseToken(lltok::lparen, "expected '(' in versions"))
11515 return true;
11516
11517 SmallVector<uint8_t> Versions;
11518 do {
11519 uint8_t V = 0;
11520 if (parseAllocType(V))
11521 return true;
11522 Versions.push_back(V);
11523 } while (EatIfPresent(lltok::comma));
11524
11525 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11526 parseToken(lltok::comma, "expected ',' in alloc"))
11527 return true;
11528
11529 std::vector<MIBInfo> MIBs;
11530 if (parseMemProfs(MIBs))
11531 return true;
11532
11533 Allocs.push_back({Versions, MIBs});
11534
11535 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11536 return true;
11537 } while (EatIfPresent(lltok::comma));
11538
11539 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11540 return true;
11541
11542 return false;
11543}
11544
11545/// MemProfs
11546/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11547/// MemProf ::= '(' 'type' ':' AllocType
11548/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11549/// StackId ::= UInt64
11550bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11551 assert(Lex.getKind() == lltok::kw_memProf);
11552 Lex.Lex();
11553
11554 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11555 parseToken(lltok::lparen, "expected '(' in memprof"))
11556 return true;
11557
11558 // parse each MIB
11559 do {
11560 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11561 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11562 parseToken(lltok::colon, "expected ':'"))
11563 return true;
11564
11565 uint8_t AllocType;
11566 if (parseAllocType(AllocType))
11567 return true;
11568
11569 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11570 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11571 parseToken(lltok::colon, "expected ':'") ||
11572 parseToken(lltok::lparen, "expected '(' in stackIds"))
11573 return true;
11574
11575 SmallVector<unsigned> StackIdIndices;
11576 // Combined index alloc records may not have a stack id list.
11577 if (Lex.getKind() != lltok::rparen) {
11578 do {
11579 uint64_t StackId = 0;
11580 if (parseUInt64(StackId))
11581 return true;
11582 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11583 } while (EatIfPresent(lltok::comma));
11584 }
11585
11586 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11587 return true;
11588
11589 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11590
11591 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11592 return true;
11593 } while (EatIfPresent(lltok::comma));
11594
11595 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11596 return true;
11597
11598 return false;
11599}
11600
11601/// AllocType
11602/// := ('none'|'notcold'|'cold'|'hot'|'ambiguous')
11603bool LLParser::parseAllocType(uint8_t &AllocType) {
11604 switch (Lex.getKind()) {
11605 case lltok::kw_none:
11607 break;
11608 case lltok::kw_notcold:
11610 break;
11612 // Both not cold and cold: the contexts reaching the allocation could not
11613 // be disambiguated.
11614 AllocType =
11616 break;
11617 case lltok::kw_cold:
11619 break;
11620 case lltok::kw_hot:
11621 AllocType = (uint8_t)AllocationType::Hot;
11622 break;
11623 default:
11624 return error(Lex.getLoc(), "invalid alloc type");
11625 }
11626 Lex.Lex();
11627 return false;
11628}
11629
11630/// OptionalCallsites
11631/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11632/// Callsite ::= '(' 'callee' ':' GVReference
11633/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11634/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11635/// Version ::= UInt32
11636/// StackId ::= UInt64
11637bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11638 assert(Lex.getKind() == lltok::kw_callsites);
11639 Lex.Lex();
11640
11641 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11642 parseToken(lltok::lparen, "expected '(' in callsites"))
11643 return true;
11644
11645 IdToIndexMapType IdToIndexMap;
11646 // parse each callsite
11647 do {
11648 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11649 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11650 parseToken(lltok::colon, "expected ':'"))
11651 return true;
11652
11653 ValueInfo VI;
11654 unsigned GVId = 0;
11655 LocTy Loc = Lex.getLoc();
11656 if (!EatIfPresent(lltok::kw_null)) {
11657 if (parseGVReference(VI, GVId))
11658 return true;
11659 }
11660
11661 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11662 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11663 parseToken(lltok::colon, "expected ':'") ||
11664 parseToken(lltok::lparen, "expected '(' in clones"))
11665 return true;
11666
11667 SmallVector<unsigned> Clones;
11668 do {
11669 unsigned V = 0;
11670 if (parseUInt32(V))
11671 return true;
11672 Clones.push_back(V);
11673 } while (EatIfPresent(lltok::comma));
11674
11675 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11676 parseToken(lltok::comma, "expected ',' in callsite") ||
11677 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11678 parseToken(lltok::colon, "expected ':'") ||
11679 parseToken(lltok::lparen, "expected '(' in stackIds"))
11680 return true;
11681
11682 SmallVector<unsigned> StackIdIndices;
11683 // Synthesized callsite records will not have a stack id list.
11684 if (Lex.getKind() != lltok::rparen) {
11685 do {
11686 uint64_t StackId = 0;
11687 if (parseUInt64(StackId))
11688 return true;
11689 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11690 } while (EatIfPresent(lltok::comma));
11691 }
11692
11693 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11694 return true;
11695
11696 // Keep track of the Callsites array index needing a forward reference.
11697 // We will save the location of the ValueInfo needing an update, but
11698 // can only do so once the SmallVector is finalized.
11699 if (VI.getRef() == FwdVIRef)
11700 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11701 Callsites.push_back({VI, Clones, StackIdIndices});
11702
11703 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11704 return true;
11705 } while (EatIfPresent(lltok::comma));
11706
11707 // Now that the Callsites vector is finalized, it is safe to save the
11708 // locations of any forward GV references that need updating later.
11709 for (auto I : IdToIndexMap) {
11710 auto &Infos = ForwardRefValueInfos[I.first];
11711 for (auto P : I.second) {
11712 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11713 "Forward referenced ValueInfo expected to be empty");
11714 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11715 }
11716 }
11717
11718 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11719 return true;
11720
11721 return false;
11722}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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")
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
Definition Compiler.h:276
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
Definition Compiler.h:277
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static uint64_t align(uint64_t Size)
dxil container 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:317
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 bool blockCommentCrossesBoundary(SMLoc BeginLoc, SMLoc EndLoc, SMLoc BoundaryLoc)
Return whether skipped trivia contains a block comment that crosses the boundary between two metadata...
Definition LLParser.cpp:77
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static SmallVector< MemoryEffects::Location, 2 > keywordToLoc(lltok::Kind Tok)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:235
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:68
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool isAtomic(MachineBasicBlock::iterator I)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
if(PassOpts->AAPipeline)
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
dot regions Print regions of function to dot file(with no function bodies)"
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
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 scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:399
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:119
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
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:800
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:146
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:126
@ None
No attributes have been set.
Definition Attributes.h:128
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
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 const char * areInvalidOperands(const Type *Ty, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitextract operation, otherwise return nu...
static BitExtractInst * Create(Type *Ty, Value *Src, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
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:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH 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:1477
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1624
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 LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
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.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label)
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)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
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:452
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:447
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:169
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:826
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:451
arg_iterator arg_begin()
Definition Function.h:862
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1034
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:332
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1046
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
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:692
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:749
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
std::pair< key_type, mapped_type > value_type
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:80
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:318
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.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
Definition Globals.cpp:110
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:158
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:234
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:324
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:301
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
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:660
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:68
lltok::Kind getKind() const
Definition LLLexer.h:73
LocTy getLoc() const
Definition LLLexer.h:71
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:170
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:239
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:154
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:141
LLVM_ABI bool parseMetadataDefinitions(SlotMapping &Slots, ArrayRef< SMLoc > DefinitionEnds)
Definition LLParser.cpp:185
LLVM_ABI bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:122
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:1081
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1590
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1582
A single uniqued string.
Definition Metadata.h:733
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1539
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1528
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1548
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:224
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
Definition ModRef.h:279
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:83
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 PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:899
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:209
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
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:462
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:738
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:576
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:937
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:274
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:225
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:268
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
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:236
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:228
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:512
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static constexpr uint64_t MaximumAlignment
Definition Value.h:801
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:103
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:615
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:275
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
Definition Dwarf.cpp:634
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:670
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:424
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:386
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:405
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:742
#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 IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
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
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ WASM_EmscriptenInvoke
For emscripten __invoke_* functions.
@ 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:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
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 isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:343
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:856
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:226
MacinfoRecordType
Definition Dwarf.h:918
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:924
@ 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:155
@ kw_riscv_vls_cc
Definition LLToken.h:192
@ kw_cxx_fast_tlscc
Definition LLToken.h:174
@ kw_extractvalue
Definition LLToken.h:378
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:520
@ DwarfLangDialect
Definition LLToken.h:523
@ kw_arm_apcscc
Definition LLToken.h:147
@ kw_inteldialect
Definition LLToken.h:129
@ kw_x86_stdcallcc
Definition LLToken.h:142
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:153
@ kw_provenance
Definition LLToken.h:226
@ kw_mustBeUnreachable
Definition LLToken.h:428
@ kw_internal
Definition LLToken.h:54
@ kw_wasm_emscripten_invokecc
Definition LLToken.h:189
@ kw_target_mem
Definition LLToken.h:212
@ kw_no_sanitize_hwaddress
Definition LLToken.h:499
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:468
@ kw_canAutoHide
Definition LLToken.h:411
@ kw_alwaysInline
Definition LLToken.h:424
@ kw_insertelement
Definition LLToken.h:375
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:195
@ kw_fmaximumnum
Definition LLToken.h:297
@ kw_inaccessiblememonly
Definition LLToken.h:219
@ kw_amdgpu_gfx
Definition LLToken.h:185
@ kw_getelementptr
Definition LLToken.h:372
@ FloatHexLiteral
Definition LLToken.h:540
@ kw_m68k_rtdcc
Definition LLToken.h:188
@ kw_preserve_nonecc
Definition LLToken.h:169
@ kw_x86_fastcallcc
Definition LLToken.h:143
@ kw_visibility
Definition LLToken.h:407
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:194
@ kw_positivezero
Definition LLToken.h:232
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:471
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:448
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:151
@ kw_amdgpu_kernel
Definition LLToken.h:184
@ kw_uselistorder
Definition LLToken.h:393
@ kw_blockcount
Definition LLToken.h:403
@ kw_notEligibleToImport
Definition LLToken.h:408
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_cfiFunctionDecls
Definition LLToken.h:405
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:145
@ kw_ptx_device
Definition LLToken.h:159
@ kw_personality
Definition LLToken.h:347
@ DwarfEnumKind
Definition LLToken.h:534
@ kw_declaration
Definition LLToken.h:414
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:519
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:160
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:427
@ kw_x86_intrcc
Definition LLToken.h:171
@ kw_addrspacecast
Definition LLToken.h:342
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:517
@ kw_x86_thiscallcc
Definition LLToken.h:144
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:193
@ kw_unnamed_addr
Definition LLToken.h:67
@ NameTableKind
Definition LLToken.h:526
@ kw_inlineBits
Definition LLToken.h:466
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:218
@ kw_blockaddress
Definition LLToken.h:380
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:186
@ kw_landingpad
Definition LLToken.h:346
@ kw_aarch64_vector_pcs
Definition LLToken.h:150
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:447
@ FixedPointKind
Definition LLToken.h:527
@ kw_target_mem1
Definition LLToken.h:214
@ kw_ptx_kernel
Definition LLToken.h:158
@ kw_extractelement
Definition LLToken.h:374
@ kw_branchFunnel
Definition LLToken.h:472
@ kw_typeidCompatibleVTable
Definition LLToken.h:453
@ kw_vTableFuncs
Definition LLToken.h:439
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:446
@ kw_no_sanitize_address
Definition LLToken.h:496
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:220
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:502
@ DwarfSourceLangName
Definition LLToken.h:522
@ kw_noRenameOnPromotion
Definition LLToken.h:415
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:183
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:360
@ kw_cfiFunctionDefs
Definition LLToken.h:404
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:148
@ kw_read_provenance
Definition LLToken.h:227
@ kw_cleanuppad
Definition LLToken.h:363
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:474
@ kw_target_mem0
Definition LLToken.h:213
@ kw_swifttailcc
Definition LLToken.h:166
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:445
@ kw_preservesign
Definition LLToken.h:231
@ kw_attributes
Definition LLToken.h:198
@ kw_code_model
Definition LLToken.h:123
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:477
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:462
@ kw_nodeduplicate
Definition LLToken.h:262
@ kw_avr_signalcc
Definition LLToken.h:157
@ kw_bitextract
Definition LLToken.h:385
@ kw_exactmatch
Definition LLToken.h:260
@ kw_fminimumnum
Definition LLToken.h:298
@ kw_unreachable
Definition LLToken.h:358
@ kw_intel_ocl_bicc
Definition LLToken.h:140
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:422
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:168
@ kw_importType
Definition LLToken.h:412
@ kw_cleanupret
Definition LLToken.h:359
@ kw_shufflevector
Definition LLToken.h:376
@ kw_riscv_vector_cc
Definition LLToken.h:191
@ kw_avr_intrcc
Definition LLToken.h:156
@ kw_definition
Definition LLToken.h:413
@ kw_virtualConstProp
Definition LLToken.h:479
@ kw_vcall_visibility
Definition LLToken.h:467
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:211
@ kw_preserve_mostcc
Definition LLToken.h:167
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:149
@ kw_typeTestRes
Definition LLToken.h:455
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:443
@ kw_amdgpu_cs_chain
Definition LLToken.h:182
@ kw_dso_local_equivalent
Definition LLToken.h:381
@ kw_x86_64_sysvcc
Definition LLToken.h:162
@ DbgRecordType
Definition LLToken.h:533
@ kw_address_is_null
Definition LLToken.h:225
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:154
@ kw_uniqueRetVal
Definition LLToken.h:478
@ kw_insertvalue
Definition LLToken.h:379
@ kw_speculative
Definition LLToken.h:473
@ kw_indirectbr
Definition LLToken.h:355
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:594
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
DebugVariableAggregate VarID
A unique key that represents one instance of a debug variable.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:55
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeInstructionMetadata(Module &M)
Discover metadata used by instructions in this module, and apply the suitable upgrade.
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:649
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:362
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:365
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:364
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:373
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
IRMemLocation
The locations at which a function might access memory.
Definition ModRef.h:60
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:37
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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:2028
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
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:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
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)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
#define N
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
Definition Module.cpp:1073
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ Speculative
Speculative devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.