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
554
555 if (!Slots)
556 return false;
557 // Initialize the slot mapping.
558 // Because by this point we've parsed and validated everything, we can "steal"
559 // the mapping from LLParser as it doesn't need it anymore.
560 Slots->GlobalValues = std::move(NumberedVals);
561 Slots->MetadataNodes = std::move(NumberedMetadata);
562 for (const auto &I : NamedTypes)
563 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
564 for (const auto &I : NumberedTypes)
565 Slots->Types.insert(std::make_pair(I.first, I.second.first));
566
567 return false;
568}
569
570/// Do final validity and basic correctness checks at the end of the index.
571bool LLParser::validateEndOfIndex() {
572 if (!Index)
573 return false;
574
575 if (!ForwardRefValueInfos.empty())
576 return error(ForwardRefValueInfos.begin()->second.front().second,
577 "use of undefined summary '^" +
578 Twine(ForwardRefValueInfos.begin()->first) + "'");
579
580 if (!ForwardRefAliasees.empty())
581 return error(ForwardRefAliasees.begin()->second.front().second,
582 "use of undefined summary '^" +
583 Twine(ForwardRefAliasees.begin()->first) + "'");
584
585 if (!ForwardRefTypeIds.empty())
586 return error(ForwardRefTypeIds.begin()->second.front().second,
587 "use of undefined type id summary '^" +
588 Twine(ForwardRefTypeIds.begin()->first) + "'");
589
590 return false;
591}
592
593//===----------------------------------------------------------------------===//
594// Top-Level Entities
595//===----------------------------------------------------------------------===//
596
597bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
598 // Delay parsing of the data layout string until the target triple is known.
599 // Then, pass both the the target triple and the tentative data layout string
600 // to DataLayoutCallback, allowing to override the DL string.
601 // This enables importing modules with invalid DL strings.
602 std::string TentativeDLStr = M->getDataLayoutStr();
603 LocTy DLStrLoc;
604
605 bool Done = false;
606 while (!Done) {
607 switch (Lex.getKind()) {
608 case lltok::kw_target:
609 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
610 return true;
611 break;
613 if (parseSourceFileName())
614 return true;
615 break;
616 default:
617 Done = true;
618 }
619 }
620 // Run the override callback to potentially change the data layout string, and
621 // parse the data layout string.
622 if (auto LayoutOverride =
623 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
624 TentativeDLStr = *LayoutOverride;
625 DLStrLoc = {};
626 }
627 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
628 if (!MaybeDL)
629 return error(DLStrLoc, toString(MaybeDL.takeError()));
630 M->setDataLayout(MaybeDL.get());
631 return false;
632}
633
634bool LLParser::parseTopLevelEntities() {
635 // If there is no Module, then parse just the summary index entries.
636 if (!M) {
637 while (true) {
638 switch (Lex.getKind()) {
639 case lltok::Eof:
640 return false;
641 case lltok::SummaryID:
642 if (parseSummaryEntry())
643 return true;
644 break;
646 if (parseSourceFileName())
647 return true;
648 break;
649 default:
650 // Skip everything else
651 Lex.Lex();
652 }
653 }
654 }
655 while (true) {
656 switch (Lex.getKind()) {
657 default:
658 return tokError("expected top-level entity");
659 case lltok::Eof: return false;
661 if (parseDeclare())
662 return true;
663 break;
664 case lltok::kw_define:
665 if (parseDefine())
666 return true;
667 break;
668 case lltok::kw_module:
669 if (parseModuleAsm())
670 return true;
671 break;
673 if (parseUnnamedType())
674 return true;
675 break;
676 case lltok::LocalVar:
677 if (parseNamedType())
678 return true;
679 break;
680 case lltok::GlobalID:
681 if (parseUnnamedGlobal())
682 return true;
683 break;
684 case lltok::GlobalVar:
685 if (parseNamedGlobal())
686 return true;
687 break;
688 case lltok::ComdatVar: if (parseComdat()) return true; break;
689 case lltok::exclaim:
690 if (parseStandaloneMetadata())
691 return true;
692 break;
693 case lltok::SummaryID:
694 if (parseSummaryEntry())
695 return true;
696 break;
698 if (parseNamedMetadata())
699 return true;
700 break;
702 if (parseUnnamedAttrGrp())
703 return true;
704 break;
706 if (parseUseListOrder())
707 return true;
708 break;
709 }
710 }
711}
712
713/// toplevelentity
714/// ::= 'module' 'asm' STRINGCONSTANT
715/// ::= 'module' 'asm' '(' 'property_name1:' STRINGCONSTANT ','
716/// 'property_name2:' STRINGCONSTANT ')'
717/// STRINGCONSTANT
718bool LLParser::parseModuleAsm() {
719 assert(Lex.getKind() == lltok::kw_module);
720 Lex.Lex();
721
722 std::string AsmStr;
723 if (parseToken(lltok::kw_asm, "expected 'module asm'"))
724 return true;
725
726 Module::GlobalAsmProperties Props;
727 if (EatIfPresent(lltok::lparen)) {
728 while (true) {
729 std::string Key, Value;
730 SMLoc Loc = Lex.getLoc();
731 if (Lex.getKind() != lltok::LabelStr)
732 return error(Loc, "expected property name followed by ':'");
733
734 Key = Lex.getStrVal();
735 Lex.Lex();
736
737 if (parseStringConstant(Value))
738 return true;
739
740 if (!Props.set(Key, Value))
741 return error(Loc, "unknown property name");
742
743 if (EatIfPresent(lltok::rparen))
744 break;
745 if (parseToken(lltok::comma, "expected ',' or ')'"))
746 return true;
747 }
748 }
749
750 do {
751 std::string AsmStrPart;
752 if (parseStringConstant(AsmStrPart))
753 return true;
754 AsmStr += AsmStrPart + "\n";
755 } while (Lex.getKind() == lltok::StringConstant);
756
757 M->appendModuleInlineAsm({AsmStr, Props});
758 return false;
759}
760
761/// toplevelentity
762/// ::= 'target' 'triple' '=' STRINGCONSTANT
763/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
764bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
765 LocTy &DLStrLoc) {
766 assert(Lex.getKind() == lltok::kw_target);
767 std::string Str;
768 switch (Lex.Lex()) {
769 default:
770 return tokError("unknown target property");
771 case lltok::kw_triple:
772 Lex.Lex();
773 if (parseToken(lltok::equal, "expected '=' after target triple") ||
774 parseStringConstant(Str))
775 return true;
776 M->setTargetTriple(Triple(std::move(Str)));
777 return false;
779 Lex.Lex();
780 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
781 return true;
782 DLStrLoc = Lex.getLoc();
783 if (parseStringConstant(TentativeDLStr))
784 return true;
785 return false;
786 }
787}
788
789/// toplevelentity
790/// ::= 'source_filename' '=' STRINGCONSTANT
791bool LLParser::parseSourceFileName() {
792 assert(Lex.getKind() == lltok::kw_source_filename);
793 Lex.Lex();
794 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
795 parseStringConstant(SourceFileName))
796 return true;
797 if (M)
798 M->setSourceFileName(SourceFileName);
799 return false;
800}
801
802/// parseUnnamedType:
803/// ::= LocalVarID '=' 'type' type
804bool LLParser::parseUnnamedType() {
805 LocTy TypeLoc = Lex.getLoc();
806 unsigned TypeID = Lex.getUIntVal();
807 Lex.Lex(); // eat LocalVarID;
808
809 if (parseToken(lltok::equal, "expected '=' after name") ||
810 parseToken(lltok::kw_type, "expected 'type' after '='"))
811 return true;
812
813 Type *Result = nullptr;
814 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
815 return true;
816
817 if (!isa<StructType>(Result)) {
818 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
819 if (Entry.first)
820 return error(TypeLoc, "non-struct types may not be recursive");
821 Entry.first = Result;
822 Entry.second = SMLoc();
823 }
824
825 return false;
826}
827
828/// toplevelentity
829/// ::= LocalVar '=' 'type' type
830bool LLParser::parseNamedType() {
831 std::string Name = Lex.getStrVal();
832 LocTy NameLoc = Lex.getLoc();
833 Lex.Lex(); // eat LocalVar.
834
835 if (parseToken(lltok::equal, "expected '=' after name") ||
836 parseToken(lltok::kw_type, "expected 'type' after name"))
837 return true;
838
839 Type *Result = nullptr;
840 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
841 return true;
842
843 if (!isa<StructType>(Result)) {
844 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
845 if (Entry.first)
846 return error(NameLoc, "non-struct types may not be recursive");
847 Entry.first = Result;
848 Entry.second = SMLoc();
849 }
850
851 return false;
852}
853
854/// toplevelentity
855/// ::= 'declare' FunctionHeader
856bool LLParser::parseDeclare() {
857 assert(Lex.getKind() == lltok::kw_declare);
858 Lex.Lex();
859
860 std::vector<std::pair<unsigned, MDNode *>> MDs;
861 while (Lex.getKind() == lltok::MetadataVar) {
862 unsigned MDK;
863 MDNode *N;
864 if (parseMetadataAttachment(MDK, N))
865 return true;
866 MDs.push_back({MDK, N});
867 }
868
869 Function *F;
870 unsigned FunctionNumber = -1;
871 SmallVector<unsigned> UnnamedArgNums;
872 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
873 return true;
874 for (auto &MD : MDs)
875 F->addMetadata(MD.first, *MD.second);
876 return false;
877}
878
879/// toplevelentity
880/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
881bool LLParser::parseDefine() {
882 assert(Lex.getKind() == lltok::kw_define);
883
884 FileLoc FunctionStart = getTokLineColumnPos();
885 Lex.Lex();
886
887 Function *F;
888 unsigned FunctionNumber = -1;
889 SmallVector<unsigned> UnnamedArgNums;
890 bool RetValue =
891 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
892 parseOptionalFunctionMetadata(*F) ||
893 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
894 if (ParserContext)
895 ParserContext->addFunctionLocation(
896 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
897
898 return RetValue;
899}
900
901/// parseGlobalType
902/// ::= 'constant'
903/// ::= 'global'
904bool LLParser::parseGlobalType(bool &IsConstant) {
905 if (Lex.getKind() == lltok::kw_constant)
906 IsConstant = true;
907 else if (Lex.getKind() == lltok::kw_global)
908 IsConstant = false;
909 else {
910 IsConstant = false;
911 return tokError("expected 'global' or 'constant'");
912 }
913 Lex.Lex();
914 return false;
915}
916
917bool LLParser::parseOptionalUnnamedAddr(
918 GlobalVariable::UnnamedAddr &UnnamedAddr) {
919 if (EatIfPresent(lltok::kw_unnamed_addr))
921 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
923 else
924 UnnamedAddr = GlobalValue::UnnamedAddr::None;
925 return false;
926}
927
928/// parseUnnamedGlobal:
929/// OptionalVisibility (ALIAS | IFUNC) ...
930/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
931/// OptionalDLLStorageClass
932/// ... -> global variable
933/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
934/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
935/// OptionalVisibility
936/// OptionalDLLStorageClass
937/// ... -> global variable
938bool LLParser::parseUnnamedGlobal() {
939 unsigned VarID;
940 std::string Name;
941 LocTy NameLoc = Lex.getLoc();
942
943 // Handle the GlobalID form.
944 if (Lex.getKind() == lltok::GlobalID) {
945 VarID = Lex.getUIntVal();
946 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
947 return true;
948
949 Lex.Lex(); // eat GlobalID;
950 if (parseToken(lltok::equal, "expected '=' after name"))
951 return true;
952 } else {
953 VarID = NumberedVals.getNext();
954 }
955
956 bool HasLinkage;
957 unsigned Linkage, Visibility, DLLStorageClass;
958 bool DSOLocal;
960 GlobalVariable::UnnamedAddr UnnamedAddr;
961 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
962 DSOLocal) ||
963 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
964 return true;
965
966 switch (Lex.getKind()) {
967 default:
968 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
969 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
970 case lltok::kw_alias:
971 case lltok::kw_ifunc:
972 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
973 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
974 }
975}
976
977/// parseNamedGlobal:
978/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
979/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
980/// OptionalVisibility OptionalDLLStorageClass
981/// ... -> global variable
982bool LLParser::parseNamedGlobal() {
983 assert(Lex.getKind() == lltok::GlobalVar);
984 LocTy NameLoc = Lex.getLoc();
985 std::string Name = Lex.getStrVal();
986 Lex.Lex();
987
988 bool HasLinkage;
989 unsigned Linkage, Visibility, DLLStorageClass;
990 bool DSOLocal;
992 GlobalVariable::UnnamedAddr UnnamedAddr;
993 if (parseToken(lltok::equal, "expected '=' in global variable") ||
994 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
995 DSOLocal) ||
996 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
997 return true;
998
999 switch (Lex.getKind()) {
1000 default:
1001 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
1002 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1003 case lltok::kw_alias:
1004 case lltok::kw_ifunc:
1005 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
1006 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1007 }
1008}
1009
1010bool LLParser::parseComdat() {
1011 assert(Lex.getKind() == lltok::ComdatVar);
1012 std::string Name = Lex.getStrVal();
1013 LocTy NameLoc = Lex.getLoc();
1014 Lex.Lex();
1015
1016 if (parseToken(lltok::equal, "expected '=' here"))
1017 return true;
1018
1019 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
1020 return tokError("expected comdat type");
1021
1023 switch (Lex.getKind()) {
1024 default:
1025 return tokError("unknown selection kind");
1026 case lltok::kw_any:
1027 SK = Comdat::Any;
1028 break;
1030 SK = Comdat::ExactMatch;
1031 break;
1032 case lltok::kw_largest:
1033 SK = Comdat::Largest;
1034 break;
1037 break;
1038 case lltok::kw_samesize:
1039 SK = Comdat::SameSize;
1040 break;
1041 }
1042 Lex.Lex();
1043
1044 // See if the comdat was forward referenced, if so, use the comdat.
1045 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1046 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1047 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
1048 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
1049
1050 Comdat *C;
1051 if (I != ComdatSymTab.end())
1052 C = &I->second;
1053 else
1054 C = M->getOrInsertComdat(Name);
1055 C->setSelectionKind(SK);
1056
1057 return false;
1058}
1059
1060// MDString:
1061// ::= '!' STRINGCONSTANT
1062bool LLParser::parseMDString(MDString *&Result) {
1063 std::string Str;
1064 if (parseStringConstant(Str))
1065 return true;
1066 Result = MDString::get(Context, Str);
1067 return false;
1068}
1069
1070// MDNode:
1071// ::= '!' MDNodeNumber
1072bool LLParser::parseMDNodeID(MDNode *&Result) {
1073 // !{ ..., !42, ... }
1074 LocTy IDLoc = Lex.getLoc();
1075 unsigned MID = 0;
1076 if (parseUInt32(MID))
1077 return true;
1078
1079 // If not a forward reference, just return it now.
1080 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
1081 if (!Inserted) {
1082 Result = It->second;
1083 return false;
1084 }
1085
1086 // Otherwise, create MDNode forward reference.
1087 auto &FwdRef = ForwardRefMDNodes[MID];
1088 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
1089
1090 Result = FwdRef.first.get();
1091 It->second.reset(Result);
1092 return false;
1093}
1094
1095/// parseNamedMetadata:
1096/// !foo = !{ !1, !2 }
1097bool LLParser::parseNamedMetadata() {
1098 assert(Lex.getKind() == lltok::MetadataVar);
1099 std::string Name = Lex.getStrVal();
1100 Lex.Lex();
1101
1102 if (parseToken(lltok::equal, "expected '=' here") ||
1103 parseToken(lltok::exclaim, "Expected '!' here") ||
1104 parseToken(lltok::lbrace, "Expected '{' here"))
1105 return true;
1106
1107 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1108 if (Lex.getKind() != lltok::rbrace)
1109 do {
1110 MDNode *N = nullptr;
1111 // parse DIExpressions inline as a special case. They are still MDNodes,
1112 // so they can still appear in named metadata. Remove this logic if they
1113 // become plain Metadata.
1114 if (Lex.getKind() == lltok::MetadataVar &&
1115 Lex.getStrVal() == "DIExpression") {
1116 if (parseDIExpression(N, /*IsDistinct=*/false))
1117 return true;
1118 // DIArgLists should only appear inline in a function, as they may
1119 // contain LocalAsMetadata arguments which require a function context.
1120 } else if (Lex.getKind() == lltok::MetadataVar &&
1121 Lex.getStrVal() == "DIArgList") {
1122 return tokError("found DIArgList outside of function");
1123 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1124 parseMDNodeID(N)) {
1125 return true;
1126 }
1127 NMD->addOperand(N);
1128 } while (EatIfPresent(lltok::comma));
1129
1130 return parseToken(lltok::rbrace, "expected end of metadata node");
1131}
1132
1133/// parseStandaloneMetadata:
1134/// !42 = !{...}
1135bool LLParser::parseStandaloneMetadata() {
1136 assert(Lex.getKind() == lltok::exclaim);
1137 Lex.Lex();
1138 unsigned MetadataID = 0;
1139
1140 MDNode *Init;
1141 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1142 return true;
1143
1144 // Detect common error, from old metadata syntax.
1145 if (Lex.getKind() == lltok::Type)
1146 return tokError("unexpected type in metadata definition");
1147
1148 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1149 if (Lex.getKind() == lltok::MetadataVar) {
1150 if (parseSpecializedMDNode(Init, IsDistinct))
1151 return true;
1152 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1153 parseMDTuple(Init, IsDistinct))
1154 return true;
1155
1156 // See if this was forward referenced, if so, handle it.
1157 auto FI = ForwardRefMDNodes.find(MetadataID);
1158 if (FI != ForwardRefMDNodes.end()) {
1159 auto *ToReplace = FI->second.first.get();
1160 // DIAssignID has its own special forward-reference "replacement" for
1161 // attachments (the temporary attachments are never actually attached).
1162 if (isa<DIAssignID>(Init)) {
1163 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1164 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1165 "Inst unexpectedly already has DIAssignID attachment");
1166 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1167 }
1168 }
1169
1170 ToReplace->replaceAllUsesWith(Init);
1171 ForwardRefMDNodes.erase(FI);
1172
1173 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1174 } else {
1175 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1176 if (!Inserted)
1177 return tokError("Metadata id is already used");
1178 It->second.reset(Init);
1179 }
1180
1181 return false;
1182}
1183
1184// Skips a single module summary entry.
1185bool LLParser::skipModuleSummaryEntry() {
1186 // Each module summary entry consists of a tag for the entry
1187 // type, followed by a colon, then the fields which may be surrounded by
1188 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1189 // support is in place we will look for the tokens corresponding to the
1190 // expected tags.
1191 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1192 Lex.getKind() != lltok::kw_typeid &&
1193 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1194 Lex.getKind() != lltok::kw_flags && Lex.getKind() != lltok::kw_blockcount)
1195 return tokError("Expected 'gv', 'module', 'typeid', "
1196 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1197 "start of summary entry");
1198 if (Lex.getKind() == lltok::kw_flags)
1199 return parseSummaryIndexFlags();
1200 if (Lex.getKind() == lltok::kw_blockcount)
1201 return parseBlockCount();
1202 Lex.Lex();
1203 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1204 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1205 return true;
1206 // Now walk through the parenthesized entry, until the number of open
1207 // parentheses goes back down to 0 (the first '(' was parsed above).
1208 unsigned NumOpenParen = 1;
1209 do {
1210 switch (Lex.getKind()) {
1211 case lltok::lparen:
1212 NumOpenParen++;
1213 break;
1214 case lltok::rparen:
1215 NumOpenParen--;
1216 break;
1217 case lltok::Eof:
1218 return tokError("found end of file while parsing summary entry");
1219 default:
1220 // Skip everything in between parentheses.
1221 break;
1222 }
1223 Lex.Lex();
1224 } while (NumOpenParen > 0);
1225 return false;
1226}
1227
1228/// SummaryEntry
1229/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1230bool LLParser::parseSummaryEntry() {
1231 assert(Lex.getKind() == lltok::SummaryID);
1232 unsigned SummaryID = Lex.getUIntVal();
1233
1234 // For summary entries, colons should be treated as distinct tokens,
1235 // not an indication of the end of a label token.
1236 Lex.setIgnoreColonInIdentifiers(true);
1237
1238 Lex.Lex();
1239 if (parseToken(lltok::equal, "expected '=' here"))
1240 return true;
1241
1242 // If we don't have an index object, skip the summary entry.
1243 if (!Index)
1244 return skipModuleSummaryEntry();
1245
1246 bool result = false;
1247 switch (Lex.getKind()) {
1248 case lltok::kw_gv:
1249 result = parseGVEntry(SummaryID);
1250 break;
1251 case lltok::kw_module:
1252 result = parseModuleEntry(SummaryID);
1253 break;
1254 case lltok::kw_typeid:
1255 result = parseTypeIdEntry(SummaryID);
1256 break;
1258 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1259 break;
1260 case lltok::kw_flags:
1261 result = parseSummaryIndexFlags();
1262 break;
1264 result = parseBlockCount();
1265 break;
1266 default:
1267 result = error(Lex.getLoc(), "unexpected summary kind");
1268 break;
1269 }
1270 Lex.setIgnoreColonInIdentifiers(false);
1271 return result;
1272}
1273
1282
1283// If there was an explicit dso_local, update GV. In the absence of an explicit
1284// dso_local we keep the default value.
1285static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1286 if (DSOLocal)
1287 GV.setDSOLocal(true);
1288}
1289
1290/// parseAliasOrIFunc:
1291/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1292/// OptionalVisibility OptionalDLLStorageClass
1293/// OptionalThreadLocal OptionalUnnamedAddr
1294/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1295///
1296/// AliaseeOrResolver
1297/// ::= TypeAndValue
1298///
1299/// SymbolAttrs
1300/// ::= ',' 'partition' StringConstant
1301///
1302/// Everything through OptionalUnnamedAddr has already been parsed.
1303///
1304bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1305 LocTy NameLoc, unsigned L, unsigned Visibility,
1306 unsigned DLLStorageClass, bool DSOLocal,
1308 GlobalVariable::UnnamedAddr UnnamedAddr) {
1309 bool IsAlias;
1310 if (Lex.getKind() == lltok::kw_alias)
1311 IsAlias = true;
1312 else if (Lex.getKind() == lltok::kw_ifunc)
1313 IsAlias = false;
1314 else
1315 llvm_unreachable("Not an alias or ifunc!");
1316 Lex.Lex();
1317
1319
1320 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1321 return error(NameLoc, "invalid linkage type for alias");
1322
1323 if (!isValidVisibilityForLinkage(Visibility, L))
1324 return error(NameLoc,
1325 "symbol with local linkage must have default visibility");
1326
1327 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1328 return error(NameLoc,
1329 "symbol with local linkage cannot have a DLL storage class");
1330
1331 Type *Ty;
1332 LocTy ExplicitTypeLoc = Lex.getLoc();
1333 if (parseType(Ty) ||
1334 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1335 return true;
1336
1337 Constant *Aliasee;
1338 LocTy AliaseeLoc = Lex.getLoc();
1339 if (Lex.getKind() != lltok::kw_bitcast &&
1340 Lex.getKind() != lltok::kw_getelementptr &&
1341 Lex.getKind() != lltok::kw_addrspacecast &&
1342 Lex.getKind() != lltok::kw_inttoptr) {
1343 if (parseGlobalTypeAndValue(Aliasee))
1344 return true;
1345 } else {
1346 // The bitcast dest type is not present, it is implied by the dest type.
1347 ValID ID;
1348 if (parseValID(ID, /*PFS=*/nullptr))
1349 return true;
1350 if (ID.Kind != ValID::t_Constant)
1351 return error(AliaseeLoc, "invalid aliasee");
1352 Aliasee = ID.ConstantVal;
1353 }
1354
1355 Type *AliaseeType = Aliasee->getType();
1356 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1357 if (!PTy)
1358 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1359 unsigned AddrSpace = PTy->getAddressSpace();
1360
1361 GlobalValue *GVal = nullptr;
1362
1363 // See if the alias was forward referenced, if so, prepare to replace the
1364 // forward reference.
1365 if (!Name.empty()) {
1366 auto I = ForwardRefVals.find(Name);
1367 if (I != ForwardRefVals.end()) {
1368 GVal = I->second.first;
1369 ForwardRefVals.erase(Name);
1370 } else if (M->getNamedValue(Name)) {
1371 return error(NameLoc, "redefinition of global '@" + Name + "'");
1372 }
1373 } else {
1374 auto I = ForwardRefValIDs.find(NameID);
1375 if (I != ForwardRefValIDs.end()) {
1376 GVal = I->second.first;
1377 ForwardRefValIDs.erase(I);
1378 }
1379 }
1380
1381 // Okay, create the alias/ifunc but do not insert it into the module yet.
1382 std::unique_ptr<GlobalAlias> GA;
1383 std::unique_ptr<GlobalIFunc> GI;
1384 GlobalValue *GV;
1385 if (IsAlias) {
1386 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1387 /*Parent=*/nullptr));
1388 GV = GA.get();
1389 } else {
1390 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1391 /*Parent=*/nullptr));
1392 GV = GI.get();
1393 }
1394 GV->setThreadLocalMode(TLM);
1397 GV->setUnnamedAddr(UnnamedAddr);
1398 maybeSetDSOLocal(DSOLocal, *GV);
1399
1400 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1401 // Now parse them if there are any.
1402 while (Lex.getKind() == lltok::comma) {
1403 Lex.Lex();
1404
1405 if (Lex.getKind() == lltok::kw_partition) {
1406 Lex.Lex();
1407 GV->setPartition(Lex.getStrVal());
1408 if (parseToken(lltok::StringConstant, "expected partition string"))
1409 return true;
1410 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1411 if (parseGlobalObjectMetadataAttachment(*GI))
1412 return true;
1413 } else {
1414 return tokError("unknown alias or ifunc property!");
1415 }
1416 }
1417
1418 if (Name.empty())
1419 NumberedVals.add(NameID, GV);
1420
1421 if (GVal) {
1422 // Verify that types agree.
1423 if (GVal->getType() != GV->getType())
1424 return error(
1425 ExplicitTypeLoc,
1426 "forward reference and definition of alias have different types");
1427
1428 // If they agree, just RAUW the old value with the alias and remove the
1429 // forward ref info.
1430 GVal->replaceAllUsesWith(GV);
1431 GVal->eraseFromParent();
1432 }
1433
1434 // Insert into the module, we know its name won't collide now.
1435 if (IsAlias)
1436 M->insertAlias(GA.release());
1437 else
1438 M->insertIFunc(GI.release());
1439 assert(GV->getName() == Name && "Should not be a name conflict!");
1440
1441 return false;
1442}
1443
1444static bool isSanitizer(lltok::Kind Kind) {
1445 switch (Kind) {
1448 case lltok::kw_sanitize_memtag:
1450 return true;
1451 default:
1452 return false;
1453 }
1454}
1455
1456bool LLParser::parseSanitizer(GlobalVariable *GV) {
1457 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1459 if (GV->hasSanitizerMetadata())
1460 Meta = GV->getSanitizerMetadata();
1461
1462 switch (Lex.getKind()) {
1464 Meta.NoAddress = true;
1465 break;
1467 Meta.NoHWAddress = true;
1468 break;
1469 case lltok::kw_sanitize_memtag:
1470 Meta.Memtag = true;
1471 break;
1473 Meta.IsDynInit = true;
1474 break;
1475 default:
1476 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1477 }
1478 GV->setSanitizerMetadata(Meta);
1479 Lex.Lex();
1480 return false;
1481}
1482
1483/// parseGlobal
1484/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1485/// OptionalVisibility OptionalDLLStorageClass
1486/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1487/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1488/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1489/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1490/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1491/// Const OptionalAttrs
1492///
1493/// Everything up to and including OptionalUnnamedAddr has been parsed
1494/// already.
1495///
1496bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1497 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1498 unsigned Visibility, unsigned DLLStorageClass,
1499 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1500 GlobalVariable::UnnamedAddr UnnamedAddr) {
1501 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1502 return error(NameLoc,
1503 "symbol with local linkage must have default visibility");
1504
1505 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1506 return error(NameLoc,
1507 "symbol with local linkage cannot have a DLL storage class");
1508
1509 unsigned AddrSpace;
1510 bool IsConstant, IsExternallyInitialized;
1511 LocTy IsExternallyInitializedLoc;
1512 LocTy TyLoc;
1513
1514 Type *Ty = nullptr;
1515 if (parseOptionalAddrSpace(AddrSpace) ||
1516 parseOptionalToken(lltok::kw_externally_initialized,
1517 IsExternallyInitialized,
1518 &IsExternallyInitializedLoc) ||
1519 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1520 return true;
1521
1522 // If the linkage is specified and is external, then no initializer is
1523 // present.
1524 Constant *Init = nullptr;
1525 if (!HasLinkage ||
1528 if (parseGlobalValue(Ty, Init))
1529 return true;
1530 }
1531
1533 return error(TyLoc, "invalid type for global variable");
1534
1535 GlobalValue *GVal = nullptr;
1536
1537 // See if the global was forward referenced, if so, use the global.
1538 if (!Name.empty()) {
1539 auto I = ForwardRefVals.find(Name);
1540 if (I != ForwardRefVals.end()) {
1541 GVal = I->second.first;
1542 ForwardRefVals.erase(I);
1543 } else if (M->getNamedValue(Name)) {
1544 return error(NameLoc, "redefinition of global '@" + Name + "'");
1545 }
1546 } else {
1547 // Handle @"", where a name is syntactically specified, but semantically
1548 // missing.
1549 if (NameID == (unsigned)-1)
1550 NameID = NumberedVals.getNext();
1551
1552 auto I = ForwardRefValIDs.find(NameID);
1553 if (I != ForwardRefValIDs.end()) {
1554 GVal = I->second.first;
1555 ForwardRefValIDs.erase(I);
1556 }
1557 }
1558
1559 GlobalVariable *GV = new GlobalVariable(
1560 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1562
1563 if (Name.empty())
1564 NumberedVals.add(NameID, GV);
1565
1566 // Set the parsed properties on the global.
1567 if (Init)
1568 GV->setInitializer(Init);
1569 GV->setConstant(IsConstant);
1571 maybeSetDSOLocal(DSOLocal, *GV);
1574 GV->setExternallyInitialized(IsExternallyInitialized);
1575 GV->setThreadLocalMode(TLM);
1576 GV->setUnnamedAddr(UnnamedAddr);
1577
1578 if (GVal) {
1579 if (GVal->getAddressSpace() != AddrSpace)
1580 return error(
1581 TyLoc,
1582 "forward reference and definition of global have different types");
1583
1584 GVal->replaceAllUsesWith(GV);
1585 GVal->eraseFromParent();
1586 }
1587
1588 // parse attributes on the global.
1589 while (Lex.getKind() == lltok::comma) {
1590 Lex.Lex();
1591
1592 if (Lex.getKind() == lltok::kw_section) {
1593 Lex.Lex();
1594 GV->setSection(Lex.getStrVal());
1595 if (parseToken(lltok::StringConstant, "expected global section string"))
1596 return true;
1597 } else if (Lex.getKind() == lltok::kw_partition) {
1598 Lex.Lex();
1599 GV->setPartition(Lex.getStrVal());
1600 if (parseToken(lltok::StringConstant, "expected partition string"))
1601 return true;
1602 } else if (Lex.getKind() == lltok::kw_align) {
1603 MaybeAlign Alignment;
1604 if (parseOptionalAlignment(Alignment))
1605 return true;
1606 if (Alignment)
1607 GV->setAlignment(*Alignment);
1608 } else if (Lex.getKind() == lltok::kw_code_model) {
1610 if (parseOptionalCodeModel(CodeModel))
1611 return true;
1612 GV->setCodeModel(CodeModel);
1613 } else if (Lex.getKind() == lltok::MetadataVar) {
1614 if (parseGlobalObjectMetadataAttachment(*GV))
1615 return true;
1616 } else if (isSanitizer(Lex.getKind())) {
1617 if (parseSanitizer(GV))
1618 return true;
1619 } else {
1620 Comdat *C;
1621 if (parseOptionalComdat(Name, C))
1622 return true;
1623 if (C)
1624 GV->setComdat(C);
1625 else
1626 return tokError("unknown global variable property!");
1627 }
1628 }
1629
1630 AttrBuilder Attrs(M->getContext());
1631 LocTy BuiltinLoc;
1632 std::vector<unsigned> FwdRefAttrGrps;
1633 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1634 return true;
1635 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1636 GV->setAttributes(AttributeSet::get(Context, Attrs));
1637 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1638 }
1639
1640 return false;
1641}
1642
1643/// parseUnnamedAttrGrp
1644/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1645bool LLParser::parseUnnamedAttrGrp() {
1646 assert(Lex.getKind() == lltok::kw_attributes);
1647 LocTy AttrGrpLoc = Lex.getLoc();
1648 Lex.Lex();
1649
1650 if (Lex.getKind() != lltok::AttrGrpID)
1651 return tokError("expected attribute group id");
1652
1653 unsigned VarID = Lex.getUIntVal();
1654 std::vector<unsigned> unused;
1655 LocTy BuiltinLoc;
1656 Lex.Lex();
1657
1658 if (parseToken(lltok::equal, "expected '=' here") ||
1659 parseToken(lltok::lbrace, "expected '{' here"))
1660 return true;
1661
1662 auto R = NumberedAttrBuilders.find(VarID);
1663 if (R == NumberedAttrBuilders.end())
1664 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1665
1666 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1667 parseToken(lltok::rbrace, "expected end of attribute group"))
1668 return true;
1669
1670 if (!R->second.hasAttributes())
1671 return error(AttrGrpLoc, "attribute group has no attributes");
1672
1673 return false;
1674}
1675
1677 switch (Kind) {
1678#define GET_ATTR_NAMES
1679#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1680 case lltok::kw_##DISPLAY_NAME: \
1681 return Attribute::ENUM_NAME;
1682#include "llvm/IR/Attributes.inc"
1683 default:
1684 return Attribute::None;
1685 }
1686}
1687
1688bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1689 bool InAttrGroup) {
1690 if (Attribute::isTypeAttrKind(Attr))
1691 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1692
1693 switch (Attr) {
1694 case Attribute::Alignment: {
1695 MaybeAlign Alignment;
1696 if (InAttrGroup) {
1697 uint32_t Value = 0;
1698 Lex.Lex();
1699 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1700 return true;
1702 } else {
1703 if (parseOptionalAlignment(Alignment, true))
1704 return true;
1705 }
1706 B.addAlignmentAttr(Alignment);
1707 return false;
1708 }
1709 case Attribute::StackAlignment: {
1710 unsigned Alignment;
1711 if (InAttrGroup) {
1712 Lex.Lex();
1713 if (parseToken(lltok::equal, "expected '=' here") ||
1714 parseUInt32(Alignment))
1715 return true;
1716 } else {
1717 if (parseOptionalStackAlignment(Alignment))
1718 return true;
1719 }
1720 B.addStackAlignmentAttr(Alignment);
1721 return false;
1722 }
1723 case Attribute::AllocSize: {
1724 unsigned ElemSizeArg;
1725 std::optional<unsigned> NumElemsArg;
1726 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1727 return true;
1728 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1729 return false;
1730 }
1731 case Attribute::VScaleRange: {
1732 unsigned MinValue, MaxValue;
1733 if (parseVScaleRangeArguments(MinValue, MaxValue))
1734 return true;
1735 B.addVScaleRangeAttr(MinValue,
1736 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1737 return false;
1738 }
1739 case Attribute::Dereferenceable: {
1740 std::optional<uint64_t> Bytes;
1741 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1742 return true;
1743 assert(Bytes.has_value());
1744 B.addDereferenceableAttr(Bytes.value());
1745 return false;
1746 }
1747 case Attribute::DeadOnReturn: {
1748 std::optional<uint64_t> Bytes;
1749 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1750 /*ErrorNoBytes=*/false))
1751 return true;
1752 if (Bytes.has_value()) {
1753 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1754 } else {
1755 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1756 }
1757 return false;
1758 }
1759 case Attribute::DereferenceableOrNull: {
1760 std::optional<uint64_t> Bytes;
1761 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1762 return true;
1763 assert(Bytes.has_value());
1764 B.addDereferenceableOrNullAttr(Bytes.value());
1765 return false;
1766 }
1767 case Attribute::UWTable: {
1769 if (parseOptionalUWTableKind(Kind))
1770 return true;
1771 B.addUWTableAttr(Kind);
1772 return false;
1773 }
1774 case Attribute::AllocKind: {
1776 if (parseAllocKind(Kind))
1777 return true;
1778 B.addAllocKindAttr(Kind);
1779 return false;
1780 }
1781 case Attribute::Memory: {
1782 std::optional<MemoryEffects> ME = parseMemoryAttr();
1783 if (!ME)
1784 return true;
1785 B.addMemoryAttr(*ME);
1786 return false;
1787 }
1788 case Attribute::DenormalFPEnv: {
1789 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1790 if (!Mode)
1791 return true;
1792
1793 B.addDenormalFPEnvAttr(*Mode);
1794 return false;
1795 }
1796 case Attribute::NoFPClass: {
1797 if (FPClassTest NoFPClass =
1798 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1799 B.addNoFPClassAttr(NoFPClass);
1800 return false;
1801 }
1802
1803 return true;
1804 }
1805 case Attribute::Range:
1806 return parseRangeAttr(B);
1807 case Attribute::Initializes:
1808 return parseInitializesAttr(B);
1809 case Attribute::Captures:
1810 return parseCapturesAttr(B);
1811 default:
1812 B.addAttribute(Attr);
1813 Lex.Lex();
1814 return false;
1815 }
1816}
1817
1819 switch (Kind) {
1820 case lltok::kw_readnone:
1821 ME &= MemoryEffects::none();
1822 return true;
1823 case lltok::kw_readonly:
1825 return true;
1826 case lltok::kw_writeonly:
1828 return true;
1831 return true;
1834 return true;
1837 return true;
1838 default:
1839 return false;
1840 }
1841}
1842
1843/// parseFnAttributeValuePairs
1844/// ::= <attr> | <attr> '=' <value>
1845bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1846 std::vector<unsigned> &FwdRefAttrGrps,
1847 bool InAttrGrp, LocTy &BuiltinLoc) {
1848 bool HaveError = false;
1849
1850 B.clear();
1851
1853 while (true) {
1854 lltok::Kind Token = Lex.getKind();
1855 if (Token == lltok::rbrace)
1856 break; // Finished.
1857
1858 if (Token == lltok::StringConstant) {
1859 if (parseStringAttribute(B))
1860 return true;
1861 continue;
1862 }
1863
1864 if (Token == lltok::AttrGrpID) {
1865 // Allow a function to reference an attribute group:
1866 //
1867 // define void @foo() #1 { ... }
1868 if (InAttrGrp) {
1869 HaveError |= error(
1870 Lex.getLoc(),
1871 "cannot have an attribute group reference in an attribute group");
1872 } else {
1873 // Save the reference to the attribute group. We'll fill it in later.
1874 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1875 }
1876 Lex.Lex();
1877 continue;
1878 }
1879
1880 SMLoc Loc = Lex.getLoc();
1881 if (Token == lltok::kw_builtin)
1882 BuiltinLoc = Loc;
1883
1884 if (upgradeMemoryAttr(ME, Token)) {
1885 Lex.Lex();
1886 continue;
1887 }
1888
1890 if (Attr == Attribute::None) {
1891 if (!InAttrGrp)
1892 break;
1893 return error(Lex.getLoc(), "unterminated attribute group");
1894 }
1895
1896 if (parseEnumAttribute(Attr, B, InAttrGrp))
1897 return true;
1898
1899 // As a hack, we allow function alignment to be initially parsed as an
1900 // attribute on a function declaration/definition or added to an attribute
1901 // group and later moved to the alignment field.
1902 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1903 HaveError |= error(Loc, "this attribute does not apply to functions");
1904 }
1905
1906 if (ME != MemoryEffects::unknown())
1907 B.addMemoryAttr(ME);
1908 return HaveError;
1909}
1910
1911//===----------------------------------------------------------------------===//
1912// GlobalValue Reference/Resolution Routines.
1913//===----------------------------------------------------------------------===//
1914
1916 // The used global type does not matter. We will later RAUW it with a
1917 // global/function of the correct type.
1918 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1921 PTy->getAddressSpace());
1922}
1923
1924Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1925 Value *Val) {
1926 Type *ValTy = Val->getType();
1927 if (ValTy == Ty)
1928 return Val;
1929 if (Ty->isLabelTy())
1930 error(Loc, "'" + Name + "' is not a basic block");
1931 else
1932 error(Loc, "'" + Name + "' defined with type '" +
1933 getTypeString(Val->getType()) + "' but expected '" +
1934 getTypeString(Ty) + "'");
1935 return nullptr;
1936}
1937
1938/// getGlobalVal - Get a value with the specified name or ID, creating a
1939/// forward reference record if needed. This can return null if the value
1940/// exists but does not have the right type.
1941GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1942 LocTy Loc) {
1944 if (!PTy) {
1945 error(Loc, "global variable reference must have pointer type");
1946 return nullptr;
1947 }
1948
1949 // Look this name up in the normal function symbol table.
1950 GlobalValue *Val =
1951 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1952
1953 // If this is a forward reference for the value, see if we already created a
1954 // forward ref record.
1955 if (!Val) {
1956 auto I = ForwardRefVals.find(Name);
1957 if (I != ForwardRefVals.end())
1958 Val = I->second.first;
1959 }
1960
1961 // If we have the value in the symbol table or fwd-ref table, return it.
1962 if (Val)
1964 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1965
1966 // Otherwise, create a new forward reference for this value and remember it.
1967 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1968 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1969 return FwdVal;
1970}
1971
1972GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1974 if (!PTy) {
1975 error(Loc, "global variable reference must have pointer type");
1976 return nullptr;
1977 }
1978
1979 GlobalValue *Val = NumberedVals.get(ID);
1980
1981 // If this is a forward reference for the value, see if we already created a
1982 // forward ref record.
1983 if (!Val) {
1984 auto I = ForwardRefValIDs.find(ID);
1985 if (I != ForwardRefValIDs.end())
1986 Val = I->second.first;
1987 }
1988
1989 // If we have the value in the symbol table or fwd-ref table, return it.
1990 if (Val)
1992 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1993
1994 // Otherwise, create a new forward reference for this value and remember it.
1995 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1996 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1997 return FwdVal;
1998}
1999
2000//===----------------------------------------------------------------------===//
2001// Comdat Reference/Resolution Routines.
2002//===----------------------------------------------------------------------===//
2003
2004Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
2005 // Look this name up in the comdat symbol table.
2006 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
2007 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
2008 if (I != ComdatSymTab.end())
2009 return &I->second;
2010
2011 // Otherwise, create a new forward reference for this value and remember it.
2012 Comdat *C = M->getOrInsertComdat(Name);
2013 ForwardRefComdats[Name] = Loc;
2014 return C;
2015}
2016
2017//===----------------------------------------------------------------------===//
2018// Helper Routines.
2019//===----------------------------------------------------------------------===//
2020
2021/// parseToken - If the current token has the specified kind, eat it and return
2022/// success. Otherwise, emit the specified error and return failure.
2023bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
2024 if (Lex.getKind() != T)
2025 return tokError(ErrMsg);
2026 Lex.Lex();
2027 return false;
2028}
2029
2030/// parseStringConstant
2031/// ::= StringConstant
2032bool LLParser::parseStringConstant(std::string &Result) {
2033 if (Lex.getKind() != lltok::StringConstant)
2034 return tokError("expected string constant");
2035 Result = Lex.getStrVal();
2036 Lex.Lex();
2037 return false;
2038}
2039
2040/// parseUInt32
2041/// ::= uint32
2042bool LLParser::parseUInt32(uint32_t &Val) {
2043 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2044 return tokError("expected integer");
2045 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2046 if (Val64 != unsigned(Val64))
2047 return tokError("expected 32-bit integer (too large)");
2048 Val = Val64;
2049 Lex.Lex();
2050 return false;
2051}
2052
2053/// parseUInt64
2054/// ::= uint64
2055bool LLParser::parseUInt64(uint64_t &Val) {
2056 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2057 return tokError("expected integer");
2058 Val = Lex.getAPSIntVal().getLimitedValue();
2059 Lex.Lex();
2060 return false;
2061}
2062
2063/// parseTLSModel
2064/// := 'localdynamic'
2065/// := 'initialexec'
2066/// := 'localexec'
2067bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
2068 switch (Lex.getKind()) {
2069 default:
2070 return tokError("expected localdynamic, initialexec or localexec");
2073 break;
2076 break;
2079 break;
2080 }
2081
2082 Lex.Lex();
2083 return false;
2084}
2085
2086/// parseOptionalThreadLocal
2087/// := /*empty*/
2088/// := 'thread_local'
2089/// := 'thread_local' '(' tlsmodel ')'
2090bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
2092 if (!EatIfPresent(lltok::kw_thread_local))
2093 return false;
2094
2096 if (Lex.getKind() == lltok::lparen) {
2097 Lex.Lex();
2098 return parseTLSModel(TLM) ||
2099 parseToken(lltok::rparen, "expected ')' after thread local model");
2100 }
2101 return false;
2102}
2103
2104/// parseOptionalAddrSpace
2105/// := /*empty*/
2106/// := 'addrspace' '(' uint32 ')'
2107bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
2108 AddrSpace = DefaultAS;
2109 if (!EatIfPresent(lltok::kw_addrspace))
2110 return false;
2111
2112 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
2113 if (Lex.getKind() == lltok::StringConstant) {
2114 const std::string &AddrSpaceStr = Lex.getStrVal();
2115 if (AddrSpaceStr == "A") {
2116 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2117 } else if (AddrSpaceStr == "G") {
2118 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2119 } else if (AddrSpaceStr == "P") {
2120 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2121 } else if (std::optional<unsigned> AS =
2122 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2123 AddrSpace = *AS;
2124 } else {
2125 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2126 }
2127 Lex.Lex();
2128 return false;
2129 }
2130 if (Lex.getKind() != lltok::APSInt)
2131 return tokError("expected integer or string constant");
2132 SMLoc Loc = Lex.getLoc();
2133 if (parseUInt32(AddrSpace))
2134 return true;
2135 if (!isUInt<24>(AddrSpace))
2136 return error(Loc, "invalid address space, must be a 24-bit integer");
2137 return false;
2138 };
2139
2140 return parseToken(lltok::lparen, "expected '(' in address space") ||
2141 ParseAddrspaceValue(AddrSpace) ||
2142 parseToken(lltok::rparen, "expected ')' in address space");
2143}
2144
2145/// parseStringAttribute
2146/// := StringConstant
2147/// := StringConstant '=' StringConstant
2148bool LLParser::parseStringAttribute(AttrBuilder &B) {
2149 std::string Attr = Lex.getStrVal();
2150 Lex.Lex();
2151 std::string Val;
2152 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2153 return true;
2154 B.addAttribute(Attr, Val);
2155 return false;
2156}
2157
2158/// Parse a potentially empty list of parameter or return attributes.
2159bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2160 bool HaveError = false;
2161
2162 B.clear();
2163
2164 while (true) {
2165 lltok::Kind Token = Lex.getKind();
2166 if (Token == lltok::StringConstant) {
2167 if (parseStringAttribute(B))
2168 return true;
2169 continue;
2170 }
2171
2172 if (Token == lltok::kw_nocapture) {
2173 Lex.Lex();
2174 B.addCapturesAttr(CaptureInfo::none());
2175 continue;
2176 }
2177
2178 SMLoc Loc = Lex.getLoc();
2180 if (Attr == Attribute::None)
2181 return HaveError;
2182
2183 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2184 return true;
2185
2186 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2187 HaveError |= error(Loc, "this attribute does not apply to parameters");
2188 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2189 HaveError |= error(Loc, "this attribute does not apply to return values");
2190 }
2191}
2192
2193static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2194 HasLinkage = true;
2195 switch (Kind) {
2196 default:
2197 HasLinkage = false;
2199 case lltok::kw_private:
2201 case lltok::kw_internal:
2203 case lltok::kw_weak:
2205 case lltok::kw_weak_odr:
2207 case lltok::kw_linkonce:
2215 case lltok::kw_common:
2219 case lltok::kw_external:
2221 }
2222}
2223
2224/// parseOptionalLinkage
2225/// ::= /*empty*/
2226/// ::= 'private'
2227/// ::= 'internal'
2228/// ::= 'weak'
2229/// ::= 'weak_odr'
2230/// ::= 'linkonce'
2231/// ::= 'linkonce_odr'
2232/// ::= 'available_externally'
2233/// ::= 'appending'
2234/// ::= 'common'
2235/// ::= 'extern_weak'
2236/// ::= 'external'
2237bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2238 unsigned &Visibility,
2239 unsigned &DLLStorageClass, bool &DSOLocal) {
2240 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2241 if (HasLinkage)
2242 Lex.Lex();
2243 parseOptionalDSOLocal(DSOLocal);
2244 parseOptionalVisibility(Visibility);
2245 parseOptionalDLLStorageClass(DLLStorageClass);
2246
2247 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2248 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2249 }
2250
2251 return false;
2252}
2253
2254void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2255 switch (Lex.getKind()) {
2256 default:
2257 DSOLocal = false;
2258 break;
2260 DSOLocal = true;
2261 Lex.Lex();
2262 break;
2264 DSOLocal = false;
2265 Lex.Lex();
2266 break;
2267 }
2268}
2269
2270/// parseOptionalVisibility
2271/// ::= /*empty*/
2272/// ::= 'default'
2273/// ::= 'hidden'
2274/// ::= 'protected'
2275///
2276void LLParser::parseOptionalVisibility(unsigned &Res) {
2277 switch (Lex.getKind()) {
2278 default:
2280 return;
2281 case lltok::kw_default:
2283 break;
2284 case lltok::kw_hidden:
2286 break;
2289 break;
2290 }
2291 Lex.Lex();
2292}
2293
2294bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2296 switch (Kind) {
2297 default:
2298 return tokError("unknown import kind. Expect definition or declaration.");
2301 return false;
2304 return false;
2305 }
2306}
2307
2308/// parseOptionalDLLStorageClass
2309/// ::= /*empty*/
2310/// ::= 'dllimport'
2311/// ::= 'dllexport'
2312///
2313void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2314 switch (Lex.getKind()) {
2315 default:
2317 return;
2320 break;
2323 break;
2324 }
2325 Lex.Lex();
2326}
2327
2328/// parseOptionalCallingConv
2329/// ::= /*empty*/
2330/// ::= 'ccc'
2331/// ::= 'fastcc'
2332/// ::= 'intel_ocl_bicc'
2333/// ::= 'coldcc'
2334/// ::= 'cfguard_checkcc'
2335/// ::= 'x86_stdcallcc'
2336/// ::= 'x86_fastcallcc'
2337/// ::= 'x86_thiscallcc'
2338/// ::= 'x86_vectorcallcc'
2339/// ::= 'arm_apcscc'
2340/// ::= 'arm_aapcscc'
2341/// ::= 'arm_aapcs_vfpcc'
2342/// ::= 'aarch64_vector_pcs'
2343/// ::= 'aarch64_sve_vector_pcs'
2344/// ::= 'aarch64_sme_preservemost_from_x0'
2345/// ::= 'aarch64_sme_preservemost_from_x1'
2346/// ::= 'aarch64_sme_preservemost_from_x2'
2347/// ::= 'msp430_intrcc'
2348/// ::= 'avr_intrcc'
2349/// ::= 'avr_signalcc'
2350/// ::= 'ptx_kernel'
2351/// ::= 'ptx_device'
2352/// ::= 'spir_func'
2353/// ::= 'spir_kernel'
2354/// ::= 'x86_64_sysvcc'
2355/// ::= 'win64cc'
2356/// ::= 'anyregcc'
2357/// ::= 'preserve_mostcc'
2358/// ::= 'preserve_allcc'
2359/// ::= 'preserve_nonecc'
2360/// ::= 'ghccc'
2361/// ::= 'swiftcc'
2362/// ::= 'swifttailcc'
2363/// ::= 'x86_intrcc'
2364/// ::= 'hhvmcc'
2365/// ::= 'hhvm_ccc'
2366/// ::= 'cxx_fast_tlscc'
2367/// ::= 'amdgpu_vs'
2368/// ::= 'amdgpu_ls'
2369/// ::= 'amdgpu_hs'
2370/// ::= 'amdgpu_es'
2371/// ::= 'amdgpu_gs'
2372/// ::= 'amdgpu_ps'
2373/// ::= 'amdgpu_cs'
2374/// ::= 'amdgpu_cs_chain'
2375/// ::= 'amdgpu_cs_chain_preserve'
2376/// ::= 'amdgpu_kernel'
2377/// ::= 'tailcc'
2378/// ::= 'm68k_rtdcc'
2379/// ::= 'wasm_emscripten_invokecc'
2380/// ::= 'graalcc'
2381/// ::= 'riscv_vector_cc'
2382/// ::= 'riscv_vls_cc'
2383/// ::= 'cc' UINT
2384///
2385bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2386 switch (Lex.getKind()) {
2387 default: CC = CallingConv::C; return false;
2388 case lltok::kw_ccc: CC = CallingConv::C; break;
2389 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2390 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2403 break;
2406 break;
2409 break;
2412 break;
2422 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2423 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2427 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2428 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2431 case lltok::kw_hhvmcc:
2433 break;
2434 case lltok::kw_hhvm_ccc:
2436 break;
2448 break;
2451 break;
2455 break;
2456 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2460 break;
2461 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2464 break;
2466 // Default ABI_VLEN
2468 Lex.Lex();
2469 if (!EatIfPresent(lltok::lparen))
2470 break;
2471 uint32_t ABIVlen;
2472 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2473 return true;
2474 switch (ABIVlen) {
2475 default:
2476 return tokError("unknown RISC-V ABI VLEN");
2477#define CC_VLS_CASE(ABIVlen) \
2478 case ABIVlen: \
2479 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2480 break;
2481 CC_VLS_CASE(32)
2482 CC_VLS_CASE(64)
2483 CC_VLS_CASE(128)
2484 CC_VLS_CASE(256)
2485 CC_VLS_CASE(512)
2486 CC_VLS_CASE(1024)
2487 CC_VLS_CASE(2048)
2488 CC_VLS_CASE(4096)
2489 CC_VLS_CASE(8192)
2490 CC_VLS_CASE(16384)
2491 CC_VLS_CASE(32768)
2492 CC_VLS_CASE(65536)
2493#undef CC_VLS_CASE
2494 }
2495 return false;
2498 break;
2501 break;
2504 break;
2505 case lltok::kw_cc: {
2506 Lex.Lex();
2507 return parseUInt32(CC);
2508 }
2509 }
2510
2511 Lex.Lex();
2512 return false;
2513}
2514
2515/// parseMetadataAttachment
2516/// ::= !dbg !42
2517bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2518 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2519
2520 std::string Name = Lex.getStrVal();
2521 Kind = M->getMDKindID(Name);
2522 Lex.Lex();
2523
2524 return parseMDNode(MD);
2525}
2526
2527/// parseInstructionMetadata
2528/// ::= !dbg !42 (',' !dbg !57)*
2529bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2530 do {
2531 if (Lex.getKind() != lltok::MetadataVar)
2532 return tokError("expected metadata after comma");
2533
2534 unsigned MDK;
2535 MDNode *N;
2536 auto Loc = Lex.getLoc();
2537 if (parseMetadataAttachment(MDK, N))
2538 return true;
2539
2540 if (MDK == LLVMContext::MD_DIAssignID)
2541 TempDIAssignIDAttachments[N].push_back(&Inst);
2542 else if (MDK == LLVMContext::MD_dbg)
2543 PendingDbgInsts.emplace_back(Loc, &Inst, N);
2544 else
2545 Inst.setMetadata(MDK, N);
2546
2547 // If this is the end of the list, we're done.
2548 } while (EatIfPresent(lltok::comma));
2549 return false;
2550}
2551
2552/// parseGlobalObjectMetadataAttachment
2553/// ::= !dbg !57
2554bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2555 unsigned MDK;
2556 MDNode *N;
2557 if (parseMetadataAttachment(MDK, N))
2558 return true;
2559
2560 GO.addMetadata(MDK, *N);
2561 return false;
2562}
2563
2564/// parseOptionalFunctionMetadata
2565/// ::= (!dbg !57)*
2566bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2567 while (Lex.getKind() == lltok::MetadataVar)
2568 if (parseGlobalObjectMetadataAttachment(F))
2569 return true;
2570 return false;
2571}
2572
2573/// parseOptionalAlignment
2574/// ::= /* empty */
2575/// ::= 'align' 4
2576bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2577 Alignment = std::nullopt;
2578 if (!EatIfPresent(lltok::kw_align))
2579 return false;
2580 LocTy AlignLoc = Lex.getLoc();
2581 uint64_t Value = 0;
2582
2583 LocTy ParenLoc = Lex.getLoc();
2584 bool HaveParens = false;
2585 if (AllowParens) {
2586 if (EatIfPresent(lltok::lparen))
2587 HaveParens = true;
2588 }
2589
2590 if (parseUInt64(Value))
2591 return true;
2592
2593 if (HaveParens && !EatIfPresent(lltok::rparen))
2594 return error(ParenLoc, "expected ')'");
2595
2596 if (!isPowerOf2_64(Value))
2597 return error(AlignLoc, "alignment is not a power of two");
2599 return error(AlignLoc, "huge alignments are not supported yet");
2601 return false;
2602}
2603
2604/// parseOptionalPrefAlignment
2605/// ::= /* empty */
2606/// ::= 'prefalign' '(' 4 ')'
2607bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2608 Alignment = std::nullopt;
2609 if (!EatIfPresent(lltok::kw_prefalign))
2610 return false;
2611 LocTy AlignLoc = Lex.getLoc();
2612 uint64_t Value = 0;
2613
2614 LocTy ParenLoc = Lex.getLoc();
2615 if (!EatIfPresent(lltok::lparen))
2616 return error(ParenLoc, "expected '('");
2617
2618 if (parseUInt64(Value))
2619 return true;
2620
2621 ParenLoc = Lex.getLoc();
2622 if (!EatIfPresent(lltok::rparen))
2623 return error(ParenLoc, "expected ')'");
2624
2625 if (!isPowerOf2_64(Value))
2626 return error(AlignLoc, "alignment is not a power of two");
2628 return error(AlignLoc, "huge alignments are not supported yet");
2630 return false;
2631}
2632
2633/// parseOptionalCodeModel
2634/// ::= /* empty */
2635/// ::= 'code_model' "large"
2636bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2637 Lex.Lex();
2638 auto StrVal = Lex.getStrVal();
2639 auto ErrMsg = "expected global code model string";
2640 if (StrVal == "tiny")
2641 model = CodeModel::Tiny;
2642 else if (StrVal == "small")
2643 model = CodeModel::Small;
2644 else if (StrVal == "kernel")
2645 model = CodeModel::Kernel;
2646 else if (StrVal == "medium")
2647 model = CodeModel::Medium;
2648 else if (StrVal == "large")
2649 model = CodeModel::Large;
2650 else
2651 return tokError(ErrMsg);
2652 if (parseToken(lltok::StringConstant, ErrMsg))
2653 return true;
2654 return false;
2655}
2656
2657/// parseOptionalAttrBytes
2658/// ::= /* empty */
2659/// ::= AttrKind '(' 4 ')'
2660///
2661/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2662/// 'dead_on_return'
2663bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2664 std::optional<uint64_t> &Bytes,
2665 bool ErrorNoBytes) {
2666 assert((AttrKind == lltok::kw_dereferenceable ||
2667 AttrKind == lltok::kw_dereferenceable_or_null ||
2668 AttrKind == lltok::kw_dead_on_return) &&
2669 "contract!");
2670
2671 Bytes = 0;
2672 if (!EatIfPresent(AttrKind))
2673 return false;
2674 LocTy ParenLoc = Lex.getLoc();
2675 if (!EatIfPresent(lltok::lparen)) {
2676 if (ErrorNoBytes)
2677 return error(ParenLoc, "expected '('");
2678 Bytes = std::nullopt;
2679 return false;
2680 }
2681 LocTy DerefLoc = Lex.getLoc();
2682 if (parseUInt64(Bytes.value()))
2683 return true;
2684 ParenLoc = Lex.getLoc();
2685 if (!EatIfPresent(lltok::rparen))
2686 return error(ParenLoc, "expected ')'");
2687 if (!Bytes.value())
2688 return error(DerefLoc, "byte count specified must be non-zero");
2689 return false;
2690}
2691
2692bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2693 Lex.Lex();
2695 if (!EatIfPresent(lltok::lparen))
2696 return false;
2697 LocTy KindLoc = Lex.getLoc();
2698 if (Lex.getKind() == lltok::kw_sync)
2700 else if (Lex.getKind() == lltok::kw_async)
2702 else
2703 return error(KindLoc, "expected unwind table kind");
2704 Lex.Lex();
2705 return parseToken(lltok::rparen, "expected ')'");
2706}
2707
2708bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2709 Lex.Lex();
2710 LocTy ParenLoc = Lex.getLoc();
2711 if (!EatIfPresent(lltok::lparen))
2712 return error(ParenLoc, "expected '('");
2713 LocTy KindLoc = Lex.getLoc();
2714 std::string Arg;
2715 if (parseStringConstant(Arg))
2716 return error(KindLoc, "expected allockind value");
2717 for (StringRef A : llvm::split(Arg, ",")) {
2718 if (A == "alloc") {
2720 } else if (A == "realloc") {
2722 } else if (A == "free") {
2724 } else if (A == "uninitialized") {
2726 } else if (A == "zeroed") {
2728 } else if (A == "aligned") {
2730 } else {
2731 return error(KindLoc, Twine("unknown allockind ") + A);
2732 }
2733 }
2734 ParenLoc = Lex.getLoc();
2735 if (!EatIfPresent(lltok::rparen))
2736 return error(ParenLoc, "expected ')'");
2737 if (Kind == AllocFnKind::Unknown)
2738 return error(KindLoc, "expected allockind value");
2739 return false;
2740}
2741
2743 using Loc = IRMemLocation;
2744
2745 switch (Tok) {
2746 case lltok::kw_argmem:
2747 return {Loc::ArgMem};
2749 return {Loc::InaccessibleMem};
2750 case lltok::kw_errnomem:
2751 return {Loc::ErrnoMem};
2753 return {Loc::TargetMem0};
2755 return {Loc::TargetMem1};
2756 case lltok::kw_target_mem: {
2759 Targets.push_back(Loc);
2760 return Targets;
2761 }
2762 default:
2763 return {};
2764 }
2765}
2766
2767static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2768 switch (Tok) {
2769 case lltok::kw_none:
2770 return ModRefInfo::NoModRef;
2771 case lltok::kw_read:
2772 return ModRefInfo::Ref;
2773 case lltok::kw_write:
2774 return ModRefInfo::Mod;
2776 return ModRefInfo::ModRef;
2777 default:
2778 return std::nullopt;
2779 }
2780}
2781
2782static std::optional<DenormalMode::DenormalModeKind>
2784 switch (Tok) {
2785 case lltok::kw_ieee:
2786 return DenormalMode::IEEE;
2791 case lltok::kw_dynamic:
2792 return DenormalMode::Dynamic;
2793 default:
2794 return std::nullopt;
2795 }
2796}
2797
2798std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2800
2801 // We use syntax like memory(argmem: read), so the colon should not be
2802 // interpreted as a label terminator.
2803 Lex.setIgnoreColonInIdentifiers(true);
2804 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2805
2806 Lex.Lex();
2807 if (!EatIfPresent(lltok::lparen)) {
2808 tokError("expected '('");
2809 return std::nullopt;
2810 }
2811
2812 bool SeenLoc = false;
2813 bool SeenTargetLoc = false;
2814 do {
2815 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2816 if (!Locs.empty()) {
2817 Lex.Lex();
2818 if (!EatIfPresent(lltok::colon)) {
2819 tokError("expected ':' after location");
2820 return std::nullopt;
2821 }
2822 }
2823
2824 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2825 if (!MR) {
2826 if (Locs.empty())
2827 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2828 "or access kind (none, read, write, readwrite)");
2829 else
2830 tokError("expected access kind (none, read, write, readwrite)");
2831 return std::nullopt;
2832 }
2833
2834 Lex.Lex();
2835 if (!Locs.empty()) {
2836 SeenLoc = true;
2837 for (IRMemLocation Loc : Locs) {
2838 ME = ME.getWithModRef(Loc, *MR);
2839 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2840 SeenTargetLoc = true;
2841 }
2842 if (Locs.size() > 1 && SeenTargetLoc) {
2843 tokError("target memory default access kind must be specified first");
2844 return std::nullopt;
2845 }
2846
2847 } else {
2848 if (SeenLoc) {
2849 tokError("default access kind must be specified first");
2850 return std::nullopt;
2851 }
2852 ME = MemoryEffects(*MR);
2853 }
2854
2855 if (EatIfPresent(lltok::rparen))
2856 return ME;
2857 } while (EatIfPresent(lltok::comma));
2858
2859 tokError("unterminated memory attribute");
2860 return std::nullopt;
2861}
2862
2863std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2864 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2865 keywordToDenormalModeKind(Lex.getKind());
2866 if (!OutputMode) {
2867 tokError("expected denormal behavior kind (ieee, preservesign, "
2868 "positivezero, dynamic)");
2869 return {};
2870 }
2871
2872 Lex.Lex();
2873
2874 std::optional<DenormalMode::DenormalModeKind> InputMode;
2875 if (EatIfPresent(lltok::bar)) {
2876 InputMode = keywordToDenormalModeKind(Lex.getKind());
2877 if (!InputMode) {
2878 tokError("expected denormal behavior kind (ieee, preservesign, "
2879 "positivezero, dynamic)");
2880 return {};
2881 }
2882
2883 Lex.Lex();
2884 } else {
2885 // Single item, input == output mode
2886 InputMode = OutputMode;
2887 }
2888
2889 return DenormalMode(*OutputMode, *InputMode);
2890}
2891
2892std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2893 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2894 // not be interpreted as a label terminator.
2895 Lex.setIgnoreColonInIdentifiers(true);
2896 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2897
2898 Lex.Lex();
2899
2900 if (parseToken(lltok::lparen, "expected '('"))
2901 return {};
2902
2903 DenormalMode DefaultMode = DenormalMode::getIEEE();
2904 DenormalMode F32Mode = DenormalMode::getInvalid();
2905
2906 bool HasDefaultSection = false;
2907 if (Lex.getKind() != lltok::Type) {
2908 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2909 if (!ParsedDefaultMode)
2910 return {};
2911 DefaultMode = *ParsedDefaultMode;
2912 HasDefaultSection = true;
2913 }
2914
2915 bool HasComma = EatIfPresent(lltok::comma);
2916 if (Lex.getKind() == lltok::Type) {
2917 if (HasDefaultSection && !HasComma) {
2918 tokError("expected ',' before float:");
2919 return {};
2920 }
2921
2922 Type *Ty = nullptr;
2923 if (parseType(Ty) || !Ty->isFloatTy()) {
2924 tokError("expected float:");
2925 return {};
2926 }
2927
2928 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2929 return {};
2930
2931 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2932 if (!ParsedF32Mode)
2933 return {};
2934
2935 F32Mode = *ParsedF32Mode;
2936 }
2937
2938 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2939 return {};
2940
2941 return DenormalFPEnv(DefaultMode, F32Mode);
2942}
2943
2944static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2945 switch (Tok) {
2946 case lltok::kw_all:
2947 return fcAllFlags;
2948 case lltok::kw_nan:
2949 return fcNan;
2950 case lltok::kw_snan:
2951 return fcSNan;
2952 case lltok::kw_qnan:
2953 return fcQNan;
2954 case lltok::kw_inf:
2955 return fcInf;
2956 case lltok::kw_ninf:
2957 return fcNegInf;
2958 case lltok::kw_pinf:
2959 return fcPosInf;
2960 case lltok::kw_norm:
2961 return fcNormal;
2962 case lltok::kw_nnorm:
2963 return fcNegNormal;
2964 case lltok::kw_pnorm:
2965 return fcPosNormal;
2966 case lltok::kw_sub:
2967 return fcSubnormal;
2968 case lltok::kw_nsub:
2969 return fcNegSubnormal;
2970 case lltok::kw_psub:
2971 return fcPosSubnormal;
2972 case lltok::kw_zero:
2973 return fcZero;
2974 case lltok::kw_nzero:
2975 return fcNegZero;
2976 case lltok::kw_pzero:
2977 return fcPosZero;
2978 default:
2979 return 0;
2980 }
2981}
2982
2983unsigned LLParser::parseNoFPClassAttr() {
2984 unsigned Mask = fcNone;
2985
2986 Lex.Lex();
2987 if (!EatIfPresent(lltok::lparen)) {
2988 tokError("expected '('");
2989 return 0;
2990 }
2991
2992 do {
2993 uint64_t Value = 0;
2994 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2995 if (TestMask != 0) {
2996 Mask |= TestMask;
2997 // TODO: Disallow overlapping masks to avoid copy paste errors
2998 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2999 !parseUInt64(Value)) {
3000 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
3001 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
3002 return 0;
3003 }
3004
3005 if (!EatIfPresent(lltok::rparen)) {
3006 error(Lex.getLoc(), "expected ')'");
3007 return 0;
3008 }
3009
3010 return Value;
3011 } else {
3012 error(Lex.getLoc(), "expected nofpclass test mask");
3013 return 0;
3014 }
3015
3016 Lex.Lex();
3017 if (EatIfPresent(lltok::rparen))
3018 return Mask;
3019 } while (1);
3020
3021 llvm_unreachable("unterminated nofpclass attribute");
3022}
3023
3024/// parseOptionalCommaAlign
3025/// ::=
3026/// ::= ',' align 4
3027///
3028/// This returns with AteExtraComma set to true if it ate an excess comma at the
3029/// end.
3030bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
3031 bool &AteExtraComma) {
3032 AteExtraComma = false;
3033 while (EatIfPresent(lltok::comma)) {
3034 // Metadata at the end is an early exit.
3035 if (Lex.getKind() == lltok::MetadataVar) {
3036 AteExtraComma = true;
3037 return false;
3038 }
3039
3040 if (Lex.getKind() != lltok::kw_align)
3041 return error(Lex.getLoc(), "expected metadata or 'align'");
3042
3043 if (parseOptionalAlignment(Alignment))
3044 return true;
3045 }
3046
3047 return false;
3048}
3049
3050/// parseOptionalCommaAddrSpace
3051/// ::=
3052/// ::= ',' addrspace(1)
3053///
3054/// This returns with AteExtraComma set to true if it ate an excess comma at the
3055/// end.
3056bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
3057 bool &AteExtraComma) {
3058 AteExtraComma = false;
3059 while (EatIfPresent(lltok::comma)) {
3060 // Metadata at the end is an early exit.
3061 if (Lex.getKind() == lltok::MetadataVar) {
3062 AteExtraComma = true;
3063 return false;
3064 }
3065
3066 Loc = Lex.getLoc();
3067 if (Lex.getKind() != lltok::kw_addrspace)
3068 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
3069
3070 if (parseOptionalAddrSpace(AddrSpace))
3071 return true;
3072 }
3073
3074 return false;
3075}
3076
3077bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
3078 std::optional<unsigned> &HowManyArg) {
3079 Lex.Lex();
3080
3081 auto StartParen = Lex.getLoc();
3082 if (!EatIfPresent(lltok::lparen))
3083 return error(StartParen, "expected '('");
3084
3085 if (parseUInt32(BaseSizeArg))
3086 return true;
3087
3088 if (EatIfPresent(lltok::comma)) {
3089 auto HowManyAt = Lex.getLoc();
3090 unsigned HowMany;
3091 if (parseUInt32(HowMany))
3092 return true;
3093 if (HowMany == BaseSizeArg)
3094 return error(HowManyAt,
3095 "'allocsize' indices can't refer to the same parameter");
3096 HowManyArg = HowMany;
3097 } else
3098 HowManyArg = std::nullopt;
3099
3100 auto EndParen = Lex.getLoc();
3101 if (!EatIfPresent(lltok::rparen))
3102 return error(EndParen, "expected ')'");
3103 return false;
3104}
3105
3106bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
3107 unsigned &MaxValue) {
3108 Lex.Lex();
3109
3110 auto StartParen = Lex.getLoc();
3111 if (!EatIfPresent(lltok::lparen))
3112 return error(StartParen, "expected '('");
3113
3114 if (parseUInt32(MinValue))
3115 return true;
3116
3117 if (EatIfPresent(lltok::comma)) {
3118 if (parseUInt32(MaxValue))
3119 return true;
3120 } else
3121 MaxValue = MinValue;
3122
3123 auto EndParen = Lex.getLoc();
3124 if (!EatIfPresent(lltok::rparen))
3125 return error(EndParen, "expected ')'");
3126 return false;
3127}
3128
3129/// parseScopeAndOrdering
3130/// if isAtomic: ::= SyncScope? AtomicOrdering
3131/// else: ::=
3132///
3133/// This sets Scope and Ordering to the parsed values.
3134bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3135 AtomicOrdering &Ordering) {
3136 if (!IsAtomic)
3137 return false;
3138
3139 return parseScope(SSID) || parseOrdering(Ordering);
3140}
3141
3142/// parseScope
3143/// ::= syncscope("singlethread" | "<target scope>")?
3144///
3145/// This sets synchronization scope ID to the ID of the parsed value.
3146bool LLParser::parseScope(SyncScope::ID &SSID) {
3147 SSID = SyncScope::System;
3148 if (EatIfPresent(lltok::kw_syncscope)) {
3149 auto StartParenAt = Lex.getLoc();
3150 if (!EatIfPresent(lltok::lparen))
3151 return error(StartParenAt, "Expected '(' in syncscope");
3152
3153 std::string SSN;
3154 auto SSNAt = Lex.getLoc();
3155 if (parseStringConstant(SSN))
3156 return error(SSNAt, "Expected synchronization scope name");
3157
3158 auto EndParenAt = Lex.getLoc();
3159 if (!EatIfPresent(lltok::rparen))
3160 return error(EndParenAt, "Expected ')' in syncscope");
3161
3162 SSID = Context.getOrInsertSyncScopeID(SSN);
3163 }
3164
3165 return false;
3166}
3167
3168/// parseOrdering
3169/// ::= AtomicOrdering
3170///
3171/// This sets Ordering to the parsed value.
3172bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3173 switch (Lex.getKind()) {
3174 default:
3175 return tokError("Expected ordering on atomic instruction");
3178 // Not specified yet:
3179 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3183 case lltok::kw_seq_cst:
3185 break;
3186 }
3187 Lex.Lex();
3188 return false;
3189}
3190
3191/// parseOptionalStackAlignment
3192/// ::= /* empty */
3193/// ::= 'alignstack' '(' 4 ')'
3194bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3195 Alignment = 0;
3196 if (!EatIfPresent(lltok::kw_alignstack))
3197 return false;
3198 LocTy ParenLoc = Lex.getLoc();
3199 if (!EatIfPresent(lltok::lparen))
3200 return error(ParenLoc, "expected '('");
3201 LocTy AlignLoc = Lex.getLoc();
3202 if (parseUInt32(Alignment))
3203 return true;
3204 ParenLoc = Lex.getLoc();
3205 if (!EatIfPresent(lltok::rparen))
3206 return error(ParenLoc, "expected ')'");
3207 if (!isPowerOf2_32(Alignment))
3208 return error(AlignLoc, "stack alignment is not a power of two");
3209 return false;
3210}
3211
3212/// parseIndexList - This parses the index list for an insert/extractvalue
3213/// instruction. This sets AteExtraComma in the case where we eat an extra
3214/// comma at the end of the line and find that it is followed by metadata.
3215/// Clients that don't allow metadata can call the version of this function that
3216/// only takes one argument.
3217///
3218/// parseIndexList
3219/// ::= (',' uint32)+
3220///
3221bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3222 bool &AteExtraComma) {
3223 AteExtraComma = false;
3224
3225 if (Lex.getKind() != lltok::comma)
3226 return tokError("expected ',' as start of index list");
3227
3228 while (EatIfPresent(lltok::comma)) {
3229 if (Lex.getKind() == lltok::MetadataVar) {
3230 if (Indices.empty())
3231 return tokError("expected index");
3232 AteExtraComma = true;
3233 return false;
3234 }
3235 unsigned Idx = 0;
3236 if (parseUInt32(Idx))
3237 return true;
3238 Indices.push_back(Idx);
3239 }
3240
3241 return false;
3242}
3243
3244//===----------------------------------------------------------------------===//
3245// Type Parsing.
3246//===----------------------------------------------------------------------===//
3247
3248/// parseType - parse a type.
3249bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3250 SMLoc TypeLoc = Lex.getLoc();
3251 switch (Lex.getKind()) {
3252 default:
3253 return tokError(Msg);
3254 case lltok::Type:
3255 // Type ::= 'float' | 'void' (etc)
3256 Result = Lex.getTyVal();
3257 Lex.Lex();
3258
3259 // Handle "ptr" opaque pointer type.
3260 //
3261 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3262 if (Result->isPointerTy()) {
3263 unsigned AddrSpace;
3264 if (parseOptionalAddrSpace(AddrSpace))
3265 return true;
3266 Result = PointerType::get(getContext(), AddrSpace);
3267
3268 // Give a nice error for 'ptr*'.
3269 if (Lex.getKind() == lltok::star)
3270 return tokError("ptr* is invalid - use ptr instead");
3271
3272 // Fall through to parsing the type suffixes only if this 'ptr' is a
3273 // function return. Otherwise, return success, implicitly rejecting other
3274 // suffixes.
3275 if (Lex.getKind() != lltok::lparen)
3276 return false;
3277 }
3278 break;
3279 case lltok::kw_target: {
3280 // Type ::= TargetExtType
3281 if (parseTargetExtType(Result))
3282 return true;
3283 break;
3284 }
3285 case lltok::lbrace:
3286 // Type ::= StructType
3287 if (parseAnonStructType(Result, false))
3288 return true;
3289 break;
3290 case lltok::lsquare:
3291 // Type ::= '[' ... ']'
3292 Lex.Lex(); // eat the lsquare.
3293 if (parseArrayVectorType(Result, false))
3294 return true;
3295 break;
3296 case lltok::less: // Either vector or packed struct.
3297 // Type ::= '<' ... '>'
3298 Lex.Lex();
3299 if (Lex.getKind() == lltok::lbrace) {
3300 if (parseAnonStructType(Result, true) ||
3301 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3302 return true;
3303 } else if (parseArrayVectorType(Result, true))
3304 return true;
3305 break;
3306 case lltok::LocalVar: {
3307 // Type ::= %foo
3308 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3309
3310 // If the type hasn't been defined yet, create a forward definition and
3311 // remember where that forward def'n was seen (in case it never is defined).
3312 if (!Entry.first) {
3313 Entry.first = StructType::create(Context, Lex.getStrVal());
3314 Entry.second = Lex.getLoc();
3315 }
3316 Result = Entry.first;
3317 Lex.Lex();
3318 break;
3319 }
3320
3321 case lltok::LocalVarID: {
3322 // Type ::= %4
3323 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3324
3325 // If the type hasn't been defined yet, create a forward definition and
3326 // remember where that forward def'n was seen (in case it never is defined).
3327 if (!Entry.first) {
3328 Entry.first = StructType::create(Context);
3329 Entry.second = Lex.getLoc();
3330 }
3331 Result = Entry.first;
3332 Lex.Lex();
3333 break;
3334 }
3335 }
3336
3337 // parse the type suffixes.
3338 while (true) {
3339 switch (Lex.getKind()) {
3340 // End of type.
3341 default:
3342 if (!AllowVoid && Result->isVoidTy())
3343 return error(TypeLoc, "void type only allowed for function results");
3344 return false;
3345
3346 // Type ::= Type '*'
3347 case lltok::star:
3348 if (Result->isLabelTy())
3349 return tokError("basic block pointers are invalid");
3350 if (Result->isVoidTy())
3351 return tokError("pointers to void are invalid - use i8* instead");
3353 return tokError("pointer to this type is invalid");
3354 Result = PointerType::getUnqual(Context);
3355 Lex.Lex();
3356 break;
3357
3358 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3359 case lltok::kw_addrspace: {
3360 if (Result->isLabelTy())
3361 return tokError("basic block pointers are invalid");
3362 if (Result->isVoidTy())
3363 return tokError("pointers to void are invalid; use i8* instead");
3365 return tokError("pointer to this type is invalid");
3366 unsigned AddrSpace;
3367 if (parseOptionalAddrSpace(AddrSpace) ||
3368 parseToken(lltok::star, "expected '*' in address space"))
3369 return true;
3370
3371 Result = PointerType::get(Context, AddrSpace);
3372 break;
3373 }
3374
3375 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3376 case lltok::lparen:
3377 if (parseFunctionType(Result))
3378 return true;
3379 break;
3380 }
3381 }
3382}
3383
3384/// parseParameterList
3385/// ::= '(' ')'
3386/// ::= '(' Arg (',' Arg)* ')'
3387/// Arg
3388/// ::= Type OptionalAttributes Value OptionalAttributes
3389bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3390 PerFunctionState &PFS, bool IsMustTailCall,
3391 bool InVarArgsFunc) {
3392 if (parseToken(lltok::lparen, "expected '(' in call"))
3393 return true;
3394
3395 while (Lex.getKind() != lltok::rparen) {
3396 // If this isn't the first argument, we need a comma.
3397 if (!ArgList.empty() &&
3398 parseToken(lltok::comma, "expected ',' in argument list"))
3399 return true;
3400
3401 // parse an ellipsis if this is a musttail call in a variadic function.
3402 if (Lex.getKind() == lltok::dotdotdot) {
3403 const char *Msg = "unexpected ellipsis in argument list for ";
3404 if (!IsMustTailCall)
3405 return tokError(Twine(Msg) + "non-musttail call");
3406 if (!InVarArgsFunc)
3407 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3408 Lex.Lex(); // Lex the '...', it is purely for readability.
3409 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3410 }
3411
3412 // parse the argument.
3413 LocTy ArgLoc;
3414 Type *ArgTy = nullptr;
3415 Value *V;
3416 if (parseType(ArgTy, ArgLoc))
3417 return true;
3419 return error(ArgLoc, "invalid type for function argument");
3420
3421 AttrBuilder ArgAttrs(M->getContext());
3422
3423 if (ArgTy->isMetadataTy()) {
3424 if (parseMetadataAsValue(V, PFS))
3425 return true;
3426 } else {
3427 // Otherwise, handle normal operands.
3428 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3429 return true;
3430 }
3431 ArgList.push_back(ParamInfo(
3432 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3433 }
3434
3435 if (IsMustTailCall && InVarArgsFunc)
3436 return tokError("expected '...' at end of argument list for musttail call "
3437 "in varargs function");
3438
3439 Lex.Lex(); // Lex the ')'.
3440 return false;
3441}
3442
3443/// parseRequiredTypeAttr
3444/// ::= attrname(<ty>)
3445bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3446 Attribute::AttrKind AttrKind) {
3447 Type *Ty = nullptr;
3448 if (!EatIfPresent(AttrToken))
3449 return true;
3450 if (!EatIfPresent(lltok::lparen))
3451 return error(Lex.getLoc(), "expected '('");
3452 if (parseType(Ty))
3453 return true;
3454 if (!EatIfPresent(lltok::rparen))
3455 return error(Lex.getLoc(), "expected ')'");
3456
3457 B.addTypeAttr(AttrKind, Ty);
3458 return false;
3459}
3460
3461/// parseRangeAttr
3462/// ::= range(<ty> <n>,<n>)
3463bool LLParser::parseRangeAttr(AttrBuilder &B) {
3464 Lex.Lex();
3465
3466 APInt Lower;
3467 APInt Upper;
3468 Type *Ty = nullptr;
3469 LocTy TyLoc;
3470
3471 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3472 if (Lex.getKind() != lltok::APSInt)
3473 return tokError("expected integer");
3474 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3475 return tokError(
3476 "integer is too large for the bit width of specified type");
3477 Val = Lex.getAPSIntVal().extend(BitWidth);
3478 Lex.Lex();
3479 return false;
3480 };
3481
3482 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3483 return true;
3484 if (!Ty->isIntegerTy())
3485 return error(TyLoc, "the range must have integer type!");
3486
3487 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3488
3489 if (ParseAPSInt(BitWidth, Lower) ||
3490 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3491 return true;
3492 if (Lower == Upper && !Lower.isZero())
3493 return tokError("the range represent the empty set but limits aren't 0!");
3494
3495 if (parseToken(lltok::rparen, "expected ')'"))
3496 return true;
3497
3498 B.addRangeAttr(ConstantRange(Lower, Upper));
3499 return false;
3500}
3501
3502/// parseInitializesAttr
3503/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3504bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3505 Lex.Lex();
3506
3507 auto ParseAPSInt = [&](APInt &Val) {
3508 if (Lex.getKind() != lltok::APSInt)
3509 return tokError("expected integer");
3510 Val = Lex.getAPSIntVal().extend(64);
3511 Lex.Lex();
3512 return false;
3513 };
3514
3515 if (parseToken(lltok::lparen, "expected '('"))
3516 return true;
3517
3519 // Parse each constant range.
3520 do {
3521 APInt Lower, Upper;
3522 if (parseToken(lltok::lparen, "expected '('"))
3523 return true;
3524
3525 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3526 ParseAPSInt(Upper))
3527 return true;
3528
3529 if (Lower == Upper)
3530 return tokError("the range should not represent the full or empty set!");
3531
3532 if (parseToken(lltok::rparen, "expected ')'"))
3533 return true;
3534
3535 RangeList.push_back(ConstantRange(Lower, Upper));
3536 } while (EatIfPresent(lltok::comma));
3537
3538 if (parseToken(lltok::rparen, "expected ')'"))
3539 return true;
3540
3541 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3542 if (!CRLOrNull.has_value())
3543 return tokError("Invalid (unordered or overlapping) range list");
3544 B.addInitializesAttr(*CRLOrNull);
3545 return false;
3546}
3547
3548bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3550 std::optional<CaptureComponents> Ret;
3551
3552 // We use syntax like captures(ret: address, provenance), so the colon
3553 // should not be interpreted as a label terminator.
3554 Lex.setIgnoreColonInIdentifiers(true);
3555 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3556
3557 Lex.Lex();
3558 if (parseToken(lltok::lparen, "expected '('"))
3559 return true;
3560
3561 CaptureComponents *Current = &Other;
3562 bool SeenComponent = false;
3563 while (true) {
3564 if (EatIfPresent(lltok::kw_ret)) {
3565 if (parseToken(lltok::colon, "expected ':'"))
3566 return true;
3567 if (Ret)
3568 return tokError("duplicate 'ret' location");
3570 Current = &*Ret;
3571 SeenComponent = false;
3572 }
3573
3574 if (EatIfPresent(lltok::kw_none)) {
3575 if (SeenComponent)
3576 return tokError("cannot use 'none' with other component");
3577 *Current = CaptureComponents::None;
3578 } else {
3579 if (SeenComponent && capturesNothing(*Current))
3580 return tokError("cannot use 'none' with other component");
3581
3582 if (EatIfPresent(lltok::kw_address_is_null))
3584 else if (EatIfPresent(lltok::kw_address))
3585 *Current |= CaptureComponents::Address;
3586 else if (EatIfPresent(lltok::kw_provenance))
3588 else if (EatIfPresent(lltok::kw_read_provenance))
3590 else
3591 return tokError("expected one of 'none', 'address', 'address_is_null', "
3592 "'provenance' or 'read_provenance'");
3593 }
3594
3595 SeenComponent = true;
3596 if (EatIfPresent(lltok::rparen))
3597 break;
3598
3599 if (parseToken(lltok::comma, "expected ',' or ')'"))
3600 return true;
3601 }
3602
3603 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3604 return false;
3605}
3606
3607/// parseOptionalOperandBundles
3608/// ::= /*empty*/
3609/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3610///
3611/// OperandBundle
3612/// ::= bundle-tag '(' ')'
3613/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3614///
3615/// bundle-tag ::= String Constant
3616bool LLParser::parseOptionalOperandBundles(
3617 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3618 LocTy BeginLoc = Lex.getLoc();
3619 if (!EatIfPresent(lltok::lsquare))
3620 return false;
3621
3622 while (Lex.getKind() != lltok::rsquare) {
3623 // If this isn't the first operand bundle, we need a comma.
3624 if (!BundleList.empty() &&
3625 parseToken(lltok::comma, "expected ',' in input list"))
3626 return true;
3627
3628 std::string Tag;
3629 if (parseStringConstant(Tag))
3630 return true;
3631
3632 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3633 return true;
3634
3635 std::vector<Value *> Inputs;
3636 while (Lex.getKind() != lltok::rparen) {
3637 // If this isn't the first input, we need a comma.
3638 if (!Inputs.empty() &&
3639 parseToken(lltok::comma, "expected ',' in input list"))
3640 return true;
3641
3642 Type *Ty = nullptr;
3643 Value *Input = nullptr;
3644 if (parseType(Ty))
3645 return true;
3646 if (Ty->isMetadataTy()) {
3647 if (parseMetadataAsValue(Input, PFS))
3648 return true;
3649 } else if (parseValue(Ty, Input, PFS)) {
3650 return true;
3651 }
3652 Inputs.push_back(Input);
3653 }
3654
3655 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3656
3657 Lex.Lex(); // Lex the ')'.
3658 }
3659
3660 if (BundleList.empty())
3661 return error(BeginLoc, "operand bundle set must not be empty");
3662
3663 Lex.Lex(); // Lex the ']'.
3664 return false;
3665}
3666
3667bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3668 unsigned NextID, unsigned ID) {
3669 if (ID < NextID)
3670 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3671 Twine(NextID) + "' or greater");
3672
3673 return false;
3674}
3675
3676/// parseArgumentList - parse the argument list for a function type or function
3677/// prototype.
3678/// ::= '(' ArgTypeListI ')'
3679/// ArgTypeListI
3680/// ::= /*empty*/
3681/// ::= '...'
3682/// ::= ArgTypeList ',' '...'
3683/// ::= ArgType (',' ArgType)*
3684///
3685bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3686 SmallVectorImpl<unsigned> &UnnamedArgNums,
3687 bool &IsVarArg) {
3688 unsigned CurValID = 0;
3689 IsVarArg = false;
3690 assert(Lex.getKind() == lltok::lparen);
3691 Lex.Lex(); // eat the (.
3692
3693 if (Lex.getKind() != lltok::rparen) {
3694 do {
3695 // Handle ... at end of arg list.
3696 if (EatIfPresent(lltok::dotdotdot)) {
3697 IsVarArg = true;
3698 break;
3699 }
3700
3701 // Otherwise must be an argument type.
3702 LocTy TypeLoc = Lex.getLoc();
3703 Type *ArgTy = nullptr;
3704 AttrBuilder Attrs(M->getContext());
3705 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3706 return true;
3707
3708 if (ArgTy->isVoidTy())
3709 return error(TypeLoc, "argument can not have void type");
3710
3711 std::string Name;
3712 FileLoc IdentStart;
3713 FileLoc IdentEnd;
3714 bool Unnamed = false;
3715 if (Lex.getKind() == lltok::LocalVar) {
3716 Name = Lex.getStrVal();
3717 IdentStart = getTokLineColumnPos();
3718 Lex.Lex();
3719 IdentEnd = getPrevTokEndLineColumnPos();
3720 } else {
3721 unsigned ArgID;
3722 if (Lex.getKind() == lltok::LocalVarID) {
3723 ArgID = Lex.getUIntVal();
3724 IdentStart = getTokLineColumnPos();
3725 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3726 return true;
3727 Lex.Lex();
3728 IdentEnd = getPrevTokEndLineColumnPos();
3729 } else {
3730 ArgID = CurValID;
3731 Unnamed = true;
3732 }
3733 UnnamedArgNums.push_back(ArgID);
3734 CurValID = ArgID + 1;
3735 }
3736
3738 return error(TypeLoc, "invalid type for function argument");
3739
3740 ArgList.emplace_back(
3741 TypeLoc, ArgTy,
3742 Unnamed ? std::nullopt
3743 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3744 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3745 } while (EatIfPresent(lltok::comma));
3746 }
3747
3748 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3749}
3750
3751/// parseFunctionType
3752/// ::= Type ArgumentList OptionalAttrs
3753bool LLParser::parseFunctionType(Type *&Result) {
3754 assert(Lex.getKind() == lltok::lparen);
3755
3757 return tokError("invalid function return type");
3758
3760 bool IsVarArg;
3761 SmallVector<unsigned> UnnamedArgNums;
3762 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3763 return true;
3764
3765 // Reject names on the arguments lists.
3766 for (const ArgInfo &Arg : ArgList) {
3767 if (!Arg.Name.empty())
3768 return error(Arg.Loc, "argument name invalid in function type");
3769 if (Arg.Attrs.hasAttributes())
3770 return error(Arg.Loc, "argument attributes invalid in function type");
3771 }
3772
3773 SmallVector<Type*, 16> ArgListTy;
3774 for (const ArgInfo &Arg : ArgList)
3775 ArgListTy.push_back(Arg.Ty);
3776
3777 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3778 return false;
3779}
3780
3781/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3782/// other structs.
3783bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3785 if (parseStructBody(Elts))
3786 return true;
3787
3788 Result = StructType::get(Context, Elts, Packed);
3789 return false;
3790}
3791
3792/// parseStructDefinition - parse a struct in a 'type' definition.
3793bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3794 std::pair<Type *, LocTy> &Entry,
3795 Type *&ResultTy) {
3796 // If the type was already defined, diagnose the redefinition.
3797 if (Entry.first && !Entry.second.isValid())
3798 return error(TypeLoc, "redefinition of type");
3799
3800 // If we have opaque, just return without filling in the definition for the
3801 // struct. This counts as a definition as far as the .ll file goes.
3802 if (EatIfPresent(lltok::kw_opaque)) {
3803 // This type is being defined, so clear the location to indicate this.
3804 Entry.second = SMLoc();
3805
3806 // If this type number has never been uttered, create it.
3807 if (!Entry.first)
3808 Entry.first = StructType::create(Context, Name);
3809 ResultTy = Entry.first;
3810 return false;
3811 }
3812
3813 // If the type starts with '<', then it is either a packed struct or a vector.
3814 bool isPacked = EatIfPresent(lltok::less);
3815
3816 // If we don't have a struct, then we have a random type alias, which we
3817 // accept for compatibility with old files. These types are not allowed to be
3818 // forward referenced and not allowed to be recursive.
3819 if (Lex.getKind() != lltok::lbrace) {
3820 if (Entry.first)
3821 return error(TypeLoc, "forward references to non-struct type");
3822
3823 ResultTy = nullptr;
3824 if (isPacked)
3825 return parseArrayVectorType(ResultTy, true);
3826 return parseType(ResultTy);
3827 }
3828
3829 // This type is being defined, so clear the location to indicate this.
3830 Entry.second = SMLoc();
3831
3832 // If this type number has never been uttered, create it.
3833 if (!Entry.first)
3834 Entry.first = StructType::create(Context, Name);
3835
3836 StructType *STy = cast<StructType>(Entry.first);
3837
3839 if (parseStructBody(Body) ||
3840 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3841 return true;
3842
3843 if (auto E = STy->setBodyOrError(Body, isPacked))
3844 return tokError(toString(std::move(E)));
3845
3846 ResultTy = STy;
3847 return false;
3848}
3849
3850/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3851/// StructType
3852/// ::= '{' '}'
3853/// ::= '{' Type (',' Type)* '}'
3854/// ::= '<' '{' '}' '>'
3855/// ::= '<' '{' Type (',' Type)* '}' '>'
3856bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3857 assert(Lex.getKind() == lltok::lbrace);
3858 Lex.Lex(); // Consume the '{'
3859
3860 // Handle the empty struct.
3861 if (EatIfPresent(lltok::rbrace))
3862 return false;
3863
3864 LocTy EltTyLoc = Lex.getLoc();
3865 Type *Ty = nullptr;
3866 if (parseType(Ty))
3867 return true;
3868 Body.push_back(Ty);
3869
3871 return error(EltTyLoc, "invalid element type for struct");
3872
3873 while (EatIfPresent(lltok::comma)) {
3874 EltTyLoc = Lex.getLoc();
3875 if (parseType(Ty))
3876 return true;
3877
3879 return error(EltTyLoc, "invalid element type for struct");
3880
3881 Body.push_back(Ty);
3882 }
3883
3884 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3885}
3886
3887/// parseArrayVectorType - parse an array or vector type, assuming the first
3888/// token has already been consumed.
3889/// Type
3890/// ::= '[' APSINTVAL 'x' Types ']'
3891/// ::= '<' APSINTVAL 'x' Types '>'
3892/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3893bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3894 bool Scalable = false;
3895
3896 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3897 Lex.Lex(); // consume the 'vscale'
3898 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3899 return true;
3900
3901 Scalable = true;
3902 }
3903
3904 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3905 Lex.getAPSIntVal().getBitWidth() > 64)
3906 return tokError("expected number in address space");
3907
3908 LocTy SizeLoc = Lex.getLoc();
3909 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3910 Lex.Lex();
3911
3912 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3913 return true;
3914
3915 LocTy TypeLoc = Lex.getLoc();
3916 Type *EltTy = nullptr;
3917 if (parseType(EltTy))
3918 return true;
3919
3920 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3921 "expected end of sequential type"))
3922 return true;
3923
3924 if (IsVector) {
3925 if (Size == 0)
3926 return error(SizeLoc, "zero element vector is illegal");
3927 if ((unsigned)Size != Size)
3928 return error(SizeLoc, "size too large for vector");
3930 return error(TypeLoc, "invalid vector element type");
3931 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3932 } else {
3934 return error(TypeLoc, "invalid array element type");
3935 Result = ArrayType::get(EltTy, Size);
3936 }
3937 return false;
3938}
3939
3940/// parseTargetExtType - handle target extension type syntax
3941/// TargetExtType
3942/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3943///
3944/// TargetExtTypeParams
3945/// ::= /*empty*/
3946/// ::= ',' Type TargetExtTypeParams
3947///
3948/// TargetExtIntParams
3949/// ::= /*empty*/
3950/// ::= ',' uint32 TargetExtIntParams
3951bool LLParser::parseTargetExtType(Type *&Result) {
3952 Lex.Lex(); // Eat the 'target' keyword.
3953
3954 // Get the mandatory type name.
3955 std::string TypeName;
3956 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3957 parseStringConstant(TypeName))
3958 return true;
3959
3960 // Parse all of the integer and type parameters at the same time; the use of
3961 // SeenInt will allow us to catch cases where type parameters follow integer
3962 // parameters.
3963 SmallVector<Type *> TypeParams;
3964 SmallVector<unsigned> IntParams;
3965 bool SeenInt = false;
3966 while (Lex.getKind() == lltok::comma) {
3967 Lex.Lex(); // Eat the comma.
3968
3969 if (Lex.getKind() == lltok::APSInt) {
3970 SeenInt = true;
3971 unsigned IntVal;
3972 if (parseUInt32(IntVal))
3973 return true;
3974 IntParams.push_back(IntVal);
3975 } else if (SeenInt) {
3976 // The only other kind of parameter we support is type parameters, which
3977 // must precede the integer parameters. This is therefore an error.
3978 return tokError("expected uint32 param");
3979 } else {
3980 Type *TypeParam;
3981 if (parseType(TypeParam, /*AllowVoid=*/true))
3982 return true;
3983 TypeParams.push_back(TypeParam);
3984 }
3985 }
3986
3987 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3988 return true;
3989
3990 auto TTy =
3991 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3992 if (auto E = TTy.takeError())
3993 return tokError(toString(std::move(E)));
3994
3995 Result = *TTy;
3996 return false;
3997}
3998
3999//===----------------------------------------------------------------------===//
4000// Function Semantic Analysis.
4001//===----------------------------------------------------------------------===//
4002
4003LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
4004 int functionNumber,
4005 ArrayRef<unsigned> UnnamedArgNums)
4006 : P(p), F(f), FunctionNumber(functionNumber) {
4007
4008 // Insert unnamed arguments into the NumberedVals list.
4009 auto It = UnnamedArgNums.begin();
4010 for (Argument &A : F.args()) {
4011 if (!A.hasName()) {
4012 unsigned ArgNum = *It++;
4013 NumberedVals.add(ArgNum, &A);
4014 }
4015 }
4016}
4017
4018LLParser::PerFunctionState::~PerFunctionState() {
4019 // If there were any forward referenced non-basicblock values, delete them.
4020
4021 for (const auto &P : ForwardRefVals) {
4022 if (isa<BasicBlock>(P.second.first))
4023 continue;
4024 P.second.first->replaceAllUsesWith(
4025 PoisonValue::get(P.second.first->getType()));
4026 P.second.first->deleteValue();
4027 }
4028
4029 for (const auto &P : ForwardRefValIDs) {
4030 if (isa<BasicBlock>(P.second.first))
4031 continue;
4032 P.second.first->replaceAllUsesWith(
4033 PoisonValue::get(P.second.first->getType()));
4034 P.second.first->deleteValue();
4035 }
4036}
4037
4038bool LLParser::PerFunctionState::finishFunction() {
4039 if (!ForwardRefVals.empty())
4040 return P.error(ForwardRefVals.begin()->second.second,
4041 "use of undefined value '%" + ForwardRefVals.begin()->first +
4042 "'");
4043 if (!ForwardRefValIDs.empty())
4044 return P.error(ForwardRefValIDs.begin()->second.second,
4045 "use of undefined value '%" +
4046 Twine(ForwardRefValIDs.begin()->first) + "'");
4047 return false;
4048}
4049
4050/// getVal - Get a value with the specified name or ID, creating a
4051/// forward reference record if needed. This can return null if the value
4052/// exists but does not have the right type.
4053Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
4054 LocTy Loc) {
4055 // Look this name up in the normal function symbol table.
4056 Value *Val = F.getValueSymbolTable()->lookup(Name);
4057
4058 // If this is a forward reference for the value, see if we already created a
4059 // forward ref record.
4060 if (!Val) {
4061 auto I = ForwardRefVals.find(Name);
4062 if (I != ForwardRefVals.end())
4063 Val = I->second.first;
4064 }
4065
4066 // If we have the value in the symbol table or fwd-ref table, return it.
4067 if (Val)
4068 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
4069
4070 // Don't make placeholders with invalid type.
4071 if (!Ty->isFirstClassType()) {
4072 P.error(Loc, "invalid use of a non-first-class type");
4073 return nullptr;
4074 }
4075
4076 // Otherwise, create a new forward reference for this value and remember it.
4077 Value *FwdVal;
4078 if (Ty->isLabelTy()) {
4079 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
4080 } else {
4081 FwdVal = new Argument(Ty, Name);
4082 }
4083 if (FwdVal->getName() != Name) {
4084 P.error(Loc, "name is too long which can result in name collisions, "
4085 "consider making the name shorter or "
4086 "increasing -non-global-value-max-name-size");
4087 return nullptr;
4088 }
4089
4090 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
4091 return FwdVal;
4092}
4093
4094Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
4095 // Look this name up in the normal function symbol table.
4096 Value *Val = NumberedVals.get(ID);
4097
4098 // If this is a forward reference for the value, see if we already created a
4099 // forward ref record.
4100 if (!Val) {
4101 auto I = ForwardRefValIDs.find(ID);
4102 if (I != ForwardRefValIDs.end())
4103 Val = I->second.first;
4104 }
4105
4106 // If we have the value in the symbol table or fwd-ref table, return it.
4107 if (Val)
4108 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
4109
4110 if (!Ty->isFirstClassType()) {
4111 P.error(Loc, "invalid use of a non-first-class type");
4112 return nullptr;
4113 }
4114
4115 // Otherwise, create a new forward reference for this value and remember it.
4116 Value *FwdVal;
4117 if (Ty->isLabelTy()) {
4118 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
4119 } else {
4120 FwdVal = new Argument(Ty);
4121 }
4122
4123 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
4124 return FwdVal;
4125}
4126
4127/// setInstName - After an instruction is parsed and inserted into its
4128/// basic block, this installs its name.
4129bool LLParser::PerFunctionState::setInstName(int NameID,
4130 const std::string &NameStr,
4131 LocTy NameLoc, Instruction *Inst) {
4132 // If this instruction has void type, it cannot have a name or ID specified.
4133 if (Inst->getType()->isVoidTy()) {
4134 if (NameID != -1 || !NameStr.empty())
4135 return P.error(NameLoc, "instructions returning void cannot have a name");
4136 return false;
4137 }
4138
4139 // If this was a numbered instruction, verify that the instruction is the
4140 // expected value and resolve any forward references.
4141 if (NameStr.empty()) {
4142 // If neither a name nor an ID was specified, just use the next ID.
4143 if (NameID == -1)
4144 NameID = NumberedVals.getNext();
4145
4146 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4147 NameID))
4148 return true;
4149
4150 auto FI = ForwardRefValIDs.find(NameID);
4151 if (FI != ForwardRefValIDs.end()) {
4152 Value *Sentinel = FI->second.first;
4153 if (Sentinel->getType() != Inst->getType())
4154 return P.error(NameLoc, "instruction forward referenced with type '" +
4155 getTypeString(FI->second.first->getType()) +
4156 "'");
4157
4158 Sentinel->replaceAllUsesWith(Inst);
4159 Sentinel->deleteValue();
4160 ForwardRefValIDs.erase(FI);
4161 }
4162
4163 NumberedVals.add(NameID, Inst);
4164 return false;
4165 }
4166
4167 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4168 auto FI = ForwardRefVals.find(NameStr);
4169 if (FI != ForwardRefVals.end()) {
4170 Value *Sentinel = FI->second.first;
4171 if (Sentinel->getType() != Inst->getType())
4172 return P.error(NameLoc, "instruction forward referenced with type '" +
4173 getTypeString(FI->second.first->getType()) +
4174 "'");
4175
4176 Sentinel->replaceAllUsesWith(Inst);
4177 Sentinel->deleteValue();
4178 ForwardRefVals.erase(FI);
4179 }
4180
4181 // Set the name on the instruction.
4182 Inst->setName(NameStr);
4183
4184 if (Inst->getName() != NameStr)
4185 return P.error(NameLoc, "multiple definition of local value named '" +
4186 NameStr + "'");
4187 return false;
4188}
4189
4190/// getBB - Get a basic block with the specified name or ID, creating a
4191/// forward reference record if needed.
4192BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4193 LocTy Loc) {
4195 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4196}
4197
4198BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4200 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4201}
4202
4203/// defineBB - Define the specified basic block, which is either named or
4204/// unnamed. If there is an error, this returns null otherwise it returns
4205/// the block being defined.
4206BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4207 int NameID, LocTy Loc) {
4208 BasicBlock *BB;
4209 if (Name.empty()) {
4210 if (NameID != -1) {
4211 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4212 return nullptr;
4213 } else {
4214 NameID = NumberedVals.getNext();
4215 }
4216 BB = getBB(NameID, Loc);
4217 if (!BB) {
4218 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4219 return nullptr;
4220 }
4221 } else {
4222 BB = getBB(Name, Loc);
4223 if (!BB) {
4224 P.error(Loc, "unable to create block named '" + Name + "'");
4225 return nullptr;
4226 }
4227 }
4228
4229 // Move the block to the end of the function. Forward ref'd blocks are
4230 // inserted wherever they happen to be referenced.
4231 F.splice(F.end(), &F, BB->getIterator());
4232
4233 // Remove the block from forward ref sets.
4234 if (Name.empty()) {
4235 ForwardRefValIDs.erase(NameID);
4236 NumberedVals.add(NameID, BB);
4237 } else {
4238 // BB forward references are already in the function symbol table.
4239 ForwardRefVals.erase(Name);
4240 }
4241
4242 return BB;
4243}
4244
4245//===----------------------------------------------------------------------===//
4246// Constants.
4247//===----------------------------------------------------------------------===//
4248
4249/// parseValID - parse an abstract value that doesn't necessarily have a
4250/// type implied. For example, if we parse "4" we don't know what integer type
4251/// it has. The value will later be combined with its type and checked for
4252/// basic correctness. PFS is used to convert function-local operands of
4253/// metadata (since metadata operands are not just parsed here but also
4254/// converted to values). PFS can be null when we are not parsing metadata
4255/// values inside a function.
4256bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4257 ID.Loc = Lex.getLoc();
4258 switch (Lex.getKind()) {
4259 default:
4260 return tokError("expected value token");
4261 case lltok::GlobalID: // @42
4262 ID.UIntVal = Lex.getUIntVal();
4263 ID.Kind = ValID::t_GlobalID;
4264 break;
4265 case lltok::GlobalVar: // @foo
4266 ID.StrVal = Lex.getStrVal();
4267 ID.Kind = ValID::t_GlobalName;
4268 break;
4269 case lltok::LocalVarID: // %42
4270 ID.UIntVal = Lex.getUIntVal();
4271 ID.Kind = ValID::t_LocalID;
4272 break;
4273 case lltok::LocalVar: // %foo
4274 ID.StrVal = Lex.getStrVal();
4275 ID.Kind = ValID::t_LocalName;
4276 break;
4277 case lltok::APSInt:
4278 ID.APSIntVal = Lex.getAPSIntVal();
4279 ID.Kind = ValID::t_APSInt;
4280 break;
4281 case lltok::APFloat: {
4282 ID.APFloatVal = Lex.getAPFloatVal();
4283 ID.Kind = ValID::t_APFloat;
4284 break;
4285 }
4286 case lltok::FloatLiteral: {
4287 if (!ExpectedTy)
4288 return error(ID.Loc, "unexpected floating-point literal");
4289 if (!ExpectedTy->isFloatingPointTy())
4290 return error(ID.Loc, "floating-point constant invalid for type");
4291 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4292 APFloat::opStatus Except =
4293 cantFail(ID.APFloatVal.convertFromString(
4294 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4295 "Invalid float strings should be caught by the lexer");
4296 // Forbid overflowing and underflowing literals, but permit inexact
4297 // literals. Underflow is thrown when the result is denormal, so to allow
4298 // denormals, only reject underflowing literals that resulted in a zero.
4299 if (Except & APFloat::opOverflow)
4300 return error(ID.Loc, "floating-point constant overflowed type");
4301 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4302 return error(ID.Loc, "floating-point constant underflowed type");
4303 ID.Kind = ValID::t_APFloat;
4304 break;
4305 }
4307 if (!ExpectedTy)
4308 return error(ID.Loc, "unexpected floating-point literal");
4309 const auto &Semantics = ExpectedTy->getFltSemantics();
4310 const APInt &Bits = Lex.getAPSIntVal();
4311 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4312 return error(ID.Loc, "float hex literal has incorrect number of bits");
4313 ID.APFloatVal = APFloat(Semantics, Bits);
4314 ID.Kind = ValID::t_APFloat;
4315 break;
4316 }
4317 case lltok::kw_true:
4318 ID.ConstantVal = ConstantInt::getTrue(Context);
4319 ID.Kind = ValID::t_Constant;
4320 break;
4321 case lltok::kw_false:
4322 ID.ConstantVal = ConstantInt::getFalse(Context);
4323 ID.Kind = ValID::t_Constant;
4324 break;
4325 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4326 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4327 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4328 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4329 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4330
4331 case lltok::lbrace: {
4332 // ValID ::= '{' ConstVector '}'
4333 Lex.Lex();
4335 if (parseGlobalValueVector(Elts) ||
4336 parseToken(lltok::rbrace, "expected end of struct constant"))
4337 return true;
4338
4339 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4340 ID.UIntVal = Elts.size();
4341 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4342 Elts.size() * sizeof(Elts[0]));
4344 return false;
4345 }
4346 case lltok::less: {
4347 // ValID ::= '<' ConstVector '>' --> Vector.
4348 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4349 Lex.Lex();
4350 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4351
4353 LocTy FirstEltLoc = Lex.getLoc();
4354 if (parseGlobalValueVector(Elts) ||
4355 (isPackedStruct &&
4356 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4357 parseToken(lltok::greater, "expected end of constant"))
4358 return true;
4359
4360 if (isPackedStruct) {
4361 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4362 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4363 Elts.size() * sizeof(Elts[0]));
4364 ID.UIntVal = Elts.size();
4366 return false;
4367 }
4368
4369 if (Elts.empty())
4370 return error(ID.Loc, "constant vector must not be empty");
4371
4372 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4373 !Elts[0]->getType()->isFloatingPointTy() &&
4374 !Elts[0]->getType()->isPointerTy())
4375 return error(
4376 FirstEltLoc,
4377 "vector elements must have integer, byte, pointer or floating point "
4378 "type");
4379
4380 // Verify that all the vector elements have the same type.
4381 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4382 if (Elts[i]->getType() != Elts[0]->getType())
4383 return error(FirstEltLoc, "vector element #" + Twine(i) +
4384 " is not of type '" +
4385 getTypeString(Elts[0]->getType()));
4386
4387 ID.ConstantVal = ConstantVector::get(Elts);
4388 ID.Kind = ValID::t_Constant;
4389 return false;
4390 }
4391 case lltok::lsquare: { // Array Constant
4392 Lex.Lex();
4394 LocTy FirstEltLoc = Lex.getLoc();
4395 if (parseGlobalValueVector(Elts) ||
4396 parseToken(lltok::rsquare, "expected end of array constant"))
4397 return true;
4398
4399 // Handle empty element.
4400 if (Elts.empty()) {
4401 // Use undef instead of an array because it's inconvenient to determine
4402 // the element type at this point, there being no elements to examine.
4403 ID.Kind = ValID::t_EmptyArray;
4404 return false;
4405 }
4406
4407 if (!Elts[0]->getType()->isFirstClassType())
4408 return error(FirstEltLoc, "invalid array element type: " +
4409 getTypeString(Elts[0]->getType()));
4410
4411 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4412
4413 // Verify all elements are correct type!
4414 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4415 if (Elts[i]->getType() != Elts[0]->getType())
4416 return error(FirstEltLoc, "array element #" + Twine(i) +
4417 " is not of type '" +
4418 getTypeString(Elts[0]->getType()));
4419 }
4420
4421 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4422 ID.Kind = ValID::t_Constant;
4423 return false;
4424 }
4425 case lltok::kw_c: { // c "foo"
4426 Lex.Lex();
4427 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4428 ID.ConstantVal = ConstantDataArray::getString(
4429 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4430 if (parseToken(lltok::StringConstant, "expected string"))
4431 return true;
4432 ID.Kind = ValID::t_Constant;
4433 return false;
4434 }
4435 case lltok::kw_asm: {
4436 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4437 // STRINGCONSTANT
4438 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4439 Lex.Lex();
4440 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4441 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4442 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4443 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4444 parseStringConstant(ID.StrVal) ||
4445 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4446 parseToken(lltok::StringConstant, "expected constraint string"))
4447 return true;
4448 ID.StrVal2 = Lex.getStrVal();
4449 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4450 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4451 ID.Kind = ValID::t_InlineAsm;
4452 return false;
4453 }
4454
4456 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4457 Lex.Lex();
4458
4459 ValID Fn, Label;
4460
4461 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4462 parseValID(Fn, PFS) ||
4463 parseToken(lltok::comma,
4464 "expected comma in block address expression") ||
4465 parseValID(Label, PFS) ||
4466 parseToken(lltok::rparen, "expected ')' in block address expression"))
4467 return true;
4468
4470 return error(Fn.Loc, "expected function name in blockaddress");
4471 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4472 return error(Label.Loc, "expected basic block name in blockaddress");
4473
4474 // Try to find the function (but skip it if it's forward-referenced).
4475 GlobalValue *GV = nullptr;
4476 if (Fn.Kind == ValID::t_GlobalID) {
4477 GV = NumberedVals.get(Fn.UIntVal);
4478 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4479 GV = M->getNamedValue(Fn.StrVal);
4480 }
4481 Function *F = nullptr;
4482 if (GV) {
4483 // Confirm that it's actually a function with a definition.
4484 if (!isa<Function>(GV))
4485 return error(Fn.Loc, "expected function name in blockaddress");
4486 F = cast<Function>(GV);
4487 if (F->isDeclaration())
4488 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4489 }
4490
4491 if (!F) {
4492 // Make a global variable as a placeholder for this reference.
4493 GlobalValue *&FwdRef =
4494 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4495 if (!FwdRef) {
4496 unsigned FwdDeclAS;
4497 if (ExpectedTy) {
4498 // If we know the type that the blockaddress is being assigned to,
4499 // we can use the address space of that type.
4500 if (!ExpectedTy->isPointerTy())
4501 return error(ID.Loc,
4502 "type of blockaddress must be a pointer and not '" +
4503 getTypeString(ExpectedTy) + "'");
4504 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4505 } else if (PFS) {
4506 // Otherwise, we default the address space of the current function.
4507 FwdDeclAS = PFS->getFunction().getAddressSpace();
4508 } else {
4509 llvm_unreachable("Unknown address space for blockaddress");
4510 }
4511 FwdRef = new GlobalVariable(
4512 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4513 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4514 }
4515
4516 ID.ConstantVal = FwdRef;
4517 ID.Kind = ValID::t_Constant;
4518 return false;
4519 }
4520
4521 // We found the function; now find the basic block. Don't use PFS, since we
4522 // might be inside a constant expression.
4523 BasicBlock *BB;
4524 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4525 if (Label.Kind == ValID::t_LocalID)
4526 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4527 else
4528 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4529 if (!BB)
4530 return error(Label.Loc, "referenced value is not a basic block");
4531 } else {
4532 if (Label.Kind == ValID::t_LocalID)
4533 return error(Label.Loc, "cannot take address of numeric label after "
4534 "the function is defined");
4536 F->getValueSymbolTable()->lookup(Label.StrVal));
4537 if (!BB)
4538 return error(Label.Loc, "referenced value is not a basic block");
4539 }
4540
4541 ID.ConstantVal = BlockAddress::get(F, BB);
4542 ID.Kind = ValID::t_Constant;
4543 return false;
4544 }
4545
4547 // ValID ::= 'dso_local_equivalent' @foo
4548 Lex.Lex();
4549
4550 ValID Fn;
4551
4552 if (parseValID(Fn, PFS))
4553 return true;
4554
4556 return error(Fn.Loc,
4557 "expected global value name in dso_local_equivalent");
4558
4559 // Try to find the function (but skip it if it's forward-referenced).
4560 GlobalValue *GV = nullptr;
4561 if (Fn.Kind == ValID::t_GlobalID) {
4562 GV = NumberedVals.get(Fn.UIntVal);
4563 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4564 GV = M->getNamedValue(Fn.StrVal);
4565 }
4566
4567 if (!GV) {
4568 // Make a placeholder global variable as a placeholder for this reference.
4569 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4570 ? ForwardRefDSOLocalEquivalentIDs
4571 : ForwardRefDSOLocalEquivalentNames;
4572 GlobalValue *&FwdRef = FwdRefMap[Fn];
4573 if (!FwdRef) {
4574 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4575 GlobalValue::InternalLinkage, nullptr, "",
4577 }
4578
4579 ID.ConstantVal = FwdRef;
4580 ID.Kind = ValID::t_Constant;
4581 return false;
4582 }
4583
4584 if (!GV->getValueType()->isFunctionTy())
4585 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4586 "in dso_local_equivalent");
4587
4588 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4589 ID.Kind = ValID::t_Constant;
4590 return false;
4591 }
4592
4593 case lltok::kw_no_cfi: {
4594 // ValID ::= 'no_cfi' @foo
4595 Lex.Lex();
4596
4597 if (parseValID(ID, PFS))
4598 return true;
4599
4600 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4601 return error(ID.Loc, "expected global value name in no_cfi");
4602
4603 ID.NoCFI = true;
4604 return false;
4605 }
4606 case lltok::kw_ptrauth: {
4607 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4608 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4609 // )? )? ')'
4610 Lex.Lex();
4611
4612 Constant *Ptr, *Key;
4613 Constant *Disc = nullptr, *AddrDisc = nullptr,
4614 *DeactivationSymbol = nullptr;
4615
4616 if (parseToken(lltok::lparen,
4617 "expected '(' in constant ptrauth expression") ||
4618 parseGlobalTypeAndValue(Ptr) ||
4619 parseToken(lltok::comma,
4620 "expected comma in constant ptrauth expression") ||
4621 parseGlobalTypeAndValue(Key))
4622 return true;
4623 // If present, parse the optional disc/addrdisc/ds.
4624 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4625 return true;
4626 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4627 return true;
4628 if (EatIfPresent(lltok::comma) &&
4629 parseGlobalTypeAndValue(DeactivationSymbol))
4630 return true;
4631 if (parseToken(lltok::rparen,
4632 "expected ')' in constant ptrauth expression"))
4633 return true;
4634
4635 if (!Ptr->getType()->isPointerTy())
4636 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4637
4638 auto *KeyC = dyn_cast<ConstantInt>(Key);
4639 if (!KeyC || KeyC->getBitWidth() != 32)
4640 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4641
4642 ConstantInt *DiscC = nullptr;
4643 if (Disc) {
4644 DiscC = dyn_cast<ConstantInt>(Disc);
4645 if (!DiscC || DiscC->getBitWidth() != 64)
4646 return error(
4647 ID.Loc,
4648 "constant ptrauth integer discriminator must be i64 constant");
4649 } else {
4650 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4651 }
4652
4653 if (AddrDisc) {
4654 if (!AddrDisc->getType()->isPointerTy())
4655 return error(
4656 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4657 } else {
4658 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4659 }
4660
4661 if (!DeactivationSymbol)
4662 DeactivationSymbol =
4664 if (!DeactivationSymbol->getType()->isPointerTy())
4665 return error(ID.Loc,
4666 "constant ptrauth deactivation symbol must be a pointer");
4667
4668 ID.ConstantVal =
4669 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4670 ID.Kind = ValID::t_Constant;
4671 return false;
4672 }
4673
4674 case lltok::kw_trunc:
4675 case lltok::kw_bitcast:
4677 case lltok::kw_inttoptr:
4679 case lltok::kw_ptrtoint: {
4680 unsigned Opc = Lex.getUIntVal();
4681 Type *DestTy = nullptr;
4682 Constant *SrcVal;
4683 Lex.Lex();
4684 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4685 parseGlobalTypeAndValue(SrcVal) ||
4686 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4687 parseType(DestTy) ||
4688 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4689 return true;
4690 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4691 return error(ID.Loc, "invalid cast opcode for cast from '" +
4692 getTypeString(SrcVal->getType()) + "' to '" +
4693 getTypeString(DestTy) + "'");
4695 SrcVal, DestTy);
4696 ID.Kind = ValID::t_Constant;
4697 return false;
4698 }
4700 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4702 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4703 case lltok::kw_udiv:
4704 return error(ID.Loc, "udiv constexprs are no longer supported");
4705 case lltok::kw_sdiv:
4706 return error(ID.Loc, "sdiv constexprs are no longer supported");
4707 case lltok::kw_urem:
4708 return error(ID.Loc, "urem constexprs are no longer supported");
4709 case lltok::kw_srem:
4710 return error(ID.Loc, "srem constexprs are no longer supported");
4711 case lltok::kw_fadd:
4712 return error(ID.Loc, "fadd constexprs are no longer supported");
4713 case lltok::kw_fsub:
4714 return error(ID.Loc, "fsub constexprs are no longer supported");
4715 case lltok::kw_fmul:
4716 return error(ID.Loc, "fmul constexprs are no longer supported");
4717 case lltok::kw_fdiv:
4718 return error(ID.Loc, "fdiv constexprs are no longer supported");
4719 case lltok::kw_frem:
4720 return error(ID.Loc, "frem constexprs are no longer supported");
4721 case lltok::kw_and:
4722 return error(ID.Loc, "and constexprs are no longer supported");
4723 case lltok::kw_or:
4724 return error(ID.Loc, "or constexprs are no longer supported");
4725 case lltok::kw_lshr:
4726 return error(ID.Loc, "lshr constexprs are no longer supported");
4727 case lltok::kw_ashr:
4728 return error(ID.Loc, "ashr constexprs are no longer supported");
4729 case lltok::kw_shl:
4730 return error(ID.Loc, "shl constexprs are no longer supported");
4731 case lltok::kw_mul:
4732 return error(ID.Loc, "mul constexprs are no longer supported");
4733 case lltok::kw_fneg:
4734 return error(ID.Loc, "fneg constexprs are no longer supported");
4735 case lltok::kw_select:
4736 return error(ID.Loc, "select constexprs are no longer supported");
4737 case lltok::kw_zext:
4738 return error(ID.Loc, "zext constexprs are no longer supported");
4739 case lltok::kw_sext:
4740 return error(ID.Loc, "sext constexprs are no longer supported");
4741 case lltok::kw_fptrunc:
4742 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4743 case lltok::kw_fpext:
4744 return error(ID.Loc, "fpext constexprs are no longer supported");
4745 case lltok::kw_uitofp:
4746 return error(ID.Loc, "uitofp constexprs are no longer supported");
4747 case lltok::kw_sitofp:
4748 return error(ID.Loc, "sitofp constexprs are no longer supported");
4749 case lltok::kw_fptoui:
4750 return error(ID.Loc, "fptoui constexprs are no longer supported");
4751 case lltok::kw_fptosi:
4752 return error(ID.Loc, "fptosi constexprs are no longer supported");
4753 case lltok::kw_icmp:
4754 return error(ID.Loc, "icmp constexprs are no longer supported");
4755 case lltok::kw_fcmp:
4756 return error(ID.Loc, "fcmp constexprs are no longer supported");
4757
4758 // Binary Operators.
4759 case lltok::kw_add:
4760 case lltok::kw_sub:
4761 case lltok::kw_xor: {
4762 bool NUW = false;
4763 bool NSW = false;
4764 unsigned Opc = Lex.getUIntVal();
4765 Constant *Val0, *Val1;
4766 Lex.Lex();
4767 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4768 Opc == Instruction::Mul) {
4769 if (EatIfPresent(lltok::kw_nuw))
4770 NUW = true;
4771 if (EatIfPresent(lltok::kw_nsw)) {
4772 NSW = true;
4773 if (EatIfPresent(lltok::kw_nuw))
4774 NUW = true;
4775 }
4776 }
4777 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4778 parseGlobalTypeAndValue(Val0) ||
4779 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4780 parseGlobalTypeAndValue(Val1) ||
4781 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4782 return true;
4783 if (Val0->getType() != Val1->getType())
4784 return error(ID.Loc, "operands of constexpr must have same type");
4785 // Check that the type is valid for the operator.
4786 if (!Val0->getType()->isIntOrIntVectorTy())
4787 return error(ID.Loc,
4788 "constexpr requires integer or integer vector operands");
4789 unsigned Flags = 0;
4792 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4793 ID.Kind = ValID::t_Constant;
4794 return false;
4795 }
4796
4797 case lltok::kw_splat: {
4798 Lex.Lex();
4799 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4800 return true;
4801 Constant *C;
4802 if (parseGlobalTypeAndValue(C))
4803 return true;
4804 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4805 return true;
4806
4807 ID.ConstantVal = C;
4809 return false;
4810 }
4811
4816 unsigned Opc = Lex.getUIntVal();
4818 GEPNoWrapFlags NW;
4819 bool HasInRange = false;
4820 APSInt InRangeStart;
4821 APSInt InRangeEnd;
4822 Type *Ty;
4823 Lex.Lex();
4824
4825 if (Opc == Instruction::GetElementPtr) {
4826 while (true) {
4827 if (EatIfPresent(lltok::kw_inbounds))
4829 else if (EatIfPresent(lltok::kw_nusw))
4831 else if (EatIfPresent(lltok::kw_nuw))
4833 else
4834 break;
4835 }
4836
4837 if (EatIfPresent(lltok::kw_inrange)) {
4838 if (parseToken(lltok::lparen, "expected '('"))
4839 return true;
4840 if (Lex.getKind() != lltok::APSInt)
4841 return tokError("expected integer");
4842 InRangeStart = Lex.getAPSIntVal();
4843 Lex.Lex();
4844 if (parseToken(lltok::comma, "expected ','"))
4845 return true;
4846 if (Lex.getKind() != lltok::APSInt)
4847 return tokError("expected integer");
4848 InRangeEnd = Lex.getAPSIntVal();
4849 Lex.Lex();
4850 if (parseToken(lltok::rparen, "expected ')'"))
4851 return true;
4852 HasInRange = true;
4853 }
4854 }
4855
4856 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4857 return true;
4858
4859 if (Opc == Instruction::GetElementPtr) {
4860 if (parseType(Ty) ||
4861 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4862 return true;
4863 }
4864
4865 if (parseGlobalValueVector(Elts) ||
4866 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4867 return true;
4868
4869 if (Opc == Instruction::GetElementPtr) {
4870 if (Elts.size() == 0 ||
4871 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4872 return error(ID.Loc, "base of getelementptr must be a pointer");
4873
4874 Type *BaseType = Elts[0]->getType();
4875 std::optional<ConstantRange> InRange;
4876 if (HasInRange) {
4877 unsigned IndexWidth =
4878 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4879 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4880 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4881 if (InRangeStart.sge(InRangeEnd))
4882 return error(ID.Loc, "expected end to be larger than start");
4883 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4884 }
4885
4886 unsigned GEPWidth =
4887 BaseType->isVectorTy()
4888 ? cast<FixedVectorType>(BaseType)->getNumElements()
4889 : 0;
4890
4891 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4892 for (Constant *Val : Indices) {
4893 Type *ValTy = Val->getType();
4894 if (!ValTy->isIntOrIntVectorTy())
4895 return error(ID.Loc, "getelementptr index must be an integer");
4896 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4897 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4898 if (GEPWidth && (ValNumEl != GEPWidth))
4899 return error(
4900 ID.Loc,
4901 "getelementptr vector index has a wrong number of elements");
4902 // GEPWidth may have been unknown because the base is a scalar,
4903 // but it is known now.
4904 GEPWidth = ValNumEl;
4905 }
4906 }
4907
4908 if (!Indices.empty() && !Ty->isSized())
4909 return error(ID.Loc, "base element of getelementptr must be sized");
4910
4912 return error(ID.Loc, "invalid base element for constant getelementptr");
4913
4914 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4915 return error(ID.Loc, "invalid getelementptr indices");
4916
4918 ID.ConstantVal =
4919 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4921 } else if (Opc == Instruction::ShuffleVector) {
4922 if (Elts.size() != 3)
4923 return error(ID.Loc, "expected three operands to shufflevector");
4924 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4925 return error(ID.Loc, "invalid operands to shufflevector");
4926 SmallVector<int, 16> Mask;
4928 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4929 } else if (Opc == Instruction::ExtractElement) {
4930 if (Elts.size() != 2)
4931 return error(ID.Loc, "expected two operands to extractelement");
4932 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4933 return error(ID.Loc, "invalid extractelement operands");
4934 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4935 } else {
4936 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4937 if (Elts.size() != 3)
4938 return error(ID.Loc, "expected three operands to insertelement");
4939 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4940 return error(ID.Loc, "invalid insertelement operands");
4941 ID.ConstantVal =
4942 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4943 }
4944
4945 ID.Kind = ValID::t_Constant;
4946 return false;
4947 }
4948 }
4949
4950 Lex.Lex();
4951 return false;
4952}
4953
4954/// parseGlobalValue - parse a global value with the specified type.
4955bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4956 C = nullptr;
4957 ValID ID;
4958 Value *V = nullptr;
4959 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4960 convertValIDToValue(Ty, ID, V, nullptr);
4961 if (V && !(C = dyn_cast<Constant>(V)))
4962 return error(ID.Loc, "global values must be constants");
4963 return Parsed;
4964}
4965
4966bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4967 Type *Ty = nullptr;
4968 return parseType(Ty) || parseGlobalValue(Ty, V);
4969}
4970
4971bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4972 C = nullptr;
4973
4974 LocTy KwLoc = Lex.getLoc();
4975 if (!EatIfPresent(lltok::kw_comdat))
4976 return false;
4977
4978 if (EatIfPresent(lltok::lparen)) {
4979 if (Lex.getKind() != lltok::ComdatVar)
4980 return tokError("expected comdat variable");
4981 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4982 Lex.Lex();
4983 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4984 return true;
4985 } else {
4986 if (GlobalName.empty())
4987 return tokError("comdat cannot be unnamed");
4988 C = getComdat(std::string(GlobalName), KwLoc);
4989 }
4990
4991 return false;
4992}
4993
4994/// parseGlobalValueVector
4995/// ::= /*empty*/
4996/// ::= TypeAndValue (',' TypeAndValue)*
4997bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4998 // Empty list.
4999 if (Lex.getKind() == lltok::rbrace ||
5000 Lex.getKind() == lltok::rsquare ||
5001 Lex.getKind() == lltok::greater ||
5002 Lex.getKind() == lltok::rparen)
5003 return false;
5004
5005 do {
5006 // Let the caller deal with inrange.
5007 if (Lex.getKind() == lltok::kw_inrange)
5008 return false;
5009
5010 Constant *C;
5011 if (parseGlobalTypeAndValue(C))
5012 return true;
5013 Elts.push_back(C);
5014 } while (EatIfPresent(lltok::comma));
5015
5016 return false;
5017}
5018
5019bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
5021 if (parseMDNodeVector(Elts))
5022 return true;
5023
5024 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
5025 return false;
5026}
5027
5028/// MDNode:
5029/// ::= !{ ... }
5030/// ::= !7
5031/// ::= !DILocation(...)
5032bool LLParser::parseMDNode(MDNode *&N) {
5033 if (Lex.getKind() == lltok::MetadataVar)
5034 return parseSpecializedMDNode(N);
5035
5036 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
5037}
5038
5039bool LLParser::parseMDNodeTail(MDNode *&N) {
5040 // !{ ... }
5041 if (Lex.getKind() == lltok::lbrace)
5042 return parseMDTuple(N);
5043
5044 // !42
5045 return parseMDNodeID(N);
5046}
5047
5048namespace {
5049
5050/// Structure to represent an optional metadata field.
5051template <class FieldTy> struct MDFieldImpl {
5052 typedef MDFieldImpl ImplTy;
5053 FieldTy Val;
5054 bool Seen;
5055
5056 void assign(FieldTy Val) {
5057 Seen = true;
5058 this->Val = std::move(Val);
5059 }
5060
5061 explicit MDFieldImpl(FieldTy Default)
5062 : Val(std::move(Default)), Seen(false) {}
5063};
5064
5065/// Structure to represent an optional metadata field that
5066/// can be of either type (A or B) and encapsulates the
5067/// MD<typeofA>Field and MD<typeofB>Field structs, so not
5068/// to reimplement the specifics for representing each Field.
5069template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
5070 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5071 FieldTypeA A;
5072 FieldTypeB B;
5073 bool Seen;
5074
5075 enum {
5076 IsInvalid = 0,
5077 IsTypeA = 1,
5078 IsTypeB = 2
5079 } WhatIs;
5080
5081 void assign(FieldTypeA A) {
5082 Seen = true;
5083 this->A = std::move(A);
5084 WhatIs = IsTypeA;
5085 }
5086
5087 void assign(FieldTypeB B) {
5088 Seen = true;
5089 this->B = std::move(B);
5090 WhatIs = IsTypeB;
5091 }
5092
5093 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5094 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
5095 WhatIs(IsInvalid) {}
5096};
5097
5098struct MDUnsignedField : public MDFieldImpl<uint64_t> {
5099 uint64_t Max;
5100
5101 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
5102 : ImplTy(Default), Max(Max) {}
5103};
5104
5105struct LineField : public MDUnsignedField {
5106 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5107};
5108
5109struct ColumnField : public MDUnsignedField {
5110 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5111};
5112
5113struct DwarfTagField : public MDUnsignedField {
5114 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
5115 DwarfTagField(dwarf::Tag DefaultTag)
5116 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
5117};
5118
5119struct DwarfMacinfoTypeField : public MDUnsignedField {
5120 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
5121 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
5122 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
5123};
5124
5125struct DwarfAttEncodingField : public MDUnsignedField {
5126 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5127};
5128
5129struct DwarfVirtualityField : public MDUnsignedField {
5130 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5131};
5132
5133struct DwarfLangField : public MDUnsignedField {
5134 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5135};
5136
5137struct DwarfSourceLangNameField : public MDUnsignedField {
5138 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5139};
5140
5141struct DwarfLangDialectField : public MDUnsignedField {
5142 DwarfLangDialectField()
5143 : MDUnsignedField(0, dwarf::DW_LLVM_LANG_DIALECT_max) {}
5144};
5145
5146struct DwarfCCField : public MDUnsignedField {
5147 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5148};
5149
5150struct DwarfEnumKindField : public MDUnsignedField {
5151 DwarfEnumKindField()
5152 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5153 dwarf::DW_APPLE_ENUM_KIND_max) {}
5154};
5155
5156struct EmissionKindField : public MDUnsignedField {
5157 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5158};
5159
5160struct FixedPointKindField : public MDUnsignedField {
5161 FixedPointKindField()
5162 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5163};
5164
5165struct NameTableKindField : public MDUnsignedField {
5166 NameTableKindField()
5167 : MDUnsignedField(
5168 0, (unsigned)
5169 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5170};
5171
5172struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5173 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5174};
5175
5176struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5177 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5178};
5179
5180struct MDAPSIntField : public MDFieldImpl<APSInt> {
5181 MDAPSIntField() : ImplTy(APSInt()) {}
5182};
5183
5184struct MDSignedField : public MDFieldImpl<int64_t> {
5185 int64_t Min = INT64_MIN;
5186 int64_t Max = INT64_MAX;
5187
5188 MDSignedField(int64_t Default = 0)
5189 : ImplTy(Default) {}
5190 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5191 : ImplTy(Default), Min(Min), Max(Max) {}
5192};
5193
5194struct MDBoolField : public MDFieldImpl<bool> {
5195 MDBoolField(bool Default = false) : ImplTy(Default) {}
5196};
5197
5198struct MDField : public MDFieldImpl<Metadata *> {
5199 bool AllowNull;
5200
5201 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5202};
5203
5204struct MDStringField : public MDFieldImpl<MDString *> {
5205 enum class EmptyIs {
5206 Null, //< Allow empty input string, map to nullptr
5207 Empty, //< Allow empty input string, map to an empty MDString
5208 Error, //< Disallow empty string, map to an error
5209 } EmptyIs;
5210 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5211 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5212};
5213
5214struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5215 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5216};
5217
5218struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5219 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5220};
5221
5222struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5223 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5224 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5225
5226 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5227 bool AllowNull = true)
5228 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5229
5230 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5231 bool isMDField() const { return WhatIs == IsTypeB; }
5232 int64_t getMDSignedValue() const {
5233 assert(isMDSignedField() && "Wrong field type");
5234 return A.Val;
5235 }
5236 Metadata *getMDFieldValue() const {
5237 assert(isMDField() && "Wrong field type");
5238 return B.Val;
5239 }
5240};
5241
5242struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5243 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5244 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5245
5246 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5247 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5248
5249 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5250 bool isMDField() const { return WhatIs == IsTypeB; }
5251 uint64_t getMDUnsignedValue() const {
5252 assert(isMDUnsignedField() && "Wrong field type");
5253 return A.Val;
5254 }
5255 Metadata *getMDFieldValue() const {
5256 assert(isMDField() && "Wrong field type");
5257 return B.Val;
5258 }
5259
5260 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5261 if (isMDUnsignedField())
5263 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5264 if (isMDField())
5265 return getMDFieldValue();
5266 return nullptr;
5267 }
5268};
5269
5270} // end anonymous namespace
5271
5272namespace llvm {
5273
5274template <>
5275bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5276 if (Lex.getKind() != lltok::APSInt)
5277 return tokError("expected integer");
5278
5279 Result.assign(Lex.getAPSIntVal());
5280 Lex.Lex();
5281 return false;
5282}
5283
5284template <>
5285bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5286 MDUnsignedField &Result) {
5287 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5288 return tokError("expected unsigned integer");
5289
5290 auto &U = Lex.getAPSIntVal();
5291 if (U.ugt(Result.Max))
5292 return tokError("value for '" + Name + "' too large, limit is " +
5293 Twine(Result.Max));
5294 Result.assign(U.getZExtValue());
5295 assert(Result.Val <= Result.Max && "Expected value in range");
5296 Lex.Lex();
5297 return false;
5298}
5299
5300template <>
5301bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5302 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5303}
5304template <>
5305bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5306 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5307}
5308
5309template <>
5310bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5311 if (Lex.getKind() == lltok::APSInt)
5312 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5313
5314 if (Lex.getKind() != lltok::DwarfTag)
5315 return tokError("expected DWARF tag");
5316
5317 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5319 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5320 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5321
5322 Result.assign(Tag);
5323 Lex.Lex();
5324 return false;
5325}
5326
5327template <>
5328bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5329 DwarfMacinfoTypeField &Result) {
5330 if (Lex.getKind() == lltok::APSInt)
5331 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5332
5333 if (Lex.getKind() != lltok::DwarfMacinfo)
5334 return tokError("expected DWARF macinfo type");
5335
5336 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5337 if (Macinfo == dwarf::DW_MACINFO_invalid)
5338 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5339 Lex.getStrVal() + "'");
5340 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5341
5342 Result.assign(Macinfo);
5343 Lex.Lex();
5344 return false;
5345}
5346
5347template <>
5348bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5349 DwarfVirtualityField &Result) {
5350 if (Lex.getKind() == lltok::APSInt)
5351 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5352
5353 if (Lex.getKind() != lltok::DwarfVirtuality)
5354 return tokError("expected DWARF virtuality code");
5355
5356 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5357 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5358 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5359 Lex.getStrVal() + "'");
5360 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5361 Result.assign(Virtuality);
5362 Lex.Lex();
5363 return false;
5364}
5365
5366template <>
5367bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5368 DwarfEnumKindField &Result) {
5369 if (Lex.getKind() == lltok::APSInt)
5370 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5371
5372 if (Lex.getKind() != lltok::DwarfEnumKind)
5373 return tokError("expected DWARF enum kind code");
5374
5375 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5376 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5377 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5378 Lex.getStrVal() + "'");
5379 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5380 Result.assign(EnumKind);
5381 Lex.Lex();
5382 return false;
5383}
5384
5385template <>
5386bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5387 if (Lex.getKind() == lltok::APSInt)
5388 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5389
5390 if (Lex.getKind() != lltok::DwarfLang)
5391 return tokError("expected DWARF language");
5392
5393 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5394 if (!Lang)
5395 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5396 "'");
5397 assert(Lang <= Result.Max && "Expected valid DWARF language");
5398 Result.assign(Lang);
5399 Lex.Lex();
5400 return false;
5401}
5402
5403template <>
5404bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5405 DwarfSourceLangNameField &Result) {
5406 if (Lex.getKind() == lltok::APSInt)
5407 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5408
5409 if (Lex.getKind() != lltok::DwarfSourceLangName)
5410 return tokError("expected DWARF source language name");
5411
5412 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5413 if (!Lang)
5414 return tokError("invalid DWARF source language name" + Twine(" '") +
5415 Lex.getStrVal() + "'");
5416 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5417 Result.assign(Lang);
5418 Lex.Lex();
5419 return false;
5420}
5421
5422template <>
5423bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5424 DwarfLangDialectField &Result) {
5425 // Specifying the dialect field requires a recognized dialect: simt or
5426 // tile (numerically 1 or 2). Omitting the field is the only way to
5427 // express "no dialect specified".
5428 if (Lex.getKind() == lltok::APSInt) {
5429 if (Lex.getAPSIntVal() == 0)
5430 return tokError("value for 'dialect' must be a known DWARF language "
5431 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5432 "DW_LLVM_LANG_DIALECT_tile)");
5433 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5434 }
5435
5436 if (Lex.getKind() != lltok::DwarfLangDialect)
5437 return tokError("expected DWARF language dialect");
5438
5439 StringRef DialectString = Lex.getStrVal();
5440 // getLanguageDialect returns a sentinel above Result.Max for unknown
5441 // spellings; only simt and tile are registered, so any unrecognized
5442 // DW_LLVM_LANG_DIALECT_* token is rejected here.
5443 unsigned Dialect = dwarf::getLanguageDialect(DialectString);
5444 if (Dialect > Result.Max)
5445 return tokError("invalid DWARF language dialect" + Twine(" '") +
5446 DialectString + "'");
5447 Result.assign(Dialect);
5448 Lex.Lex();
5449 return false;
5450}
5451
5452template <>
5453bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5454 if (Lex.getKind() == lltok::APSInt)
5455 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5456
5457 if (Lex.getKind() != lltok::DwarfCC)
5458 return tokError("expected DWARF calling convention");
5459
5460 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5461 if (!CC)
5462 return tokError("invalid DWARF calling convention" + Twine(" '") +
5463 Lex.getStrVal() + "'");
5464 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5465 Result.assign(CC);
5466 Lex.Lex();
5467 return false;
5468}
5469
5470template <>
5471bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5472 EmissionKindField &Result) {
5473 if (Lex.getKind() == lltok::APSInt)
5474 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5475
5476 if (Lex.getKind() != lltok::EmissionKind)
5477 return tokError("expected emission kind");
5478
5479 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5480 if (!Kind)
5481 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5482 "'");
5483 assert(*Kind <= Result.Max && "Expected valid emission kind");
5484 Result.assign(*Kind);
5485 Lex.Lex();
5486 return false;
5487}
5488
5489template <>
5490bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5491 FixedPointKindField &Result) {
5492 if (Lex.getKind() == lltok::APSInt)
5493 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5494
5495 if (Lex.getKind() != lltok::FixedPointKind)
5496 return tokError("expected fixed-point kind");
5497
5498 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5499 if (!Kind)
5500 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5501 "'");
5502 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5503 Result.assign(*Kind);
5504 Lex.Lex();
5505 return false;
5506}
5507
5508template <>
5509bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5510 NameTableKindField &Result) {
5511 if (Lex.getKind() == lltok::APSInt)
5512 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5513
5514 if (Lex.getKind() != lltok::NameTableKind)
5515 return tokError("expected nameTable kind");
5516
5517 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5518 if (!Kind)
5519 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5520 "'");
5521 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5522 Result.assign((unsigned)*Kind);
5523 Lex.Lex();
5524 return false;
5525}
5526
5527template <>
5528bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5529 DwarfAttEncodingField &Result) {
5530 if (Lex.getKind() == lltok::APSInt)
5531 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5532
5533 if (Lex.getKind() != lltok::DwarfAttEncoding)
5534 return tokError("expected DWARF type attribute encoding");
5535
5536 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5537 if (!Encoding)
5538 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5539 Lex.getStrVal() + "'");
5540 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5541 Result.assign(Encoding);
5542 Lex.Lex();
5543 return false;
5544}
5545
5546/// DIFlagField
5547/// ::= uint32
5548/// ::= DIFlagVector
5549/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5550template <>
5551bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5552
5553 // parser for a single flag.
5554 auto parseFlag = [&](DINode::DIFlags &Val) {
5555 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5556 uint32_t TempVal = static_cast<uint32_t>(Val);
5557 bool Res = parseUInt32(TempVal);
5558 Val = static_cast<DINode::DIFlags>(TempVal);
5559 return Res;
5560 }
5561
5562 if (Lex.getKind() != lltok::DIFlag)
5563 return tokError("expected debug info flag");
5564
5565 Val = DINode::getFlag(Lex.getStrVal());
5566 if (!Val)
5567 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5568 "'");
5569 Lex.Lex();
5570 return false;
5571 };
5572
5573 // parse the flags and combine them together.
5574 DINode::DIFlags Combined = DINode::FlagZero;
5575 do {
5576 DINode::DIFlags Val;
5577 if (parseFlag(Val))
5578 return true;
5579 Combined |= Val;
5580 } while (EatIfPresent(lltok::bar));
5581
5582 Result.assign(Combined);
5583 return false;
5584}
5585
5586/// DISPFlagField
5587/// ::= uint32
5588/// ::= DISPFlagVector
5589/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5590template <>
5591bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5592
5593 // parser for a single flag.
5594 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5595 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5596 uint32_t TempVal = static_cast<uint32_t>(Val);
5597 bool Res = parseUInt32(TempVal);
5598 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5599 return Res;
5600 }
5601
5602 if (Lex.getKind() != lltok::DISPFlag)
5603 return tokError("expected debug info flag");
5604
5605 Val = DISubprogram::getFlag(Lex.getStrVal());
5606 if (!Val)
5607 return tokError(Twine("invalid subprogram debug info flag '") +
5608 Lex.getStrVal() + "'");
5609 Lex.Lex();
5610 return false;
5611 };
5612
5613 // parse the flags and combine them together.
5614 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5615 do {
5617 if (parseFlag(Val))
5618 return true;
5619 Combined |= Val;
5620 } while (EatIfPresent(lltok::bar));
5621
5622 Result.assign(Combined);
5623 return false;
5624}
5625
5626template <>
5627bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5628 if (Lex.getKind() != lltok::APSInt)
5629 return tokError("expected signed integer");
5630
5631 auto &S = Lex.getAPSIntVal();
5632 if (S < Result.Min)
5633 return tokError("value for '" + Name + "' too small, limit is " +
5634 Twine(Result.Min));
5635 if (S > Result.Max)
5636 return tokError("value for '" + Name + "' too large, limit is " +
5637 Twine(Result.Max));
5638 Result.assign(S.getExtValue());
5639 assert(Result.Val >= Result.Min && "Expected value in range");
5640 assert(Result.Val <= Result.Max && "Expected value in range");
5641 Lex.Lex();
5642 return false;
5643}
5644
5645template <>
5646bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5647 switch (Lex.getKind()) {
5648 default:
5649 return tokError("expected 'true' or 'false'");
5650 case lltok::kw_true:
5651 Result.assign(true);
5652 break;
5653 case lltok::kw_false:
5654 Result.assign(false);
5655 break;
5656 }
5657 Lex.Lex();
5658 return false;
5659}
5660
5661template <>
5662bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5663 if (Lex.getKind() == lltok::kw_null) {
5664 if (!Result.AllowNull)
5665 return tokError("'" + Name + "' cannot be null");
5666 Lex.Lex();
5667 Result.assign(nullptr);
5668 return false;
5669 }
5670
5671 Metadata *MD;
5672 if (parseMetadata(MD, nullptr))
5673 return true;
5674
5675 Result.assign(MD);
5676 return false;
5677}
5678
5679template <>
5680bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5681 MDSignedOrMDField &Result) {
5682 // Try to parse a signed int.
5683 if (Lex.getKind() == lltok::APSInt) {
5684 MDSignedField Res = Result.A;
5685 if (!parseMDField(Loc, Name, Res)) {
5686 Result.assign(Res);
5687 return false;
5688 }
5689 return true;
5690 }
5691
5692 // Otherwise, try to parse as an MDField.
5693 MDField Res = Result.B;
5694 if (!parseMDField(Loc, Name, Res)) {
5695 Result.assign(Res);
5696 return false;
5697 }
5698
5699 return true;
5700}
5701
5702template <>
5703bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5704 MDUnsignedOrMDField &Result) {
5705 // Try to parse an unsigned int.
5706 if (Lex.getKind() == lltok::APSInt) {
5707 MDUnsignedField Res = Result.A;
5708 if (!parseMDField(Loc, Name, Res)) {
5709 Result.assign(Res);
5710 return false;
5711 }
5712 return true;
5713 }
5714
5715 // Otherwise, try to parse as an MDField.
5716 MDField Res = Result.B;
5717 if (!parseMDField(Loc, Name, Res)) {
5718 Result.assign(Res);
5719 return false;
5720 }
5721
5722 return true;
5723}
5724
5725template <>
5726bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5727 LocTy ValueLoc = Lex.getLoc();
5728 std::string S;
5729 if (parseStringConstant(S))
5730 return true;
5731
5732 if (S.empty()) {
5733 switch (Result.EmptyIs) {
5734 case MDStringField::EmptyIs::Null:
5735 Result.assign(nullptr);
5736 return false;
5737 case MDStringField::EmptyIs::Empty:
5738 break;
5739 case MDStringField::EmptyIs::Error:
5740 return error(ValueLoc, "'" + Name + "' cannot be empty");
5741 }
5742 }
5743
5744 Result.assign(MDString::get(Context, S));
5745 return false;
5746}
5747
5748template <>
5749bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5751 if (parseMDNodeVector(MDs))
5752 return true;
5753
5754 Result.assign(std::move(MDs));
5755 return false;
5756}
5757
5758template <>
5759bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5760 ChecksumKindField &Result) {
5761 std::optional<DIFile::ChecksumKind> CSKind =
5762 DIFile::getChecksumKind(Lex.getStrVal());
5763
5764 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5765 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5766 "'");
5767
5768 Result.assign(*CSKind);
5769 Lex.Lex();
5770 return false;
5771}
5772
5773} // end namespace llvm
5774
5775template <class ParserTy>
5776bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5777 do {
5778 if (Lex.getKind() != lltok::LabelStr)
5779 return tokError("expected field label here");
5780
5781 if (ParseField())
5782 return true;
5783 } while (EatIfPresent(lltok::comma));
5784
5785 return false;
5786}
5787
5788template <class ParserTy>
5789bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5790 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5791 Lex.Lex();
5792
5793 if (parseToken(lltok::lparen, "expected '(' here"))
5794 return true;
5795 if (Lex.getKind() != lltok::rparen)
5796 if (parseMDFieldsImplBody(ParseField))
5797 return true;
5798
5799 ClosingLoc = Lex.getLoc();
5800 return parseToken(lltok::rparen, "expected ')' here");
5801}
5802
5803template <class FieldTy>
5804bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5805 if (Result.Seen)
5806 return tokError("field '" + Name + "' cannot be specified more than once");
5807
5808 LocTy Loc = Lex.getLoc();
5809 Lex.Lex();
5810 return parseMDField(Loc, Name, Result);
5811}
5812
5813bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5814 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5815
5816#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5817 if (Lex.getStrVal() == #CLASS) \
5818 return parse##CLASS(N, IsDistinct);
5819#include "llvm/IR/Metadata.def"
5820
5821 return tokError("expected metadata type");
5822}
5823
5824#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5825#define NOP_FIELD(NAME, TYPE, INIT)
5826#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5827 if (!NAME.Seen) \
5828 return error(ClosingLoc, "missing required field '" #NAME "'");
5829#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5830 if (Lex.getStrVal() == #NAME) \
5831 return parseMDField(#NAME, NAME);
5832#define PARSE_MD_FIELDS() \
5833 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5834 do { \
5835 LocTy ClosingLoc; \
5836 if (parseMDFieldsImpl( \
5837 [&]() -> bool { \
5838 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5839 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5840 "'"); \
5841 }, \
5842 ClosingLoc)) \
5843 return true; \
5844 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5845 } while (false)
5846#define GET_OR_DISTINCT(CLASS, ARGS) \
5847 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5848
5849/// parseDILocationFields:
5850/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5851/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5852bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5853#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5854 OPTIONAL(line, LineField, ); \
5855 OPTIONAL(column, ColumnField, ); \
5856 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5857 OPTIONAL(inlinedAt, MDField, ); \
5858 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5859 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5860 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
5861 OPTIONAL(irlayers, MDField, );
5863#undef VISIT_MD_FIELDS
5864
5865 Result =
5866 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5867 inlinedAt.Val, isImplicitCode.Val,
5868 atomGroup.Val, atomRank.Val, irlayers.Val));
5869 return false;
5870}
5871
5872bool LLParser::parseDILayerLoc(MDNode *&Result, bool IsDistinct) {
5873#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5874 OPTIONAL(line, LineField, ); \
5875 OPTIONAL(column, ColumnField, ); \
5876 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5877 REQUIRED(kind, MDStringField, );
5879#undef VISIT_MD_FIELDS
5880
5881 Result = GET_OR_DISTINCT(DILayerLoc,
5882 (Context, kind.Val, file.Val, line.Val, column.Val));
5883 return false;
5884}
5885
5886bool LLParser::parseDILayerLocList(MDNode *&Result, bool IsDistinct) {
5887 // ::= !DILayerLocList(!a, !b, ...)
5888 Lex.Lex(); // eat the '!DILayerLocList' type name
5889 if (parseToken(lltok::lparen, "expected '(' here"))
5890 return true;
5892 if (!EatIfPresent(lltok::rparen)) {
5893 do {
5894 Metadata *MD;
5895 if (parseMetadata(MD, nullptr))
5896 return true;
5897 Layers.push_back(MD);
5898 } while (EatIfPresent(lltok::comma));
5899 if (parseToken(lltok::rparen, "expected ')' here"))
5900 return true;
5901 }
5902 Result = GET_OR_DISTINCT(DILayerLocList, (Context, Layers));
5903 return false;
5904}
5905
5906/// parseDIAssignID:
5907/// ::= distinct !DIAssignID()
5908bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5909 if (!IsDistinct)
5910 return tokError("missing 'distinct', required for !DIAssignID()");
5911
5912 Lex.Lex();
5913
5914 // Now eat the parens.
5915 if (parseToken(lltok::lparen, "expected '(' here"))
5916 return true;
5917 if (parseToken(lltok::rparen, "expected ')' here"))
5918 return true;
5919
5921 return false;
5922}
5923
5924/// parseGenericDINode:
5925/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5926bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5927#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5928 REQUIRED(tag, DwarfTagField, ); \
5929 OPTIONAL(header, MDStringField, ); \
5930 OPTIONAL(operands, MDFieldList, );
5932#undef VISIT_MD_FIELDS
5933
5934 Result = GET_OR_DISTINCT(GenericDINode,
5935 (Context, tag.Val, header.Val, operands.Val));
5936 return false;
5937}
5938
5939/// parseDISubrangeType:
5940/// ::= !DISubrangeType(name: "whatever", file: !0,
5941/// line: 7, scope: !1, baseType: !2, size: 32,
5942/// align: 32, flags: 0, lowerBound: !3
5943/// upperBound: !4, stride: !5, bias: !6)
5944bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5945#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5946 OPTIONAL(name, MDStringField, ); \
5947 OPTIONAL(file, MDField, ); \
5948 OPTIONAL(line, LineField, ); \
5949 OPTIONAL(scope, MDField, ); \
5950 OPTIONAL(baseType, MDField, ); \
5951 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5952 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5953 OPTIONAL(flags, DIFlagField, ); \
5954 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5955 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5956 OPTIONAL(stride, MDSignedOrMDField, ); \
5957 OPTIONAL(bias, MDSignedOrMDField, );
5959#undef VISIT_MD_FIELDS
5960
5961 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5962 if (Bound.isMDSignedField())
5964 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5965 if (Bound.isMDField())
5966 return Bound.getMDFieldValue();
5967 return nullptr;
5968 };
5969
5970 Metadata *LowerBound = convToMetadata(lowerBound);
5971 Metadata *UpperBound = convToMetadata(upperBound);
5972 Metadata *Stride = convToMetadata(stride);
5973 Metadata *Bias = convToMetadata(bias);
5974
5976 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5977 size.getValueAsMetadata(Context), align.Val, flags.Val,
5978 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5979
5980 return false;
5981}
5982
5983/// parseDISubrange:
5984/// ::= !DISubrange(count: 30, lowerBound: 2)
5985/// ::= !DISubrange(count: !node, lowerBound: 2)
5986/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5987bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5988#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5989 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5990 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5991 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5992 OPTIONAL(stride, MDSignedOrMDField, );
5994#undef VISIT_MD_FIELDS
5995
5996 Metadata *Count = nullptr;
5997 Metadata *LowerBound = nullptr;
5998 Metadata *UpperBound = nullptr;
5999 Metadata *Stride = nullptr;
6000
6001 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6002 if (Bound.isMDSignedField())
6004 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
6005 if (Bound.isMDField())
6006 return Bound.getMDFieldValue();
6007 return nullptr;
6008 };
6009
6010 Count = convToMetadata(count);
6011 LowerBound = convToMetadata(lowerBound);
6012 UpperBound = convToMetadata(upperBound);
6013 Stride = convToMetadata(stride);
6014
6015 Result = GET_OR_DISTINCT(DISubrange,
6016 (Context, Count, LowerBound, UpperBound, Stride));
6017
6018 return false;
6019}
6020
6021/// parseDIGenericSubrange:
6022/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
6023/// !node3)
6024bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
6025#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6026 OPTIONAL(count, MDSignedOrMDField, ); \
6027 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6028 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6029 OPTIONAL(stride, MDSignedOrMDField, );
6031#undef VISIT_MD_FIELDS
6032
6033 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6034 if (Bound.isMDSignedField())
6035 return DIExpression::get(
6036 Context, {dwarf::DW_OP_consts,
6037 static_cast<uint64_t>(Bound.getMDSignedValue())});
6038 if (Bound.isMDField())
6039 return Bound.getMDFieldValue();
6040 return nullptr;
6041 };
6042
6043 Metadata *Count = ConvToMetadata(count);
6044 Metadata *LowerBound = ConvToMetadata(lowerBound);
6045 Metadata *UpperBound = ConvToMetadata(upperBound);
6046 Metadata *Stride = ConvToMetadata(stride);
6047
6048 Result = GET_OR_DISTINCT(DIGenericSubrange,
6049 (Context, Count, LowerBound, UpperBound, Stride));
6050
6051 return false;
6052}
6053
6054/// parseDIEnumerator:
6055/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
6056bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
6057#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6058 REQUIRED(name, MDStringField, ); \
6059 REQUIRED(value, MDAPSIntField, ); \
6060 OPTIONAL(isUnsigned, MDBoolField, (false));
6062#undef VISIT_MD_FIELDS
6063
6064 if (isUnsigned.Val && value.Val.isNegative())
6065 return tokError("unsigned enumerator with negative value");
6066
6067 APSInt Value(value.Val);
6068 // Add a leading zero so that unsigned values with the msb set are not
6069 // mistaken for negative values when used for signed enumerators.
6070 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6071 Value = Value.zext(Value.getBitWidth() + 1);
6072
6073 Result =
6074 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
6075
6076 return false;
6077}
6078
6079/// parseDIBasicType:
6080/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
6081/// encoding: DW_ATE_encoding, flags: 0)
6082bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
6083#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6084 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6085 OPTIONAL(name, MDStringField, ); \
6086 OPTIONAL(file, MDField, ); \
6087 OPTIONAL(line, LineField, ); \
6088 OPTIONAL(scope, MDField, ); \
6089 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6090 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6091 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6092 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6093 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6094 OPTIONAL(flags, DIFlagField, );
6096#undef VISIT_MD_FIELDS
6097
6099 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6100 size.getValueAsMetadata(Context), align.Val, encoding.Val,
6101 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6102 return false;
6103}
6104
6105/// parseDIFixedPointType:
6106/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
6107/// align: 32, encoding: DW_ATE_signed_fixed,
6108/// flags: 0, kind: Rational, factor: 3, numerator: 1,
6109/// denominator: 8)
6110bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
6111#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6112 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6113 OPTIONAL(name, MDStringField, ); \
6114 OPTIONAL(file, MDField, ); \
6115 OPTIONAL(line, LineField, ); \
6116 OPTIONAL(scope, MDField, ); \
6117 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6118 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6119 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6120 OPTIONAL(flags, DIFlagField, ); \
6121 OPTIONAL(kind, FixedPointKindField, ); \
6122 OPTIONAL(factor, MDSignedField, ); \
6123 OPTIONAL(numerator, MDAPSIntField, ); \
6124 OPTIONAL(denominator, MDAPSIntField, );
6126#undef VISIT_MD_FIELDS
6127
6128 Result = GET_OR_DISTINCT(DIFixedPointType,
6129 (Context, tag.Val, name.Val, file.Val, line.Val,
6130 scope.Val, size.getValueAsMetadata(Context),
6131 align.Val, encoding.Val, flags.Val, kind.Val,
6132 factor.Val, numerator.Val, denominator.Val));
6133 return false;
6134}
6135
6136/// parseDIStringType:
6137/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
6138bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
6139#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6140 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6141 OPTIONAL(name, MDStringField, ); \
6142 OPTIONAL(stringLength, MDField, ); \
6143 OPTIONAL(stringLengthExpression, MDField, ); \
6144 OPTIONAL(stringLocationExpression, MDField, ); \
6145 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6146 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6147 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6148 OPTIONAL(charType, MDField, );
6150#undef VISIT_MD_FIELDS
6151
6153 DIStringType,
6154 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
6155 stringLocationExpression.Val, size.getValueAsMetadata(Context),
6156 align.Val, encoding.Val, charType.Val));
6157 return false;
6158}
6159
6160/// parseDIDerivedType:
6161/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
6162/// line: 7, scope: !1, baseType: !2, size: 32,
6163/// align: 32, offset: 0, flags: 0, extraData: !3,
6164/// dwarfAddressSpace: 3, ptrAuthKey: 1,
6165/// ptrAuthIsAddressDiscriminated: true,
6166/// ptrAuthExtraDiscriminator: 0x1234,
6167/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
6168/// )
6169bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
6170#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6171 REQUIRED(tag, DwarfTagField, ); \
6172 OPTIONAL(name, MDStringField, ); \
6173 OPTIONAL(file, MDField, ); \
6174 OPTIONAL(line, LineField, ); \
6175 OPTIONAL(scope, MDField, ); \
6176 REQUIRED(baseType, MDField, ); \
6177 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6178 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6179 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6180 OPTIONAL(flags, DIFlagField, ); \
6181 OPTIONAL(extraData, MDField, ); \
6182 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6183 OPTIONAL(annotations, MDField, ); \
6184 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6185 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6186 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6187 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6188 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6190#undef VISIT_MD_FIELDS
6191
6192 std::optional<unsigned> DWARFAddressSpace;
6193 if (dwarfAddressSpace.Val != UINT32_MAX)
6194 DWARFAddressSpace = dwarfAddressSpace.Val;
6195 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6196 if (ptrAuthKey.Val)
6197 PtrAuthData.emplace(
6198 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6199 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6200 ptrAuthAuthenticatesNullValues.Val);
6201
6203 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6204 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6205 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6206 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6207 return false;
6208}
6209
6210bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6211#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6212 REQUIRED(tag, DwarfTagField, ); \
6213 OPTIONAL(name, MDStringField, ); \
6214 OPTIONAL(file, MDField, ); \
6215 OPTIONAL(line, LineField, ); \
6216 OPTIONAL(scope, MDField, ); \
6217 OPTIONAL(baseType, MDField, ); \
6218 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6219 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6220 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6221 OPTIONAL(flags, DIFlagField, ); \
6222 OPTIONAL(elements, MDField, ); \
6223 OPTIONAL(runtimeLang, DwarfLangField, ); \
6224 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6225 OPTIONAL(vtableHolder, MDField, ); \
6226 OPTIONAL(templateParams, MDField, ); \
6227 OPTIONAL(identifier, MDStringField, ); \
6228 OPTIONAL(discriminator, MDField, ); \
6229 OPTIONAL(dataLocation, MDField, ); \
6230 OPTIONAL(associated, MDField, ); \
6231 OPTIONAL(allocated, MDField, ); \
6232 OPTIONAL(rank, MDSignedOrMDField, ); \
6233 OPTIONAL(annotations, MDField, ); \
6234 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6235 OPTIONAL(specification, MDField, ); \
6236 OPTIONAL(bitStride, MDField, );
6238#undef VISIT_MD_FIELDS
6239
6240 Metadata *Rank = nullptr;
6241 if (rank.isMDSignedField())
6243 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6244 else if (rank.isMDField())
6245 Rank = rank.getMDFieldValue();
6246
6247 std::optional<unsigned> EnumKind;
6248 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6249 EnumKind = enumKind.Val;
6250
6251 // If this has an identifier try to build an ODR type.
6252 if (identifier.Val)
6253 if (auto *CT = DICompositeType::buildODRType(
6254 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6255 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6256 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6257 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6258 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6259 dataLocation.Val, associated.Val, allocated.Val, Rank,
6260 annotations.Val, bitStride.Val)) {
6261 Result = CT;
6262 return false;
6263 }
6264
6265 // Create a new node, and save it in the context if it belongs in the type
6266 // map.
6268 DICompositeType,
6269 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6270 size.getValueAsMetadata(Context), align.Val,
6271 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6272 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6273 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6274 allocated.Val, Rank, annotations.Val, specification.Val,
6275 num_extra_inhabitants.Val, bitStride.Val));
6276 return false;
6277}
6278
6279bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6280#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6281 OPTIONAL(flags, DIFlagField, ); \
6282 OPTIONAL(cc, DwarfCCField, ); \
6283 REQUIRED(types, MDField, );
6285#undef VISIT_MD_FIELDS
6286
6287 Result = GET_OR_DISTINCT(DISubroutineType,
6288 (Context, flags.Val, cc.Val, types.Val));
6289 return false;
6290}
6291
6292/// parseDIFileType:
6293/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6294/// checksumkind: CSK_MD5,
6295/// checksum: "000102030405060708090a0b0c0d0e0f",
6296/// source: "source file contents")
6297bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6298 // The default constructed value for checksumkind is required, but will never
6299 // be used, as the parser checks if the field was actually Seen before using
6300 // the Val.
6301#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6302 REQUIRED(filename, MDStringField, ); \
6303 REQUIRED(directory, MDStringField, ); \
6304 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6305 OPTIONAL(checksum, MDStringField, ); \
6306 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6308#undef VISIT_MD_FIELDS
6309
6310 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6311 if (checksumkind.Seen && checksum.Seen)
6312 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6313 else if (checksumkind.Seen || checksum.Seen)
6314 return tokError("'checksumkind' and 'checksum' must be provided together");
6315
6316 MDString *Source = nullptr;
6317 if (source.Seen)
6318 Source = source.Val;
6320 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6321 return false;
6322}
6323
6324/// parseDICompileUnit:
6325/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6326/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6327/// splitDebugFilename: "abc.debug",
6328/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6329/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6330/// sysroot: "/", sdk: "MacOSX.sdk",
6331/// dialect: DW_LLVM_LANG_DIALECT_simt)
6332bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6333 if (!IsDistinct)
6334 return tokError("missing 'distinct', required for !DICompileUnit");
6335
6336 LocTy Loc = Lex.getLoc();
6337
6338#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6339 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6340 OPTIONAL(language, DwarfLangField, ); \
6341 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6342 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6343 OPTIONAL(producer, MDStringField, ); \
6344 OPTIONAL(isOptimized, MDBoolField, ); \
6345 OPTIONAL(flags, MDStringField, ); \
6346 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6347 OPTIONAL(splitDebugFilename, MDStringField, ); \
6348 OPTIONAL(emissionKind, EmissionKindField, ); \
6349 OPTIONAL(enums, MDField, ); \
6350 OPTIONAL(retainedTypes, MDField, ); \
6351 OPTIONAL(globals, MDField, ); \
6352 OPTIONAL(imports, MDField, ); \
6353 OPTIONAL(macros, MDField, ); \
6354 OPTIONAL(dwoId, MDUnsignedField, ); \
6355 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6356 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6357 OPTIONAL(nameTableKind, NameTableKindField, ); \
6358 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6359 OPTIONAL(sysroot, MDStringField, ); \
6360 OPTIONAL(sdk, MDStringField, ); \
6361 OPTIONAL(dialect, DwarfLangDialectField, );
6363#undef VISIT_MD_FIELDS
6364
6365 if (!language.Seen && !sourceLanguageName.Seen)
6366 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6367 "required for !DICompileUnit");
6368
6369 if (language.Seen && sourceLanguageName.Seen)
6370 return error(Loc, "can only specify one of 'language' and "
6371 "'sourceLanguageName' on !DICompileUnit");
6372
6373 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6374 return error(Loc, "'sourceLanguageVersion' requires an associated "
6375 "'sourceLanguageName' on !DICompileUnit");
6376
6377 uint16_t Dialect = static_cast<uint16_t>(dialect.Val);
6378 DISourceLanguageName SourceLanguage =
6379 language.Seen
6380 ? DISourceLanguageName(static_cast<uint16_t>(language.Val), Dialect)
6381 : DISourceLanguageName(
6382 static_cast<uint16_t>(sourceLanguageName.Val),
6383 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6384
6386 Context, SourceLanguage, file.Val, producer.Val, isOptimized.Val,
6387 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6388 enums.Val, retainedTypes.Val, globals.Val, imports.Val, macros.Val,
6389 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6390 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6391 return false;
6392}
6393
6394/// parseDISubprogram:
6395/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6396/// file: !1, line: 7, type: !2, isLocal: false,
6397/// isDefinition: true, scopeLine: 8, containingType: !3,
6398/// virtuality: DW_VIRTUALTIY_pure_virtual,
6399/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6400/// spFlags: 10, isOptimized: false, templateParams: !4,
6401/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6402/// annotations: !8)
6403bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6404 auto Loc = Lex.getLoc();
6405#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6406 OPTIONAL(scope, MDField, ); \
6407 OPTIONAL(name, MDStringField, ); \
6408 OPTIONAL(linkageName, MDStringField, ); \
6409 OPTIONAL(file, MDField, ); \
6410 OPTIONAL(line, LineField, ); \
6411 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6412 OPTIONAL(isLocal, MDBoolField, ); \
6413 OPTIONAL(isDefinition, MDBoolField, (true)); \
6414 OPTIONAL(scopeLine, LineField, ); \
6415 OPTIONAL(containingType, MDField, ); \
6416 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6417 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6418 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6419 OPTIONAL(flags, DIFlagField, ); \
6420 OPTIONAL(spFlags, DISPFlagField, ); \
6421 OPTIONAL(isOptimized, MDBoolField, ); \
6422 OPTIONAL(unit, MDField, ); \
6423 OPTIONAL(templateParams, MDField, ); \
6424 OPTIONAL(declaration, MDField, ); \
6425 OPTIONAL(retainedNodes, MDField, ); \
6426 OPTIONAL(thrownTypes, MDField, ); \
6427 OPTIONAL(annotations, MDField, ); \
6428 OPTIONAL(targetFuncName, MDStringField, ); \
6429 OPTIONAL(keyInstructions, MDBoolField, );
6431#undef VISIT_MD_FIELDS
6432
6433 // An explicit spFlags field takes precedence over individual fields in
6434 // older IR versions.
6435 DISubprogram::DISPFlags SPFlags =
6436 spFlags.Seen ? spFlags.Val
6437 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6438 isOptimized.Val, virtuality.Val);
6439 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6440 return error(
6441 Loc,
6442 "missing 'distinct', required for !DISubprogram that is a Definition");
6444 DISubprogram,
6445 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6446 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6447 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6448 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6449 targetFuncName.Val, keyInstructions.Val));
6450
6451 if (IsDistinct)
6452 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6453
6454 return false;
6455}
6456
6457/// parseDILexicalBlock:
6458/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6459bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6460#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6461 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6462 OPTIONAL(file, MDField, ); \
6463 OPTIONAL(line, LineField, ); \
6464 OPTIONAL(column, ColumnField, );
6466#undef VISIT_MD_FIELDS
6467
6469 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6470 return false;
6471}
6472
6473/// parseDILexicalBlockFile:
6474/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6475bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6476#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6477 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6478 OPTIONAL(file, MDField, ); \
6479 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6481#undef VISIT_MD_FIELDS
6482
6483 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6484 (Context, scope.Val, file.Val, discriminator.Val));
6485 return false;
6486}
6487
6488/// parseDICommonBlock:
6489/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6490bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6491#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6492 REQUIRED(scope, MDField, ); \
6493 OPTIONAL(declaration, MDField, ); \
6494 OPTIONAL(name, MDStringField, ); \
6495 OPTIONAL(file, MDField, ); \
6496 OPTIONAL(line, LineField, );
6498#undef VISIT_MD_FIELDS
6499
6500 Result = GET_OR_DISTINCT(DICommonBlock,
6501 (Context, scope.Val, declaration.Val, name.Val,
6502 file.Val, line.Val));
6503 return false;
6504}
6505
6506/// parseDINamespace:
6507/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6508bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6509#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6510 REQUIRED(scope, MDField, ); \
6511 OPTIONAL(name, MDStringField, ); \
6512 OPTIONAL(exportSymbols, MDBoolField, );
6514#undef VISIT_MD_FIELDS
6515
6516 Result = GET_OR_DISTINCT(DINamespace,
6517 (Context, scope.Val, name.Val, exportSymbols.Val));
6518 return false;
6519}
6520
6521/// parseDIMacro:
6522/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6523/// "SomeValue")
6524bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6525#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6526 REQUIRED(type, DwarfMacinfoTypeField, ); \
6527 OPTIONAL(line, LineField, ); \
6528 REQUIRED(name, MDStringField, ); \
6529 OPTIONAL(value, MDStringField, );
6531#undef VISIT_MD_FIELDS
6532
6533 Result = GET_OR_DISTINCT(DIMacro,
6534 (Context, type.Val, line.Val, name.Val, value.Val));
6535 return false;
6536}
6537
6538/// parseDIMacroFile:
6539/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6540bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6541#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6542 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6543 OPTIONAL(line, LineField, ); \
6544 REQUIRED(file, MDField, ); \
6545 OPTIONAL(nodes, MDField, );
6547#undef VISIT_MD_FIELDS
6548
6549 Result = GET_OR_DISTINCT(DIMacroFile,
6550 (Context, type.Val, line.Val, file.Val, nodes.Val));
6551 return false;
6552}
6553
6554/// parseDIModule:
6555/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6556/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6557/// file: !1, line: 4, isDecl: false)
6558bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6559#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6560 REQUIRED(scope, MDField, ); \
6561 REQUIRED(name, MDStringField, ); \
6562 OPTIONAL(configMacros, MDStringField, ); \
6563 OPTIONAL(includePath, MDStringField, ); \
6564 OPTIONAL(apinotes, MDStringField, ); \
6565 OPTIONAL(file, MDField, ); \
6566 OPTIONAL(line, LineField, ); \
6567 OPTIONAL(isDecl, MDBoolField, );
6569#undef VISIT_MD_FIELDS
6570
6571 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6572 configMacros.Val, includePath.Val,
6573 apinotes.Val, line.Val, isDecl.Val));
6574 return false;
6575}
6576
6577/// parseDITemplateTypeParameter:
6578/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6579bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6580#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6581 OPTIONAL(name, MDStringField, ); \
6582 REQUIRED(type, MDField, ); \
6583 OPTIONAL(defaulted, MDBoolField, );
6585#undef VISIT_MD_FIELDS
6586
6587 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6588 (Context, name.Val, type.Val, defaulted.Val));
6589 return false;
6590}
6591
6592/// parseDITemplateValueParameter:
6593/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6594/// name: "V", type: !1, defaulted: false,
6595/// value: i32 7)
6596bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6597#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6598 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6599 OPTIONAL(name, MDStringField, ); \
6600 OPTIONAL(type, MDField, ); \
6601 OPTIONAL(defaulted, MDBoolField, ); \
6602 REQUIRED(value, MDField, );
6603
6605#undef VISIT_MD_FIELDS
6606
6608 DITemplateValueParameter,
6609 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6610 return false;
6611}
6612
6613/// parseDIGlobalVariable:
6614/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6615/// file: !1, line: 7, type: !2, isLocal: false,
6616/// isDefinition: true, templateParams: !3,
6617/// declaration: !4, align: 8)
6618bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6619#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6620 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6621 OPTIONAL(scope, MDField, ); \
6622 OPTIONAL(linkageName, MDStringField, ); \
6623 OPTIONAL(file, MDField, ); \
6624 OPTIONAL(line, LineField, ); \
6625 OPTIONAL(type, MDField, ); \
6626 OPTIONAL(isLocal, MDBoolField, ); \
6627 OPTIONAL(isDefinition, MDBoolField, (true)); \
6628 OPTIONAL(templateParams, MDField, ); \
6629 OPTIONAL(declaration, MDField, ); \
6630 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6631 OPTIONAL(annotations, MDField, );
6633#undef VISIT_MD_FIELDS
6634
6635 Result =
6636 GET_OR_DISTINCT(DIGlobalVariable,
6637 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6638 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6639 declaration.Val, templateParams.Val, align.Val,
6640 annotations.Val));
6641 return false;
6642}
6643
6644/// parseDILocalVariable:
6645/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6646/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6647/// align: 8)
6648/// ::= !DILocalVariable(scope: !0, name: "foo",
6649/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6650/// align: 8)
6651bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6652#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6653 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6654 OPTIONAL(name, MDStringField, ); \
6655 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6656 OPTIONAL(file, MDField, ); \
6657 OPTIONAL(line, LineField, ); \
6658 OPTIONAL(type, MDField, ); \
6659 OPTIONAL(flags, DIFlagField, ); \
6660 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6661 OPTIONAL(annotations, MDField, );
6663#undef VISIT_MD_FIELDS
6664
6665 Result = GET_OR_DISTINCT(DILocalVariable,
6666 (Context, scope.Val, name.Val, file.Val, line.Val,
6667 type.Val, arg.Val, flags.Val, align.Val,
6668 annotations.Val));
6669 return false;
6670}
6671
6672/// parseDILabel:
6673/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6674bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6675#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6676 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6677 REQUIRED(name, MDStringField, ); \
6678 REQUIRED(file, MDField, ); \
6679 REQUIRED(line, LineField, ); \
6680 OPTIONAL(column, ColumnField, ); \
6681 OPTIONAL(isArtificial, MDBoolField, ); \
6682 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6684#undef VISIT_MD_FIELDS
6685
6686 std::optional<unsigned> CoroSuspendIdx =
6687 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6688 : std::nullopt;
6689
6690 Result = GET_OR_DISTINCT(DILabel,
6691 (Context, scope.Val, name.Val, file.Val, line.Val,
6692 column.Val, isArtificial.Val, CoroSuspendIdx));
6693 return false;
6694}
6695
6696/// parseDIExpressionBody:
6697/// ::= (0, 7, -1)
6698bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6699 if (parseToken(lltok::lparen, "expected '(' here"))
6700 return true;
6701
6702 SmallVector<uint64_t, 8> Elements;
6703 if (Lex.getKind() != lltok::rparen)
6704 do {
6705 if (Lex.getKind() == lltok::DwarfOp) {
6706 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6707 Lex.Lex();
6708 Elements.push_back(Op);
6709 continue;
6710 }
6711 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6712 }
6713
6714 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6715 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6716 Lex.Lex();
6717 Elements.push_back(Op);
6718 continue;
6719 }
6720 return tokError(Twine("invalid DWARF attribute encoding '") +
6721 Lex.getStrVal() + "'");
6722 }
6723
6724 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6725 return tokError("expected unsigned integer");
6726
6727 auto &U = Lex.getAPSIntVal();
6728 if (U.ugt(UINT64_MAX))
6729 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6730 Elements.push_back(U.getZExtValue());
6731 Lex.Lex();
6732 } while (EatIfPresent(lltok::comma));
6733
6734 if (parseToken(lltok::rparen, "expected ')' here"))
6735 return true;
6736
6737 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6738 return false;
6739}
6740
6741/// parseDIExpression:
6742/// ::= !DIExpression(0, 7, -1)
6743bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6744 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6745 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6746 Lex.Lex();
6747
6748 return parseDIExpressionBody(Result, IsDistinct);
6749}
6750
6751/// ParseDIArgList:
6752/// ::= !DIArgList(i32 7, i64 %0)
6753bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6754 assert(PFS && "Expected valid function state");
6755 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6756 Lex.Lex();
6757
6758 if (parseToken(lltok::lparen, "expected '(' here"))
6759 return true;
6760
6762 if (Lex.getKind() != lltok::rparen)
6763 do {
6764 Metadata *MD;
6765 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6766 return true;
6767 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6768 } while (EatIfPresent(lltok::comma));
6769
6770 if (parseToken(lltok::rparen, "expected ')' here"))
6771 return true;
6772
6773 MD = DIArgList::get(Context, Args);
6774 return false;
6775}
6776
6777/// parseDIGlobalVariableExpression:
6778/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6779bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6780 bool IsDistinct) {
6781#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6782 REQUIRED(var, MDField, ); \
6783 REQUIRED(expr, MDField, );
6785#undef VISIT_MD_FIELDS
6786
6787 Result =
6788 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6789 return false;
6790}
6791
6792/// parseDIObjCProperty:
6793/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6794/// getter: "getFoo", attributes: 7, type: !2)
6795bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6796#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6797 OPTIONAL(name, MDStringField, ); \
6798 OPTIONAL(file, MDField, ); \
6799 OPTIONAL(line, LineField, ); \
6800 OPTIONAL(setter, MDStringField, ); \
6801 OPTIONAL(getter, MDStringField, ); \
6802 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6803 OPTIONAL(type, MDField, );
6805#undef VISIT_MD_FIELDS
6806
6807 Result = GET_OR_DISTINCT(DIObjCProperty,
6808 (Context, name.Val, file.Val, line.Val, getter.Val,
6809 setter.Val, attributes.Val, type.Val));
6810 return false;
6811}
6812
6813/// parseDIProperty:
6814/// ::= !DIProperty(name: "x", file: !1, line: 7, type: !2,
6815/// backing_storage: !3)
6816bool LLParser::parseDIProperty(MDNode *&Result, bool IsDistinct) {
6817#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6818 OPTIONAL(name, MDStringField, ); \
6819 OPTIONAL(file, MDField, ); \
6820 OPTIONAL(line, LineField, ); \
6821 OPTIONAL(type, MDField, ); \
6822 OPTIONAL(backing_storage, MDField, );
6824#undef VISIT_MD_FIELDS
6825
6826 Result = GET_OR_DISTINCT(DIProperty, (Context, name.Val, file.Val, line.Val,
6827 type.Val, backing_storage.Val));
6828 return false;
6829}
6830
6831/// parseDIImportedEntity:
6832/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6833/// line: 7, name: "foo", elements: !2)
6834bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6835#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6836 REQUIRED(tag, DwarfTagField, ); \
6837 REQUIRED(scope, MDField, ); \
6838 OPTIONAL(entity, MDField, ); \
6839 OPTIONAL(file, MDField, ); \
6840 OPTIONAL(line, LineField, ); \
6841 OPTIONAL(name, MDStringField, ); \
6842 OPTIONAL(elements, MDField, );
6844#undef VISIT_MD_FIELDS
6845
6846 Result = GET_OR_DISTINCT(DIImportedEntity,
6847 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6848 line.Val, name.Val, elements.Val));
6849 return false;
6850}
6851
6852#undef PARSE_MD_FIELD
6853#undef NOP_FIELD
6854#undef REQUIRE_FIELD
6855#undef DECLARE_FIELD
6856
6857/// parseMetadataAsValue
6858/// ::= metadata i32 %local
6859/// ::= metadata i32 @global
6860/// ::= metadata i32 7
6861/// ::= metadata !0
6862/// ::= metadata !{...}
6863/// ::= metadata !"string"
6864bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6865 // Note: the type 'metadata' has already been parsed.
6866 Metadata *MD;
6867 if (parseMetadata(MD, &PFS))
6868 return true;
6869
6870 V = MetadataAsValue::get(Context, MD);
6871 return false;
6872}
6873
6874/// parseValueAsMetadata
6875/// ::= i32 %local
6876/// ::= i32 @global
6877/// ::= i32 7
6878bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6879 PerFunctionState *PFS) {
6880 Type *Ty;
6881 LocTy Loc;
6882 if (parseType(Ty, TypeMsg, Loc))
6883 return true;
6884 if (Ty->isMetadataTy())
6885 return error(Loc, "invalid metadata-value-metadata roundtrip");
6886
6887 Value *V;
6888 if (parseValue(Ty, V, PFS))
6889 return true;
6890
6891 MD = ValueAsMetadata::get(V);
6892 return false;
6893}
6894
6895/// parseMetadata
6896/// ::= i32 %local
6897/// ::= i32 @global
6898/// ::= i32 7
6899/// ::= !42
6900/// ::= !{...}
6901/// ::= !"string"
6902/// ::= !DILocation(...)
6903bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6904 if (Lex.getKind() == lltok::MetadataVar) {
6905 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6906 // so parsing this requires a Function State.
6907 if (Lex.getStrVal() == "DIArgList") {
6908 Metadata *AL;
6909 if (parseDIArgList(AL, PFS))
6910 return true;
6911 MD = AL;
6912 return false;
6913 }
6914 MDNode *N;
6915 if (parseSpecializedMDNode(N)) {
6916 return true;
6917 }
6918 MD = N;
6919 return false;
6920 }
6921
6922 // ValueAsMetadata:
6923 // <type> <value>
6924 if (Lex.getKind() != lltok::exclaim)
6925 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6926
6927 // '!'.
6928 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6929 Lex.Lex();
6930
6931 // MDString:
6932 // ::= '!' STRINGCONSTANT
6933 if (Lex.getKind() == lltok::StringConstant) {
6934 MDString *S;
6935 if (parseMDString(S))
6936 return true;
6937 MD = S;
6938 return false;
6939 }
6940
6941 // MDNode:
6942 // !{ ... }
6943 // !7
6944 MDNode *N;
6945 if (parseMDNodeTail(N))
6946 return true;
6947 MD = N;
6948 return false;
6949}
6950
6951//===----------------------------------------------------------------------===//
6952// Function Parsing.
6953//===----------------------------------------------------------------------===//
6954
6955bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6956 PerFunctionState *PFS) {
6957 if (Ty->isFunctionTy())
6958 return error(ID.Loc, "functions are not values, refer to them as pointers");
6959
6960 switch (ID.Kind) {
6961 case ValID::t_LocalID:
6962 if (!PFS)
6963 return error(ID.Loc, "invalid use of function-local name");
6964 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6965 return V == nullptr;
6966 case ValID::t_LocalName:
6967 if (!PFS)
6968 return error(ID.Loc, "invalid use of function-local name");
6969 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6970 return V == nullptr;
6971 case ValID::t_InlineAsm: {
6972 if (!ID.FTy)
6973 return error(ID.Loc, "invalid type for inline asm constraint string");
6974 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6975 return error(ID.Loc, toString(std::move(Err)));
6976 V = InlineAsm::get(
6977 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6978 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6979 return false;
6980 }
6982 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6983 if (V && ID.NoCFI)
6985 return V == nullptr;
6986 case ValID::t_GlobalID:
6987 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6988 if (V && ID.NoCFI)
6990 return V == nullptr;
6991 case ValID::t_APSInt:
6992 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6993 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6994 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6995 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6996 : V = ConstantByte::get(Context, ID.APSIntVal);
6997 return false;
6998 case ValID::t_APFloat:
6999 if (!Ty->isFloatingPointTy() ||
7000 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
7001 return error(ID.Loc, "floating point constant invalid for type");
7002
7003 // The lexer has no type info, so builds all half, bfloat, float, and double
7004 // FP constants as double. Fix this here. Long double does not need this.
7005 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
7006 // Check for signaling before potentially converting and losing that info.
7007 bool IsSNAN = ID.APFloatVal.isSignaling();
7008 bool Ignored;
7009 if (Ty->isHalfTy())
7010 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7011 &Ignored);
7012 else if (Ty->isBFloatTy())
7013 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7014 &Ignored);
7015 else if (Ty->isFloatTy())
7016 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7017 &Ignored);
7018 if (IsSNAN) {
7019 // The convert call above may quiet an SNaN, so manufacture another
7020 // SNaN. The bitcast works because the payload (significand) parameter
7021 // is truncated to fit.
7022 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7023 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7024 ID.APFloatVal.isNegative(), &Payload);
7025 }
7026 }
7027 V = ConstantFP::get(Context, ID.APFloatVal);
7028
7029 if (V->getType() != Ty)
7030 return error(ID.Loc, "floating point constant does not have type '" +
7031 getTypeString(Ty) + "'");
7032
7033 return false;
7034 case ValID::t_Null:
7035 if (!Ty->isPointerTy())
7036 return error(ID.Loc, "null must be a pointer type");
7038 return false;
7039 case ValID::t_Undef:
7040 // FIXME: LabelTy should not be a first-class type.
7041 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7042 return error(ID.Loc, "invalid type for undef constant");
7043 V = UndefValue::get(Ty);
7044 return false;
7046 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
7047 return error(ID.Loc, "invalid empty array initializer");
7048 V = PoisonValue::get(Ty);
7049 return false;
7050 case ValID::t_Zero:
7051 // FIXME: LabelTy should not be a first-class type.
7052 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7053 return error(ID.Loc, "invalid type for null constant");
7054 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
7055 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
7056 return error(ID.Loc, "invalid type for null constant");
7058 return false;
7059 case ValID::t_None:
7060 if (!Ty->isTokenTy())
7061 return error(ID.Loc, "invalid type for none constant");
7063 return false;
7064 case ValID::t_Poison:
7065 // FIXME: LabelTy should not be a first-class type.
7066 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7067 return error(ID.Loc, "invalid type for poison constant");
7068 V = PoisonValue::get(Ty);
7069 return false;
7070 case ValID::t_Constant:
7071 if (ID.ConstantVal->getType() != Ty)
7072 return error(ID.Loc, "constant expression type mismatch: got type '" +
7073 getTypeString(ID.ConstantVal->getType()) +
7074 "' but expected '" + getTypeString(Ty) + "'");
7075 V = ID.ConstantVal;
7076 return false;
7078 if (!Ty->isVectorTy())
7079 return error(ID.Loc, "vector constant must have vector type");
7080 if (ID.ConstantVal->getType() != Ty->getScalarType())
7081 return error(ID.Loc, "constant expression type mismatch: got type '" +
7082 getTypeString(ID.ConstantVal->getType()) +
7083 "' but expected '" +
7084 getTypeString(Ty->getScalarType()) + "'");
7085 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
7086 ID.ConstantVal);
7087 return false;
7090 if (StructType *ST = dyn_cast<StructType>(Ty)) {
7091 if (ST->getNumElements() != ID.UIntVal)
7092 return error(ID.Loc,
7093 "initializer with struct type has wrong # elements");
7094 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
7095 return error(ID.Loc, "packed'ness of initializer and type don't match");
7096
7097 // Verify that the elements are compatible with the structtype.
7098 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
7099 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
7100 return error(
7101 ID.Loc,
7102 "element " + Twine(i) +
7103 " of struct initializer doesn't match struct element type");
7104
7106 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
7107 } else
7108 return error(ID.Loc, "constant expression type mismatch");
7109 return false;
7110 }
7111 llvm_unreachable("Invalid ValID");
7112}
7113
7114bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
7115 C = nullptr;
7116 ValID ID;
7117 auto Loc = Lex.getLoc();
7118 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
7119 return true;
7120 switch (ID.Kind) {
7121 case ValID::t_APSInt:
7122 case ValID::t_APFloat:
7123 case ValID::t_Undef:
7124 case ValID::t_Poison:
7125 case ValID::t_Zero:
7126 case ValID::t_Constant:
7130 Value *V;
7131 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
7132 return true;
7133 assert(isa<Constant>(V) && "Expected a constant value");
7134 C = cast<Constant>(V);
7135 return false;
7136 }
7137 case ValID::t_Null:
7139 return false;
7140 default:
7141 return error(Loc, "expected a constant value");
7142 }
7143}
7144
7145bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
7146 V = nullptr;
7147 ValID ID;
7148
7149 FileLoc Start = getTokLineColumnPos();
7150 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7151 if (!Ret && ParserContext) {
7152 FileLoc End = getPrevTokEndLineColumnPos();
7153 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7154 }
7155 return Ret;
7156}
7157
7158bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
7159 Type *Ty = nullptr;
7160 return parseType(Ty) || parseValue(Ty, V, PFS);
7161}
7162
7163bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
7164 PerFunctionState &PFS) {
7165 Value *V;
7166 Loc = Lex.getLoc();
7167 if (parseTypeAndValue(V, PFS))
7168 return true;
7169 if (!isa<BasicBlock>(V))
7170 return error(Loc, "expected a basic block");
7171 BB = cast<BasicBlock>(V);
7172 return false;
7173}
7174
7176 // Exit early for the common (non-debug-intrinsic) case.
7177 // We can make this the only check when we begin supporting all "llvm.dbg"
7178 // intrinsics in the new debug info format.
7179 if (!Name.starts_with("llvm.dbg."))
7180 return false;
7182 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7183 FnID == Intrinsic::dbg_assign;
7184}
7185
7186/// FunctionHeader
7187/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7188/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7189/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7190/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7191bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7192 unsigned &FunctionNumber,
7193 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7194 // parse the linkage.
7195 LocTy LinkageLoc = Lex.getLoc();
7196 unsigned Linkage;
7197 unsigned Visibility;
7198 unsigned DLLStorageClass;
7199 bool DSOLocal;
7200 AttrBuilder RetAttrs(M->getContext());
7201 unsigned CC;
7202 bool HasLinkage;
7203 Type *RetType = nullptr;
7204 LocTy RetTypeLoc = Lex.getLoc();
7205 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7206 DSOLocal) ||
7207 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7208 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7209 return true;
7210
7211 // Verify that the linkage is ok.
7214 break; // always ok.
7216 if (IsDefine)
7217 return error(LinkageLoc, "invalid linkage for function definition");
7218 break;
7226 if (!IsDefine)
7227 return error(LinkageLoc, "invalid linkage for function declaration");
7228 break;
7231 return error(LinkageLoc, "invalid function linkage type");
7232 }
7233
7234 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7235 return error(LinkageLoc,
7236 "symbol with local linkage must have default visibility");
7237
7238 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7239 return error(LinkageLoc,
7240 "symbol with local linkage cannot have a DLL storage class");
7241
7242 if (!FunctionType::isValidReturnType(RetType))
7243 return error(RetTypeLoc, "invalid function return type");
7244
7245 LocTy NameLoc = Lex.getLoc();
7246
7247 std::string FunctionName;
7248 if (Lex.getKind() == lltok::GlobalVar) {
7249 FunctionName = Lex.getStrVal();
7250 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7251 FunctionNumber = Lex.getUIntVal();
7252 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7253 FunctionNumber))
7254 return true;
7255 } else {
7256 return tokError("expected function name");
7257 }
7258
7259 Lex.Lex();
7260
7261 if (Lex.getKind() != lltok::lparen)
7262 return tokError("expected '(' in function argument list");
7263
7265 bool IsVarArg;
7266 AttrBuilder FuncAttrs(M->getContext());
7267 std::vector<unsigned> FwdRefAttrGrps;
7268 LocTy BuiltinLoc;
7269 std::string Section;
7270 std::string Partition;
7271 MaybeAlign Alignment, PrefAlignment;
7272 std::string GC;
7274 unsigned AddrSpace = 0;
7275 Constant *Prefix = nullptr;
7276 Constant *Prologue = nullptr;
7277 Constant *PersonalityFn = nullptr;
7278 Comdat *C;
7279
7280 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7281 parseOptionalUnnamedAddr(UnnamedAddr) ||
7282 parseOptionalProgramAddrSpace(AddrSpace) ||
7283 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7284 BuiltinLoc) ||
7285 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7286 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7287 parseOptionalComdat(FunctionName, C) ||
7288 parseOptionalAlignment(Alignment) ||
7289 parseOptionalPrefAlignment(PrefAlignment) ||
7290 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7291 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7292 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7293 (EatIfPresent(lltok::kw_personality) &&
7294 parseGlobalTypeAndValue(PersonalityFn)))
7295 return true;
7296
7297 if (FuncAttrs.contains(Attribute::Builtin))
7298 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7299
7300 // If the alignment was parsed as an attribute, move to the alignment field.
7301 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7302 Alignment = A;
7303 FuncAttrs.removeAttribute(Attribute::Alignment);
7304 }
7305
7306 // Okay, if we got here, the function is syntactically valid. Convert types
7307 // and do semantic checks.
7308 std::vector<Type*> ParamTypeList;
7310
7311 for (const ArgInfo &Arg : ArgList) {
7312 ParamTypeList.push_back(Arg.Ty);
7313 Attrs.push_back(Arg.Attrs);
7314 }
7315
7316 AttributeList PAL =
7317 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7318 AttributeSet::get(Context, RetAttrs), Attrs);
7319
7320 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7321 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7322
7323 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7324 PointerType *PFT = PointerType::get(Context, AddrSpace);
7325
7326 Fn = nullptr;
7327 GlobalValue *FwdFn = nullptr;
7328 if (!FunctionName.empty()) {
7329 // If this was a definition of a forward reference, remove the definition
7330 // from the forward reference table and fill in the forward ref.
7331 auto FRVI = ForwardRefVals.find(FunctionName);
7332 if (FRVI != ForwardRefVals.end()) {
7333 FwdFn = FRVI->second.first;
7334 if (FwdFn->getType() != PFT)
7335 return error(FRVI->second.second,
7336 "invalid forward reference to "
7337 "function '" +
7338 FunctionName +
7339 "' with wrong type: "
7340 "expected '" +
7341 getTypeString(PFT) + "' but was '" +
7342 getTypeString(FwdFn->getType()) + "'");
7343 ForwardRefVals.erase(FRVI);
7344 } else if ((Fn = M->getFunction(FunctionName))) {
7345 // Reject redefinitions.
7346 return error(NameLoc,
7347 "invalid redefinition of function '" + FunctionName + "'");
7348 } else if (M->getNamedValue(FunctionName)) {
7349 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7350 }
7351
7352 } else {
7353 // Handle @"", where a name is syntactically specified, but semantically
7354 // missing.
7355 if (FunctionNumber == (unsigned)-1)
7356 FunctionNumber = NumberedVals.getNext();
7357
7358 // If this is a definition of a forward referenced function, make sure the
7359 // types agree.
7360 auto I = ForwardRefValIDs.find(FunctionNumber);
7361 if (I != ForwardRefValIDs.end()) {
7362 FwdFn = I->second.first;
7363 if (FwdFn->getType() != PFT)
7364 return error(NameLoc, "type of definition and forward reference of '@" +
7365 Twine(FunctionNumber) +
7366 "' disagree: "
7367 "expected '" +
7368 getTypeString(PFT) + "' but was '" +
7369 getTypeString(FwdFn->getType()) + "'");
7370 ForwardRefValIDs.erase(I);
7371 }
7372 }
7373
7375 FunctionName, M);
7376
7377 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7378
7379 if (FunctionName.empty())
7380 NumberedVals.add(FunctionNumber, Fn);
7381
7383 maybeSetDSOLocal(DSOLocal, *Fn);
7386 Fn->setCallingConv(CC);
7387 Fn->setAttributes(PAL);
7388 Fn->setUnnamedAddr(UnnamedAddr);
7389 if (Alignment)
7390 Fn->setAlignment(*Alignment);
7391 Fn->setPreferredAlignment(PrefAlignment);
7392 Fn->setSection(Section);
7393 Fn->setPartition(Partition);
7394 Fn->setComdat(C);
7395 Fn->setPersonalityFn(PersonalityFn);
7396 if (!GC.empty()) Fn->setGC(GC);
7397 Fn->setPrefixData(Prefix);
7398 Fn->setPrologueData(Prologue);
7399 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7400
7401 // Add all of the arguments we parsed to the function.
7402 Function::arg_iterator ArgIt = Fn->arg_begin();
7403 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7404 if (ParserContext && ArgList[i].IdentLoc)
7405 ParserContext->addInstructionOrArgumentLocation(
7406 &*ArgIt, ArgList[i].IdentLoc.value());
7407 // If the argument has a name, insert it into the argument symbol table.
7408 if (ArgList[i].Name.empty()) continue;
7409
7410 // Set the name, if it conflicted, it will be auto-renamed.
7411 ArgIt->setName(ArgList[i].Name);
7412
7413 if (ArgIt->getName() != ArgList[i].Name)
7414 return error(ArgList[i].Loc,
7415 "redefinition of argument '%" + ArgList[i].Name + "'");
7416 }
7417
7418 if (FwdFn) {
7419 FwdFn->replaceAllUsesWith(Fn);
7420 FwdFn->eraseFromParent();
7421 }
7422
7423 if (IsDefine)
7424 return false;
7425
7426 // Check the declaration has no block address forward references.
7427 ValID ID;
7428 if (FunctionName.empty()) {
7429 ID.Kind = ValID::t_GlobalID;
7430 ID.UIntVal = FunctionNumber;
7431 } else {
7432 ID.Kind = ValID::t_GlobalName;
7433 ID.StrVal = FunctionName;
7434 }
7435 auto Blocks = ForwardRefBlockAddresses.find(ID);
7436 if (Blocks != ForwardRefBlockAddresses.end())
7437 return error(Blocks->first.Loc,
7438 "cannot take blockaddress inside a declaration");
7439 return false;
7440}
7441
7442bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7443 ValID ID;
7444 if (FunctionNumber == -1) {
7445 ID.Kind = ValID::t_GlobalName;
7446 ID.StrVal = std::string(F.getName());
7447 } else {
7448 ID.Kind = ValID::t_GlobalID;
7449 ID.UIntVal = FunctionNumber;
7450 }
7451
7452 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7453 if (Blocks == P.ForwardRefBlockAddresses.end())
7454 return false;
7455
7456 for (const auto &I : Blocks->second) {
7457 const ValID &BBID = I.first;
7458 GlobalValue *GV = I.second;
7459
7460 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7461 "Expected local id or name");
7462 BasicBlock *BB;
7463 if (BBID.Kind == ValID::t_LocalName)
7464 BB = getBB(BBID.StrVal, BBID.Loc);
7465 else
7466 BB = getBB(BBID.UIntVal, BBID.Loc);
7467 if (!BB)
7468 return P.error(BBID.Loc, "referenced value is not a basic block");
7469
7470 Value *ResolvedVal = BlockAddress::get(&F, BB);
7471 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7472 ResolvedVal);
7473 if (!ResolvedVal)
7474 return true;
7475 GV->replaceAllUsesWith(ResolvedVal);
7476 GV->eraseFromParent();
7477 }
7478
7479 P.ForwardRefBlockAddresses.erase(Blocks);
7480 return false;
7481}
7482
7483/// parseFunctionBody
7484/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7485bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7486 ArrayRef<unsigned> UnnamedArgNums) {
7487 if (Lex.getKind() != lltok::lbrace)
7488 return tokError("expected '{' in function body");
7489 Lex.Lex(); // eat the {.
7490
7491 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7492
7493 // Resolve block addresses and allow basic blocks to be forward-declared
7494 // within this function.
7495 if (PFS.resolveForwardRefBlockAddresses())
7496 return true;
7497 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7498
7499 // We need at least one basic block.
7500 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7501 return tokError("function body requires at least one basic block");
7502
7503 while (Lex.getKind() != lltok::rbrace &&
7504 Lex.getKind() != lltok::kw_uselistorder)
7505 if (parseBasicBlock(PFS))
7506 return true;
7507
7508 while (Lex.getKind() != lltok::rbrace)
7509 if (parseUseListOrder(&PFS))
7510 return true;
7511
7512 // Eat the }.
7513 Lex.Lex();
7514
7515 // Verify function is ok.
7516 return PFS.finishFunction();
7517}
7518
7519/// parseBasicBlock
7520/// ::= (LabelStr|LabelID)? Instruction*
7521bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7522 FileLoc BBStart = getTokLineColumnPos();
7523
7524 // If this basic block starts out with a name, remember it.
7525 std::string Name;
7526 int NameID = -1;
7527 LocTy NameLoc = Lex.getLoc();
7528 if (Lex.getKind() == lltok::LabelStr) {
7529 Name = Lex.getStrVal();
7530 Lex.Lex();
7531 } else if (Lex.getKind() == lltok::LabelID) {
7532 NameID = Lex.getUIntVal();
7533 Lex.Lex();
7534 }
7535
7536 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7537 if (!BB)
7538 return true;
7539
7540 std::string NameStr;
7541
7542 // Parse the instructions and debug values in this block until we get a
7543 // terminator.
7544 Instruction *Inst;
7545 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7546 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7547 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7548 do {
7549 // Handle debug records first - there should always be an instruction
7550 // following the debug records, i.e. they cannot appear after the block
7551 // terminator.
7552 while (Lex.getKind() == lltok::hash) {
7553 if (SeenOldDbgInfoFormat)
7554 return error(Lex.getLoc(), "debug record should not appear in a module "
7555 "containing debug info intrinsics");
7556 SeenNewDbgInfoFormat = true;
7557 Lex.Lex();
7558
7559 DbgRecord *DR;
7560 if (parseDebugRecord(DR, PFS))
7561 return true;
7562 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7563 }
7564
7565 FileLoc InstStart = getTokLineColumnPos();
7566 // This instruction may have three possibilities for a name: a) none
7567 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7568 LocTy NameLoc = Lex.getLoc();
7569 int NameID = -1;
7570 NameStr = "";
7571
7572 if (Lex.getKind() == lltok::LocalVarID) {
7573 NameID = Lex.getUIntVal();
7574 Lex.Lex();
7575 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7576 return true;
7577 } else if (Lex.getKind() == lltok::LocalVar) {
7578 NameStr = Lex.getStrVal();
7579 Lex.Lex();
7580 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7581 return true;
7582 }
7583
7584 switch (parseInstruction(Inst, BB, PFS)) {
7585 default:
7586 llvm_unreachable("Unknown parseInstruction result!");
7587 case InstError: return true;
7588 case InstNormal:
7589 Inst->insertInto(BB, BB->end());
7590
7591 // With a normal result, we check to see if the instruction is followed by
7592 // a comma and metadata.
7593 if (EatIfPresent(lltok::comma))
7594 if (parseInstructionMetadata(*Inst))
7595 return true;
7596 break;
7597 case InstExtraComma:
7598 Inst->insertInto(BB, BB->end());
7599
7600 // If the instruction parser ate an extra comma at the end of it, it
7601 // *must* be followed by metadata.
7602 if (parseInstructionMetadata(*Inst))
7603 return true;
7604 break;
7605 }
7606
7607 // Set the name on the instruction.
7608 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7609 return true;
7610
7611 // Attach any preceding debug values to this instruction.
7612 for (DbgRecordPtr &DR : TrailingDbgRecord)
7613 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7614 TrailingDbgRecord.clear();
7615 if (ParserContext) {
7616 ParserContext->addInstructionOrArgumentLocation(
7617 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7618 }
7619 } while (!Inst->isTerminator());
7620
7621 if (ParserContext)
7622 ParserContext->addBlockLocation(
7623 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7624
7625 assert(TrailingDbgRecord.empty() &&
7626 "All debug values should have been attached to an instruction.");
7627
7628 return false;
7629}
7630
7631/// parseDebugRecord
7632/// ::= #dbg_label '(' MDNode ')'
7633/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7634/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7635bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7636 using RecordKind = DbgRecord::Kind;
7637 using LocType = DbgVariableRecord::LocationType;
7638 LocTy DVRLoc = Lex.getLoc();
7639 if (Lex.getKind() != lltok::DbgRecordType)
7640 return error(DVRLoc, "expected debug record type here");
7641 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7642 .Case("declare", RecordKind::ValueKind)
7643 .Case("value", RecordKind::ValueKind)
7644 .Case("assign", RecordKind::ValueKind)
7645 .Case("label", RecordKind::LabelKind)
7646 .Case("declare_value", RecordKind::ValueKind);
7647
7648 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7649 // full DbgVariableRecord processing stage.
7650 if (RecordType == RecordKind::LabelKind) {
7651 Lex.Lex();
7652 if (parseToken(lltok::lparen, "Expected '(' here"))
7653 return true;
7654 MDNode *Label;
7655 if (parseMDNode(Label))
7656 return true;
7657 if (parseToken(lltok::comma, "Expected ',' here"))
7658 return true;
7659 MDNode *DbgLoc;
7660 if (parseMDNode(DbgLoc))
7661 return true;
7662 if (parseToken(lltok::rparen, "Expected ')' here"))
7663 return true;
7665 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7666 return false;
7667 }
7668
7669 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7670 .Case("declare", LocType::Declare)
7671 .Case("value", LocType::Value)
7672 .Case("assign", LocType::Assign)
7673 .Case("declare_value", LocType::DeclareValue);
7674
7675 Lex.Lex();
7676 if (parseToken(lltok::lparen, "Expected '(' here"))
7677 return true;
7678
7679 // Parse Value field.
7680 Metadata *ValLocMD;
7681 if (parseMetadata(ValLocMD, &PFS))
7682 return true;
7683 if (parseToken(lltok::comma, "Expected ',' here"))
7684 return true;
7685
7686 // Parse Variable field.
7687 MDNode *Variable;
7688 if (parseMDNode(Variable))
7689 return true;
7690 if (parseToken(lltok::comma, "Expected ',' here"))
7691 return true;
7692
7693 // Parse Expression field.
7694 MDNode *Expression;
7695 if (parseMDNode(Expression))
7696 return true;
7697 if (parseToken(lltok::comma, "Expected ',' here"))
7698 return true;
7699
7700 // Parse additional fields for #dbg_assign.
7701 MDNode *AssignID = nullptr;
7702 Metadata *AddressLocation = nullptr;
7703 MDNode *AddressExpression = nullptr;
7704 if (ValueType == LocType::Assign) {
7705 // Parse DIAssignID.
7706 if (parseMDNode(AssignID))
7707 return true;
7708 if (parseToken(lltok::comma, "Expected ',' here"))
7709 return true;
7710
7711 // Parse address ValueAsMetadata.
7712 if (parseMetadata(AddressLocation, &PFS))
7713 return true;
7714 if (parseToken(lltok::comma, "Expected ',' here"))
7715 return true;
7716
7717 // Parse address DIExpression.
7718 if (parseMDNode(AddressExpression))
7719 return true;
7720 if (parseToken(lltok::comma, "Expected ',' here"))
7721 return true;
7722 }
7723
7724 /// Parse DILocation.
7725 MDNode *DebugLoc;
7726 if (parseMDNode(DebugLoc))
7727 return true;
7728
7729 if (parseToken(lltok::rparen, "Expected ')' here"))
7730 return true;
7732 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7733 AddressExpression);
7734 PendingDbgRecords.emplace_back(DVRLoc, DR, DebugLoc);
7735 return false;
7736}
7737//===----------------------------------------------------------------------===//
7738// Instruction Parsing.
7739//===----------------------------------------------------------------------===//
7740
7741/// parseInstruction - parse one of the many different instructions.
7742///
7743int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7744 PerFunctionState &PFS) {
7745 lltok::Kind Token = Lex.getKind();
7746 if (Token == lltok::Eof)
7747 return tokError("found end of file when expecting more instructions");
7748 LocTy Loc = Lex.getLoc();
7749 unsigned KeywordVal = Lex.getUIntVal();
7750 Lex.Lex(); // Eat the keyword.
7751
7752 switch (Token) {
7753 default:
7754 return error(Loc, "expected instruction opcode");
7755 // Terminator Instructions.
7756 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7757 case lltok::kw_ret:
7758 return parseRet(Inst, BB, PFS);
7759 case lltok::kw_br:
7760 return parseBr(Inst, PFS);
7761 case lltok::kw_switch:
7762 return parseSwitch(Inst, PFS);
7764 return parseIndirectBr(Inst, PFS);
7765 case lltok::kw_invoke:
7766 return parseInvoke(Inst, PFS);
7767 case lltok::kw_resume:
7768 return parseResume(Inst, PFS);
7770 return parseCleanupRet(Inst, PFS);
7771 case lltok::kw_catchret:
7772 return parseCatchRet(Inst, PFS);
7774 return parseCatchSwitch(Inst, PFS);
7775 case lltok::kw_catchpad:
7776 return parseCatchPad(Inst, PFS);
7778 return parseCleanupPad(Inst, PFS);
7779 case lltok::kw_callbr:
7780 return parseCallBr(Inst, PFS);
7781 // Unary Operators.
7782 case lltok::kw_fneg: {
7783 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7784 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7785 if (Res != 0)
7786 return Res;
7787 if (FMF.any())
7788 Inst->setFastMathFlags(FMF);
7789 return false;
7790 }
7791 // Binary Operators.
7792 case lltok::kw_add:
7793 case lltok::kw_sub:
7794 case lltok::kw_mul:
7795 case lltok::kw_shl: {
7796 bool NUW = EatIfPresent(lltok::kw_nuw);
7797 bool NSW = EatIfPresent(lltok::kw_nsw);
7798 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7799
7800 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7801 return true;
7802
7803 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7804 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7805 return false;
7806 }
7807 case lltok::kw_fadd:
7808 case lltok::kw_fsub:
7809 case lltok::kw_fmul:
7810 case lltok::kw_fdiv:
7811 case lltok::kw_frem: {
7812 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7813 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7814 if (Res != 0)
7815 return Res;
7816 if (FMF.any())
7817 Inst->setFastMathFlags(FMF);
7818 return 0;
7819 }
7820
7821 case lltok::kw_sdiv:
7822 case lltok::kw_udiv:
7823 case lltok::kw_lshr:
7824 case lltok::kw_ashr: {
7825 bool Exact = EatIfPresent(lltok::kw_exact);
7826
7827 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7828 return true;
7829 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7830 return false;
7831 }
7832
7833 case lltok::kw_urem:
7834 case lltok::kw_srem:
7835 return parseArithmetic(Inst, PFS, KeywordVal,
7836 /*IsFP*/ false);
7837 case lltok::kw_or: {
7838 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7839 if (parseLogical(Inst, PFS, KeywordVal))
7840 return true;
7841 if (Disjoint)
7842 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7843 return false;
7844 }
7845 case lltok::kw_and:
7846 case lltok::kw_xor:
7847 return parseLogical(Inst, PFS, KeywordVal);
7848 case lltok::kw_icmp: {
7849 bool SameSign = EatIfPresent(lltok::kw_samesign);
7850 if (parseCompare(Inst, PFS, KeywordVal))
7851 return true;
7852 if (SameSign)
7853 cast<ICmpInst>(Inst)->setSameSign();
7854 return false;
7855 }
7856 case lltok::kw_fcmp: {
7857 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7858 int Res = parseCompare(Inst, PFS, KeywordVal);
7859 if (Res != 0)
7860 return Res;
7861 if (FMF.any())
7862 Inst->setFastMathFlags(FMF);
7863 return 0;
7864 }
7865
7866 // Casts.
7867 case lltok::kw_uitofp: {
7868 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7869 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7870 bool Res = parseCast(Inst, PFS, KeywordVal);
7871 if (Res != 0)
7872 return Res;
7873 if (NonNeg)
7874 Inst->setNonNeg();
7875 Inst->setFastMathFlags(FMF);
7876 return 0;
7877 }
7878 case lltok::kw_zext: {
7879 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7880 bool Res = parseCast(Inst, PFS, KeywordVal);
7881 if (Res != 0)
7882 return Res;
7883 if (NonNeg)
7884 Inst->setNonNeg();
7885 return 0;
7886 }
7887 case lltok::kw_trunc: {
7888 bool NUW = EatIfPresent(lltok::kw_nuw);
7889 bool NSW = EatIfPresent(lltok::kw_nsw);
7890 if (!NUW)
7891 NUW = EatIfPresent(lltok::kw_nuw);
7892 if (parseCast(Inst, PFS, KeywordVal))
7893 return true;
7894 if (NUW)
7895 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7896 if (NSW)
7897 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7898 return false;
7899 }
7901 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7902 if (parseCast(Inst, PFS, KeywordVal))
7903 return true;
7904 if (NonNull)
7905 cast<AddrSpaceCastInst>(Inst)->setNonNull();
7906 return false;
7907 }
7908 case lltok::kw_sext:
7909 case lltok::kw_bitcast:
7910 case lltok::kw_fptoui:
7911 case lltok::kw_fptosi:
7912 case lltok::kw_inttoptr:
7914 case lltok::kw_ptrtoint:
7915 return parseCast(Inst, PFS, KeywordVal);
7916 case lltok::kw_fptrunc:
7917 case lltok::kw_fpext:
7918 case lltok::kw_sitofp: {
7919 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7920 if (parseCast(Inst, PFS, KeywordVal))
7921 return true;
7922 if (FMF.any())
7923 Inst->setFastMathFlags(FMF);
7924 return false;
7925 }
7926
7927 // Other.
7928 case lltok::kw_select: {
7929 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7930 int Res = parseSelect(Inst, PFS);
7931 if (Res != 0)
7932 return Res;
7933 if (FMF.any()) {
7934 if (!isa<FPMathOperator>(Inst)) {
7935 Inst->deleteValue();
7936 return error(Loc, "fast-math-flags specified for select without "
7937 "floating-point scalar or vector return type");
7938 }
7939 Inst->setFastMathFlags(FMF);
7940 }
7941 return 0;
7942 }
7943 case lltok::kw_va_arg:
7944 return parseVAArg(Inst, PFS);
7946 return parseExtractElement(Inst, PFS);
7948 return parseInsertElement(Inst, PFS);
7950 return parseShuffleVector(Inst, PFS);
7951 case lltok::kw_phi: {
7952 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7953 int Res = parsePHI(Inst, PFS);
7954 if (Res != 0)
7955 return Res;
7956 if (FMF.any()) {
7957 if (!isa<FPMathOperator>(Inst)) {
7958 Inst->deleteValue();
7959 return error(Loc, "fast-math-flags specified for phi without "
7960 "floating-point scalar or vector return type");
7961 }
7962 Inst->setFastMathFlags(FMF);
7963 }
7964 return 0;
7965 }
7967 return parseLandingPad(Inst, PFS);
7968 case lltok::kw_freeze:
7969 return parseFreeze(Inst, PFS);
7971 return parseBitInsert(Inst, PFS);
7973 return parseBitExtract(Inst, PFS);
7974 // Call.
7975 case lltok::kw_call:
7976 return parseCall(Inst, PFS, CallInst::TCK_None);
7977 case lltok::kw_tail:
7978 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7979 case lltok::kw_musttail:
7980 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7981 case lltok::kw_notail:
7982 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7983 // Memory.
7984 case lltok::kw_alloca:
7985 return parseAlloc(Inst, PFS);
7986 case lltok::kw_load:
7987 return parseLoad(Inst, PFS);
7988 case lltok::kw_store:
7989 return parseStore(Inst, PFS);
7990 case lltok::kw_cmpxchg:
7991 return parseCmpXchg(Inst, PFS);
7993 return parseAtomicRMW(Inst, PFS);
7994 case lltok::kw_fence:
7995 return parseFence(Inst, PFS);
7997 return parseGetElementPtr(Inst, PFS);
7999 return parseExtractValue(Inst, PFS);
8001 return parseInsertValue(Inst, PFS);
8002 }
8003}
8004
8005/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
8006bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
8007 if (Opc == Instruction::FCmp) {
8008 switch (Lex.getKind()) {
8009 default:
8010 return tokError("expected fcmp predicate (e.g. 'oeq')");
8011 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
8012 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
8013 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
8014 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
8015 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
8016 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
8017 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
8018 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
8019 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
8020 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
8021 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
8022 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
8023 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
8024 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
8025 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
8026 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
8027 }
8028 } else {
8029 switch (Lex.getKind()) {
8030 default:
8031 return tokError("expected icmp predicate (e.g. 'eq')");
8032 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
8033 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
8034 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
8035 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
8036 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
8037 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
8038 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
8039 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
8040 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
8041 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
8042 }
8043 }
8044 Lex.Lex();
8045 return false;
8046}
8047
8048//===----------------------------------------------------------------------===//
8049// Terminator Instructions.
8050//===----------------------------------------------------------------------===//
8051
8052/// parseRet - parse a return instruction.
8053/// ::= 'ret' void (',' !dbg, !1)*
8054/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
8055bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8056 PerFunctionState &PFS) {
8057 SMLoc TypeLoc = Lex.getLoc();
8058 Type *Ty = nullptr;
8059 if (parseType(Ty, true /*void allowed*/))
8060 return true;
8061
8062 Type *ResType = PFS.getFunction().getReturnType();
8063
8064 if (Ty->isVoidTy()) {
8065 if (!ResType->isVoidTy())
8066 return error(TypeLoc, "value doesn't match function result type '" +
8067 getTypeString(ResType) + "'");
8068
8069 Inst = ReturnInst::Create(Context);
8070 return false;
8071 }
8072
8073 Value *RV;
8074 if (parseValue(Ty, RV, PFS))
8075 return true;
8076
8077 if (ResType != RV->getType())
8078 return error(TypeLoc, "value doesn't match function result type '" +
8079 getTypeString(ResType) + "'");
8080
8081 Inst = ReturnInst::Create(Context, RV);
8082 return false;
8083}
8084
8085/// parseBr
8086/// ::= 'br' TypeAndValue
8087/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8088bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8089 LocTy Loc, Loc2;
8090 Value *Op0;
8091 BasicBlock *Op1, *Op2;
8092 if (parseTypeAndValue(Op0, Loc, PFS))
8093 return true;
8094
8095 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
8096 Inst = UncondBrInst::Create(BB);
8097 return false;
8098 }
8099
8100 if (Op0->getType() != Type::getInt1Ty(Context))
8101 return error(Loc, "branch condition must have 'i1' type");
8102
8103 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
8104 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8105 parseToken(lltok::comma, "expected ',' after true destination") ||
8106 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8107 return true;
8108
8109 Inst = CondBrInst::Create(Op0, Op1, Op2);
8110 return false;
8111}
8112
8113/// parseSwitch
8114/// Instruction
8115/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
8116/// JumpTable
8117/// ::= (TypeAndValue ',' TypeAndValue)*
8118bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8119 LocTy CondLoc, BBLoc;
8120 Value *Cond;
8121 BasicBlock *DefaultBB;
8122 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
8123 parseToken(lltok::comma, "expected ',' after switch condition") ||
8124 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8125 parseToken(lltok::lsquare, "expected '[' with switch table"))
8126 return true;
8127
8128 if (!Cond->getType()->isIntegerTy())
8129 return error(CondLoc, "switch condition must have integer type");
8130
8131 // parse the jump table pairs.
8132 SmallPtrSet<Value*, 32> SeenCases;
8134 while (Lex.getKind() != lltok::rsquare) {
8135 Value *Constant;
8136 BasicBlock *DestBB;
8137
8138 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8139 parseToken(lltok::comma, "expected ',' after case value") ||
8140 parseTypeAndBasicBlock(DestBB, PFS))
8141 return true;
8142
8143 if (!SeenCases.insert(Constant).second)
8144 return error(CondLoc, "duplicate case value in switch");
8145 if (!isa<ConstantInt>(Constant))
8146 return error(CondLoc, "case value is not a constant integer");
8147
8148 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
8149 }
8150
8151 Lex.Lex(); // Eat the ']'.
8152
8153 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
8154 for (const auto &[OnVal, Dest] : Table)
8155 SI->addCase(OnVal, Dest);
8156 Inst = SI;
8157 return false;
8158}
8159
8160/// parseIndirectBr
8161/// Instruction
8162/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
8163bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8164 LocTy AddrLoc;
8165 Value *Address;
8166 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
8167 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
8168 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
8169 return true;
8170
8171 if (!Address->getType()->isPointerTy())
8172 return error(AddrLoc, "indirectbr address must have pointer type");
8173
8174 // parse the destination list.
8175 SmallVector<BasicBlock*, 16> DestList;
8176
8177 if (Lex.getKind() != lltok::rsquare) {
8178 BasicBlock *DestBB;
8179 if (parseTypeAndBasicBlock(DestBB, PFS))
8180 return true;
8181 DestList.push_back(DestBB);
8182
8183 while (EatIfPresent(lltok::comma)) {
8184 if (parseTypeAndBasicBlock(DestBB, PFS))
8185 return true;
8186 DestList.push_back(DestBB);
8187 }
8188 }
8189
8190 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8191 return true;
8192
8193 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
8194 for (BasicBlock *Dest : DestList)
8195 IBI->addDestination(Dest);
8196 Inst = IBI;
8197 return false;
8198}
8199
8200// If RetType is a non-function pointer type, then this is the short syntax
8201// for the call, which means that RetType is just the return type. Infer the
8202// rest of the function argument types from the arguments that are present.
8203bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
8204 FunctionType *&FuncTy) {
8205 FuncTy = dyn_cast<FunctionType>(RetType);
8206 if (!FuncTy) {
8207 // Pull out the types of all of the arguments...
8208 SmallVector<Type *, 8> ParamTypes;
8209 ParamTypes.reserve(ArgList.size());
8210 for (const ParamInfo &Arg : ArgList)
8211 ParamTypes.push_back(Arg.V->getType());
8212
8213 if (!FunctionType::isValidReturnType(RetType))
8214 return true;
8215
8216 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8217 }
8218 return false;
8219}
8220
8221/// parseInvoke
8222/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8223/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8224bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8225 LocTy CallLoc = Lex.getLoc();
8226 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8227 std::vector<unsigned> FwdRefAttrGrps;
8228 LocTy NoBuiltinLoc;
8229 unsigned CC;
8230 unsigned InvokeAddrSpace;
8231 Type *RetType = nullptr;
8232 LocTy RetTypeLoc;
8233 ValID CalleeID;
8236
8237 BasicBlock *NormalBB, *UnwindBB;
8238 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8239 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8240 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8241 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8242 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8243 NoBuiltinLoc) ||
8244 parseOptionalOperandBundles(BundleList, PFS) ||
8245 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8246 parseTypeAndBasicBlock(NormalBB, PFS) ||
8247 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8248 parseTypeAndBasicBlock(UnwindBB, PFS))
8249 return true;
8250
8251 // If RetType is a non-function pointer type, then this is the short syntax
8252 // for the call, which means that RetType is just the return type. Infer the
8253 // rest of the function argument types from the arguments that are present.
8254 FunctionType *Ty;
8255 if (resolveFunctionType(RetType, ArgList, Ty))
8256 return error(RetTypeLoc, "Invalid result type for LLVM function");
8257
8258 CalleeID.FTy = Ty;
8259
8260 // Look up the callee.
8261 Value *Callee;
8262 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8263 Callee, &PFS))
8264 return true;
8265
8266 // Set up the Attribute for the function.
8267 SmallVector<Value *, 8> Args;
8269
8270 // Loop through FunctionType's arguments and ensure they are specified
8271 // correctly. Also, gather any parameter attributes.
8272 FunctionType::param_iterator I = Ty->param_begin();
8273 FunctionType::param_iterator E = Ty->param_end();
8274 for (const ParamInfo &Arg : ArgList) {
8275 Type *ExpectedTy = nullptr;
8276 if (I != E) {
8277 ExpectedTy = *I++;
8278 } else if (!Ty->isVarArg()) {
8279 return error(Arg.Loc, "too many arguments specified");
8280 }
8281
8282 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8283 return error(Arg.Loc, "argument is not of expected type '" +
8284 getTypeString(ExpectedTy) + "'");
8285 Args.push_back(Arg.V);
8286 ArgAttrs.push_back(Arg.Attrs);
8287 }
8288
8289 if (I != E)
8290 return error(CallLoc, "not enough parameters specified for call");
8291
8292 // Finish off the Attribute and check them
8293 AttributeList PAL =
8294 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8295 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8296
8297 InvokeInst *II =
8298 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8299 II->setCallingConv(CC);
8300 II->setAttributes(PAL);
8301 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8302 Inst = II;
8303 return false;
8304}
8305
8306/// parseResume
8307/// ::= 'resume' TypeAndValue
8308bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8309 Value *Exn; LocTy ExnLoc;
8310 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8311 return true;
8312
8313 ResumeInst *RI = ResumeInst::Create(Exn);
8314 Inst = RI;
8315 return false;
8316}
8317
8318bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8319 PerFunctionState &PFS) {
8320 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8321 return true;
8322
8323 while (Lex.getKind() != lltok::rsquare) {
8324 // If this isn't the first argument, we need a comma.
8325 if (!Args.empty() &&
8326 parseToken(lltok::comma, "expected ',' in argument list"))
8327 return true;
8328
8329 // parse the argument.
8330 LocTy ArgLoc;
8331 Type *ArgTy = nullptr;
8332 if (parseType(ArgTy, ArgLoc))
8333 return true;
8334
8335 Value *V;
8336 if (ArgTy->isMetadataTy()) {
8337 if (parseMetadataAsValue(V, PFS))
8338 return true;
8339 } else {
8340 if (parseValue(ArgTy, V, PFS))
8341 return true;
8342 }
8343 Args.push_back(V);
8344 }
8345
8346 Lex.Lex(); // Lex the ']'.
8347 return false;
8348}
8349
8350/// parseCleanupRet
8351/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8352bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8353 Value *CleanupPad = nullptr;
8354
8355 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8356 return true;
8357
8358 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8359 return true;
8360
8361 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8362 return true;
8363
8364 BasicBlock *UnwindBB = nullptr;
8365 if (Lex.getKind() == lltok::kw_to) {
8366 Lex.Lex();
8367 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8368 return true;
8369 } else {
8370 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8371 return true;
8372 }
8373 }
8374
8375 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8376 return false;
8377}
8378
8379/// parseCatchRet
8380/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8381bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8382 Value *CatchPad = nullptr;
8383
8384 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8385 return true;
8386
8387 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8388 return true;
8389
8390 BasicBlock *BB;
8391 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8392 parseTypeAndBasicBlock(BB, PFS))
8393 return true;
8394
8395 Inst = CatchReturnInst::Create(CatchPad, BB);
8396 return false;
8397}
8398
8399/// parseCatchSwitch
8400/// ::= 'catchswitch' within Parent
8401bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8402 Value *ParentPad;
8403
8404 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8405 return true;
8406
8407 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8408 Lex.getKind() != lltok::LocalVarID)
8409 return tokError("expected scope value for catchswitch");
8410
8411 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8412 return true;
8413
8414 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8415 return true;
8416
8418 do {
8419 BasicBlock *DestBB;
8420 if (parseTypeAndBasicBlock(DestBB, PFS))
8421 return true;
8422 Table.push_back(DestBB);
8423 } while (EatIfPresent(lltok::comma));
8424
8425 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8426 return true;
8427
8428 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8429 return true;
8430
8431 BasicBlock *UnwindBB = nullptr;
8432 if (EatIfPresent(lltok::kw_to)) {
8433 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8434 return true;
8435 } else {
8436 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8437 return true;
8438 }
8439
8440 auto *CatchSwitch =
8441 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8442 for (BasicBlock *DestBB : Table)
8443 CatchSwitch->addHandler(DestBB);
8444 Inst = CatchSwitch;
8445 return false;
8446}
8447
8448/// parseCatchPad
8449/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8450bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8451 Value *CatchSwitch = nullptr;
8452
8453 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8454 return true;
8455
8456 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8457 return tokError("expected scope value for catchpad");
8458
8459 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8460 return true;
8461
8462 SmallVector<Value *, 8> Args;
8463 if (parseExceptionArgs(Args, PFS))
8464 return true;
8465
8466 Inst = CatchPadInst::Create(CatchSwitch, Args);
8467 return false;
8468}
8469
8470/// parseCleanupPad
8471/// ::= 'cleanuppad' within Parent ParamList
8472bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8473 Value *ParentPad = nullptr;
8474
8475 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8476 return true;
8477
8478 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8479 Lex.getKind() != lltok::LocalVarID)
8480 return tokError("expected scope value for cleanuppad");
8481
8482 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8483 return true;
8484
8485 SmallVector<Value *, 8> Args;
8486 if (parseExceptionArgs(Args, PFS))
8487 return true;
8488
8489 Inst = CleanupPadInst::Create(ParentPad, Args);
8490 return false;
8491}
8492
8493//===----------------------------------------------------------------------===//
8494// Unary Operators.
8495//===----------------------------------------------------------------------===//
8496
8497/// parseUnaryOp
8498/// ::= UnaryOp TypeAndValue ',' Value
8499///
8500/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8501/// operand is allowed.
8502bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8503 unsigned Opc, bool IsFP) {
8504 LocTy Loc; Value *LHS;
8505 if (parseTypeAndValue(LHS, Loc, PFS))
8506 return true;
8507
8508 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8510
8511 if (!Valid)
8512 return error(Loc, "invalid operand type for instruction");
8513
8515 return false;
8516}
8517
8518/// parseCallBr
8519/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8520/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8521/// '[' LabelList ']'
8522bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8523 LocTy CallLoc = Lex.getLoc();
8524 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8525 std::vector<unsigned> FwdRefAttrGrps;
8526 LocTy NoBuiltinLoc;
8527 unsigned CC;
8528 Type *RetType = nullptr;
8529 LocTy RetTypeLoc;
8530 ValID CalleeID;
8533
8534 BasicBlock *DefaultDest;
8535 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8536 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8537 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8538 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8539 NoBuiltinLoc) ||
8540 parseOptionalOperandBundles(BundleList, PFS) ||
8541 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8542 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8543 parseToken(lltok::lsquare, "expected '[' in callbr"))
8544 return true;
8545
8546 // parse the destination list.
8547 SmallVector<BasicBlock *, 16> IndirectDests;
8548
8549 if (Lex.getKind() != lltok::rsquare) {
8550 BasicBlock *DestBB;
8551 if (parseTypeAndBasicBlock(DestBB, PFS))
8552 return true;
8553 IndirectDests.push_back(DestBB);
8554
8555 while (EatIfPresent(lltok::comma)) {
8556 if (parseTypeAndBasicBlock(DestBB, PFS))
8557 return true;
8558 IndirectDests.push_back(DestBB);
8559 }
8560 }
8561
8562 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8563 return true;
8564
8565 // If RetType is a non-function pointer type, then this is the short syntax
8566 // for the call, which means that RetType is just the return type. Infer the
8567 // rest of the function argument types from the arguments that are present.
8568 FunctionType *Ty;
8569 if (resolveFunctionType(RetType, ArgList, Ty))
8570 return error(RetTypeLoc, "Invalid result type for LLVM function");
8571
8572 CalleeID.FTy = Ty;
8573
8574 // Look up the callee.
8575 Value *Callee;
8576 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8577 &PFS))
8578 return true;
8579
8580 // Set up the Attribute for the function.
8581 SmallVector<Value *, 8> Args;
8583
8584 // Loop through FunctionType's arguments and ensure they are specified
8585 // correctly. Also, gather any parameter attributes.
8586 FunctionType::param_iterator I = Ty->param_begin();
8587 FunctionType::param_iterator E = Ty->param_end();
8588 for (const ParamInfo &Arg : ArgList) {
8589 Type *ExpectedTy = nullptr;
8590 if (I != E) {
8591 ExpectedTy = *I++;
8592 } else if (!Ty->isVarArg()) {
8593 return error(Arg.Loc, "too many arguments specified");
8594 }
8595
8596 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8597 return error(Arg.Loc, "argument is not of expected type '" +
8598 getTypeString(ExpectedTy) + "'");
8599 Args.push_back(Arg.V);
8600 ArgAttrs.push_back(Arg.Attrs);
8601 }
8602
8603 if (I != E)
8604 return error(CallLoc, "not enough parameters specified for call");
8605
8606 // Finish off the Attribute and check them
8607 AttributeList PAL =
8608 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8609 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8610
8611 CallBrInst *CBI =
8612 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8613 BundleList);
8614 CBI->setCallingConv(CC);
8615 CBI->setAttributes(PAL);
8616 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8617 Inst = CBI;
8618 return false;
8619}
8620
8621//===----------------------------------------------------------------------===//
8622// Binary Operators.
8623//===----------------------------------------------------------------------===//
8624
8625/// parseArithmetic
8626/// ::= ArithmeticOps TypeAndValue ',' Value
8627///
8628/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8629/// operand is allowed.
8630bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8631 unsigned Opc, bool IsFP) {
8632 LocTy Loc; Value *LHS, *RHS;
8633 if (parseTypeAndValue(LHS, Loc, PFS) ||
8634 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8635 parseValue(LHS->getType(), RHS, PFS))
8636 return true;
8637
8638 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8640
8641 if (!Valid)
8642 return error(Loc, "invalid operand type for instruction");
8643
8645 return false;
8646}
8647
8648/// parseLogical
8649/// ::= ArithmeticOps TypeAndValue ',' Value {
8650bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8651 unsigned Opc) {
8652 LocTy Loc; Value *LHS, *RHS;
8653 if (parseTypeAndValue(LHS, Loc, PFS) ||
8654 parseToken(lltok::comma, "expected ',' in logical operation") ||
8655 parseValue(LHS->getType(), RHS, PFS))
8656 return true;
8657
8658 if (!LHS->getType()->isIntOrIntVectorTy())
8659 return error(Loc,
8660 "instruction requires integer or integer vector operands");
8661
8663 return false;
8664}
8665
8666/// parseCompare
8667/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8668/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8669bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8670 unsigned Opc) {
8671 // parse the integer/fp comparison predicate.
8672 LocTy Loc;
8673 unsigned Pred;
8674 Value *LHS, *RHS;
8675 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8676 parseToken(lltok::comma, "expected ',' after compare value") ||
8677 parseValue(LHS->getType(), RHS, PFS))
8678 return true;
8679
8680 if (Opc == Instruction::FCmp) {
8681 if (!LHS->getType()->isFPOrFPVectorTy())
8682 return error(Loc, "fcmp requires floating point operands");
8683 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8684 } else {
8685 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8686 if (!LHS->getType()->isIntOrIntVectorTy() &&
8688 return error(Loc, "icmp requires integer operands");
8689 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8690 }
8691 return false;
8692}
8693
8694//===----------------------------------------------------------------------===//
8695// Other Instructions.
8696//===----------------------------------------------------------------------===//
8697
8698/// parseCast
8699/// ::= CastOpc TypeAndValue 'to' Type
8700bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8701 unsigned Opc) {
8702 LocTy Loc;
8703 Value *Op;
8704 Type *DestTy = nullptr;
8705 if (parseTypeAndValue(Op, Loc, PFS) ||
8706 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8707 parseType(DestTy))
8708 return true;
8709
8711 return error(Loc, "invalid cast opcode for cast from '" +
8712 getTypeString(Op->getType()) + "' to '" +
8713 getTypeString(DestTy) + "'");
8714 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8715 return false;
8716}
8717
8718/// parseSelect
8719/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8720bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8721 LocTy Loc;
8722 Value *Op0, *Op1, *Op2;
8723 if (parseTypeAndValue(Op0, Loc, PFS) ||
8724 parseToken(lltok::comma, "expected ',' after select condition") ||
8725 parseTypeAndValue(Op1, PFS) ||
8726 parseToken(lltok::comma, "expected ',' after select value") ||
8727 parseTypeAndValue(Op2, PFS))
8728 return true;
8729
8730 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8731 return error(Loc, Reason);
8732
8733 Inst = SelectInst::Create(Op0, Op1, Op2);
8734 return false;
8735}
8736
8737/// parseVAArg
8738/// ::= 'va_arg' TypeAndValue ',' Type
8739bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8740 Value *Op;
8741 Type *EltTy = nullptr;
8742 LocTy TypeLoc;
8743 if (parseTypeAndValue(Op, PFS) ||
8744 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8745 parseType(EltTy, TypeLoc))
8746 return true;
8747
8748 if (!EltTy->isFirstClassType())
8749 return error(TypeLoc, "va_arg requires operand with first class type");
8750
8751 Inst = new VAArgInst(Op, EltTy);
8752 return false;
8753}
8754
8755/// parseExtractElement
8756/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8757bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8758 LocTy Loc;
8759 Value *Op0, *Op1;
8760 if (parseTypeAndValue(Op0, Loc, PFS) ||
8761 parseToken(lltok::comma, "expected ',' after extract value") ||
8762 parseTypeAndValue(Op1, PFS))
8763 return true;
8764
8766 return error(Loc, "invalid extractelement operands");
8767
8768 Inst = ExtractElementInst::Create(Op0, Op1);
8769 return false;
8770}
8771
8772/// parseInsertElement
8773/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8774bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8775 LocTy Loc;
8776 Value *Op0, *Op1, *Op2;
8777 if (parseTypeAndValue(Op0, Loc, PFS) ||
8778 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8779 parseTypeAndValue(Op1, PFS) ||
8780 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8781 parseTypeAndValue(Op2, PFS))
8782 return true;
8783
8784 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8785 return error(Loc, "invalid insertelement operands");
8786
8787 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8788 return false;
8789}
8790
8791// parseBitExtract
8792// ::= 'bitextract' Type ',' TypeAndValue ',' TypeAndValue
8793bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
8794 LocTy Loc;
8795 Type *Ty = nullptr;
8796 Value *Op0, *Op1;
8797 if (parseType(Ty, Loc) ||
8798 parseToken(lltok::comma, "expected ',' after bitextract type") ||
8799 parseTypeAndValue(Op0, Loc, PFS) ||
8800 parseToken(lltok::comma, "expected ',' after bitextract source value") ||
8801 parseTypeAndValue(Op1, PFS))
8802 return true;
8803
8804 if (const char *Reason = BitExtractInst::areInvalidOperands(Ty, Op0, Op1))
8805 return error(Loc, Reason);
8806
8807 Inst = BitExtractInst::Create(Ty, Op0, Op1);
8808 return false;
8809}
8810
8811// parseBitInsert
8812// ::= 'bitinsert' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8813bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
8814 LocTy Loc;
8815 Value *Op0, *Op1, *Op2;
8816 if (parseTypeAndValue(Op0, Loc, PFS) ||
8817 parseToken(lltok::comma, "expected ',' after bitinsert source value") ||
8818 parseTypeAndValue(Op1, PFS) ||
8819 parseToken(lltok::comma, "expected ',' after bitinsert insert value") ||
8820 parseTypeAndValue(Op2, PFS))
8821 return true;
8822
8823 if (const char *Reason = BitInsertInst::areInvalidOperands(Op0, Op1, Op2))
8824 return error(Loc, Reason);
8825
8826 Inst = BitInsertInst::Create(Op0, Op1, Op2);
8827 return false;
8828}
8829
8830/// parseShuffleVector
8831/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8832bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8833 LocTy Loc;
8834 Value *Op0, *Op1, *Op2;
8835 if (parseTypeAndValue(Op0, Loc, PFS) ||
8836 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8837 parseTypeAndValue(Op1, PFS) ||
8838 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8839 parseTypeAndValue(Op2, PFS))
8840 return true;
8841
8842 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8843 return error(Loc, "invalid shufflevector operands");
8844
8845 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8846 return false;
8847}
8848
8849/// parsePHI
8850/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8851int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8852 Type *Ty = nullptr; LocTy TypeLoc;
8853 Value *Op0, *Op1;
8854
8855 if (parseType(Ty, TypeLoc))
8856 return true;
8857
8858 if (!Ty->isFirstClassType())
8859 return error(TypeLoc, "phi node must have first class type");
8860
8861 bool First = true;
8862 bool AteExtraComma = false;
8864
8865 while (true) {
8866 if (First) {
8867 if (Lex.getKind() != lltok::lsquare)
8868 break;
8869 First = false;
8870 } else if (!EatIfPresent(lltok::comma))
8871 break;
8872
8873 if (Lex.getKind() == lltok::MetadataVar) {
8874 AteExtraComma = true;
8875 break;
8876 }
8877
8878 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8879 parseValue(Ty, Op0, PFS) ||
8880 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8881 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8882 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8883 return true;
8884
8885 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8886 }
8887
8888 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8889 for (const auto &[Val, BB] : PHIVals)
8890 PN->addIncoming(Val, BB);
8891 Inst = PN;
8892 return AteExtraComma ? InstExtraComma : InstNormal;
8893}
8894
8895/// parseLandingPad
8896/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8897/// Clause
8898/// ::= 'catch' TypeAndValue
8899/// ::= 'filter'
8900/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8901bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8902 Type *Ty = nullptr; LocTy TyLoc;
8903
8904 if (parseType(Ty, TyLoc))
8905 return true;
8906
8907 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8908 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8909
8910 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8912 if (EatIfPresent(lltok::kw_catch))
8914 else if (EatIfPresent(lltok::kw_filter))
8916 else
8917 return tokError("expected 'catch' or 'filter' clause type");
8918
8919 Value *V;
8920 LocTy VLoc;
8921 if (parseTypeAndValue(V, VLoc, PFS))
8922 return true;
8923
8924 // A 'catch' type expects a non-array constant. A filter clause expects an
8925 // array constant.
8926 if (CT == LandingPadInst::Catch) {
8927 if (isa<ArrayType>(V->getType()))
8928 return error(VLoc, "'catch' clause has an invalid type");
8929 } else {
8930 if (!isa<ArrayType>(V->getType()))
8931 return error(VLoc, "'filter' clause has an invalid type");
8932 }
8933
8935 if (!CV)
8936 return error(VLoc, "clause argument must be a constant");
8937 LP->addClause(CV);
8938 }
8939
8940 Inst = LP.release();
8941 return false;
8942}
8943
8944/// parseFreeze
8945/// ::= 'freeze' Type Value
8946bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8947 LocTy Loc;
8948 Value *Op;
8949 if (parseTypeAndValue(Op, Loc, PFS))
8950 return true;
8951
8952 Inst = new FreezeInst(Op);
8953 return false;
8954}
8955
8956/// parseCall
8957/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8958/// OptionalAttrs Type Value ParameterList OptionalAttrs
8959/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8960/// OptionalAttrs Type Value ParameterList OptionalAttrs
8961/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8962/// OptionalAttrs Type Value ParameterList OptionalAttrs
8963/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8964/// OptionalAttrs Type Value ParameterList OptionalAttrs
8965bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8967 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8968 std::vector<unsigned> FwdRefAttrGrps;
8969 LocTy BuiltinLoc;
8970 unsigned CallAddrSpace;
8971 unsigned CC;
8972 Type *RetType = nullptr;
8973 LocTy RetTypeLoc;
8974 ValID CalleeID;
8977 LocTy CallLoc = Lex.getLoc();
8978
8979 if (TCK != CallInst::TCK_None &&
8980 parseToken(lltok::kw_call,
8981 "expected 'tail call', 'musttail call', or 'notail call'"))
8982 return true;
8983
8984 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8985
8986 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8987 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8988 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8989 parseValID(CalleeID, &PFS) ||
8990 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8991 PFS.getFunction().isVarArg()) ||
8992 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8993 parseOptionalOperandBundles(BundleList, PFS))
8994 return true;
8995
8996 // If RetType is a non-function pointer type, then this is the short syntax
8997 // for the call, which means that RetType is just the return type. Infer the
8998 // rest of the function argument types from the arguments that are present.
8999 FunctionType *Ty;
9000 if (resolveFunctionType(RetType, ArgList, Ty))
9001 return error(RetTypeLoc, "Invalid result type for LLVM function");
9002
9003 CalleeID.FTy = Ty;
9004
9005 // Look up the callee.
9006 Value *Callee;
9007 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
9008 Callee, &PFS))
9009 return true;
9010
9011 // Set up the Attribute for the function.
9013
9014 SmallVector<Value*, 8> Args;
9015
9016 // Loop through FunctionType's arguments and ensure they are specified
9017 // correctly. Also, gather any parameter attributes.
9018 FunctionType::param_iterator I = Ty->param_begin();
9019 FunctionType::param_iterator E = Ty->param_end();
9020 for (const ParamInfo &Arg : ArgList) {
9021 Type *ExpectedTy = nullptr;
9022 if (I != E) {
9023 ExpectedTy = *I++;
9024 } else if (!Ty->isVarArg()) {
9025 return error(Arg.Loc, "too many arguments specified");
9026 }
9027
9028 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9029 return error(Arg.Loc, "argument is not of expected type '" +
9030 getTypeString(ExpectedTy) + "'");
9031 Args.push_back(Arg.V);
9032 Attrs.push_back(Arg.Attrs);
9033 }
9034
9035 if (I != E)
9036 return error(CallLoc, "not enough parameters specified for call");
9037
9038 // Finish off the Attribute and check them
9039 AttributeList PAL =
9040 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
9041 AttributeSet::get(Context, RetAttrs), Attrs);
9042
9043 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
9044 CI->setTailCallKind(TCK);
9045 CI->setCallingConv(CC);
9046 if (FMF.any()) {
9047 if (!isa<FPMathOperator>(CI)) {
9048 CI->deleteValue();
9049 return error(CallLoc, "fast-math-flags specified for call without "
9050 "floating-point scalar or vector return type");
9051 }
9052 CI->setFastMathFlags(FMF);
9053 }
9054
9055 if (CalleeID.Kind == ValID::t_GlobalName &&
9056 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
9057 if (SeenNewDbgInfoFormat) {
9058 CI->deleteValue();
9059 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
9060 "using non-intrinsic debug info");
9061 }
9062 SeenOldDbgInfoFormat = true;
9063 }
9064 CI->setAttributes(PAL);
9065 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9066 Inst = CI;
9067 return false;
9068}
9069
9070//===----------------------------------------------------------------------===//
9071// Memory Instructions.
9072//===----------------------------------------------------------------------===//
9073
9074/// parseAlloc
9075/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
9076/// (',' 'align' i32)? (',', 'addrspace(n))?
9077int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9078 Value *Size = nullptr;
9079 LocTy SizeLoc, TyLoc, ASLoc;
9080 MaybeAlign Alignment;
9081 unsigned AddrSpace = 0;
9082 Type *Ty = nullptr;
9083
9084 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9085 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9086
9087 if (parseType(Ty, TyLoc))
9088 return true;
9089
9091 return error(TyLoc, "invalid type for alloca");
9092
9093 bool AteExtraComma = false;
9094 if (EatIfPresent(lltok::comma)) {
9095 if (Lex.getKind() == lltok::kw_align) {
9096 if (parseOptionalAlignment(Alignment))
9097 return true;
9098 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9099 return true;
9100 } else if (Lex.getKind() == lltok::kw_addrspace) {
9101 ASLoc = Lex.getLoc();
9102 if (parseOptionalAddrSpace(AddrSpace))
9103 return true;
9104 } else if (Lex.getKind() == lltok::MetadataVar) {
9105 AteExtraComma = true;
9106 } else {
9107 if (parseTypeAndValue(Size, SizeLoc, PFS))
9108 return true;
9109 if (EatIfPresent(lltok::comma)) {
9110 if (Lex.getKind() == lltok::kw_align) {
9111 if (parseOptionalAlignment(Alignment))
9112 return true;
9113 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9114 return true;
9115 } else if (Lex.getKind() == lltok::kw_addrspace) {
9116 ASLoc = Lex.getLoc();
9117 if (parseOptionalAddrSpace(AddrSpace))
9118 return true;
9119 } else if (Lex.getKind() == lltok::MetadataVar) {
9120 AteExtraComma = true;
9121 }
9122 }
9123 }
9124 }
9125
9126 if (Size && !Size->getType()->isIntegerTy())
9127 return error(SizeLoc, "element count must have integer type");
9128
9129 if (!Alignment && !Ty->isSized())
9130 return error(TyLoc, "Cannot allocate unsized type");
9131 if (!Alignment)
9132 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9133 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
9134 AI->setUsedWithInAlloca(IsInAlloca);
9135 AI->setSwiftError(IsSwiftError);
9136 Inst = AI;
9137 return AteExtraComma ? InstExtraComma : InstNormal;
9138}
9139
9140/// parseLoad
9141/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
9142/// ::= 'load' 'atomic' 'volatile'? 'elementwise'? TypeAndValue
9143/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
9144int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9145 Value *Val; LocTy Loc;
9146 MaybeAlign Alignment;
9147 bool AteExtraComma = false;
9148 bool isAtomic = false;
9151
9152 if (Lex.getKind() == lltok::kw_atomic) {
9153 isAtomic = true;
9154 Lex.Lex();
9155 }
9156
9157 bool isVolatile = false;
9158 if (Lex.getKind() == lltok::kw_volatile) {
9159 isVolatile = true;
9160 Lex.Lex();
9161 }
9162
9163 bool IsElementwise = false;
9164 if (Lex.getKind() == lltok::kw_elementwise) {
9165 IsElementwise = true;
9166 Lex.Lex();
9167 }
9168
9169 Type *Ty;
9170 LocTy ExplicitTypeLoc = Lex.getLoc();
9171 if (parseType(Ty) ||
9172 parseToken(lltok::comma, "expected comma after load's type") ||
9173 parseTypeAndValue(Val, Loc, PFS) ||
9174 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9175 parseOptionalCommaAlign(Alignment, AteExtraComma))
9176 return true;
9177
9178 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
9179 return error(Loc, "load operand must be a pointer to a first class type");
9180
9181 if (IsElementwise && !isAtomic)
9182 return error(Loc, "elementwise load must be atomic");
9183
9184 if (IsElementwise && !isa<FixedVectorType>(Ty))
9185 return error(ExplicitTypeLoc,
9186 "atomic elementwise load operand must have fixed vector type");
9187
9188 if (isAtomic && !Alignment)
9189 return error(Loc, "atomic load must have explicit non-zero alignment");
9190
9191 if (Ordering == AtomicOrdering::Release ||
9193 return error(Loc, "atomic load cannot use Release ordering");
9194 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9195 return error(Loc,
9196 "atomic elementwise load cannot be sequentially consistent");
9197
9198 if (!Alignment && !Ty->isSized())
9199 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
9200 if (!Alignment)
9201 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9202 Inst = new LoadInst(Ty, Val, "",
9203 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9204 SSID, IsElementwise},
9205 /*InsertBefore=*/nullptr);
9206 return AteExtraComma ? InstExtraComma : InstNormal;
9207}
9208
9209/// parseStore
9210
9211/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
9212/// ::= 'store' 'atomic' 'volatile'? 'elementwise'? TypeAndValue ','
9213/// TypeAndValue 'singlethread'? AtomicOrdering (',' 'align' i32)?
9214int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9215 Value *Val, *Ptr;
9216 LocTy Loc, PtrLoc;
9217 MaybeAlign Alignment;
9218 bool AteExtraComma = false;
9219 bool isAtomic = false;
9222
9223 if (Lex.getKind() == lltok::kw_atomic) {
9224 isAtomic = true;
9225 Lex.Lex();
9226 }
9227
9228 bool isVolatile = false;
9229 if (Lex.getKind() == lltok::kw_volatile) {
9230 isVolatile = true;
9231 Lex.Lex();
9232 }
9233
9234 bool IsElementwise = false;
9235 if (Lex.getKind() == lltok::kw_elementwise) {
9236 IsElementwise = true;
9237 Lex.Lex();
9238 }
9239
9240 if (parseTypeAndValue(Val, Loc, PFS) ||
9241 parseToken(lltok::comma, "expected ',' after store operand") ||
9242 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9243 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9244 parseOptionalCommaAlign(Alignment, AteExtraComma))
9245 return true;
9246
9247 if (!Ptr->getType()->isPointerTy())
9248 return error(PtrLoc, "store operand must be a pointer");
9249 if (!Val->getType()->isFirstClassType())
9250 return error(Loc, "store operand must be a first class value");
9251 if (isAtomic && !Alignment)
9252 return error(Loc, "atomic store must have explicit non-zero alignment");
9253 if (Ordering == AtomicOrdering::Acquire ||
9255 return error(Loc, "atomic store cannot use Acquire ordering");
9256
9257 if (IsElementwise && !isAtomic)
9258 return error(Loc, "elementwise store must be atomic");
9259
9260 if (IsElementwise && !isa<FixedVectorType>(Val->getType()))
9261 return error(
9262 Loc, "atomic elementwise store operand must have fixed vector type");
9263
9264 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9265 return error(Loc,
9266 "atomic elementwise store cannot be sequentially consistent");
9267
9268 if (!Alignment && !Val->getType()->isSized())
9269 return error(Loc, "storing unsized types is not allowed");
9270 if (!Alignment)
9271 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9272
9273 Inst = new StoreInst(Val, Ptr,
9274 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9275 SSID, IsElementwise},
9276 /*InsertBefore=*/nullptr);
9277 return AteExtraComma ? InstExtraComma : InstNormal;
9278}
9279
9280/// parseCmpXchg
9281/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9282/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9283/// 'Align'?
9284int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9285 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9286 bool AteExtraComma = false;
9287 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9288 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9290 bool isVolatile = false;
9291 bool isWeak = false;
9292 MaybeAlign Alignment;
9293
9294 if (EatIfPresent(lltok::kw_weak))
9295 isWeak = true;
9296
9297 if (EatIfPresent(lltok::kw_volatile))
9298 isVolatile = true;
9299
9300 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9301 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9302 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9303 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9304 parseTypeAndValue(New, NewLoc, PFS) ||
9305 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9306 parseOrdering(FailureOrdering) ||
9307 parseOptionalCommaAlign(Alignment, AteExtraComma))
9308 return true;
9309
9310 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9311 return tokError("invalid cmpxchg success ordering");
9312 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9313 return tokError("invalid cmpxchg failure ordering");
9314 if (!Ptr->getType()->isPointerTy())
9315 return error(PtrLoc, "cmpxchg operand must be a pointer");
9316 if (Cmp->getType() != New->getType())
9317 return error(NewLoc, "compare value and new value type do not match");
9318 if (!New->getType()->isFirstClassType())
9319 return error(NewLoc, "cmpxchg operand must be a first class value");
9320
9321 const Align DefaultAlignment(
9322 PFS.getFunction().getDataLayout().getTypeStoreSize(
9323 Cmp->getType()));
9324
9325 AtomicCmpXchgInst *CXI =
9326 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9327 SuccessOrdering, FailureOrdering, SSID);
9328 CXI->setVolatile(isVolatile);
9329 CXI->setWeak(isWeak);
9330
9331 Inst = CXI;
9332 return AteExtraComma ? InstExtraComma : InstNormal;
9333}
9334
9335/// parseAtomicRMW
9336/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9337/// TypeAndValue
9338/// 'singlethread'? AtomicOrdering
9339int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9340 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9341 bool AteExtraComma = false;
9344 bool IsVolatile = false;
9345 bool IsElementwise = false;
9346 bool IsFP = false;
9348 MaybeAlign Alignment;
9349
9350 if (EatIfPresent(lltok::kw_volatile))
9351 IsVolatile = true;
9352 if (EatIfPresent(lltok::kw_elementwise))
9353 IsElementwise = true;
9354
9355 switch (Lex.getKind()) {
9356 default:
9357 return tokError("expected binary operation in atomicrmw");
9371 break;
9374 break;
9377 break;
9378 case lltok::kw_usub_sat:
9380 break;
9381 case lltok::kw_fadd:
9383 IsFP = true;
9384 break;
9385 case lltok::kw_fsub:
9387 IsFP = true;
9388 break;
9389 case lltok::kw_fmax:
9391 IsFP = true;
9392 break;
9393 case lltok::kw_fmin:
9395 IsFP = true;
9396 break;
9397 case lltok::kw_fmaximum:
9399 IsFP = true;
9400 break;
9401 case lltok::kw_fminimum:
9403 IsFP = true;
9404 break;
9407 IsFP = true;
9408 break;
9411 IsFP = true;
9412 break;
9413 }
9414 Lex.Lex(); // Eat the operation.
9415
9416 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9417 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9418 parseTypeAndValue(Val, ValLoc, PFS) ||
9419 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9420 parseOptionalCommaAlign(Alignment, AteExtraComma))
9421 return true;
9422
9423 if (Ordering == AtomicOrdering::Unordered)
9424 return tokError("atomicrmw cannot be unordered");
9425 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9426 return tokError("atomicrmw elementwise cannot be sequentially consistent");
9427 if (!Ptr->getType()->isPointerTy())
9428 return error(PtrLoc, "atomicrmw operand must be a pointer");
9429 if (Val->getType()->isScalableTy())
9430 return error(ValLoc, "atomicrmw operand may not be scalable");
9431
9432 Type *ValTy = Val->getType();
9433 if (IsElementwise) {
9434 if (!isa<FixedVectorType>(Val->getType()))
9435 return error(ValLoc,
9436 "atomicrmw elementwise operand must be a fixed vector type");
9437 }
9438
9440 if (!ValTy->isIntOrIntVectorTy() && !ValTy->isFPOrFPVectorTy() &&
9441 !ValTy->isPtrOrPtrVectorTy()) {
9442 return error(
9443 ValLoc,
9445 " operand must be an integer type, a floating-point type, a "
9446 "pointer type, or a fixed vector of any of these types");
9447 }
9448 } else if (IsFP) {
9449 if (!ValTy->isFPOrFPVectorTy()) {
9450 return error(ValLoc, "atomicrmw " +
9452 " operand must be a floating point or fixed "
9453 "vector of floating point type");
9454 }
9455 } else {
9456 if (!ValTy->isIntOrIntVectorTy()) {
9457 return error(
9458 ValLoc,
9460 " operand must be an integer or fixed vector of integer type");
9461 }
9462 }
9463
9464 unsigned Size =
9465 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9466 if (Size < 8 || (Size & (Size - 1)))
9467 return error(ValLoc,
9468 "atomicrmw operand must have a power-of-two byte size");
9469 const Align DefaultAlignment(
9470 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9471 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9472 Alignment.value_or(DefaultAlignment),
9473 Ordering, SSID, IsElementwise);
9474 RMWI->setVolatile(IsVolatile);
9475 Inst = RMWI;
9476 return AteExtraComma ? InstExtraComma : InstNormal;
9477}
9478
9479/// parseFence
9480/// ::= 'fence' 'singlethread'? AtomicOrdering
9481int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9484 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9485 return true;
9486
9487 if (Ordering == AtomicOrdering::Unordered)
9488 return tokError("fence cannot be unordered");
9489 if (Ordering == AtomicOrdering::Monotonic)
9490 return tokError("fence cannot be monotonic");
9491
9492 Inst = new FenceInst(Context, Ordering, SSID);
9493 return InstNormal;
9494}
9495
9496/// parseGetElementPtr
9497/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9498int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9499 Value *Ptr = nullptr;
9500 Value *Val = nullptr;
9501 LocTy Loc, EltLoc;
9502 GEPNoWrapFlags NW;
9503
9504 while (true) {
9505 if (EatIfPresent(lltok::kw_inbounds))
9507 else if (EatIfPresent(lltok::kw_nusw))
9509 else if (EatIfPresent(lltok::kw_nuw))
9511 else
9512 break;
9513 }
9514
9515 Type *Ty = nullptr;
9516 if (parseType(Ty) ||
9517 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9518 parseTypeAndValue(Ptr, Loc, PFS))
9519 return true;
9520
9521 Type *BaseType = Ptr->getType();
9522 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9523 if (!BasePointerType)
9524 return error(Loc, "base of getelementptr must be a pointer");
9525
9526 SmallVector<Value*, 16> Indices;
9527 bool AteExtraComma = false;
9528 // GEP returns a vector of pointers if at least one of parameters is a vector.
9529 // All vector parameters should have the same vector width.
9530 ElementCount GEPWidth = BaseType->isVectorTy()
9531 ? cast<VectorType>(BaseType)->getElementCount()
9533
9534 while (EatIfPresent(lltok::comma)) {
9535 if (Lex.getKind() == lltok::MetadataVar) {
9536 AteExtraComma = true;
9537 break;
9538 }
9539 if (parseTypeAndValue(Val, EltLoc, PFS))
9540 return true;
9541 if (!Val->getType()->isIntOrIntVectorTy())
9542 return error(EltLoc, "getelementptr index must be an integer");
9543
9544 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9545 ElementCount ValNumEl = ValVTy->getElementCount();
9546 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9547 return error(
9548 EltLoc,
9549 "getelementptr vector index has a wrong number of elements");
9550 GEPWidth = ValNumEl;
9551 }
9552 Indices.push_back(Val);
9553 }
9554
9555 if (!Indices.empty() && !Ty->isSized())
9556 return error(Loc, "base element of getelementptr must be sized");
9557
9558 auto *STy = dyn_cast<StructType>(Ty);
9559 if (STy && STy->isScalableTy())
9560 return error(Loc, "getelementptr cannot target structure that contains "
9561 "scalable vector type");
9562
9563 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9564 return error(Loc, "invalid getelementptr indices");
9565 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9566 Inst = GEP;
9567 GEP->setNoWrapFlags(NW);
9568 return AteExtraComma ? InstExtraComma : InstNormal;
9569}
9570
9571/// parseExtractValue
9572/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9573int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9574 Value *Val; LocTy Loc;
9575 SmallVector<unsigned, 4> Indices;
9576 bool AteExtraComma;
9577 if (parseTypeAndValue(Val, Loc, PFS) ||
9578 parseIndexList(Indices, AteExtraComma))
9579 return true;
9580
9581 if (!Val->getType()->isAggregateType())
9582 return error(Loc, "extractvalue operand must be aggregate type");
9583
9584 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9585 return error(Loc, "invalid indices for extractvalue");
9586 Inst = ExtractValueInst::Create(Val, Indices);
9587 return AteExtraComma ? InstExtraComma : InstNormal;
9588}
9589
9590/// parseInsertValue
9591/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9592int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9593 Value *Val0, *Val1; LocTy Loc0, Loc1;
9594 SmallVector<unsigned, 4> Indices;
9595 bool AteExtraComma;
9596 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9597 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9598 parseTypeAndValue(Val1, Loc1, PFS) ||
9599 parseIndexList(Indices, AteExtraComma))
9600 return true;
9601
9602 if (!Val0->getType()->isAggregateType())
9603 return error(Loc0, "insertvalue operand must be aggregate type");
9604
9605 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9606 if (!IndexedType)
9607 return error(Loc0, "invalid indices for insertvalue");
9608 if (IndexedType != Val1->getType())
9609 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9610 getTypeString(Val1->getType()) + "' instead of '" +
9611 getTypeString(IndexedType) + "'");
9612 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9613 return AteExtraComma ? InstExtraComma : InstNormal;
9614}
9615
9616//===----------------------------------------------------------------------===//
9617// Embedded metadata.
9618//===----------------------------------------------------------------------===//
9619
9620/// parseMDNodeVector
9621/// ::= { Element (',' Element)* }
9622/// Element
9623/// ::= 'null' | Metadata
9624bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9625 if (parseToken(lltok::lbrace, "expected '{' here"))
9626 return true;
9627
9628 // Check for an empty list.
9629 if (EatIfPresent(lltok::rbrace))
9630 return false;
9631
9632 do {
9633 if (EatIfPresent(lltok::kw_null)) {
9634 Elts.push_back(nullptr);
9635 continue;
9636 }
9637
9638 Metadata *MD;
9639 if (parseMetadata(MD, nullptr))
9640 return true;
9641 Elts.push_back(MD);
9642 } while (EatIfPresent(lltok::comma));
9643
9644 return parseToken(lltok::rbrace, "expected end of metadata node");
9645}
9646
9647//===----------------------------------------------------------------------===//
9648// Use-list order directives.
9649//===----------------------------------------------------------------------===//
9650bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9651 SMLoc Loc) {
9652 if (!V->hasUseList())
9653 return false;
9654 if (V->use_empty())
9655 return error(Loc, "value has no uses");
9656
9657 unsigned NumUses = 0;
9658 SmallDenseMap<const Use *, unsigned, 16> Order;
9659 for (const Use &U : V->uses()) {
9660 if (++NumUses > Indexes.size())
9661 break;
9662 Order[&U] = Indexes[NumUses - 1];
9663 }
9664 if (NumUses < 2)
9665 return error(Loc, "value only has one use");
9666 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9667 return error(Loc,
9668 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9669
9670 V->sortUseList([&](const Use &L, const Use &R) {
9671 return Order.lookup(&L) < Order.lookup(&R);
9672 });
9673 return false;
9674}
9675
9676/// parseUseListOrderIndexes
9677/// ::= '{' uint32 (',' uint32)+ '}'
9678bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9679 SMLoc Loc = Lex.getLoc();
9680 if (parseToken(lltok::lbrace, "expected '{' here"))
9681 return true;
9682 if (Lex.getKind() == lltok::rbrace)
9683 return tokError("expected non-empty list of uselistorder indexes");
9684
9685 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9686 // indexes should be distinct numbers in the range [0, size-1], and should
9687 // not be in order.
9688 unsigned Offset = 0;
9689 unsigned Max = 0;
9690 bool IsOrdered = true;
9691 assert(Indexes.empty() && "Expected empty order vector");
9692 do {
9693 unsigned Index;
9694 if (parseUInt32(Index))
9695 return true;
9696
9697 // Update consistency checks.
9698 Offset += Index - Indexes.size();
9699 Max = std::max(Max, Index);
9700 IsOrdered &= Index == Indexes.size();
9701
9702 Indexes.push_back(Index);
9703 } while (EatIfPresent(lltok::comma));
9704
9705 if (parseToken(lltok::rbrace, "expected '}' here"))
9706 return true;
9707
9708 if (Indexes.size() < 2)
9709 return error(Loc, "expected >= 2 uselistorder indexes");
9710 if (Offset != 0 || Max >= Indexes.size())
9711 return error(Loc,
9712 "expected distinct uselistorder indexes in range [0, size)");
9713 if (IsOrdered)
9714 return error(Loc, "expected uselistorder indexes to change the order");
9715
9716 return false;
9717}
9718
9719/// parseUseListOrder
9720/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9721bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9722 SMLoc Loc = Lex.getLoc();
9723 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9724 return true;
9725
9726 Value *V;
9727 SmallVector<unsigned, 16> Indexes;
9728 if (parseTypeAndValue(V, PFS) ||
9729 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9730 parseUseListOrderIndexes(Indexes))
9731 return true;
9732
9733 return sortUseListOrder(V, Indexes, Loc);
9734}
9735
9736/// ModuleEntry
9737/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9738/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9739bool LLParser::parseModuleEntry(unsigned ID) {
9740 assert(Lex.getKind() == lltok::kw_module);
9741 Lex.Lex();
9742
9743 std::string Path;
9744 if (parseToken(lltok::colon, "expected ':' here") ||
9745 parseToken(lltok::lparen, "expected '(' here") ||
9746 parseToken(lltok::kw_path, "expected 'path' here") ||
9747 parseToken(lltok::colon, "expected ':' here") ||
9748 parseStringConstant(Path) ||
9749 parseToken(lltok::comma, "expected ',' here") ||
9750 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9751 parseToken(lltok::colon, "expected ':' here") ||
9752 parseToken(lltok::lparen, "expected '(' here"))
9753 return true;
9754
9755 ModuleHash Hash;
9756 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9757 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9758 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9759 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9760 parseUInt32(Hash[4]))
9761 return true;
9762
9763 if (parseToken(lltok::rparen, "expected ')' here") ||
9764 parseToken(lltok::rparen, "expected ')' here"))
9765 return true;
9766
9767 auto ModuleEntry = Index->addModule(Path, Hash);
9768 ModuleIdMap[ID] = ModuleEntry->first();
9769
9770 return false;
9771}
9772
9773/// TypeIdEntry
9774/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9775bool LLParser::parseTypeIdEntry(unsigned ID) {
9776 assert(Lex.getKind() == lltok::kw_typeid);
9777 Lex.Lex();
9778
9779 std::string Name;
9780 if (parseToken(lltok::colon, "expected ':' here") ||
9781 parseToken(lltok::lparen, "expected '(' here") ||
9782 parseToken(lltok::kw_name, "expected 'name' here") ||
9783 parseToken(lltok::colon, "expected ':' here") ||
9784 parseStringConstant(Name))
9785 return true;
9786
9787 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9788 if (parseToken(lltok::comma, "expected ',' here") ||
9789 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9790 return true;
9791
9792 // Check if this ID was forward referenced, and if so, update the
9793 // corresponding GUIDs.
9794 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9795 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9796 for (auto TIDRef : FwdRefTIDs->second) {
9797 assert(!*TIDRef.first &&
9798 "Forward referenced type id GUID expected to be 0");
9799 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9800 }
9801 ForwardRefTypeIds.erase(FwdRefTIDs);
9802 }
9803
9804 return false;
9805}
9806
9807/// TypeIdSummary
9808/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9809bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9810 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9811 parseToken(lltok::colon, "expected ':' here") ||
9812 parseToken(lltok::lparen, "expected '(' here") ||
9813 parseTypeTestResolution(TIS.TTRes))
9814 return true;
9815
9816 if (EatIfPresent(lltok::comma)) {
9817 // Expect optional wpdResolutions field
9818 if (parseOptionalWpdResolutions(TIS.WPDRes))
9819 return true;
9820 }
9821
9822 if (parseToken(lltok::rparen, "expected ')' here"))
9823 return true;
9824
9825 return false;
9826}
9827
9830
9831/// TypeIdCompatibleVtableEntry
9832/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9833/// TypeIdCompatibleVtableInfo
9834/// ')'
9835bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9837 Lex.Lex();
9838
9839 std::string Name;
9840 if (parseToken(lltok::colon, "expected ':' here") ||
9841 parseToken(lltok::lparen, "expected '(' here") ||
9842 parseToken(lltok::kw_name, "expected 'name' here") ||
9843 parseToken(lltok::colon, "expected ':' here") ||
9844 parseStringConstant(Name))
9845 return true;
9846
9848 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9849 if (parseToken(lltok::comma, "expected ',' here") ||
9850 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9851 parseToken(lltok::colon, "expected ':' here") ||
9852 parseToken(lltok::lparen, "expected '(' here"))
9853 return true;
9854
9855 IdToIndexMapType IdToIndexMap;
9856 // parse each call edge
9857 do {
9859 if (parseToken(lltok::lparen, "expected '(' here") ||
9860 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9861 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9862 parseToken(lltok::comma, "expected ',' here"))
9863 return true;
9864
9865 LocTy Loc = Lex.getLoc();
9866 unsigned GVId;
9867 ValueInfo VI;
9868 if (parseGVReference(VI, GVId))
9869 return true;
9870
9871 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9872 // forward reference. We will save the location of the ValueInfo needing an
9873 // update, but can only do so once the std::vector is finalized.
9874 if (VI == EmptyVI)
9875 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9876 TI.push_back({Offset, VI});
9877
9878 if (parseToken(lltok::rparen, "expected ')' in call"))
9879 return true;
9880 } while (EatIfPresent(lltok::comma));
9881
9882 // Now that the TI vector is finalized, it is safe to save the locations
9883 // of any forward GV references that need updating later.
9884 for (auto I : IdToIndexMap) {
9885 auto &Infos = ForwardRefValueInfos[I.first];
9886 for (auto P : I.second) {
9887 assert(TI[P.first].VTableVI == EmptyVI &&
9888 "Forward referenced ValueInfo expected to be empty");
9889 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9890 }
9891 }
9892
9893 if (parseToken(lltok::rparen, "expected ')' here") ||
9894 parseToken(lltok::rparen, "expected ')' here"))
9895 return true;
9896
9897 // Check if this ID was forward referenced, and if so, update the
9898 // corresponding GUIDs.
9899 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9900 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9901 for (auto TIDRef : FwdRefTIDs->second) {
9902 assert(!*TIDRef.first &&
9903 "Forward referenced type id GUID expected to be 0");
9904 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9905 }
9906 ForwardRefTypeIds.erase(FwdRefTIDs);
9907 }
9908
9909 return false;
9910}
9911
9912/// TypeTestResolution
9913/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9914/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9915/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9916/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9917/// [',' 'inlinesBits' ':' UInt64]? ')'
9918bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9919 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9920 parseToken(lltok::colon, "expected ':' here") ||
9921 parseToken(lltok::lparen, "expected '(' here") ||
9922 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9923 parseToken(lltok::colon, "expected ':' here"))
9924 return true;
9925
9926 switch (Lex.getKind()) {
9927 case lltok::kw_unknown:
9929 break;
9930 case lltok::kw_unsat:
9932 break;
9935 break;
9936 case lltok::kw_inline:
9938 break;
9939 case lltok::kw_single:
9941 break;
9942 case lltok::kw_allOnes:
9944 break;
9945 default:
9946 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9947 }
9948 Lex.Lex();
9949
9950 if (parseToken(lltok::comma, "expected ',' here") ||
9951 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9952 parseToken(lltok::colon, "expected ':' here") ||
9953 parseUInt32(TTRes.SizeM1BitWidth))
9954 return true;
9955
9956 // parse optional fields
9957 while (EatIfPresent(lltok::comma)) {
9958 switch (Lex.getKind()) {
9960 Lex.Lex();
9961 if (parseToken(lltok::colon, "expected ':'") ||
9962 parseUInt64(TTRes.AlignLog2))
9963 return true;
9964 break;
9965 case lltok::kw_sizeM1:
9966 Lex.Lex();
9967 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9968 return true;
9969 break;
9970 case lltok::kw_bitMask: {
9971 unsigned Val;
9972 Lex.Lex();
9973 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9974 return true;
9975 assert(Val <= 0xff);
9976 TTRes.BitMask = (uint8_t)Val;
9977 break;
9978 }
9980 Lex.Lex();
9981 if (parseToken(lltok::colon, "expected ':'") ||
9982 parseUInt64(TTRes.InlineBits))
9983 return true;
9984 break;
9985 default:
9986 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9987 }
9988 }
9989
9990 if (parseToken(lltok::rparen, "expected ')' here"))
9991 return true;
9992
9993 return false;
9994}
9995
9996/// OptionalWpdResolutions
9997/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9998/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9999bool LLParser::parseOptionalWpdResolutions(
10000 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10001 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
10002 parseToken(lltok::colon, "expected ':' here") ||
10003 parseToken(lltok::lparen, "expected '(' here"))
10004 return true;
10005
10006 do {
10008 WholeProgramDevirtResolution WPDRes;
10009 if (parseToken(lltok::lparen, "expected '(' here") ||
10010 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10011 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
10012 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
10013 parseToken(lltok::rparen, "expected ')' here"))
10014 return true;
10015 WPDResMap[Offset] = WPDRes;
10016 } while (EatIfPresent(lltok::comma));
10017
10018 if (parseToken(lltok::rparen, "expected ')' here"))
10019 return true;
10020
10021 return false;
10022}
10023
10024/// WpdRes
10025/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
10026/// [',' OptionalResByArg]? ')'
10027/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
10028/// ',' 'singleImplName' ':' STRINGCONSTANT ','
10029/// [',' OptionalResByArg]? ')'
10030/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
10031/// [',' OptionalResByArg]? ')'
10032bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10033 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
10034 parseToken(lltok::colon, "expected ':' here") ||
10035 parseToken(lltok::lparen, "expected '(' here") ||
10036 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10037 parseToken(lltok::colon, "expected ':' here"))
10038 return true;
10039
10040 switch (Lex.getKind()) {
10041 case lltok::kw_indir:
10043 break;
10046 break;
10049 break;
10050 default:
10051 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
10052 }
10053 Lex.Lex();
10054
10055 // parse optional fields
10056 while (EatIfPresent(lltok::comma)) {
10057 switch (Lex.getKind()) {
10059 Lex.Lex();
10060 if (parseToken(lltok::colon, "expected ':' here") ||
10061 parseStringConstant(WPDRes.SingleImplName))
10062 return true;
10063 break;
10064 case lltok::kw_resByArg:
10065 if (parseOptionalResByArg(WPDRes.ResByArg))
10066 return true;
10067 break;
10068 default:
10069 return error(Lex.getLoc(),
10070 "expected optional WholeProgramDevirtResolution field");
10071 }
10072 }
10073
10074 if (parseToken(lltok::rparen, "expected ')' here"))
10075 return true;
10076
10077 return false;
10078}
10079
10080/// OptionalResByArg
10081/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
10082/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
10083/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
10084/// 'virtualConstProp' )
10085/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
10086/// [',' 'bit' ':' UInt32]? ')'
10087bool LLParser::parseOptionalResByArg(
10088 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10089 &ResByArg) {
10090 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
10091 parseToken(lltok::colon, "expected ':' here") ||
10092 parseToken(lltok::lparen, "expected '(' here"))
10093 return true;
10094
10095 do {
10096 std::vector<uint64_t> Args;
10097 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
10098 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
10099 parseToken(lltok::colon, "expected ':' here") ||
10100 parseToken(lltok::lparen, "expected '(' here") ||
10101 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10102 parseToken(lltok::colon, "expected ':' here"))
10103 return true;
10104
10105 WholeProgramDevirtResolution::ByArg ByArg;
10106 switch (Lex.getKind()) {
10107 case lltok::kw_indir:
10109 break;
10112 break;
10115 break;
10118 break;
10119 default:
10120 return error(Lex.getLoc(),
10121 "unexpected WholeProgramDevirtResolution::ByArg kind");
10122 }
10123 Lex.Lex();
10124
10125 // parse optional fields
10126 while (EatIfPresent(lltok::comma)) {
10127 switch (Lex.getKind()) {
10128 case lltok::kw_info:
10129 Lex.Lex();
10130 if (parseToken(lltok::colon, "expected ':' here") ||
10131 parseUInt64(ByArg.Info))
10132 return true;
10133 break;
10134 case lltok::kw_byte:
10135 Lex.Lex();
10136 if (parseToken(lltok::colon, "expected ':' here") ||
10137 parseUInt32(ByArg.Byte))
10138 return true;
10139 break;
10140 case lltok::kw_bit:
10141 Lex.Lex();
10142 if (parseToken(lltok::colon, "expected ':' here") ||
10143 parseUInt32(ByArg.Bit))
10144 return true;
10145 break;
10146 default:
10147 return error(Lex.getLoc(),
10148 "expected optional whole program devirt field");
10149 }
10150 }
10151
10152 if (parseToken(lltok::rparen, "expected ')' here"))
10153 return true;
10154
10155 ResByArg[Args] = ByArg;
10156 } while (EatIfPresent(lltok::comma));
10157
10158 if (parseToken(lltok::rparen, "expected ')' here"))
10159 return true;
10160
10161 return false;
10162}
10163
10164/// OptionalResByArg
10165/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
10166bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10167 if (parseToken(lltok::kw_args, "expected 'args' here") ||
10168 parseToken(lltok::colon, "expected ':' here") ||
10169 parseToken(lltok::lparen, "expected '(' here"))
10170 return true;
10171
10172 do {
10173 uint64_t Val;
10174 if (parseUInt64(Val))
10175 return true;
10176 Args.push_back(Val);
10177 } while (EatIfPresent(lltok::comma));
10178
10179 if (parseToken(lltok::rparen, "expected ')' here"))
10180 return true;
10181
10182 return false;
10183}
10184
10186
10187static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
10188 bool ReadOnly = Fwd->isReadOnly();
10189 bool WriteOnly = Fwd->isWriteOnly();
10190 assert(!(ReadOnly && WriteOnly));
10191 *Fwd = Resolved;
10192 if (ReadOnly)
10193 Fwd->setReadOnly();
10194 if (WriteOnly)
10195 Fwd->setWriteOnly();
10196}
10197
10198/// Stores the given Name/GUID and associated summary into the Index.
10199/// Also updates any forward references to the associated entry ID.
10200bool LLParser::addGlobalValueToIndex(
10201 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
10202 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
10203 // First create the ValueInfo utilizing the Name or GUID.
10204 ValueInfo VI;
10205 if (GUID != 0) {
10206 assert(Name.empty());
10207 VI = Index->getOrInsertValueInfo(GUID);
10208 } else {
10209 assert(!Name.empty());
10210 if (M) {
10211 auto *GV = M->getNamedValue(Name);
10212 if (!GV)
10213 return error(Loc, "Reference to undefined global \"" + Name + "\"");
10214
10215 // Be a little lenient here, to accomodate older files without GUIDs
10216 // already computed and assigned as metadata.
10217 GUID = GV->getGUIDOrFallback();
10218
10219 VI = Index->getOrInsertValueInfo(GV, GUID);
10220 } else {
10221 assert(
10222 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
10223 "Need a source_filename to compute GUID for local");
10225 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
10226 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10227 }
10228 }
10229
10230 // Resolve forward references from calls/refs
10231 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10232 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10233 for (auto VIRef : FwdRefVIs->second) {
10234 assert(VIRef.first->getRef() == FwdVIRef &&
10235 "Forward referenced ValueInfo expected to be empty");
10236 resolveFwdRef(VIRef.first, VI);
10237 }
10238 ForwardRefValueInfos.erase(FwdRefVIs);
10239 }
10240
10241 // Resolve forward references from aliases
10242 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10243 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10244 for (auto AliaseeRef : FwdRefAliasees->second) {
10245 assert(!AliaseeRef.first->hasAliasee() &&
10246 "Forward referencing alias already has aliasee");
10247 assert(Summary && "Aliasee must be a definition");
10248 AliaseeRef.first->setAliasee(VI, Summary.get());
10249 }
10250 ForwardRefAliasees.erase(FwdRefAliasees);
10251 }
10252
10253 // Add the summary if one was provided.
10254 if (Summary)
10255 Index->addGlobalValueSummary(VI, std::move(Summary));
10256
10257 // Save the associated ValueInfo for use in later references by ID.
10258 if (ID == NumberedValueInfos.size())
10259 NumberedValueInfos.push_back(VI);
10260 else {
10261 // Handle non-continuous numbers (to make test simplification easier).
10262 if (ID > NumberedValueInfos.size())
10263 NumberedValueInfos.resize(ID + 1);
10264 NumberedValueInfos[ID] = VI;
10265 }
10266
10267 return false;
10268}
10269
10270/// parseSummaryIndexFlags
10271/// ::= 'flags' ':' UInt64
10272bool LLParser::parseSummaryIndexFlags() {
10273 assert(Lex.getKind() == lltok::kw_flags);
10274 Lex.Lex();
10275
10276 if (parseToken(lltok::colon, "expected ':' here"))
10277 return true;
10279 if (parseUInt64(Flags))
10280 return true;
10281 if (Index)
10282 Index->setFlags(Flags);
10283 return false;
10284}
10285
10286/// parseBlockCount
10287/// ::= 'blockcount' ':' UInt64
10288bool LLParser::parseBlockCount() {
10289 assert(Lex.getKind() == lltok::kw_blockcount);
10290 Lex.Lex();
10291
10292 if (parseToken(lltok::colon, "expected ':' here"))
10293 return true;
10294 uint64_t BlockCount;
10295 if (parseUInt64(BlockCount))
10296 return true;
10297 if (Index)
10298 Index->setBlockCount(BlockCount);
10299 return false;
10300}
10301
10302/// parseGVEntry
10303/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10304/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10305/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10306bool LLParser::parseGVEntry(unsigned ID) {
10307 assert(Lex.getKind() == lltok::kw_gv);
10308 Lex.Lex();
10309
10310 if (parseToken(lltok::colon, "expected ':' here") ||
10311 parseToken(lltok::lparen, "expected '(' here"))
10312 return true;
10313
10314 LocTy Loc = Lex.getLoc();
10315 std::string Name;
10317 switch (Lex.getKind()) {
10318 case lltok::kw_name:
10319 Lex.Lex();
10320 if (parseToken(lltok::colon, "expected ':' here") ||
10321 parseStringConstant(Name))
10322 return true;
10323 // Can't create GUID/ValueInfo until we have the linkage.
10324 break;
10325 case lltok::kw_guid:
10326 Lex.Lex();
10327 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10328 return true;
10329 break;
10330 default:
10331 return error(Lex.getLoc(), "expected name or guid tag");
10332 }
10333
10334 if (!EatIfPresent(lltok::comma)) {
10335 // No summaries. Wrap up.
10336 if (parseToken(lltok::rparen, "expected ')' here"))
10337 return true;
10338 // This was created for a call to an external or indirect target.
10339 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10340 // created for indirect calls with VP. A Name with no GUID came from
10341 // an external definition. We pass ExternalLinkage since that is only
10342 // used when the GUID must be computed from Name, and in that case
10343 // the symbol must have external linkage.
10344 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10345 nullptr, Loc);
10346 }
10347
10348 // Have a list of summaries
10349 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10350 parseToken(lltok::colon, "expected ':' here") ||
10351 parseToken(lltok::lparen, "expected '(' here"))
10352 return true;
10353 do {
10354 switch (Lex.getKind()) {
10355 case lltok::kw_function:
10356 if (parseFunctionSummary(Name, GUID, ID))
10357 return true;
10358 break;
10359 case lltok::kw_variable:
10360 if (parseVariableSummary(Name, GUID, ID))
10361 return true;
10362 break;
10363 case lltok::kw_alias:
10364 if (parseAliasSummary(Name, GUID, ID))
10365 return true;
10366 break;
10367 default:
10368 return error(Lex.getLoc(), "expected summary type");
10369 }
10370 } while (EatIfPresent(lltok::comma));
10371
10372 if (parseToken(lltok::rparen, "expected ')' here") ||
10373 parseToken(lltok::rparen, "expected ')' here"))
10374 return true;
10375
10376 return false;
10377}
10378
10379/// FunctionSummary
10380/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10381/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10382/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10383/// [',' OptionalRefs]? ')'
10384bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10385 unsigned ID) {
10386 LocTy Loc = Lex.getLoc();
10387 assert(Lex.getKind() == lltok::kw_function);
10388 Lex.Lex();
10389
10390 StringRef ModulePath;
10391 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10393 /*NotEligibleToImport=*/false,
10394 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10395 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10396 unsigned InstCount;
10398 FunctionSummary::TypeIdInfo TypeIdInfo;
10399 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10401 std::vector<CallsiteInfo> Callsites;
10402 std::vector<AllocInfo> Allocs;
10403 // Default is all-zeros (conservative values).
10404 FunctionSummary::FFlags FFlags = {};
10405 if (parseToken(lltok::colon, "expected ':' here") ||
10406 parseToken(lltok::lparen, "expected '(' here") ||
10407 parseModuleReference(ModulePath) ||
10408 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10409 parseToken(lltok::comma, "expected ',' here") ||
10410 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10411 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10412 return true;
10413
10414 // parse optional fields
10415 while (EatIfPresent(lltok::comma)) {
10416 switch (Lex.getKind()) {
10418 if (parseOptionalFFlags(FFlags))
10419 return true;
10420 break;
10421 case lltok::kw_calls:
10422 if (parseOptionalCalls(Calls))
10423 return true;
10424 break;
10426 if (parseOptionalTypeIdInfo(TypeIdInfo))
10427 return true;
10428 break;
10429 case lltok::kw_refs:
10430 if (parseOptionalRefs(Refs))
10431 return true;
10432 break;
10433 case lltok::kw_params:
10434 if (parseOptionalParamAccesses(ParamAccesses))
10435 return true;
10436 break;
10437 case lltok::kw_allocs:
10438 if (parseOptionalAllocs(Allocs))
10439 return true;
10440 break;
10442 if (parseOptionalCallsites(Callsites))
10443 return true;
10444 break;
10445 default:
10446 return error(Lex.getLoc(), "expected optional function summary field");
10447 }
10448 }
10449
10450 if (parseToken(lltok::rparen, "expected ')' here"))
10451 return true;
10452
10453 auto FS = std::make_unique<FunctionSummary>(
10454 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10455 std::move(TypeIdInfo.TypeTests),
10456 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10457 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10458 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10459 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10460 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10461
10462 FS->setModulePath(ModulePath);
10463
10464 return addGlobalValueToIndex(Name, GUID,
10466 std::move(FS), Loc);
10467}
10468
10469/// VariableSummary
10470/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10471/// [',' OptionalRefs]? ')'
10472bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10473 unsigned ID) {
10474 LocTy Loc = Lex.getLoc();
10475 assert(Lex.getKind() == lltok::kw_variable);
10476 Lex.Lex();
10477
10478 StringRef ModulePath;
10479 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10481 /*NotEligibleToImport=*/false,
10482 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10483 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10484 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10485 /* WriteOnly */ false,
10486 /* Constant */ false,
10489 VTableFuncList VTableFuncs;
10490 if (parseToken(lltok::colon, "expected ':' here") ||
10491 parseToken(lltok::lparen, "expected '(' here") ||
10492 parseModuleReference(ModulePath) ||
10493 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10494 parseToken(lltok::comma, "expected ',' here") ||
10495 parseGVarFlags(GVarFlags))
10496 return true;
10497
10498 // parse optional fields
10499 while (EatIfPresent(lltok::comma)) {
10500 switch (Lex.getKind()) {
10502 if (parseOptionalVTableFuncs(VTableFuncs))
10503 return true;
10504 break;
10505 case lltok::kw_refs:
10506 if (parseOptionalRefs(Refs))
10507 return true;
10508 break;
10509 default:
10510 return error(Lex.getLoc(), "expected optional variable summary field");
10511 }
10512 }
10513
10514 if (parseToken(lltok::rparen, "expected ')' here"))
10515 return true;
10516
10517 auto GS =
10518 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10519
10520 GS->setModulePath(ModulePath);
10521 GS->setVTableFuncs(std::move(VTableFuncs));
10522
10523 return addGlobalValueToIndex(Name, GUID,
10525 std::move(GS), Loc);
10526}
10527
10528/// AliasSummary
10529/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10530/// 'aliasee' ':' GVReference ')'
10531bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10532 unsigned ID) {
10533 assert(Lex.getKind() == lltok::kw_alias);
10534 LocTy Loc = Lex.getLoc();
10535 Lex.Lex();
10536
10537 StringRef ModulePath;
10538 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10540 /*NotEligibleToImport=*/false,
10541 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10542 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10543 if (parseToken(lltok::colon, "expected ':' here") ||
10544 parseToken(lltok::lparen, "expected '(' here") ||
10545 parseModuleReference(ModulePath) ||
10546 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10547 parseToken(lltok::comma, "expected ',' here") ||
10548 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10549 parseToken(lltok::colon, "expected ':' here"))
10550 return true;
10551
10552 ValueInfo AliaseeVI;
10553 unsigned GVId;
10554 auto AS = std::make_unique<AliasSummary>(GVFlags);
10555 AS->setModulePath(ModulePath);
10556
10557 if (!EatIfPresent(lltok::kw_null)) {
10558 if (parseGVReference(AliaseeVI, GVId))
10559 return true;
10560
10561 // Record forward reference if the aliasee is not parsed yet.
10562 if (AliaseeVI.getRef() == FwdVIRef) {
10563 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10564 } else {
10565 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10566 assert(Summary && "Aliasee must be a definition");
10567 AS->setAliasee(AliaseeVI, Summary);
10568 }
10569 }
10570
10571 if (parseToken(lltok::rparen, "expected ')' here"))
10572 return true;
10573
10574 return addGlobalValueToIndex(Name, GUID,
10576 std::move(AS), Loc);
10577}
10578
10579/// Flag
10580/// ::= [0|1]
10581bool LLParser::parseFlag(unsigned &Val) {
10582 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10583 return tokError("expected integer");
10584 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10585 Lex.Lex();
10586 return false;
10587}
10588
10589/// OptionalFFlags
10590/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10591/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10592/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10593/// [',' 'noInline' ':' Flag]? ')'
10594/// [',' 'alwaysInline' ':' Flag]? ')'
10595/// [',' 'noUnwind' ':' Flag]? ')'
10596/// [',' 'mayThrow' ':' Flag]? ')'
10597/// [',' 'hasUnknownCall' ':' Flag]? ')'
10598/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10599
10600bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10601 assert(Lex.getKind() == lltok::kw_funcFlags);
10602 Lex.Lex();
10603
10604 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10605 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10606 return true;
10607
10608 do {
10609 unsigned Val = 0;
10610 switch (Lex.getKind()) {
10611 case lltok::kw_readNone:
10612 Lex.Lex();
10613 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10614 return true;
10615 FFlags.ReadNone = Val;
10616 break;
10617 case lltok::kw_readOnly:
10618 Lex.Lex();
10619 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10620 return true;
10621 FFlags.ReadOnly = Val;
10622 break;
10624 Lex.Lex();
10625 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10626 return true;
10627 FFlags.NoRecurse = Val;
10628 break;
10630 Lex.Lex();
10631 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10632 return true;
10633 FFlags.ReturnDoesNotAlias = Val;
10634 break;
10635 case lltok::kw_noInline:
10636 Lex.Lex();
10637 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10638 return true;
10639 FFlags.NoInline = Val;
10640 break;
10642 Lex.Lex();
10643 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10644 return true;
10645 FFlags.AlwaysInline = Val;
10646 break;
10647 case lltok::kw_noUnwind:
10648 Lex.Lex();
10649 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10650 return true;
10651 FFlags.NoUnwind = Val;
10652 break;
10653 case lltok::kw_mayThrow:
10654 Lex.Lex();
10655 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10656 return true;
10657 FFlags.MayThrow = Val;
10658 break;
10660 Lex.Lex();
10661 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10662 return true;
10663 FFlags.HasUnknownCall = Val;
10664 break;
10666 Lex.Lex();
10667 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10668 return true;
10669 FFlags.MustBeUnreachable = Val;
10670 break;
10671 default:
10672 return error(Lex.getLoc(), "expected function flag type");
10673 }
10674 } while (EatIfPresent(lltok::comma));
10675
10676 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10677 return true;
10678
10679 return false;
10680}
10681
10682/// OptionalCalls
10683/// := 'calls' ':' '(' Call [',' Call]* ')'
10684/// Call ::= '(' 'callee' ':' GVReference
10685/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10686/// [ ',' 'tail' ]? ')'
10687bool LLParser::parseOptionalCalls(
10688 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10689 assert(Lex.getKind() == lltok::kw_calls);
10690 Lex.Lex();
10691
10692 if (parseToken(lltok::colon, "expected ':' in calls") ||
10693 parseToken(lltok::lparen, "expected '(' in calls"))
10694 return true;
10695
10696 IdToIndexMapType IdToIndexMap;
10697 // parse each call edge
10698 do {
10699 ValueInfo VI;
10700 if (parseToken(lltok::lparen, "expected '(' in call") ||
10701 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10702 parseToken(lltok::colon, "expected ':'"))
10703 return true;
10704
10705 LocTy Loc = Lex.getLoc();
10706 unsigned GVId;
10707 if (parseGVReference(VI, GVId))
10708 return true;
10709
10711 unsigned RelBF = 0;
10712 unsigned HasTailCall = false;
10713
10714 // parse optional fields
10715 while (EatIfPresent(lltok::comma)) {
10716 switch (Lex.getKind()) {
10717 case lltok::kw_hotness:
10718 Lex.Lex();
10719 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10720 return true;
10721 break;
10722 // Deprecated, keep in order to support old files.
10723 case lltok::kw_relbf:
10724 Lex.Lex();
10725 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10726 return true;
10727 break;
10728 case lltok::kw_tail:
10729 Lex.Lex();
10730 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10731 return true;
10732 break;
10733 default:
10734 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10735 }
10736 }
10737 // Keep track of the Call array index needing a forward reference.
10738 // We will save the location of the ValueInfo needing an update, but
10739 // can only do so once the std::vector is finalized.
10740 if (VI.getRef() == FwdVIRef)
10741 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10742 Calls.push_back(
10743 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10744
10745 if (parseToken(lltok::rparen, "expected ')' in call"))
10746 return true;
10747 } while (EatIfPresent(lltok::comma));
10748
10749 // Now that the Calls vector is finalized, it is safe to save the locations
10750 // of any forward GV references that need updating later.
10751 for (auto I : IdToIndexMap) {
10752 auto &Infos = ForwardRefValueInfos[I.first];
10753 for (auto P : I.second) {
10754 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10755 "Forward referenced ValueInfo expected to be empty");
10756 Infos.emplace_back(&Calls[P.first].first, P.second);
10757 }
10758 }
10759
10760 if (parseToken(lltok::rparen, "expected ')' in calls"))
10761 return true;
10762
10763 return false;
10764}
10765
10766/// Hotness
10767/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10768bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10769 switch (Lex.getKind()) {
10770 case lltok::kw_unknown:
10772 break;
10773 case lltok::kw_cold:
10775 break;
10776 case lltok::kw_none:
10778 break;
10779 case lltok::kw_hot:
10781 break;
10782 case lltok::kw_critical:
10784 break;
10785 default:
10786 return error(Lex.getLoc(), "invalid call edge hotness");
10787 }
10788 Lex.Lex();
10789 return false;
10790}
10791
10792/// OptionalVTableFuncs
10793/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10794/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10795bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10796 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10797 Lex.Lex();
10798
10799 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10800 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10801 return true;
10802
10803 IdToIndexMapType IdToIndexMap;
10804 // parse each virtual function pair
10805 do {
10806 ValueInfo VI;
10807 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10808 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10809 parseToken(lltok::colon, "expected ':'"))
10810 return true;
10811
10812 LocTy Loc = Lex.getLoc();
10813 unsigned GVId;
10814 if (parseGVReference(VI, GVId))
10815 return true;
10816
10818 if (parseToken(lltok::comma, "expected comma") ||
10819 parseToken(lltok::kw_offset, "expected offset") ||
10820 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10821 return true;
10822
10823 // Keep track of the VTableFuncs array index needing a forward reference.
10824 // We will save the location of the ValueInfo needing an update, but
10825 // can only do so once the std::vector is finalized.
10826 if (VI == EmptyVI)
10827 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10828 VTableFuncs.push_back({VI, Offset});
10829
10830 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10831 return true;
10832 } while (EatIfPresent(lltok::comma));
10833
10834 // Now that the VTableFuncs vector is finalized, it is safe to save the
10835 // locations of any forward GV references that need updating later.
10836 for (auto I : IdToIndexMap) {
10837 auto &Infos = ForwardRefValueInfos[I.first];
10838 for (auto P : I.second) {
10839 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10840 "Forward referenced ValueInfo expected to be empty");
10841 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10842 }
10843 }
10844
10845 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10846 return true;
10847
10848 return false;
10849}
10850
10851/// ParamNo := 'param' ':' UInt64
10852bool LLParser::parseParamNo(uint64_t &ParamNo) {
10853 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10854 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10855 return true;
10856 return false;
10857}
10858
10859/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10860bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10861 APSInt Lower;
10862 APSInt Upper;
10863 auto ParseAPSInt = [&](APSInt &Val) {
10864 if (Lex.getKind() != lltok::APSInt)
10865 return tokError("expected integer");
10866 Val = Lex.getAPSIntVal();
10867 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10868 Val.setIsSigned(true);
10869 Lex.Lex();
10870 return false;
10871 };
10872 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10873 parseToken(lltok::colon, "expected ':' here") ||
10874 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10875 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10876 parseToken(lltok::rsquare, "expected ']' here"))
10877 return true;
10878
10879 ++Upper;
10880 Range =
10881 (Lower == Upper && !Lower.isMaxValue())
10882 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10883 : ConstantRange(Lower, Upper);
10884
10885 return false;
10886}
10887
10888/// ParamAccessCall
10889/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10890bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10891 IdLocListType &IdLocList) {
10892 if (parseToken(lltok::lparen, "expected '(' here") ||
10893 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10894 parseToken(lltok::colon, "expected ':' here"))
10895 return true;
10896
10897 unsigned GVId;
10898 ValueInfo VI;
10899 LocTy Loc = Lex.getLoc();
10900 if (parseGVReference(VI, GVId))
10901 return true;
10902
10903 Call.Callee = VI;
10904 IdLocList.emplace_back(GVId, Loc);
10905
10906 if (parseToken(lltok::comma, "expected ',' here") ||
10907 parseParamNo(Call.ParamNo) ||
10908 parseToken(lltok::comma, "expected ',' here") ||
10909 parseParamAccessOffset(Call.Offsets))
10910 return true;
10911
10912 if (parseToken(lltok::rparen, "expected ')' here"))
10913 return true;
10914
10915 return false;
10916}
10917
10918/// ParamAccess
10919/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10920/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10921bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10922 IdLocListType &IdLocList) {
10923 if (parseToken(lltok::lparen, "expected '(' here") ||
10924 parseParamNo(Param.ParamNo) ||
10925 parseToken(lltok::comma, "expected ',' here") ||
10926 parseParamAccessOffset(Param.Use))
10927 return true;
10928
10929 if (EatIfPresent(lltok::comma)) {
10930 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10931 parseToken(lltok::colon, "expected ':' here") ||
10932 parseToken(lltok::lparen, "expected '(' here"))
10933 return true;
10934 do {
10935 FunctionSummary::ParamAccess::Call Call;
10936 if (parseParamAccessCall(Call, IdLocList))
10937 return true;
10938 Param.Calls.push_back(Call);
10939 } while (EatIfPresent(lltok::comma));
10940
10941 if (parseToken(lltok::rparen, "expected ')' here"))
10942 return true;
10943 }
10944
10945 if (parseToken(lltok::rparen, "expected ')' here"))
10946 return true;
10947
10948 return false;
10949}
10950
10951/// OptionalParamAccesses
10952/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10953bool LLParser::parseOptionalParamAccesses(
10954 std::vector<FunctionSummary::ParamAccess> &Params) {
10955 assert(Lex.getKind() == lltok::kw_params);
10956 Lex.Lex();
10957
10958 if (parseToken(lltok::colon, "expected ':' here") ||
10959 parseToken(lltok::lparen, "expected '(' here"))
10960 return true;
10961
10962 IdLocListType VContexts;
10963 size_t CallsNum = 0;
10964 do {
10965 FunctionSummary::ParamAccess ParamAccess;
10966 if (parseParamAccess(ParamAccess, VContexts))
10967 return true;
10968 CallsNum += ParamAccess.Calls.size();
10969 assert(VContexts.size() == CallsNum);
10970 (void)CallsNum;
10971 Params.emplace_back(std::move(ParamAccess));
10972 } while (EatIfPresent(lltok::comma));
10973
10974 if (parseToken(lltok::rparen, "expected ')' here"))
10975 return true;
10976
10977 // Now that the Params is finalized, it is safe to save the locations
10978 // of any forward GV references that need updating later.
10979 IdLocListType::const_iterator ItContext = VContexts.begin();
10980 for (auto &PA : Params) {
10981 for (auto &C : PA.Calls) {
10982 if (C.Callee.getRef() == FwdVIRef)
10983 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10984 ItContext->second);
10985 ++ItContext;
10986 }
10987 }
10988 assert(ItContext == VContexts.end());
10989
10990 return false;
10991}
10992
10993/// OptionalRefs
10994/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10995bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10996 assert(Lex.getKind() == lltok::kw_refs);
10997 Lex.Lex();
10998
10999 if (parseToken(lltok::colon, "expected ':' in refs") ||
11000 parseToken(lltok::lparen, "expected '(' in refs"))
11001 return true;
11002
11003 struct ValueContext {
11004 ValueInfo VI;
11005 unsigned GVId;
11006 LocTy Loc;
11007 };
11008 std::vector<ValueContext> VContexts;
11009 // parse each ref edge
11010 do {
11011 ValueContext VC;
11012 VC.Loc = Lex.getLoc();
11013 if (parseGVReference(VC.VI, VC.GVId))
11014 return true;
11015 VContexts.push_back(VC);
11016 } while (EatIfPresent(lltok::comma));
11017
11018 // Sort value contexts so that ones with writeonly
11019 // and readonly ValueInfo are at the end of VContexts vector.
11020 // See FunctionSummary::specialRefCounts()
11021 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
11022 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11023 });
11024
11025 IdToIndexMapType IdToIndexMap;
11026 for (auto &VC : VContexts) {
11027 // Keep track of the Refs array index needing a forward reference.
11028 // We will save the location of the ValueInfo needing an update, but
11029 // can only do so once the std::vector is finalized.
11030 if (VC.VI.getRef() == FwdVIRef)
11031 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
11032 Refs.push_back(VC.VI);
11033 }
11034
11035 // Now that the Refs vector is finalized, it is safe to save the locations
11036 // of any forward GV references that need updating later.
11037 for (auto I : IdToIndexMap) {
11038 auto &Infos = ForwardRefValueInfos[I.first];
11039 for (auto P : I.second) {
11040 assert(Refs[P.first].getRef() == FwdVIRef &&
11041 "Forward referenced ValueInfo expected to be empty");
11042 Infos.emplace_back(&Refs[P.first], P.second);
11043 }
11044 }
11045
11046 if (parseToken(lltok::rparen, "expected ')' in refs"))
11047 return true;
11048
11049 return false;
11050}
11051
11052/// OptionalTypeIdInfo
11053/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
11054/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
11055/// [',' TypeCheckedLoadConstVCalls]? ')'
11056bool LLParser::parseOptionalTypeIdInfo(
11057 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11058 assert(Lex.getKind() == lltok::kw_typeIdInfo);
11059 Lex.Lex();
11060
11061 if (parseToken(lltok::colon, "expected ':' here") ||
11062 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11063 return true;
11064
11065 do {
11066 switch (Lex.getKind()) {
11068 if (parseTypeTests(TypeIdInfo.TypeTests))
11069 return true;
11070 break;
11072 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
11073 TypeIdInfo.TypeTestAssumeVCalls))
11074 return true;
11075 break;
11077 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
11078 TypeIdInfo.TypeCheckedLoadVCalls))
11079 return true;
11080 break;
11082 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
11083 TypeIdInfo.TypeTestAssumeConstVCalls))
11084 return true;
11085 break;
11087 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
11088 TypeIdInfo.TypeCheckedLoadConstVCalls))
11089 return true;
11090 break;
11091 default:
11092 return error(Lex.getLoc(), "invalid typeIdInfo list type");
11093 }
11094 } while (EatIfPresent(lltok::comma));
11095
11096 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11097 return true;
11098
11099 return false;
11100}
11101
11102/// TypeTests
11103/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
11104/// [',' (SummaryID | UInt64)]* ')'
11105bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11106 assert(Lex.getKind() == lltok::kw_typeTests);
11107 Lex.Lex();
11108
11109 if (parseToken(lltok::colon, "expected ':' here") ||
11110 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11111 return true;
11112
11113 IdToIndexMapType IdToIndexMap;
11114 do {
11116 if (Lex.getKind() == lltok::SummaryID) {
11117 unsigned ID = Lex.getUIntVal();
11118 LocTy Loc = Lex.getLoc();
11119 // Keep track of the TypeTests array index needing a forward reference.
11120 // We will save the location of the GUID needing an update, but
11121 // can only do so once the std::vector is finalized.
11122 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
11123 Lex.Lex();
11124 } else if (parseUInt64(GUID))
11125 return true;
11126 TypeTests.push_back(GUID);
11127 } while (EatIfPresent(lltok::comma));
11128
11129 // Now that the TypeTests vector is finalized, it is safe to save the
11130 // locations of any forward GV references that need updating later.
11131 for (auto I : IdToIndexMap) {
11132 auto &Ids = ForwardRefTypeIds[I.first];
11133 for (auto P : I.second) {
11134 assert(TypeTests[P.first] == 0 &&
11135 "Forward referenced type id GUID expected to be 0");
11136 Ids.emplace_back(&TypeTests[P.first], P.second);
11137 }
11138 }
11139
11140 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11141 return true;
11142
11143 return false;
11144}
11145
11146/// VFuncIdList
11147/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
11148bool LLParser::parseVFuncIdList(
11149 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11150 assert(Lex.getKind() == Kind);
11151 Lex.Lex();
11152
11153 if (parseToken(lltok::colon, "expected ':' here") ||
11154 parseToken(lltok::lparen, "expected '(' here"))
11155 return true;
11156
11157 IdToIndexMapType IdToIndexMap;
11158 do {
11159 FunctionSummary::VFuncId VFuncId;
11160 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11161 return true;
11162 VFuncIdList.push_back(VFuncId);
11163 } while (EatIfPresent(lltok::comma));
11164
11165 if (parseToken(lltok::rparen, "expected ')' here"))
11166 return true;
11167
11168 // Now that the VFuncIdList vector is finalized, it is safe to save the
11169 // locations of any forward GV references that need updating later.
11170 for (auto I : IdToIndexMap) {
11171 auto &Ids = ForwardRefTypeIds[I.first];
11172 for (auto P : I.second) {
11173 assert(VFuncIdList[P.first].GUID == 0 &&
11174 "Forward referenced type id GUID expected to be 0");
11175 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
11176 }
11177 }
11178
11179 return false;
11180}
11181
11182/// ConstVCallList
11183/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
11184bool LLParser::parseConstVCallList(
11185 lltok::Kind Kind,
11186 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11187 assert(Lex.getKind() == Kind);
11188 Lex.Lex();
11189
11190 if (parseToken(lltok::colon, "expected ':' here") ||
11191 parseToken(lltok::lparen, "expected '(' here"))
11192 return true;
11193
11194 IdToIndexMapType IdToIndexMap;
11195 do {
11196 FunctionSummary::ConstVCall ConstVCall;
11197 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11198 return true;
11199 ConstVCallList.push_back(ConstVCall);
11200 } while (EatIfPresent(lltok::comma));
11201
11202 if (parseToken(lltok::rparen, "expected ')' here"))
11203 return true;
11204
11205 // Now that the ConstVCallList vector is finalized, it is safe to save the
11206 // locations of any forward GV references that need updating later.
11207 for (auto I : IdToIndexMap) {
11208 auto &Ids = ForwardRefTypeIds[I.first];
11209 for (auto P : I.second) {
11210 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
11211 "Forward referenced type id GUID expected to be 0");
11212 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
11213 }
11214 }
11215
11216 return false;
11217}
11218
11219/// ConstVCall
11220/// ::= '(' VFuncId ',' Args ')'
11221bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11222 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11223 if (parseToken(lltok::lparen, "expected '(' here") ||
11224 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
11225 return true;
11226
11227 if (EatIfPresent(lltok::comma))
11228 if (parseArgs(ConstVCall.Args))
11229 return true;
11230
11231 if (parseToken(lltok::rparen, "expected ')' here"))
11232 return true;
11233
11234 return false;
11235}
11236
11237/// VFuncId
11238/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
11239/// 'offset' ':' UInt64 ')'
11240bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11241 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11242 assert(Lex.getKind() == lltok::kw_vFuncId);
11243 Lex.Lex();
11244
11245 if (parseToken(lltok::colon, "expected ':' here") ||
11246 parseToken(lltok::lparen, "expected '(' here"))
11247 return true;
11248
11249 if (Lex.getKind() == lltok::SummaryID) {
11250 VFuncId.GUID = 0;
11251 unsigned ID = Lex.getUIntVal();
11252 LocTy Loc = Lex.getLoc();
11253 // Keep track of the array index needing a forward reference.
11254 // We will save the location of the GUID needing an update, but
11255 // can only do so once the caller's std::vector is finalized.
11256 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11257 Lex.Lex();
11258 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11259 parseToken(lltok::colon, "expected ':' here") ||
11260 parseUInt64(VFuncId.GUID))
11261 return true;
11262
11263 if (parseToken(lltok::comma, "expected ',' here") ||
11264 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11265 parseToken(lltok::colon, "expected ':' here") ||
11266 parseUInt64(VFuncId.Offset) ||
11267 parseToken(lltok::rparen, "expected ')' here"))
11268 return true;
11269
11270 return false;
11271}
11272
11273/// GVFlags
11274/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11275/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11276/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11277/// 'canAutoHide' ':' Flag ',' ')'
11278bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11279 assert(Lex.getKind() == lltok::kw_flags);
11280 Lex.Lex();
11281
11282 if (parseToken(lltok::colon, "expected ':' here") ||
11283 parseToken(lltok::lparen, "expected '(' here"))
11284 return true;
11285
11286 do {
11287 unsigned Flag = 0;
11288 switch (Lex.getKind()) {
11289 case lltok::kw_linkage:
11290 Lex.Lex();
11291 if (parseToken(lltok::colon, "expected ':'"))
11292 return true;
11293 bool HasLinkage;
11294 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11295 assert(HasLinkage && "Linkage not optional in summary entry");
11296 Lex.Lex();
11297 break;
11299 Lex.Lex();
11300 if (parseToken(lltok::colon, "expected ':'"))
11301 return true;
11302 parseOptionalVisibility(Flag);
11303 GVFlags.Visibility = Flag;
11304 break;
11306 Lex.Lex();
11307 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11308 return true;
11309 GVFlags.NotEligibleToImport = Flag;
11310 break;
11311 case lltok::kw_live:
11312 Lex.Lex();
11313 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11314 return true;
11315 GVFlags.Live = Flag;
11316 break;
11317 case lltok::kw_dsoLocal:
11318 Lex.Lex();
11319 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11320 return true;
11321 GVFlags.DSOLocal = Flag;
11322 break;
11324 Lex.Lex();
11325 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11326 return true;
11327 GVFlags.CanAutoHide = Flag;
11328 break;
11330 Lex.Lex();
11331 if (parseToken(lltok::colon, "expected ':'"))
11332 return true;
11334 if (parseOptionalImportType(Lex.getKind(), IK))
11335 return true;
11336 GVFlags.ImportType = static_cast<unsigned>(IK);
11337 Lex.Lex();
11338 break;
11340 Lex.Lex();
11341 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11342 return true;
11343 GVFlags.NoRenameOnPromotion = Flag;
11344 break;
11345 default:
11346 return error(Lex.getLoc(), "expected gv flag type");
11347 }
11348 } while (EatIfPresent(lltok::comma));
11349
11350 if (parseToken(lltok::rparen, "expected ')' here"))
11351 return true;
11352
11353 return false;
11354}
11355
11356/// GVarFlags
11357/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11358/// ',' 'writeonly' ':' Flag
11359/// ',' 'constant' ':' Flag ')'
11360bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11361 assert(Lex.getKind() == lltok::kw_varFlags);
11362 Lex.Lex();
11363
11364 if (parseToken(lltok::colon, "expected ':' here") ||
11365 parseToken(lltok::lparen, "expected '(' here"))
11366 return true;
11367
11368 auto ParseRest = [this](unsigned int &Val) {
11369 Lex.Lex();
11370 if (parseToken(lltok::colon, "expected ':'"))
11371 return true;
11372 return parseFlag(Val);
11373 };
11374
11375 do {
11376 unsigned Flag = 0;
11377 switch (Lex.getKind()) {
11378 case lltok::kw_readonly:
11379 if (ParseRest(Flag))
11380 return true;
11381 GVarFlags.MaybeReadOnly = Flag;
11382 break;
11383 case lltok::kw_writeonly:
11384 if (ParseRest(Flag))
11385 return true;
11386 GVarFlags.MaybeWriteOnly = Flag;
11387 break;
11388 case lltok::kw_constant:
11389 if (ParseRest(Flag))
11390 return true;
11391 GVarFlags.Constant = Flag;
11392 break;
11394 if (ParseRest(Flag))
11395 return true;
11396 GVarFlags.VCallVisibility = Flag;
11397 break;
11398 default:
11399 return error(Lex.getLoc(), "expected gvar flag type");
11400 }
11401 } while (EatIfPresent(lltok::comma));
11402 return parseToken(lltok::rparen, "expected ')' here");
11403}
11404
11405/// ModuleReference
11406/// ::= 'module' ':' UInt
11407bool LLParser::parseModuleReference(StringRef &ModulePath) {
11408 // parse module id.
11409 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11410 parseToken(lltok::colon, "expected ':' here") ||
11411 parseToken(lltok::SummaryID, "expected module ID"))
11412 return true;
11413
11414 unsigned ModuleID = Lex.getUIntVal();
11415 auto I = ModuleIdMap.find(ModuleID);
11416 // We should have already parsed all module IDs
11417 assert(I != ModuleIdMap.end());
11418 ModulePath = I->second;
11419 return false;
11420}
11421
11422/// GVReference
11423/// ::= SummaryID
11424bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11425 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11426 if (!ReadOnly)
11427 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11428 if (parseToken(lltok::SummaryID, "expected GV ID"))
11429 return true;
11430
11431 GVId = Lex.getUIntVal();
11432 // Check if we already have a VI for this GV
11433 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11434 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11435 VI = NumberedValueInfos[GVId];
11436 } else
11437 // We will create a forward reference to the stored location.
11438 VI = ValueInfo(false, FwdVIRef);
11439
11440 if (ReadOnly)
11441 VI.setReadOnly();
11442 if (WriteOnly)
11443 VI.setWriteOnly();
11444 return false;
11445}
11446
11447/// OptionalAllocs
11448/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11449/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11450/// ',' MemProfs ')'
11451/// Version ::= UInt32
11452bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11453 assert(Lex.getKind() == lltok::kw_allocs);
11454 Lex.Lex();
11455
11456 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11457 parseToken(lltok::lparen, "expected '(' in allocs"))
11458 return true;
11459
11460 // parse each alloc
11461 do {
11462 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11463 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11464 parseToken(lltok::colon, "expected ':'") ||
11465 parseToken(lltok::lparen, "expected '(' in versions"))
11466 return true;
11467
11468 SmallVector<uint8_t> Versions;
11469 do {
11470 uint8_t V = 0;
11471 if (parseAllocType(V))
11472 return true;
11473 Versions.push_back(V);
11474 } while (EatIfPresent(lltok::comma));
11475
11476 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11477 parseToken(lltok::comma, "expected ',' in alloc"))
11478 return true;
11479
11480 std::vector<MIBInfo> MIBs;
11481 if (parseMemProfs(MIBs))
11482 return true;
11483
11484 Allocs.push_back({Versions, MIBs});
11485
11486 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11487 return true;
11488 } while (EatIfPresent(lltok::comma));
11489
11490 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11491 return true;
11492
11493 return false;
11494}
11495
11496/// MemProfs
11497/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11498/// MemProf ::= '(' 'type' ':' AllocType
11499/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11500/// StackId ::= UInt64
11501bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11502 assert(Lex.getKind() == lltok::kw_memProf);
11503 Lex.Lex();
11504
11505 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11506 parseToken(lltok::lparen, "expected '(' in memprof"))
11507 return true;
11508
11509 // parse each MIB
11510 do {
11511 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11512 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11513 parseToken(lltok::colon, "expected ':'"))
11514 return true;
11515
11516 uint8_t AllocType;
11517 if (parseAllocType(AllocType))
11518 return true;
11519
11520 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11521 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11522 parseToken(lltok::colon, "expected ':'") ||
11523 parseToken(lltok::lparen, "expected '(' in stackIds"))
11524 return true;
11525
11526 SmallVector<unsigned> StackIdIndices;
11527 // Combined index alloc records may not have a stack id list.
11528 if (Lex.getKind() != lltok::rparen) {
11529 do {
11530 uint64_t StackId = 0;
11531 if (parseUInt64(StackId))
11532 return true;
11533 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11534 } while (EatIfPresent(lltok::comma));
11535 }
11536
11537 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11538 return true;
11539
11540 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11541
11542 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11543 return true;
11544 } while (EatIfPresent(lltok::comma));
11545
11546 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11547 return true;
11548
11549 return false;
11550}
11551
11552/// AllocType
11553/// := ('none'|'notcold'|'cold'|'hot')
11554bool LLParser::parseAllocType(uint8_t &AllocType) {
11555 switch (Lex.getKind()) {
11556 case lltok::kw_none:
11558 break;
11559 case lltok::kw_notcold:
11561 break;
11562 case lltok::kw_cold:
11564 break;
11565 case lltok::kw_hot:
11566 AllocType = (uint8_t)AllocationType::Hot;
11567 break;
11568 default:
11569 return error(Lex.getLoc(), "invalid alloc type");
11570 }
11571 Lex.Lex();
11572 return false;
11573}
11574
11575/// OptionalCallsites
11576/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11577/// Callsite ::= '(' 'callee' ':' GVReference
11578/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11579/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11580/// Version ::= UInt32
11581/// StackId ::= UInt64
11582bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11583 assert(Lex.getKind() == lltok::kw_callsites);
11584 Lex.Lex();
11585
11586 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11587 parseToken(lltok::lparen, "expected '(' in callsites"))
11588 return true;
11589
11590 IdToIndexMapType IdToIndexMap;
11591 // parse each callsite
11592 do {
11593 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11594 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11595 parseToken(lltok::colon, "expected ':'"))
11596 return true;
11597
11598 ValueInfo VI;
11599 unsigned GVId = 0;
11600 LocTy Loc = Lex.getLoc();
11601 if (!EatIfPresent(lltok::kw_null)) {
11602 if (parseGVReference(VI, GVId))
11603 return true;
11604 }
11605
11606 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11607 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11608 parseToken(lltok::colon, "expected ':'") ||
11609 parseToken(lltok::lparen, "expected '(' in clones"))
11610 return true;
11611
11612 SmallVector<unsigned> Clones;
11613 do {
11614 unsigned V = 0;
11615 if (parseUInt32(V))
11616 return true;
11617 Clones.push_back(V);
11618 } while (EatIfPresent(lltok::comma));
11619
11620 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11621 parseToken(lltok::comma, "expected ',' in callsite") ||
11622 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11623 parseToken(lltok::colon, "expected ':'") ||
11624 parseToken(lltok::lparen, "expected '(' in stackIds"))
11625 return true;
11626
11627 SmallVector<unsigned> StackIdIndices;
11628 // Synthesized callsite records will not have a stack id list.
11629 if (Lex.getKind() != lltok::rparen) {
11630 do {
11631 uint64_t StackId = 0;
11632 if (parseUInt64(StackId))
11633 return true;
11634 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11635 } while (EatIfPresent(lltok::comma));
11636 }
11637
11638 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11639 return true;
11640
11641 // Keep track of the Callsites array index needing a forward reference.
11642 // We will save the location of the ValueInfo needing an update, but
11643 // can only do so once the SmallVector is finalized.
11644 if (VI.getRef() == FwdVIRef)
11645 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11646 Callsites.push_back({VI, Clones, StackIdIndices});
11647
11648 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11649 return true;
11650 } while (EatIfPresent(lltok::comma));
11651
11652 // Now that the Callsites vector is finalized, it is safe to save the
11653 // locations of any forward GV references that need updating later.
11654 for (auto I : IdToIndexMap) {
11655 auto &Infos = ForwardRefValueInfos[I.first];
11656 for (auto P : I.second) {
11657 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11658 "Forward referenced ValueInfo expected to be empty");
11659 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11660 }
11661 }
11662
11663 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11664 return true;
11665
11666 return false;
11667}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned 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:280
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
Definition Compiler.h:281
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
static uint64_t align(uint64_t Size)
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
#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)
const SmallVectorImpl< MachineOperand > & Cond
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:805
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:145
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ None
No attributes have been set.
Definition Attributes.h:127
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
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)
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:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
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:718
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:794
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
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:457
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:452
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:829
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:455
arg_iterator arg_begin()
Definition Function.h:853
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1025
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:1037
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:1587
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
A single uniqued string.
Definition Metadata.h:733
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1536
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1525
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1545
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:107
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:887
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:904
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:467
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:662
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:743
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:581
LLVM_ABI bool isScalableTy() const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:494
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:942
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:300
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:279
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:273
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:241
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
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:296
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:514
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:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:108
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:319
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 isAtomic(const T &...O)
Definition SIDefines.h:390
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:337
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:61
@ 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:913
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:919
@ 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:515
@ DwarfLangDialect
Definition LLToken.h:518
@ 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:426
@ 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:494
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:465
@ kw_canAutoHide
Definition LLToken.h:409
@ kw_alwaysInline
Definition LLToken.h:422
@ 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:535
@ 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:405
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:194
@ kw_positivezero
Definition LLToken.h:232
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:468
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:445
@ 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:406
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:145
@ kw_ptx_device
Definition LLToken.h:159
@ kw_personality
Definition LLToken.h:347
@ DwarfEnumKind
Definition LLToken.h:529
@ kw_declaration
Definition LLToken.h:412
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:514
@ 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:425
@ kw_x86_intrcc
Definition LLToken.h:171
@ kw_addrspacecast
Definition LLToken.h:342
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:512
@ 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:521
@ kw_inlineBits
Definition LLToken.h:463
@ 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:444
@ FixedPointKind
Definition LLToken.h:522
@ 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:469
@ kw_typeidCompatibleVTable
Definition LLToken.h:450
@ kw_vTableFuncs
Definition LLToken.h:436
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:443
@ kw_no_sanitize_address
Definition LLToken.h:491
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:220
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:497
@ DwarfSourceLangName
Definition LLToken.h:517
@ kw_noRenameOnPromotion
Definition LLToken.h:413
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:183
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:360
@ 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:470
@ kw_target_mem0
Definition LLToken.h:213
@ kw_swifttailcc
Definition LLToken.h:166
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:442
@ 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:473
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:459
@ 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:420
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:168
@ kw_importType
Definition LLToken.h:410
@ 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:411
@ kw_virtualConstProp
Definition LLToken.h:475
@ kw_vcall_visibility
Definition LLToken.h:464
@ 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:452
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:440
@ 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:528
@ 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:474
@ kw_insertvalue
Definition LLToken.h:379
@ 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
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
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:54
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h: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:309
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:312
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:311
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:381
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:267
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:1033
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.