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