LLVM 23.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/AutoUpgrade.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Comdat.h"
30#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalIFunc.h"
36#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
63 "allow-incomplete-ir", cl::init(false), cl::Hidden,
65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
67
68static std::string getTypeString(Type *T) {
69 std::string Result;
70 raw_string_ostream Tmp(Result);
71 Tmp << *T;
72 return Tmp.str();
73}
74
75/// Run: module ::= toplevelentity*
76bool LLParser::Run(bool UpgradeDebugInfo,
77 DataLayoutCallbackTy DataLayoutCallback) {
78 // Prime the lexer.
79 Lex.Lex();
80
81 if (Context.shouldDiscardValueNames())
82 return error(
83 Lex.getLoc(),
84 "Can't read textual IR with a Context that discards named Values");
85
86 if (M) {
87 if (parseTargetDefinitions(DataLayoutCallback))
88 return true;
89 }
90
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
92 validateEndOfIndex();
93}
94
96 const SlotMapping *Slots) {
97 restoreParsingState(Slots);
98 Lex.Lex();
99
100 Type *Ty = nullptr;
101 if (parseType(Ty) || parseConstantValue(Ty, C))
102 return true;
103 if (Lex.getKind() != lltok::Eof)
104 return error(Lex.getLoc(), "expected end of string");
105 return false;
106}
107
109 const SlotMapping *Slots) {
110 restoreParsingState(Slots);
111 Lex.Lex();
112
113 Read = 0;
114 SMLoc Start = Lex.getLoc();
115 Ty = nullptr;
116 if (parseType(Ty))
117 return true;
118 SMLoc End = Lex.getLoc();
119 Read = End.getPointer() - Start.getPointer();
120
121 return false;
122}
123
125 const SlotMapping *Slots) {
126 restoreParsingState(Slots);
127 Lex.Lex();
128
129 Read = 0;
130 SMLoc Start = Lex.getLoc();
131 Result = nullptr;
132 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
133 SMLoc End = Lex.getLoc();
134 Read = End.getPointer() - Start.getPointer();
135
136 return Status;
137}
138
139void LLParser::restoreParsingState(const SlotMapping *Slots) {
140 if (!Slots)
141 return;
142 NumberedVals = Slots->GlobalValues;
143 NumberedMetadata = Slots->MetadataNodes;
144 for (const auto &I : Slots->NamedTypes)
145 NamedTypes.insert(
146 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
147 for (const auto &I : Slots->Types)
148 NumberedTypes.insert(
149 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
150}
151
153 // White-list intrinsics that are safe to drop.
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
156 return;
157
159 for (Value *V : II->args())
160 if (auto *MV = dyn_cast<MetadataAsValue>(V))
161 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
162 if (MD->isTemporary())
163 MVs.push_back(MV);
164
165 if (!MVs.empty()) {
166 assert(II->use_empty() && "Cannot have uses");
167 II->eraseFromParent();
168
169 // Also remove no longer used MetadataAsValue wrappers.
170 for (MetadataAsValue *MV : MVs)
171 if (MV->use_empty())
172 delete MV;
173 }
174}
175
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
178 for (Function &F : *M) {
179 F.eraseMetadataIf(Pred);
180 for (Instruction &I : make_early_inc_range(instructions(F))) {
181 I.eraseMetadataIf(Pred);
182
183 if (auto *II = dyn_cast<IntrinsicInst>(&I))
185 }
186 }
187
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
190
191 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
192 // Check whether there is only a single use left, which would be in our
193 // own NumberedMetadata.
194 if (Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(ID);
196 ForwardRefMDNodes.erase(ID);
197 }
198 }
199}
200
201/// validateEndOfModule - Do final validity and basic correctness checks at the
202/// end of the module.
203bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
204 if (!M)
205 return false;
206
207 // We should have already returned an error if we observed both intrinsics and
208 // records in this IR.
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
211
212 // Handle any function attribute group forward references.
213 for (const auto &RAG : ForwardRefAttrGroups) {
214 Value *V = RAG.first;
215 const std::vector<unsigned> &Attrs = RAG.second;
216 AttrBuilder B(Context);
217
218 for (const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(Attr);
220 if (R != NumberedAttrBuilders.end())
221 B.merge(R->second);
222 }
223
224 if (Function *Fn = dyn_cast<Function>(V)) {
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(Context);
228
229 FnAttrs.merge(B);
230
231 // If the alignment was parsed as an attribute, move to the alignment
232 // field.
233 if (MaybeAlign A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*A);
235 FnAttrs.removeAttribute(Attribute::Alignment);
236 }
237
238 AS = AS.addFnAttributes(Context, FnAttrs);
239 Fn->setAttributes(AS);
240 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(Context);
244 FnAttrs.merge(B);
245 AS = AS.addFnAttributes(Context, FnAttrs);
246 CI->setAttributes(AS);
247 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
248 AttributeList AS = II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(Context);
251 FnAttrs.merge(B);
252 AS = AS.addFnAttributes(Context, FnAttrs);
253 II->setAttributes(AS);
254 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(Context);
258 FnAttrs.merge(B);
259 AS = AS.addFnAttributes(Context, FnAttrs);
260 CBI->setAttributes(AS);
261 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
262 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
263 Attrs.merge(B);
264 GV->setAttributes(AttributeSet::get(Context,Attrs));
265 } else {
266 llvm_unreachable("invalid object with forward attribute group reference");
267 }
268 }
269
270 // If there are entries in ForwardRefBlockAddresses at this point, the
271 // function was never defined.
272 if (!ForwardRefBlockAddresses.empty())
273 return error(ForwardRefBlockAddresses.begin()->first.Loc,
274 "expected function name in blockaddress");
275
276 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV = nullptr;
279 if (GVRef.Kind == ValID::t_GlobalName) {
280 GV = M->getNamedValue(GVRef.StrVal);
281 } else {
282 GV = NumberedVals.get(GVRef.UIntVal);
283 }
284
285 if (!GV)
286 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
287 "' referenced by dso_local_equivalent");
288
289 if (!GV->getValueType()->isFunctionTy())
290 return error(GVRef.Loc,
291 "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
293
294 auto *Equiv = DSOLocalEquivalent::get(GV);
295 FwdRef->replaceAllUsesWith(Equiv);
296 FwdRef->eraseFromParent();
297 return false;
298 };
299
300 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
301 // point, they are references after the function was defined. Resolve those
302 // now.
303 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 return true;
306 }
307 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
309 return true;
310 }
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
313
314 for (const auto &NT : NumberedTypes)
315 if (NT.second.second.isValid())
316 return error(NT.second.second,
317 "use of undefined type '%" + Twine(NT.first) + "'");
318
319 for (const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(TypeInfo.second,
322 "use of undefined type named '" + Name + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 // Automatically create declarations for intrinsics. Intrinsics can only
333 // be called directly, so the call function type directly determines the
334 // declaration function type.
335 //
336 // Additionally, automatically add the required mangling suffix to the
337 // intrinsic name. This means that we may replace a single forward
338 // declaration with multiple functions here.
339 for (Use &U : make_early_inc_range(Info.first->uses())) {
340 auto *CB = dyn_cast<CallBase>(U.getUser());
341 if (!CB || !CB->isCallee(&U))
342 return error(Info.second, "intrinsic can only be used as callee");
343
344 std::string ErrorMsg;
345 raw_string_ostream ErrorOS(ErrorMsg);
346
347 SmallVector<Type *> OverloadTys;
348 if (IID != Intrinsic::not_intrinsic &&
349 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
350 ErrorOS)) {
351 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
352 } else {
353 // Try to upgrade the intrinsic.
354 Function *TmpF = Function::Create(CB->getFunctionType(),
356 Function *NewF = nullptr;
357 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
358 if (IID == Intrinsic::not_intrinsic)
359 return error(Info.second, "unknown intrinsic '" + Name + "'");
360 return error(Info.second, ErrorMsg);
361 }
362
363 U.set(TmpF);
364 UpgradeIntrinsicCall(CB, NewF);
365 if (TmpF->use_empty())
366 TmpF->eraseFromParent();
367 }
368 }
369
370 Info.first->eraseFromParent();
371 ForwardRefVals.erase(Name);
372 continue;
373 }
374
375 // If incomplete IR is allowed, also add declarations for
376 // non-intrinsics.
378 continue;
379
380 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
381 FunctionType *FTy = nullptr;
382 for (Use &U : V->uses()) {
383 auto *CB = dyn_cast<CallBase>(U.getUser());
384 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
385 return nullptr;
386 FTy = CB->getFunctionType();
387 }
388 return FTy;
389 };
390
391 // First check whether this global is only used in calls with the same
392 // type, in which case we'll insert a function. Otherwise, fall back to
393 // using a dummy i8 type.
394 Type *Ty = GetCommonFunctionType(Info.first);
395 if (!Ty)
396 Ty = Type::getInt8Ty(Context);
397
398 GlobalValue *GV;
399 if (auto *FTy = dyn_cast<FunctionType>(Ty))
401 else
402 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
404 /*Initializer*/ nullptr, Name);
405 Info.first->replaceAllUsesWith(GV);
406 Info.first->eraseFromParent();
407 ForwardRefVals.erase(Name);
408 }
409
410 if (!ForwardRefVals.empty())
411 return error(ForwardRefVals.begin()->second.second,
412 "use of undefined value '@" + ForwardRefVals.begin()->first +
413 "'");
414
415 if (!ForwardRefValIDs.empty())
416 return error(ForwardRefValIDs.begin()->second.second,
417 "use of undefined value '@" +
418 Twine(ForwardRefValIDs.begin()->first) + "'");
419
420 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
421 dropUnknownMetadataReferences();
422
423 if (!ForwardRefMDNodes.empty())
424 return error(ForwardRefMDNodes.begin()->second.second,
425 "use of undefined metadata '!" +
426 Twine(ForwardRefMDNodes.begin()->first) + "'");
427
428 // Resolve metadata cycles.
429 for (auto &N : NumberedMetadata) {
430 if (N.second && !N.second->isResolved())
431 N.second->resolveCycles();
432 }
433
435 NewDistinctSPs.clear();
436
437 for (auto *Inst : InstsWithTBAATag) {
438 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
439 // With incomplete IR, the tbaa metadata may have been dropped.
441 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
442 if (MD) {
443 auto *UpgradedMD = UpgradeTBAANode(*MD);
444 if (MD != UpgradedMD)
445 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
446 }
447 }
448
449 // Look for intrinsic functions and CallInst that need to be upgraded. We use
450 // make_early_inc_range here because we may remove some functions.
451 for (Function &F : llvm::make_early_inc_range(*M))
453
454 if (UpgradeDebugInfo)
456
461
462 if (!Slots)
463 return false;
464 // Initialize the slot mapping.
465 // Because by this point we've parsed and validated everything, we can "steal"
466 // the mapping from LLParser as it doesn't need it anymore.
467 Slots->GlobalValues = std::move(NumberedVals);
468 Slots->MetadataNodes = std::move(NumberedMetadata);
469 for (const auto &I : NamedTypes)
470 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
471 for (const auto &I : NumberedTypes)
472 Slots->Types.insert(std::make_pair(I.first, I.second.first));
473
474 return false;
475}
476
477/// Do final validity and basic correctness checks at the end of the index.
478bool LLParser::validateEndOfIndex() {
479 if (!Index)
480 return false;
481
482 if (!ForwardRefValueInfos.empty())
483 return error(ForwardRefValueInfos.begin()->second.front().second,
484 "use of undefined summary '^" +
485 Twine(ForwardRefValueInfos.begin()->first) + "'");
486
487 if (!ForwardRefAliasees.empty())
488 return error(ForwardRefAliasees.begin()->second.front().second,
489 "use of undefined summary '^" +
490 Twine(ForwardRefAliasees.begin()->first) + "'");
491
492 if (!ForwardRefTypeIds.empty())
493 return error(ForwardRefTypeIds.begin()->second.front().second,
494 "use of undefined type id summary '^" +
495 Twine(ForwardRefTypeIds.begin()->first) + "'");
496
497 return false;
498}
499
500//===----------------------------------------------------------------------===//
501// Top-Level Entities
502//===----------------------------------------------------------------------===//
503
504bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
505 // Delay parsing of the data layout string until the target triple is known.
506 // Then, pass both the the target triple and the tentative data layout string
507 // to DataLayoutCallback, allowing to override the DL string.
508 // This enables importing modules with invalid DL strings.
509 std::string TentativeDLStr = M->getDataLayoutStr();
510 LocTy DLStrLoc;
511
512 bool Done = false;
513 while (!Done) {
514 switch (Lex.getKind()) {
515 case lltok::kw_target:
516 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
517 return true;
518 break;
520 if (parseSourceFileName())
521 return true;
522 break;
523 default:
524 Done = true;
525 }
526 }
527 // Run the override callback to potentially change the data layout string, and
528 // parse the data layout string.
529 if (auto LayoutOverride =
530 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
531 TentativeDLStr = *LayoutOverride;
532 DLStrLoc = {};
533 }
534 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
535 if (!MaybeDL)
536 return error(DLStrLoc, toString(MaybeDL.takeError()));
537 M->setDataLayout(MaybeDL.get());
538 return false;
539}
540
541bool LLParser::parseTopLevelEntities() {
542 // If there is no Module, then parse just the summary index entries.
543 if (!M) {
544 while (true) {
545 switch (Lex.getKind()) {
546 case lltok::Eof:
547 return false;
548 case lltok::SummaryID:
549 if (parseSummaryEntry())
550 return true;
551 break;
553 if (parseSourceFileName())
554 return true;
555 break;
556 default:
557 // Skip everything else
558 Lex.Lex();
559 }
560 }
561 }
562 while (true) {
563 switch (Lex.getKind()) {
564 default:
565 return tokError("expected top-level entity");
566 case lltok::Eof: return false;
568 if (parseDeclare())
569 return true;
570 break;
571 case lltok::kw_define:
572 if (parseDefine())
573 return true;
574 break;
575 case lltok::kw_module:
576 if (parseModuleAsm())
577 return true;
578 break;
580 if (parseUnnamedType())
581 return true;
582 break;
583 case lltok::LocalVar:
584 if (parseNamedType())
585 return true;
586 break;
587 case lltok::GlobalID:
588 if (parseUnnamedGlobal())
589 return true;
590 break;
591 case lltok::GlobalVar:
592 if (parseNamedGlobal())
593 return true;
594 break;
595 case lltok::ComdatVar: if (parseComdat()) return true; break;
596 case lltok::exclaim:
597 if (parseStandaloneMetadata())
598 return true;
599 break;
600 case lltok::SummaryID:
601 if (parseSummaryEntry())
602 return true;
603 break;
605 if (parseNamedMetadata())
606 return true;
607 break;
609 if (parseUnnamedAttrGrp())
610 return true;
611 break;
613 if (parseUseListOrder())
614 return true;
615 break;
617 if (parseUseListOrderBB())
618 return true;
619 break;
620 }
621 }
622}
623
624/// toplevelentity
625/// ::= 'module' 'asm' STRINGCONSTANT
626bool LLParser::parseModuleAsm() {
627 assert(Lex.getKind() == lltok::kw_module);
628 Lex.Lex();
629
630 std::string AsmStr;
631 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
632 parseStringConstant(AsmStr))
633 return true;
634
635 M->appendModuleInlineAsm(AsmStr);
636 return false;
637}
638
639/// toplevelentity
640/// ::= 'target' 'triple' '=' STRINGCONSTANT
641/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
642bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
643 LocTy &DLStrLoc) {
644 assert(Lex.getKind() == lltok::kw_target);
645 std::string Str;
646 switch (Lex.Lex()) {
647 default:
648 return tokError("unknown target property");
649 case lltok::kw_triple:
650 Lex.Lex();
651 if (parseToken(lltok::equal, "expected '=' after target triple") ||
652 parseStringConstant(Str))
653 return true;
654 M->setTargetTriple(Triple(std::move(Str)));
655 return false;
657 Lex.Lex();
658 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
659 return true;
660 DLStrLoc = Lex.getLoc();
661 if (parseStringConstant(TentativeDLStr))
662 return true;
663 return false;
664 }
665}
666
667/// toplevelentity
668/// ::= 'source_filename' '=' STRINGCONSTANT
669bool LLParser::parseSourceFileName() {
670 assert(Lex.getKind() == lltok::kw_source_filename);
671 Lex.Lex();
672 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
673 parseStringConstant(SourceFileName))
674 return true;
675 if (M)
676 M->setSourceFileName(SourceFileName);
677 return false;
678}
679
680/// parseUnnamedType:
681/// ::= LocalVarID '=' 'type' type
682bool LLParser::parseUnnamedType() {
683 LocTy TypeLoc = Lex.getLoc();
684 unsigned TypeID = Lex.getUIntVal();
685 Lex.Lex(); // eat LocalVarID;
686
687 if (parseToken(lltok::equal, "expected '=' after name") ||
688 parseToken(lltok::kw_type, "expected 'type' after '='"))
689 return true;
690
691 Type *Result = nullptr;
692 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
693 return true;
694
695 if (!isa<StructType>(Result)) {
696 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
697 if (Entry.first)
698 return error(TypeLoc, "non-struct types may not be recursive");
699 Entry.first = Result;
700 Entry.second = SMLoc();
701 }
702
703 return false;
704}
705
706/// toplevelentity
707/// ::= LocalVar '=' 'type' type
708bool LLParser::parseNamedType() {
709 std::string Name = Lex.getStrVal();
710 LocTy NameLoc = Lex.getLoc();
711 Lex.Lex(); // eat LocalVar.
712
713 if (parseToken(lltok::equal, "expected '=' after name") ||
714 parseToken(lltok::kw_type, "expected 'type' after name"))
715 return true;
716
717 Type *Result = nullptr;
718 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
719 return true;
720
721 if (!isa<StructType>(Result)) {
722 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
723 if (Entry.first)
724 return error(NameLoc, "non-struct types may not be recursive");
725 Entry.first = Result;
726 Entry.second = SMLoc();
727 }
728
729 return false;
730}
731
732/// toplevelentity
733/// ::= 'declare' FunctionHeader
734bool LLParser::parseDeclare() {
735 assert(Lex.getKind() == lltok::kw_declare);
736 Lex.Lex();
737
738 std::vector<std::pair<unsigned, MDNode *>> MDs;
739 while (Lex.getKind() == lltok::MetadataVar) {
740 unsigned MDK;
741 MDNode *N;
742 if (parseMetadataAttachment(MDK, N))
743 return true;
744 MDs.push_back({MDK, N});
745 }
746
747 Function *F;
748 unsigned FunctionNumber = -1;
749 SmallVector<unsigned> UnnamedArgNums;
750 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
751 return true;
752 for (auto &MD : MDs)
753 F->addMetadata(MD.first, *MD.second);
754 return false;
755}
756
757/// toplevelentity
758/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
759bool LLParser::parseDefine() {
760 assert(Lex.getKind() == lltok::kw_define);
761
762 FileLoc FunctionStart = getTokLineColumnPos();
763 Lex.Lex();
764
765 Function *F;
766 unsigned FunctionNumber = -1;
767 SmallVector<unsigned> UnnamedArgNums;
768 bool RetValue =
769 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
770 parseOptionalFunctionMetadata(*F) ||
771 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
772 if (ParserContext)
773 ParserContext->addFunctionLocation(
774 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
775
776 return RetValue;
777}
778
779/// parseGlobalType
780/// ::= 'constant'
781/// ::= 'global'
782bool LLParser::parseGlobalType(bool &IsConstant) {
783 if (Lex.getKind() == lltok::kw_constant)
784 IsConstant = true;
785 else if (Lex.getKind() == lltok::kw_global)
786 IsConstant = false;
787 else {
788 IsConstant = false;
789 return tokError("expected 'global' or 'constant'");
790 }
791 Lex.Lex();
792 return false;
793}
794
795bool LLParser::parseOptionalUnnamedAddr(
796 GlobalVariable::UnnamedAddr &UnnamedAddr) {
797 if (EatIfPresent(lltok::kw_unnamed_addr))
799 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
801 else
802 UnnamedAddr = GlobalValue::UnnamedAddr::None;
803 return false;
804}
805
806/// parseUnnamedGlobal:
807/// OptionalVisibility (ALIAS | IFUNC) ...
808/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
809/// OptionalDLLStorageClass
810/// ... -> global variable
811/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
812/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
813/// OptionalVisibility
814/// OptionalDLLStorageClass
815/// ... -> global variable
816bool LLParser::parseUnnamedGlobal() {
817 unsigned VarID;
818 std::string Name;
819 LocTy NameLoc = Lex.getLoc();
820
821 // Handle the GlobalID form.
822 if (Lex.getKind() == lltok::GlobalID) {
823 VarID = Lex.getUIntVal();
824 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
825 return true;
826
827 Lex.Lex(); // eat GlobalID;
828 if (parseToken(lltok::equal, "expected '=' after name"))
829 return true;
830 } else {
831 VarID = NumberedVals.getNext();
832 }
833
834 bool HasLinkage;
835 unsigned Linkage, Visibility, DLLStorageClass;
836 bool DSOLocal;
838 GlobalVariable::UnnamedAddr UnnamedAddr;
839 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
840 DSOLocal) ||
841 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
842 return true;
843
844 switch (Lex.getKind()) {
845 default:
846 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
847 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
848 case lltok::kw_alias:
849 case lltok::kw_ifunc:
850 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
851 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
852 }
853}
854
855/// parseNamedGlobal:
856/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
857/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
858/// OptionalVisibility OptionalDLLStorageClass
859/// ... -> global variable
860bool LLParser::parseNamedGlobal() {
861 assert(Lex.getKind() == lltok::GlobalVar);
862 LocTy NameLoc = Lex.getLoc();
863 std::string Name = Lex.getStrVal();
864 Lex.Lex();
865
866 bool HasLinkage;
867 unsigned Linkage, Visibility, DLLStorageClass;
868 bool DSOLocal;
870 GlobalVariable::UnnamedAddr UnnamedAddr;
871 if (parseToken(lltok::equal, "expected '=' in global variable") ||
872 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
873 DSOLocal) ||
874 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
875 return true;
876
877 switch (Lex.getKind()) {
878 default:
879 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
880 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
881 case lltok::kw_alias:
882 case lltok::kw_ifunc:
883 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
884 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
885 }
886}
887
888bool LLParser::parseComdat() {
889 assert(Lex.getKind() == lltok::ComdatVar);
890 std::string Name = Lex.getStrVal();
891 LocTy NameLoc = Lex.getLoc();
892 Lex.Lex();
893
894 if (parseToken(lltok::equal, "expected '=' here"))
895 return true;
896
897 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
898 return tokError("expected comdat type");
899
901 switch (Lex.getKind()) {
902 default:
903 return tokError("unknown selection kind");
904 case lltok::kw_any:
905 SK = Comdat::Any;
906 break;
909 break;
911 SK = Comdat::Largest;
912 break;
915 break;
917 SK = Comdat::SameSize;
918 break;
919 }
920 Lex.Lex();
921
922 // See if the comdat was forward referenced, if so, use the comdat.
923 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
924 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
925 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
926 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
927
928 Comdat *C;
929 if (I != ComdatSymTab.end())
930 C = &I->second;
931 else
932 C = M->getOrInsertComdat(Name);
933 C->setSelectionKind(SK);
934
935 return false;
936}
937
938// MDString:
939// ::= '!' STRINGCONSTANT
940bool LLParser::parseMDString(MDString *&Result) {
941 std::string Str;
942 if (parseStringConstant(Str))
943 return true;
944 Result = MDString::get(Context, Str);
945 return false;
946}
947
948// MDNode:
949// ::= '!' MDNodeNumber
950bool LLParser::parseMDNodeID(MDNode *&Result) {
951 // !{ ..., !42, ... }
952 LocTy IDLoc = Lex.getLoc();
953 unsigned MID = 0;
954 if (parseUInt32(MID))
955 return true;
956
957 // If not a forward reference, just return it now.
958 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
959 if (!Inserted) {
960 Result = It->second;
961 return false;
962 }
963
964 // Otherwise, create MDNode forward reference.
965 auto &FwdRef = ForwardRefMDNodes[MID];
966 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
967
968 Result = FwdRef.first.get();
969 It->second.reset(Result);
970 return false;
971}
972
973/// parseNamedMetadata:
974/// !foo = !{ !1, !2 }
975bool LLParser::parseNamedMetadata() {
976 assert(Lex.getKind() == lltok::MetadataVar);
977 std::string Name = Lex.getStrVal();
978 Lex.Lex();
979
980 if (parseToken(lltok::equal, "expected '=' here") ||
981 parseToken(lltok::exclaim, "Expected '!' here") ||
982 parseToken(lltok::lbrace, "Expected '{' here"))
983 return true;
984
985 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
986 if (Lex.getKind() != lltok::rbrace)
987 do {
988 MDNode *N = nullptr;
989 // parse DIExpressions inline as a special case. They are still MDNodes,
990 // so they can still appear in named metadata. Remove this logic if they
991 // become plain Metadata.
992 if (Lex.getKind() == lltok::MetadataVar &&
993 Lex.getStrVal() == "DIExpression") {
994 if (parseDIExpression(N, /*IsDistinct=*/false))
995 return true;
996 // DIArgLists should only appear inline in a function, as they may
997 // contain LocalAsMetadata arguments which require a function context.
998 } else if (Lex.getKind() == lltok::MetadataVar &&
999 Lex.getStrVal() == "DIArgList") {
1000 return tokError("found DIArgList outside of function");
1001 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1002 parseMDNodeID(N)) {
1003 return true;
1004 }
1005 NMD->addOperand(N);
1006 } while (EatIfPresent(lltok::comma));
1007
1008 return parseToken(lltok::rbrace, "expected end of metadata node");
1009}
1010
1011/// parseStandaloneMetadata:
1012/// !42 = !{...}
1013bool LLParser::parseStandaloneMetadata() {
1014 assert(Lex.getKind() == lltok::exclaim);
1015 Lex.Lex();
1016 unsigned MetadataID = 0;
1017
1018 MDNode *Init;
1019 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1020 return true;
1021
1022 // Detect common error, from old metadata syntax.
1023 if (Lex.getKind() == lltok::Type)
1024 return tokError("unexpected type in metadata definition");
1025
1026 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1027 if (Lex.getKind() == lltok::MetadataVar) {
1028 if (parseSpecializedMDNode(Init, IsDistinct))
1029 return true;
1030 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1031 parseMDTuple(Init, IsDistinct))
1032 return true;
1033
1034 // See if this was forward referenced, if so, handle it.
1035 auto FI = ForwardRefMDNodes.find(MetadataID);
1036 if (FI != ForwardRefMDNodes.end()) {
1037 auto *ToReplace = FI->second.first.get();
1038 // DIAssignID has its own special forward-reference "replacement" for
1039 // attachments (the temporary attachments are never actually attached).
1040 if (isa<DIAssignID>(Init)) {
1041 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1042 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1043 "Inst unexpectedly already has DIAssignID attachment");
1044 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1045 }
1046 }
1047
1048 ToReplace->replaceAllUsesWith(Init);
1049 ForwardRefMDNodes.erase(FI);
1050
1051 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1052 } else {
1053 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1054 if (!Inserted)
1055 return tokError("Metadata id is already used");
1056 It->second.reset(Init);
1057 }
1058
1059 return false;
1060}
1061
1062// Skips a single module summary entry.
1063bool LLParser::skipModuleSummaryEntry() {
1064 // Each module summary entry consists of a tag for the entry
1065 // type, followed by a colon, then the fields which may be surrounded by
1066 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1067 // support is in place we will look for the tokens corresponding to the
1068 // expected tags.
1069 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1070 Lex.getKind() != lltok::kw_typeid &&
1071 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1072 Lex.getKind() != lltok::kw_flags && Lex.getKind() != lltok::kw_blockcount)
1073 return tokError("Expected 'gv', 'module', 'typeid', "
1074 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1075 "start of summary entry");
1076 if (Lex.getKind() == lltok::kw_flags)
1077 return parseSummaryIndexFlags();
1078 if (Lex.getKind() == lltok::kw_blockcount)
1079 return parseBlockCount();
1080 Lex.Lex();
1081 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1082 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1083 return true;
1084 // Now walk through the parenthesized entry, until the number of open
1085 // parentheses goes back down to 0 (the first '(' was parsed above).
1086 unsigned NumOpenParen = 1;
1087 do {
1088 switch (Lex.getKind()) {
1089 case lltok::lparen:
1090 NumOpenParen++;
1091 break;
1092 case lltok::rparen:
1093 NumOpenParen--;
1094 break;
1095 case lltok::Eof:
1096 return tokError("found end of file while parsing summary entry");
1097 default:
1098 // Skip everything in between parentheses.
1099 break;
1100 }
1101 Lex.Lex();
1102 } while (NumOpenParen > 0);
1103 return false;
1104}
1105
1106/// SummaryEntry
1107/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1108bool LLParser::parseSummaryEntry() {
1109 assert(Lex.getKind() == lltok::SummaryID);
1110 unsigned SummaryID = Lex.getUIntVal();
1111
1112 // For summary entries, colons should be treated as distinct tokens,
1113 // not an indication of the end of a label token.
1114 Lex.setIgnoreColonInIdentifiers(true);
1115
1116 Lex.Lex();
1117 if (parseToken(lltok::equal, "expected '=' here"))
1118 return true;
1119
1120 // If we don't have an index object, skip the summary entry.
1121 if (!Index)
1122 return skipModuleSummaryEntry();
1123
1124 bool result = false;
1125 switch (Lex.getKind()) {
1126 case lltok::kw_gv:
1127 result = parseGVEntry(SummaryID);
1128 break;
1129 case lltok::kw_module:
1130 result = parseModuleEntry(SummaryID);
1131 break;
1132 case lltok::kw_typeid:
1133 result = parseTypeIdEntry(SummaryID);
1134 break;
1136 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1137 break;
1138 case lltok::kw_flags:
1139 result = parseSummaryIndexFlags();
1140 break;
1142 result = parseBlockCount();
1143 break;
1144 default:
1145 result = error(Lex.getLoc(), "unexpected summary kind");
1146 break;
1147 }
1148 Lex.setIgnoreColonInIdentifiers(false);
1149 return result;
1150}
1151
1160
1161// If there was an explicit dso_local, update GV. In the absence of an explicit
1162// dso_local we keep the default value.
1163static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1164 if (DSOLocal)
1165 GV.setDSOLocal(true);
1166}
1167
1168/// parseAliasOrIFunc:
1169/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1170/// OptionalVisibility OptionalDLLStorageClass
1171/// OptionalThreadLocal OptionalUnnamedAddr
1172/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1173///
1174/// AliaseeOrResolver
1175/// ::= TypeAndValue
1176///
1177/// SymbolAttrs
1178/// ::= ',' 'partition' StringConstant
1179///
1180/// Everything through OptionalUnnamedAddr has already been parsed.
1181///
1182bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1183 LocTy NameLoc, unsigned L, unsigned Visibility,
1184 unsigned DLLStorageClass, bool DSOLocal,
1186 GlobalVariable::UnnamedAddr UnnamedAddr) {
1187 bool IsAlias;
1188 if (Lex.getKind() == lltok::kw_alias)
1189 IsAlias = true;
1190 else if (Lex.getKind() == lltok::kw_ifunc)
1191 IsAlias = false;
1192 else
1193 llvm_unreachable("Not an alias or ifunc!");
1194 Lex.Lex();
1195
1197
1198 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1199 return error(NameLoc, "invalid linkage type for alias");
1200
1201 if (!isValidVisibilityForLinkage(Visibility, L))
1202 return error(NameLoc,
1203 "symbol with local linkage must have default visibility");
1204
1205 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1206 return error(NameLoc,
1207 "symbol with local linkage cannot have a DLL storage class");
1208
1209 Type *Ty;
1210 LocTy ExplicitTypeLoc = Lex.getLoc();
1211 if (parseType(Ty) ||
1212 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1213 return true;
1214
1215 Constant *Aliasee;
1216 LocTy AliaseeLoc = Lex.getLoc();
1217 if (Lex.getKind() != lltok::kw_bitcast &&
1218 Lex.getKind() != lltok::kw_getelementptr &&
1219 Lex.getKind() != lltok::kw_addrspacecast &&
1220 Lex.getKind() != lltok::kw_inttoptr) {
1221 if (parseGlobalTypeAndValue(Aliasee))
1222 return true;
1223 } else {
1224 // The bitcast dest type is not present, it is implied by the dest type.
1225 ValID ID;
1226 if (parseValID(ID, /*PFS=*/nullptr))
1227 return true;
1228 if (ID.Kind != ValID::t_Constant)
1229 return error(AliaseeLoc, "invalid aliasee");
1230 Aliasee = ID.ConstantVal;
1231 }
1232
1233 Type *AliaseeType = Aliasee->getType();
1234 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1235 if (!PTy)
1236 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1237 unsigned AddrSpace = PTy->getAddressSpace();
1238
1239 GlobalValue *GVal = nullptr;
1240
1241 // See if the alias was forward referenced, if so, prepare to replace the
1242 // forward reference.
1243 if (!Name.empty()) {
1244 auto I = ForwardRefVals.find(Name);
1245 if (I != ForwardRefVals.end()) {
1246 GVal = I->second.first;
1247 ForwardRefVals.erase(Name);
1248 } else if (M->getNamedValue(Name)) {
1249 return error(NameLoc, "redefinition of global '@" + Name + "'");
1250 }
1251 } else {
1252 auto I = ForwardRefValIDs.find(NameID);
1253 if (I != ForwardRefValIDs.end()) {
1254 GVal = I->second.first;
1255 ForwardRefValIDs.erase(I);
1256 }
1257 }
1258
1259 // Okay, create the alias/ifunc but do not insert it into the module yet.
1260 std::unique_ptr<GlobalAlias> GA;
1261 std::unique_ptr<GlobalIFunc> GI;
1262 GlobalValue *GV;
1263 if (IsAlias) {
1264 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1265 /*Parent=*/nullptr));
1266 GV = GA.get();
1267 } else {
1268 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1269 /*Parent=*/nullptr));
1270 GV = GI.get();
1271 }
1272 GV->setThreadLocalMode(TLM);
1275 GV->setUnnamedAddr(UnnamedAddr);
1276 maybeSetDSOLocal(DSOLocal, *GV);
1277
1278 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1279 // Now parse them if there are any.
1280 while (Lex.getKind() == lltok::comma) {
1281 Lex.Lex();
1282
1283 if (Lex.getKind() == lltok::kw_partition) {
1284 Lex.Lex();
1285 GV->setPartition(Lex.getStrVal());
1286 if (parseToken(lltok::StringConstant, "expected partition string"))
1287 return true;
1288 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1289 if (parseGlobalObjectMetadataAttachment(*GI))
1290 return true;
1291 } else {
1292 return tokError("unknown alias or ifunc property!");
1293 }
1294 }
1295
1296 if (Name.empty())
1297 NumberedVals.add(NameID, GV);
1298
1299 if (GVal) {
1300 // Verify that types agree.
1301 if (GVal->getType() != GV->getType())
1302 return error(
1303 ExplicitTypeLoc,
1304 "forward reference and definition of alias have different types");
1305
1306 // If they agree, just RAUW the old value with the alias and remove the
1307 // forward ref info.
1308 GVal->replaceAllUsesWith(GV);
1309 GVal->eraseFromParent();
1310 }
1311
1312 // Insert into the module, we know its name won't collide now.
1313 if (IsAlias)
1314 M->insertAlias(GA.release());
1315 else
1316 M->insertIFunc(GI.release());
1317 assert(GV->getName() == Name && "Should not be a name conflict!");
1318
1319 return false;
1320}
1321
1322static bool isSanitizer(lltok::Kind Kind) {
1323 switch (Kind) {
1326 case lltok::kw_sanitize_memtag:
1328 return true;
1329 default:
1330 return false;
1331 }
1332}
1333
1334bool LLParser::parseSanitizer(GlobalVariable *GV) {
1335 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1337 if (GV->hasSanitizerMetadata())
1338 Meta = GV->getSanitizerMetadata();
1339
1340 switch (Lex.getKind()) {
1342 Meta.NoAddress = true;
1343 break;
1345 Meta.NoHWAddress = true;
1346 break;
1347 case lltok::kw_sanitize_memtag:
1348 Meta.Memtag = true;
1349 break;
1351 Meta.IsDynInit = true;
1352 break;
1353 default:
1354 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1355 }
1356 GV->setSanitizerMetadata(Meta);
1357 Lex.Lex();
1358 return false;
1359}
1360
1361/// parseGlobal
1362/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1363/// OptionalVisibility OptionalDLLStorageClass
1364/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1365/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1366/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1367/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1368/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1369/// Const OptionalAttrs
1370///
1371/// Everything up to and including OptionalUnnamedAddr has been parsed
1372/// already.
1373///
1374bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1375 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1376 unsigned Visibility, unsigned DLLStorageClass,
1377 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1378 GlobalVariable::UnnamedAddr UnnamedAddr) {
1379 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1380 return error(NameLoc,
1381 "symbol with local linkage must have default visibility");
1382
1383 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1384 return error(NameLoc,
1385 "symbol with local linkage cannot have a DLL storage class");
1386
1387 unsigned AddrSpace;
1388 bool IsConstant, IsExternallyInitialized;
1389 LocTy IsExternallyInitializedLoc;
1390 LocTy TyLoc;
1391
1392 Type *Ty = nullptr;
1393 if (parseOptionalAddrSpace(AddrSpace) ||
1394 parseOptionalToken(lltok::kw_externally_initialized,
1395 IsExternallyInitialized,
1396 &IsExternallyInitializedLoc) ||
1397 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1398 return true;
1399
1400 // If the linkage is specified and is external, then no initializer is
1401 // present.
1402 Constant *Init = nullptr;
1403 if (!HasLinkage ||
1406 if (parseGlobalValue(Ty, Init))
1407 return true;
1408 }
1409
1411 return error(TyLoc, "invalid type for global variable");
1412
1413 GlobalValue *GVal = nullptr;
1414
1415 // See if the global was forward referenced, if so, use the global.
1416 if (!Name.empty()) {
1417 auto I = ForwardRefVals.find(Name);
1418 if (I != ForwardRefVals.end()) {
1419 GVal = I->second.first;
1420 ForwardRefVals.erase(I);
1421 } else if (M->getNamedValue(Name)) {
1422 return error(NameLoc, "redefinition of global '@" + Name + "'");
1423 }
1424 } else {
1425 // Handle @"", where a name is syntactically specified, but semantically
1426 // missing.
1427 if (NameID == (unsigned)-1)
1428 NameID = NumberedVals.getNext();
1429
1430 auto I = ForwardRefValIDs.find(NameID);
1431 if (I != ForwardRefValIDs.end()) {
1432 GVal = I->second.first;
1433 ForwardRefValIDs.erase(I);
1434 }
1435 }
1436
1437 GlobalVariable *GV = new GlobalVariable(
1438 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1440
1441 if (Name.empty())
1442 NumberedVals.add(NameID, GV);
1443
1444 // Set the parsed properties on the global.
1445 if (Init)
1446 GV->setInitializer(Init);
1447 GV->setConstant(IsConstant);
1449 maybeSetDSOLocal(DSOLocal, *GV);
1452 GV->setExternallyInitialized(IsExternallyInitialized);
1453 GV->setThreadLocalMode(TLM);
1454 GV->setUnnamedAddr(UnnamedAddr);
1455
1456 if (GVal) {
1457 if (GVal->getAddressSpace() != AddrSpace)
1458 return error(
1459 TyLoc,
1460 "forward reference and definition of global have different types");
1461
1462 GVal->replaceAllUsesWith(GV);
1463 GVal->eraseFromParent();
1464 }
1465
1466 // parse attributes on the global.
1467 while (Lex.getKind() == lltok::comma) {
1468 Lex.Lex();
1469
1470 if (Lex.getKind() == lltok::kw_section) {
1471 Lex.Lex();
1472 GV->setSection(Lex.getStrVal());
1473 if (parseToken(lltok::StringConstant, "expected global section string"))
1474 return true;
1475 } else if (Lex.getKind() == lltok::kw_partition) {
1476 Lex.Lex();
1477 GV->setPartition(Lex.getStrVal());
1478 if (parseToken(lltok::StringConstant, "expected partition string"))
1479 return true;
1480 } else if (Lex.getKind() == lltok::kw_align) {
1481 MaybeAlign Alignment;
1482 if (parseOptionalAlignment(Alignment))
1483 return true;
1484 if (Alignment)
1485 GV->setAlignment(*Alignment);
1486 } else if (Lex.getKind() == lltok::kw_code_model) {
1488 if (parseOptionalCodeModel(CodeModel))
1489 return true;
1490 GV->setCodeModel(CodeModel);
1491 } else if (Lex.getKind() == lltok::MetadataVar) {
1492 if (parseGlobalObjectMetadataAttachment(*GV))
1493 return true;
1494 } else if (isSanitizer(Lex.getKind())) {
1495 if (parseSanitizer(GV))
1496 return true;
1497 } else {
1498 Comdat *C;
1499 if (parseOptionalComdat(Name, C))
1500 return true;
1501 if (C)
1502 GV->setComdat(C);
1503 else
1504 return tokError("unknown global variable property!");
1505 }
1506 }
1507
1508 AttrBuilder Attrs(M->getContext());
1509 LocTy BuiltinLoc;
1510 std::vector<unsigned> FwdRefAttrGrps;
1511 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1512 return true;
1513 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1514 GV->setAttributes(AttributeSet::get(Context, Attrs));
1515 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1516 }
1517
1518 return false;
1519}
1520
1521/// parseUnnamedAttrGrp
1522/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1523bool LLParser::parseUnnamedAttrGrp() {
1524 assert(Lex.getKind() == lltok::kw_attributes);
1525 LocTy AttrGrpLoc = Lex.getLoc();
1526 Lex.Lex();
1527
1528 if (Lex.getKind() != lltok::AttrGrpID)
1529 return tokError("expected attribute group id");
1530
1531 unsigned VarID = Lex.getUIntVal();
1532 std::vector<unsigned> unused;
1533 LocTy BuiltinLoc;
1534 Lex.Lex();
1535
1536 if (parseToken(lltok::equal, "expected '=' here") ||
1537 parseToken(lltok::lbrace, "expected '{' here"))
1538 return true;
1539
1540 auto R = NumberedAttrBuilders.find(VarID);
1541 if (R == NumberedAttrBuilders.end())
1542 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1543
1544 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1545 parseToken(lltok::rbrace, "expected end of attribute group"))
1546 return true;
1547
1548 if (!R->second.hasAttributes())
1549 return error(AttrGrpLoc, "attribute group has no attributes");
1550
1551 return false;
1552}
1553
1555 switch (Kind) {
1556#define GET_ATTR_NAMES
1557#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1558 case lltok::kw_##DISPLAY_NAME: \
1559 return Attribute::ENUM_NAME;
1560#include "llvm/IR/Attributes.inc"
1561 default:
1562 return Attribute::None;
1563 }
1564}
1565
1566bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1567 bool InAttrGroup) {
1568 if (Attribute::isTypeAttrKind(Attr))
1569 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1570
1571 switch (Attr) {
1572 case Attribute::Alignment: {
1573 MaybeAlign Alignment;
1574 if (InAttrGroup) {
1575 uint32_t Value = 0;
1576 Lex.Lex();
1577 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1578 return true;
1579 Alignment = Align(Value);
1580 } else {
1581 if (parseOptionalAlignment(Alignment, true))
1582 return true;
1583 }
1584 B.addAlignmentAttr(Alignment);
1585 return false;
1586 }
1587 case Attribute::StackAlignment: {
1588 unsigned Alignment;
1589 if (InAttrGroup) {
1590 Lex.Lex();
1591 if (parseToken(lltok::equal, "expected '=' here") ||
1592 parseUInt32(Alignment))
1593 return true;
1594 } else {
1595 if (parseOptionalStackAlignment(Alignment))
1596 return true;
1597 }
1598 B.addStackAlignmentAttr(Alignment);
1599 return false;
1600 }
1601 case Attribute::AllocSize: {
1602 unsigned ElemSizeArg;
1603 std::optional<unsigned> NumElemsArg;
1604 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1605 return true;
1606 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1607 return false;
1608 }
1609 case Attribute::VScaleRange: {
1610 unsigned MinValue, MaxValue;
1611 if (parseVScaleRangeArguments(MinValue, MaxValue))
1612 return true;
1613 B.addVScaleRangeAttr(MinValue,
1614 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1615 return false;
1616 }
1617 case Attribute::Dereferenceable: {
1618 std::optional<uint64_t> Bytes;
1619 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1620 return true;
1621 assert(Bytes.has_value());
1622 B.addDereferenceableAttr(Bytes.value());
1623 return false;
1624 }
1625 case Attribute::DeadOnReturn: {
1626 std::optional<uint64_t> Bytes;
1627 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1628 /*ErrorNoBytes=*/false))
1629 return true;
1630 if (Bytes.has_value()) {
1631 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1632 } else {
1633 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1634 }
1635 return false;
1636 }
1637 case Attribute::DereferenceableOrNull: {
1638 std::optional<uint64_t> Bytes;
1639 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1640 return true;
1641 assert(Bytes.has_value());
1642 B.addDereferenceableOrNullAttr(Bytes.value());
1643 return false;
1644 }
1645 case Attribute::UWTable: {
1647 if (parseOptionalUWTableKind(Kind))
1648 return true;
1649 B.addUWTableAttr(Kind);
1650 return false;
1651 }
1652 case Attribute::AllocKind: {
1654 if (parseAllocKind(Kind))
1655 return true;
1656 B.addAllocKindAttr(Kind);
1657 return false;
1658 }
1659 case Attribute::Memory: {
1660 std::optional<MemoryEffects> ME = parseMemoryAttr();
1661 if (!ME)
1662 return true;
1663 B.addMemoryAttr(*ME);
1664 return false;
1665 }
1666 case Attribute::DenormalFPEnv: {
1667 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1668 if (!Mode)
1669 return true;
1670
1671 B.addDenormalFPEnvAttr(*Mode);
1672 return false;
1673 }
1674 case Attribute::NoFPClass: {
1675 if (FPClassTest NoFPClass =
1676 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1677 B.addNoFPClassAttr(NoFPClass);
1678 return false;
1679 }
1680
1681 return true;
1682 }
1683 case Attribute::Range:
1684 return parseRangeAttr(B);
1685 case Attribute::Initializes:
1686 return parseInitializesAttr(B);
1687 case Attribute::Captures:
1688 return parseCapturesAttr(B);
1689 default:
1690 B.addAttribute(Attr);
1691 Lex.Lex();
1692 return false;
1693 }
1694}
1695
1697 switch (Kind) {
1698 case lltok::kw_readnone:
1699 ME &= MemoryEffects::none();
1700 return true;
1701 case lltok::kw_readonly:
1703 return true;
1704 case lltok::kw_writeonly:
1706 return true;
1709 return true;
1712 return true;
1715 return true;
1716 default:
1717 return false;
1718 }
1719}
1720
1721/// parseFnAttributeValuePairs
1722/// ::= <attr> | <attr> '=' <value>
1723bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1724 std::vector<unsigned> &FwdRefAttrGrps,
1725 bool InAttrGrp, LocTy &BuiltinLoc) {
1726 bool HaveError = false;
1727
1728 B.clear();
1729
1731 while (true) {
1732 lltok::Kind Token = Lex.getKind();
1733 if (Token == lltok::rbrace)
1734 break; // Finished.
1735
1736 if (Token == lltok::StringConstant) {
1737 if (parseStringAttribute(B))
1738 return true;
1739 continue;
1740 }
1741
1742 if (Token == lltok::AttrGrpID) {
1743 // Allow a function to reference an attribute group:
1744 //
1745 // define void @foo() #1 { ... }
1746 if (InAttrGrp) {
1747 HaveError |= error(
1748 Lex.getLoc(),
1749 "cannot have an attribute group reference in an attribute group");
1750 } else {
1751 // Save the reference to the attribute group. We'll fill it in later.
1752 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1753 }
1754 Lex.Lex();
1755 continue;
1756 }
1757
1758 SMLoc Loc = Lex.getLoc();
1759 if (Token == lltok::kw_builtin)
1760 BuiltinLoc = Loc;
1761
1762 if (upgradeMemoryAttr(ME, Token)) {
1763 Lex.Lex();
1764 continue;
1765 }
1766
1768 if (Attr == Attribute::None) {
1769 if (!InAttrGrp)
1770 break;
1771 return error(Lex.getLoc(), "unterminated attribute group");
1772 }
1773
1774 if (parseEnumAttribute(Attr, B, InAttrGrp))
1775 return true;
1776
1777 // As a hack, we allow function alignment to be initially parsed as an
1778 // attribute on a function declaration/definition or added to an attribute
1779 // group and later moved to the alignment field.
1780 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1781 HaveError |= error(Loc, "this attribute does not apply to functions");
1782 }
1783
1784 if (ME != MemoryEffects::unknown())
1785 B.addMemoryAttr(ME);
1786 return HaveError;
1787}
1788
1789//===----------------------------------------------------------------------===//
1790// GlobalValue Reference/Resolution Routines.
1791//===----------------------------------------------------------------------===//
1792
1794 // The used global type does not matter. We will later RAUW it with a
1795 // global/function of the correct type.
1796 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1799 PTy->getAddressSpace());
1800}
1801
1802Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1803 Value *Val) {
1804 Type *ValTy = Val->getType();
1805 if (ValTy == Ty)
1806 return Val;
1807 if (Ty->isLabelTy())
1808 error(Loc, "'" + Name + "' is not a basic block");
1809 else
1810 error(Loc, "'" + Name + "' defined with type '" +
1811 getTypeString(Val->getType()) + "' but expected '" +
1812 getTypeString(Ty) + "'");
1813 return nullptr;
1814}
1815
1816/// getGlobalVal - Get a value with the specified name or ID, creating a
1817/// forward reference record if needed. This can return null if the value
1818/// exists but does not have the right type.
1819GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1820 LocTy Loc) {
1822 if (!PTy) {
1823 error(Loc, "global variable reference must have pointer type");
1824 return nullptr;
1825 }
1826
1827 // Look this name up in the normal function symbol table.
1828 GlobalValue *Val =
1829 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1830
1831 // If this is a forward reference for the value, see if we already created a
1832 // forward ref record.
1833 if (!Val) {
1834 auto I = ForwardRefVals.find(Name);
1835 if (I != ForwardRefVals.end())
1836 Val = I->second.first;
1837 }
1838
1839 // If we have the value in the symbol table or fwd-ref table, return it.
1840 if (Val)
1842 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1843
1844 // Otherwise, create a new forward reference for this value and remember it.
1845 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1846 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1847 return FwdVal;
1848}
1849
1850GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1852 if (!PTy) {
1853 error(Loc, "global variable reference must have pointer type");
1854 return nullptr;
1855 }
1856
1857 GlobalValue *Val = NumberedVals.get(ID);
1858
1859 // If this is a forward reference for the value, see if we already created a
1860 // forward ref record.
1861 if (!Val) {
1862 auto I = ForwardRefValIDs.find(ID);
1863 if (I != ForwardRefValIDs.end())
1864 Val = I->second.first;
1865 }
1866
1867 // If we have the value in the symbol table or fwd-ref table, return it.
1868 if (Val)
1870 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1871
1872 // Otherwise, create a new forward reference for this value and remember it.
1873 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1874 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1875 return FwdVal;
1876}
1877
1878//===----------------------------------------------------------------------===//
1879// Comdat Reference/Resolution Routines.
1880//===----------------------------------------------------------------------===//
1881
1882Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1883 // Look this name up in the comdat symbol table.
1884 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1885 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1886 if (I != ComdatSymTab.end())
1887 return &I->second;
1888
1889 // Otherwise, create a new forward reference for this value and remember it.
1890 Comdat *C = M->getOrInsertComdat(Name);
1891 ForwardRefComdats[Name] = Loc;
1892 return C;
1893}
1894
1895//===----------------------------------------------------------------------===//
1896// Helper Routines.
1897//===----------------------------------------------------------------------===//
1898
1899/// parseToken - If the current token has the specified kind, eat it and return
1900/// success. Otherwise, emit the specified error and return failure.
1901bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1902 if (Lex.getKind() != T)
1903 return tokError(ErrMsg);
1904 Lex.Lex();
1905 return false;
1906}
1907
1908/// parseStringConstant
1909/// ::= StringConstant
1910bool LLParser::parseStringConstant(std::string &Result) {
1911 if (Lex.getKind() != lltok::StringConstant)
1912 return tokError("expected string constant");
1913 Result = Lex.getStrVal();
1914 Lex.Lex();
1915 return false;
1916}
1917
1918/// parseUInt32
1919/// ::= uint32
1920bool LLParser::parseUInt32(uint32_t &Val) {
1921 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1922 return tokError("expected integer");
1923 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1924 if (Val64 != unsigned(Val64))
1925 return tokError("expected 32-bit integer (too large)");
1926 Val = Val64;
1927 Lex.Lex();
1928 return false;
1929}
1930
1931/// parseUInt64
1932/// ::= uint64
1933bool LLParser::parseUInt64(uint64_t &Val) {
1934 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1935 return tokError("expected integer");
1936 Val = Lex.getAPSIntVal().getLimitedValue();
1937 Lex.Lex();
1938 return false;
1939}
1940
1941/// parseTLSModel
1942/// := 'localdynamic'
1943/// := 'initialexec'
1944/// := 'localexec'
1945bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1946 switch (Lex.getKind()) {
1947 default:
1948 return tokError("expected localdynamic, initialexec or localexec");
1951 break;
1954 break;
1957 break;
1958 }
1959
1960 Lex.Lex();
1961 return false;
1962}
1963
1964/// parseOptionalThreadLocal
1965/// := /*empty*/
1966/// := 'thread_local'
1967/// := 'thread_local' '(' tlsmodel ')'
1968bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1970 if (!EatIfPresent(lltok::kw_thread_local))
1971 return false;
1972
1974 if (Lex.getKind() == lltok::lparen) {
1975 Lex.Lex();
1976 return parseTLSModel(TLM) ||
1977 parseToken(lltok::rparen, "expected ')' after thread local model");
1978 }
1979 return false;
1980}
1981
1982/// parseOptionalAddrSpace
1983/// := /*empty*/
1984/// := 'addrspace' '(' uint32 ')'
1985bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1986 AddrSpace = DefaultAS;
1987 if (!EatIfPresent(lltok::kw_addrspace))
1988 return false;
1989
1990 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1991 if (Lex.getKind() == lltok::StringConstant) {
1992 const std::string &AddrSpaceStr = Lex.getStrVal();
1993 if (AddrSpaceStr == "A") {
1994 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1995 } else if (AddrSpaceStr == "G") {
1996 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1997 } else if (AddrSpaceStr == "P") {
1998 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1999 } else if (std::optional<unsigned> AS =
2000 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2001 AddrSpace = *AS;
2002 } else {
2003 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2004 }
2005 Lex.Lex();
2006 return false;
2007 }
2008 if (Lex.getKind() != lltok::APSInt)
2009 return tokError("expected integer or string constant");
2010 SMLoc Loc = Lex.getLoc();
2011 if (parseUInt32(AddrSpace))
2012 return true;
2013 if (!isUInt<24>(AddrSpace))
2014 return error(Loc, "invalid address space, must be a 24-bit integer");
2015 return false;
2016 };
2017
2018 return parseToken(lltok::lparen, "expected '(' in address space") ||
2019 ParseAddrspaceValue(AddrSpace) ||
2020 parseToken(lltok::rparen, "expected ')' in address space");
2021}
2022
2023/// parseStringAttribute
2024/// := StringConstant
2025/// := StringConstant '=' StringConstant
2026bool LLParser::parseStringAttribute(AttrBuilder &B) {
2027 std::string Attr = Lex.getStrVal();
2028 Lex.Lex();
2029 std::string Val;
2030 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2031 return true;
2032 B.addAttribute(Attr, Val);
2033 return false;
2034}
2035
2036/// Parse a potentially empty list of parameter or return attributes.
2037bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2038 bool HaveError = false;
2039
2040 B.clear();
2041
2042 while (true) {
2043 lltok::Kind Token = Lex.getKind();
2044 if (Token == lltok::StringConstant) {
2045 if (parseStringAttribute(B))
2046 return true;
2047 continue;
2048 }
2049
2050 if (Token == lltok::kw_nocapture) {
2051 Lex.Lex();
2052 B.addCapturesAttr(CaptureInfo::none());
2053 continue;
2054 }
2055
2056 SMLoc Loc = Lex.getLoc();
2058 if (Attr == Attribute::None)
2059 return HaveError;
2060
2061 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2062 return true;
2063
2064 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2065 HaveError |= error(Loc, "this attribute does not apply to parameters");
2066 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2067 HaveError |= error(Loc, "this attribute does not apply to return values");
2068 }
2069}
2070
2071static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2072 HasLinkage = true;
2073 switch (Kind) {
2074 default:
2075 HasLinkage = false;
2077 case lltok::kw_private:
2079 case lltok::kw_internal:
2081 case lltok::kw_weak:
2083 case lltok::kw_weak_odr:
2085 case lltok::kw_linkonce:
2093 case lltok::kw_common:
2097 case lltok::kw_external:
2099 }
2100}
2101
2102/// parseOptionalLinkage
2103/// ::= /*empty*/
2104/// ::= 'private'
2105/// ::= 'internal'
2106/// ::= 'weak'
2107/// ::= 'weak_odr'
2108/// ::= 'linkonce'
2109/// ::= 'linkonce_odr'
2110/// ::= 'available_externally'
2111/// ::= 'appending'
2112/// ::= 'common'
2113/// ::= 'extern_weak'
2114/// ::= 'external'
2115bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2116 unsigned &Visibility,
2117 unsigned &DLLStorageClass, bool &DSOLocal) {
2118 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2119 if (HasLinkage)
2120 Lex.Lex();
2121 parseOptionalDSOLocal(DSOLocal);
2122 parseOptionalVisibility(Visibility);
2123 parseOptionalDLLStorageClass(DLLStorageClass);
2124
2125 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2126 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2127 }
2128
2129 return false;
2130}
2131
2132void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2133 switch (Lex.getKind()) {
2134 default:
2135 DSOLocal = false;
2136 break;
2138 DSOLocal = true;
2139 Lex.Lex();
2140 break;
2142 DSOLocal = false;
2143 Lex.Lex();
2144 break;
2145 }
2146}
2147
2148/// parseOptionalVisibility
2149/// ::= /*empty*/
2150/// ::= 'default'
2151/// ::= 'hidden'
2152/// ::= 'protected'
2153///
2154void LLParser::parseOptionalVisibility(unsigned &Res) {
2155 switch (Lex.getKind()) {
2156 default:
2158 return;
2159 case lltok::kw_default:
2161 break;
2162 case lltok::kw_hidden:
2164 break;
2167 break;
2168 }
2169 Lex.Lex();
2170}
2171
2172bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2174 switch (Kind) {
2175 default:
2176 return tokError("unknown import kind. Expect definition or declaration.");
2179 return false;
2182 return false;
2183 }
2184}
2185
2186/// parseOptionalDLLStorageClass
2187/// ::= /*empty*/
2188/// ::= 'dllimport'
2189/// ::= 'dllexport'
2190///
2191void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2192 switch (Lex.getKind()) {
2193 default:
2195 return;
2198 break;
2201 break;
2202 }
2203 Lex.Lex();
2204}
2205
2206/// parseOptionalCallingConv
2207/// ::= /*empty*/
2208/// ::= 'ccc'
2209/// ::= 'fastcc'
2210/// ::= 'intel_ocl_bicc'
2211/// ::= 'coldcc'
2212/// ::= 'cfguard_checkcc'
2213/// ::= 'x86_stdcallcc'
2214/// ::= 'x86_fastcallcc'
2215/// ::= 'x86_thiscallcc'
2216/// ::= 'x86_vectorcallcc'
2217/// ::= 'arm_apcscc'
2218/// ::= 'arm_aapcscc'
2219/// ::= 'arm_aapcs_vfpcc'
2220/// ::= 'aarch64_vector_pcs'
2221/// ::= 'aarch64_sve_vector_pcs'
2222/// ::= 'aarch64_sme_preservemost_from_x0'
2223/// ::= 'aarch64_sme_preservemost_from_x1'
2224/// ::= 'aarch64_sme_preservemost_from_x2'
2225/// ::= 'msp430_intrcc'
2226/// ::= 'avr_intrcc'
2227/// ::= 'avr_signalcc'
2228/// ::= 'ptx_kernel'
2229/// ::= 'ptx_device'
2230/// ::= 'spir_func'
2231/// ::= 'spir_kernel'
2232/// ::= 'x86_64_sysvcc'
2233/// ::= 'win64cc'
2234/// ::= 'anyregcc'
2235/// ::= 'preserve_mostcc'
2236/// ::= 'preserve_allcc'
2237/// ::= 'preserve_nonecc'
2238/// ::= 'ghccc'
2239/// ::= 'swiftcc'
2240/// ::= 'swifttailcc'
2241/// ::= 'x86_intrcc'
2242/// ::= 'hhvmcc'
2243/// ::= 'hhvm_ccc'
2244/// ::= 'cxx_fast_tlscc'
2245/// ::= 'amdgpu_vs'
2246/// ::= 'amdgpu_ls'
2247/// ::= 'amdgpu_hs'
2248/// ::= 'amdgpu_es'
2249/// ::= 'amdgpu_gs'
2250/// ::= 'amdgpu_ps'
2251/// ::= 'amdgpu_cs'
2252/// ::= 'amdgpu_cs_chain'
2253/// ::= 'amdgpu_cs_chain_preserve'
2254/// ::= 'amdgpu_kernel'
2255/// ::= 'tailcc'
2256/// ::= 'm68k_rtdcc'
2257/// ::= 'graalcc'
2258/// ::= 'riscv_vector_cc'
2259/// ::= 'riscv_vls_cc'
2260/// ::= 'cc' UINT
2261///
2262bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2263 switch (Lex.getKind()) {
2264 default: CC = CallingConv::C; return false;
2265 case lltok::kw_ccc: CC = CallingConv::C; break;
2266 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2267 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2280 break;
2283 break;
2286 break;
2289 break;
2299 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2300 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2304 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2305 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2308 case lltok::kw_hhvmcc:
2310 break;
2311 case lltok::kw_hhvm_ccc:
2313 break;
2325 break;
2328 break;
2332 break;
2333 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2335 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2338 break;
2340 // Default ABI_VLEN
2342 Lex.Lex();
2343 if (!EatIfPresent(lltok::lparen))
2344 break;
2345 uint32_t ABIVlen;
2346 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2347 return true;
2348 switch (ABIVlen) {
2349 default:
2350 return tokError("unknown RISC-V ABI VLEN");
2351#define CC_VLS_CASE(ABIVlen) \
2352 case ABIVlen: \
2353 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2354 break;
2355 CC_VLS_CASE(32)
2356 CC_VLS_CASE(64)
2357 CC_VLS_CASE(128)
2358 CC_VLS_CASE(256)
2359 CC_VLS_CASE(512)
2360 CC_VLS_CASE(1024)
2361 CC_VLS_CASE(2048)
2362 CC_VLS_CASE(4096)
2363 CC_VLS_CASE(8192)
2364 CC_VLS_CASE(16384)
2365 CC_VLS_CASE(32768)
2366 CC_VLS_CASE(65536)
2367#undef CC_VLS_CASE
2368 }
2369 return false;
2372 break;
2375 break;
2378 break;
2379 case lltok::kw_cc: {
2380 Lex.Lex();
2381 return parseUInt32(CC);
2382 }
2383 }
2384
2385 Lex.Lex();
2386 return false;
2387}
2388
2389/// parseMetadataAttachment
2390/// ::= !dbg !42
2391bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2392 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2393
2394 std::string Name = Lex.getStrVal();
2395 Kind = M->getMDKindID(Name);
2396 Lex.Lex();
2397
2398 return parseMDNode(MD);
2399}
2400
2401/// parseInstructionMetadata
2402/// ::= !dbg !42 (',' !dbg !57)*
2403bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2404 do {
2405 if (Lex.getKind() != lltok::MetadataVar)
2406 return tokError("expected metadata after comma");
2407
2408 unsigned MDK;
2409 MDNode *N;
2410 if (parseMetadataAttachment(MDK, N))
2411 return true;
2412
2413 if (MDK == LLVMContext::MD_DIAssignID)
2414 TempDIAssignIDAttachments[N].push_back(&Inst);
2415 else
2416 Inst.setMetadata(MDK, N);
2417
2418 if (MDK == LLVMContext::MD_tbaa)
2419 InstsWithTBAATag.push_back(&Inst);
2420
2421 // If this is the end of the list, we're done.
2422 } while (EatIfPresent(lltok::comma));
2423 return false;
2424}
2425
2426/// parseGlobalObjectMetadataAttachment
2427/// ::= !dbg !57
2428bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2429 unsigned MDK;
2430 MDNode *N;
2431 if (parseMetadataAttachment(MDK, N))
2432 return true;
2433
2434 GO.addMetadata(MDK, *N);
2435 return false;
2436}
2437
2438/// parseOptionalFunctionMetadata
2439/// ::= (!dbg !57)*
2440bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2441 while (Lex.getKind() == lltok::MetadataVar)
2442 if (parseGlobalObjectMetadataAttachment(F))
2443 return true;
2444 return false;
2445}
2446
2447/// parseOptionalAlignment
2448/// ::= /* empty */
2449/// ::= 'align' 4
2450bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2451 Alignment = std::nullopt;
2452 if (!EatIfPresent(lltok::kw_align))
2453 return false;
2454 LocTy AlignLoc = Lex.getLoc();
2455 uint64_t Value = 0;
2456
2457 LocTy ParenLoc = Lex.getLoc();
2458 bool HaveParens = false;
2459 if (AllowParens) {
2460 if (EatIfPresent(lltok::lparen))
2461 HaveParens = true;
2462 }
2463
2464 if (parseUInt64(Value))
2465 return true;
2466
2467 if (HaveParens && !EatIfPresent(lltok::rparen))
2468 return error(ParenLoc, "expected ')'");
2469
2470 if (!isPowerOf2_64(Value))
2471 return error(AlignLoc, "alignment is not a power of two");
2473 return error(AlignLoc, "huge alignments are not supported yet");
2474 Alignment = Align(Value);
2475 return false;
2476}
2477
2478/// parseOptionalPrefAlignment
2479/// ::= /* empty */
2480/// ::= 'prefalign' '(' 4 ')'
2481bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2482 Alignment = std::nullopt;
2483 if (!EatIfPresent(lltok::kw_prefalign))
2484 return false;
2485 LocTy AlignLoc = Lex.getLoc();
2486 uint64_t Value = 0;
2487
2488 LocTy ParenLoc = Lex.getLoc();
2489 if (!EatIfPresent(lltok::lparen))
2490 return error(ParenLoc, "expected '('");
2491
2492 if (parseUInt64(Value))
2493 return true;
2494
2495 ParenLoc = Lex.getLoc();
2496 if (!EatIfPresent(lltok::rparen))
2497 return error(ParenLoc, "expected ')'");
2498
2499 if (!isPowerOf2_64(Value))
2500 return error(AlignLoc, "alignment is not a power of two");
2502 return error(AlignLoc, "huge alignments are not supported yet");
2503 Alignment = Align(Value);
2504 return false;
2505}
2506
2507/// parseOptionalCodeModel
2508/// ::= /* empty */
2509/// ::= 'code_model' "large"
2510bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2511 Lex.Lex();
2512 auto StrVal = Lex.getStrVal();
2513 auto ErrMsg = "expected global code model string";
2514 if (StrVal == "tiny")
2515 model = CodeModel::Tiny;
2516 else if (StrVal == "small")
2517 model = CodeModel::Small;
2518 else if (StrVal == "kernel")
2519 model = CodeModel::Kernel;
2520 else if (StrVal == "medium")
2521 model = CodeModel::Medium;
2522 else if (StrVal == "large")
2523 model = CodeModel::Large;
2524 else
2525 return tokError(ErrMsg);
2526 if (parseToken(lltok::StringConstant, ErrMsg))
2527 return true;
2528 return false;
2529}
2530
2531/// parseOptionalAttrBytes
2532/// ::= /* empty */
2533/// ::= AttrKind '(' 4 ')'
2534///
2535/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2536/// 'dead_on_return'
2537bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2538 std::optional<uint64_t> &Bytes,
2539 bool ErrorNoBytes) {
2540 assert((AttrKind == lltok::kw_dereferenceable ||
2541 AttrKind == lltok::kw_dereferenceable_or_null ||
2542 AttrKind == lltok::kw_dead_on_return) &&
2543 "contract!");
2544
2545 Bytes = 0;
2546 if (!EatIfPresent(AttrKind))
2547 return false;
2548 LocTy ParenLoc = Lex.getLoc();
2549 if (!EatIfPresent(lltok::lparen)) {
2550 if (ErrorNoBytes)
2551 return error(ParenLoc, "expected '('");
2552 Bytes = std::nullopt;
2553 return false;
2554 }
2555 LocTy DerefLoc = Lex.getLoc();
2556 if (parseUInt64(Bytes.value()))
2557 return true;
2558 ParenLoc = Lex.getLoc();
2559 if (!EatIfPresent(lltok::rparen))
2560 return error(ParenLoc, "expected ')'");
2561 if (!Bytes.value())
2562 return error(DerefLoc, "byte count specified must be non-zero");
2563 return false;
2564}
2565
2566bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2567 Lex.Lex();
2569 if (!EatIfPresent(lltok::lparen))
2570 return false;
2571 LocTy KindLoc = Lex.getLoc();
2572 if (Lex.getKind() == lltok::kw_sync)
2574 else if (Lex.getKind() == lltok::kw_async)
2576 else
2577 return error(KindLoc, "expected unwind table kind");
2578 Lex.Lex();
2579 return parseToken(lltok::rparen, "expected ')'");
2580}
2581
2582bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2583 Lex.Lex();
2584 LocTy ParenLoc = Lex.getLoc();
2585 if (!EatIfPresent(lltok::lparen))
2586 return error(ParenLoc, "expected '('");
2587 LocTy KindLoc = Lex.getLoc();
2588 std::string Arg;
2589 if (parseStringConstant(Arg))
2590 return error(KindLoc, "expected allockind value");
2591 for (StringRef A : llvm::split(Arg, ",")) {
2592 if (A == "alloc") {
2594 } else if (A == "realloc") {
2596 } else if (A == "free") {
2598 } else if (A == "uninitialized") {
2600 } else if (A == "zeroed") {
2602 } else if (A == "aligned") {
2604 } else {
2605 return error(KindLoc, Twine("unknown allockind ") + A);
2606 }
2607 }
2608 ParenLoc = Lex.getLoc();
2609 if (!EatIfPresent(lltok::rparen))
2610 return error(ParenLoc, "expected ')'");
2611 if (Kind == AllocFnKind::Unknown)
2612 return error(KindLoc, "expected allockind value");
2613 return false;
2614}
2615
2617 using Loc = IRMemLocation;
2618
2619 switch (Tok) {
2620 case lltok::kw_argmem:
2621 return {Loc::ArgMem};
2623 return {Loc::InaccessibleMem};
2624 case lltok::kw_errnomem:
2625 return {Loc::ErrnoMem};
2627 return {Loc::TargetMem0};
2629 return {Loc::TargetMem1};
2630 case lltok::kw_target_mem: {
2633 Targets.push_back(Loc);
2634 return Targets;
2635 }
2636 default:
2637 return {};
2638 }
2639}
2640
2641static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2642 switch (Tok) {
2643 case lltok::kw_none:
2644 return ModRefInfo::NoModRef;
2645 case lltok::kw_read:
2646 return ModRefInfo::Ref;
2647 case lltok::kw_write:
2648 return ModRefInfo::Mod;
2650 return ModRefInfo::ModRef;
2651 default:
2652 return std::nullopt;
2653 }
2654}
2655
2656static std::optional<DenormalMode::DenormalModeKind>
2658 switch (Tok) {
2659 case lltok::kw_ieee:
2660 return DenormalMode::IEEE;
2665 case lltok::kw_dynamic:
2666 return DenormalMode::Dynamic;
2667 default:
2668 return std::nullopt;
2669 }
2670}
2671
2672std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2674
2675 // We use syntax like memory(argmem: read), so the colon should not be
2676 // interpreted as a label terminator.
2677 Lex.setIgnoreColonInIdentifiers(true);
2678 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2679
2680 Lex.Lex();
2681 if (!EatIfPresent(lltok::lparen)) {
2682 tokError("expected '('");
2683 return std::nullopt;
2684 }
2685
2686 bool SeenLoc = false;
2687 bool SeenTargetLoc = false;
2688 do {
2689 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2690 if (!Locs.empty()) {
2691 Lex.Lex();
2692 if (!EatIfPresent(lltok::colon)) {
2693 tokError("expected ':' after location");
2694 return std::nullopt;
2695 }
2696 }
2697
2698 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2699 if (!MR) {
2700 if (Locs.empty())
2701 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2702 "or access kind (none, read, write, readwrite)");
2703 else
2704 tokError("expected access kind (none, read, write, readwrite)");
2705 return std::nullopt;
2706 }
2707
2708 Lex.Lex();
2709 if (!Locs.empty()) {
2710 SeenLoc = true;
2711 for (IRMemLocation Loc : Locs) {
2712 ME = ME.getWithModRef(Loc, *MR);
2713 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2714 SeenTargetLoc = true;
2715 }
2716 if (Locs.size() > 1 && SeenTargetLoc) {
2717 tokError("target memory default access kind must be specified first");
2718 return std::nullopt;
2719 }
2720
2721 } else {
2722 if (SeenLoc) {
2723 tokError("default access kind must be specified first");
2724 return std::nullopt;
2725 }
2726 ME = MemoryEffects(*MR);
2727 }
2728
2729 if (EatIfPresent(lltok::rparen))
2730 return ME;
2731 } while (EatIfPresent(lltok::comma));
2732
2733 tokError("unterminated memory attribute");
2734 return std::nullopt;
2735}
2736
2737std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2738 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2739 keywordToDenormalModeKind(Lex.getKind());
2740 if (!OutputMode) {
2741 tokError("expected denormal behavior kind (ieee, preservesign, "
2742 "positivezero, dynamic)");
2743 return {};
2744 }
2745
2746 Lex.Lex();
2747
2748 std::optional<DenormalMode::DenormalModeKind> InputMode;
2749 if (EatIfPresent(lltok::bar)) {
2750 InputMode = keywordToDenormalModeKind(Lex.getKind());
2751 if (!InputMode) {
2752 tokError("expected denormal behavior kind (ieee, preservesign, "
2753 "positivezero, dynamic)");
2754 return {};
2755 }
2756
2757 Lex.Lex();
2758 } else {
2759 // Single item, input == output mode
2760 InputMode = OutputMode;
2761 }
2762
2763 return DenormalMode(*OutputMode, *InputMode);
2764}
2765
2766std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2767 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2768 // not be interpreted as a label terminator.
2769 Lex.setIgnoreColonInIdentifiers(true);
2770 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2771
2772 Lex.Lex();
2773
2774 if (parseToken(lltok::lparen, "expected '('"))
2775 return {};
2776
2777 DenormalMode DefaultMode = DenormalMode::getIEEE();
2778 DenormalMode F32Mode = DenormalMode::getInvalid();
2779
2780 bool HasDefaultSection = false;
2781 if (Lex.getKind() != lltok::Type) {
2782 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2783 if (!ParsedDefaultMode)
2784 return {};
2785 DefaultMode = *ParsedDefaultMode;
2786 HasDefaultSection = true;
2787 }
2788
2789 bool HasComma = EatIfPresent(lltok::comma);
2790 if (Lex.getKind() == lltok::Type) {
2791 if (HasDefaultSection && !HasComma) {
2792 tokError("expected ',' before float:");
2793 return {};
2794 }
2795
2796 Type *Ty = nullptr;
2797 if (parseType(Ty) || !Ty->isFloatTy()) {
2798 tokError("expected float:");
2799 return {};
2800 }
2801
2802 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2803 return {};
2804
2805 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2806 if (!ParsedF32Mode)
2807 return {};
2808
2809 F32Mode = *ParsedF32Mode;
2810 }
2811
2812 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2813 return {};
2814
2815 return DenormalFPEnv(DefaultMode, F32Mode);
2816}
2817
2818static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2819 switch (Tok) {
2820 case lltok::kw_all:
2821 return fcAllFlags;
2822 case lltok::kw_nan:
2823 return fcNan;
2824 case lltok::kw_snan:
2825 return fcSNan;
2826 case lltok::kw_qnan:
2827 return fcQNan;
2828 case lltok::kw_inf:
2829 return fcInf;
2830 case lltok::kw_ninf:
2831 return fcNegInf;
2832 case lltok::kw_pinf:
2833 return fcPosInf;
2834 case lltok::kw_norm:
2835 return fcNormal;
2836 case lltok::kw_nnorm:
2837 return fcNegNormal;
2838 case lltok::kw_pnorm:
2839 return fcPosNormal;
2840 case lltok::kw_sub:
2841 return fcSubnormal;
2842 case lltok::kw_nsub:
2843 return fcNegSubnormal;
2844 case lltok::kw_psub:
2845 return fcPosSubnormal;
2846 case lltok::kw_zero:
2847 return fcZero;
2848 case lltok::kw_nzero:
2849 return fcNegZero;
2850 case lltok::kw_pzero:
2851 return fcPosZero;
2852 default:
2853 return 0;
2854 }
2855}
2856
2857unsigned LLParser::parseNoFPClassAttr() {
2858 unsigned Mask = fcNone;
2859
2860 Lex.Lex();
2861 if (!EatIfPresent(lltok::lparen)) {
2862 tokError("expected '('");
2863 return 0;
2864 }
2865
2866 do {
2867 uint64_t Value = 0;
2868 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2869 if (TestMask != 0) {
2870 Mask |= TestMask;
2871 // TODO: Disallow overlapping masks to avoid copy paste errors
2872 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2873 !parseUInt64(Value)) {
2874 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2875 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2876 return 0;
2877 }
2878
2879 if (!EatIfPresent(lltok::rparen)) {
2880 error(Lex.getLoc(), "expected ')'");
2881 return 0;
2882 }
2883
2884 return Value;
2885 } else {
2886 error(Lex.getLoc(), "expected nofpclass test mask");
2887 return 0;
2888 }
2889
2890 Lex.Lex();
2891 if (EatIfPresent(lltok::rparen))
2892 return Mask;
2893 } while (1);
2894
2895 llvm_unreachable("unterminated nofpclass attribute");
2896}
2897
2898/// parseOptionalCommaAlign
2899/// ::=
2900/// ::= ',' align 4
2901///
2902/// This returns with AteExtraComma set to true if it ate an excess comma at the
2903/// end.
2904bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2905 bool &AteExtraComma) {
2906 AteExtraComma = false;
2907 while (EatIfPresent(lltok::comma)) {
2908 // Metadata at the end is an early exit.
2909 if (Lex.getKind() == lltok::MetadataVar) {
2910 AteExtraComma = true;
2911 return false;
2912 }
2913
2914 if (Lex.getKind() != lltok::kw_align)
2915 return error(Lex.getLoc(), "expected metadata or 'align'");
2916
2917 if (parseOptionalAlignment(Alignment))
2918 return true;
2919 }
2920
2921 return false;
2922}
2923
2924/// parseOptionalCommaAddrSpace
2925/// ::=
2926/// ::= ',' addrspace(1)
2927///
2928/// This returns with AteExtraComma set to true if it ate an excess comma at the
2929/// end.
2930bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2931 bool &AteExtraComma) {
2932 AteExtraComma = false;
2933 while (EatIfPresent(lltok::comma)) {
2934 // Metadata at the end is an early exit.
2935 if (Lex.getKind() == lltok::MetadataVar) {
2936 AteExtraComma = true;
2937 return false;
2938 }
2939
2940 Loc = Lex.getLoc();
2941 if (Lex.getKind() != lltok::kw_addrspace)
2942 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2943
2944 if (parseOptionalAddrSpace(AddrSpace))
2945 return true;
2946 }
2947
2948 return false;
2949}
2950
2951bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2952 std::optional<unsigned> &HowManyArg) {
2953 Lex.Lex();
2954
2955 auto StartParen = Lex.getLoc();
2956 if (!EatIfPresent(lltok::lparen))
2957 return error(StartParen, "expected '('");
2958
2959 if (parseUInt32(BaseSizeArg))
2960 return true;
2961
2962 if (EatIfPresent(lltok::comma)) {
2963 auto HowManyAt = Lex.getLoc();
2964 unsigned HowMany;
2965 if (parseUInt32(HowMany))
2966 return true;
2967 if (HowMany == BaseSizeArg)
2968 return error(HowManyAt,
2969 "'allocsize' indices can't refer to the same parameter");
2970 HowManyArg = HowMany;
2971 } else
2972 HowManyArg = std::nullopt;
2973
2974 auto EndParen = Lex.getLoc();
2975 if (!EatIfPresent(lltok::rparen))
2976 return error(EndParen, "expected ')'");
2977 return false;
2978}
2979
2980bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2981 unsigned &MaxValue) {
2982 Lex.Lex();
2983
2984 auto StartParen = Lex.getLoc();
2985 if (!EatIfPresent(lltok::lparen))
2986 return error(StartParen, "expected '('");
2987
2988 if (parseUInt32(MinValue))
2989 return true;
2990
2991 if (EatIfPresent(lltok::comma)) {
2992 if (parseUInt32(MaxValue))
2993 return true;
2994 } else
2995 MaxValue = MinValue;
2996
2997 auto EndParen = Lex.getLoc();
2998 if (!EatIfPresent(lltok::rparen))
2999 return error(EndParen, "expected ')'");
3000 return false;
3001}
3002
3003/// parseScopeAndOrdering
3004/// if isAtomic: ::= SyncScope? AtomicOrdering
3005/// else: ::=
3006///
3007/// This sets Scope and Ordering to the parsed values.
3008bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3009 AtomicOrdering &Ordering) {
3010 if (!IsAtomic)
3011 return false;
3012
3013 return parseScope(SSID) || parseOrdering(Ordering);
3014}
3015
3016/// parseScope
3017/// ::= syncscope("singlethread" | "<target scope>")?
3018///
3019/// This sets synchronization scope ID to the ID of the parsed value.
3020bool LLParser::parseScope(SyncScope::ID &SSID) {
3021 SSID = SyncScope::System;
3022 if (EatIfPresent(lltok::kw_syncscope)) {
3023 auto StartParenAt = Lex.getLoc();
3024 if (!EatIfPresent(lltok::lparen))
3025 return error(StartParenAt, "Expected '(' in syncscope");
3026
3027 std::string SSN;
3028 auto SSNAt = Lex.getLoc();
3029 if (parseStringConstant(SSN))
3030 return error(SSNAt, "Expected synchronization scope name");
3031
3032 auto EndParenAt = Lex.getLoc();
3033 if (!EatIfPresent(lltok::rparen))
3034 return error(EndParenAt, "Expected ')' in syncscope");
3035
3036 SSID = Context.getOrInsertSyncScopeID(SSN);
3037 }
3038
3039 return false;
3040}
3041
3042/// parseOrdering
3043/// ::= AtomicOrdering
3044///
3045/// This sets Ordering to the parsed value.
3046bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3047 switch (Lex.getKind()) {
3048 default:
3049 return tokError("Expected ordering on atomic instruction");
3052 // Not specified yet:
3053 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3057 case lltok::kw_seq_cst:
3059 break;
3060 }
3061 Lex.Lex();
3062 return false;
3063}
3064
3065/// parseOptionalStackAlignment
3066/// ::= /* empty */
3067/// ::= 'alignstack' '(' 4 ')'
3068bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3069 Alignment = 0;
3070 if (!EatIfPresent(lltok::kw_alignstack))
3071 return false;
3072 LocTy ParenLoc = Lex.getLoc();
3073 if (!EatIfPresent(lltok::lparen))
3074 return error(ParenLoc, "expected '('");
3075 LocTy AlignLoc = Lex.getLoc();
3076 if (parseUInt32(Alignment))
3077 return true;
3078 ParenLoc = Lex.getLoc();
3079 if (!EatIfPresent(lltok::rparen))
3080 return error(ParenLoc, "expected ')'");
3081 if (!isPowerOf2_32(Alignment))
3082 return error(AlignLoc, "stack alignment is not a power of two");
3083 return false;
3084}
3085
3086/// parseIndexList - This parses the index list for an insert/extractvalue
3087/// instruction. This sets AteExtraComma in the case where we eat an extra
3088/// comma at the end of the line and find that it is followed by metadata.
3089/// Clients that don't allow metadata can call the version of this function that
3090/// only takes one argument.
3091///
3092/// parseIndexList
3093/// ::= (',' uint32)+
3094///
3095bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3096 bool &AteExtraComma) {
3097 AteExtraComma = false;
3098
3099 if (Lex.getKind() != lltok::comma)
3100 return tokError("expected ',' as start of index list");
3101
3102 while (EatIfPresent(lltok::comma)) {
3103 if (Lex.getKind() == lltok::MetadataVar) {
3104 if (Indices.empty())
3105 return tokError("expected index");
3106 AteExtraComma = true;
3107 return false;
3108 }
3109 unsigned Idx = 0;
3110 if (parseUInt32(Idx))
3111 return true;
3112 Indices.push_back(Idx);
3113 }
3114
3115 return false;
3116}
3117
3118//===----------------------------------------------------------------------===//
3119// Type Parsing.
3120//===----------------------------------------------------------------------===//
3121
3122/// parseType - parse a type.
3123bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3124 SMLoc TypeLoc = Lex.getLoc();
3125 switch (Lex.getKind()) {
3126 default:
3127 return tokError(Msg);
3128 case lltok::Type:
3129 // Type ::= 'float' | 'void' (etc)
3130 Result = Lex.getTyVal();
3131 Lex.Lex();
3132
3133 // Handle "ptr" opaque pointer type.
3134 //
3135 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3136 if (Result->isPointerTy()) {
3137 unsigned AddrSpace;
3138 if (parseOptionalAddrSpace(AddrSpace))
3139 return true;
3140 Result = PointerType::get(getContext(), AddrSpace);
3141
3142 // Give a nice error for 'ptr*'.
3143 if (Lex.getKind() == lltok::star)
3144 return tokError("ptr* is invalid - use ptr instead");
3145
3146 // Fall through to parsing the type suffixes only if this 'ptr' is a
3147 // function return. Otherwise, return success, implicitly rejecting other
3148 // suffixes.
3149 if (Lex.getKind() != lltok::lparen)
3150 return false;
3151 }
3152 break;
3153 case lltok::kw_target: {
3154 // Type ::= TargetExtType
3155 if (parseTargetExtType(Result))
3156 return true;
3157 break;
3158 }
3159 case lltok::lbrace:
3160 // Type ::= StructType
3161 if (parseAnonStructType(Result, false))
3162 return true;
3163 break;
3164 case lltok::lsquare:
3165 // Type ::= '[' ... ']'
3166 Lex.Lex(); // eat the lsquare.
3167 if (parseArrayVectorType(Result, false))
3168 return true;
3169 break;
3170 case lltok::less: // Either vector or packed struct.
3171 // Type ::= '<' ... '>'
3172 Lex.Lex();
3173 if (Lex.getKind() == lltok::lbrace) {
3174 if (parseAnonStructType(Result, true) ||
3175 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3176 return true;
3177 } else if (parseArrayVectorType(Result, true))
3178 return true;
3179 break;
3180 case lltok::LocalVar: {
3181 // Type ::= %foo
3182 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3183
3184 // If the type hasn't been defined yet, create a forward definition and
3185 // remember where that forward def'n was seen (in case it never is defined).
3186 if (!Entry.first) {
3187 Entry.first = StructType::create(Context, Lex.getStrVal());
3188 Entry.second = Lex.getLoc();
3189 }
3190 Result = Entry.first;
3191 Lex.Lex();
3192 break;
3193 }
3194
3195 case lltok::LocalVarID: {
3196 // Type ::= %4
3197 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3198
3199 // If the type hasn't been defined yet, create a forward definition and
3200 // remember where that forward def'n was seen (in case it never is defined).
3201 if (!Entry.first) {
3202 Entry.first = StructType::create(Context);
3203 Entry.second = Lex.getLoc();
3204 }
3205 Result = Entry.first;
3206 Lex.Lex();
3207 break;
3208 }
3209 }
3210
3211 // parse the type suffixes.
3212 while (true) {
3213 switch (Lex.getKind()) {
3214 // End of type.
3215 default:
3216 if (!AllowVoid && Result->isVoidTy())
3217 return error(TypeLoc, "void type only allowed for function results");
3218 return false;
3219
3220 // Type ::= Type '*'
3221 case lltok::star:
3222 if (Result->isLabelTy())
3223 return tokError("basic block pointers are invalid");
3224 if (Result->isVoidTy())
3225 return tokError("pointers to void are invalid - use i8* instead");
3227 return tokError("pointer to this type is invalid");
3228 Result = PointerType::getUnqual(Context);
3229 Lex.Lex();
3230 break;
3231
3232 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3233 case lltok::kw_addrspace: {
3234 if (Result->isLabelTy())
3235 return tokError("basic block pointers are invalid");
3236 if (Result->isVoidTy())
3237 return tokError("pointers to void are invalid; use i8* instead");
3239 return tokError("pointer to this type is invalid");
3240 unsigned AddrSpace;
3241 if (parseOptionalAddrSpace(AddrSpace) ||
3242 parseToken(lltok::star, "expected '*' in address space"))
3243 return true;
3244
3245 Result = PointerType::get(Context, AddrSpace);
3246 break;
3247 }
3248
3249 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3250 case lltok::lparen:
3251 if (parseFunctionType(Result))
3252 return true;
3253 break;
3254 }
3255 }
3256}
3257
3258/// parseParameterList
3259/// ::= '(' ')'
3260/// ::= '(' Arg (',' Arg)* ')'
3261/// Arg
3262/// ::= Type OptionalAttributes Value OptionalAttributes
3263bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3264 PerFunctionState &PFS, bool IsMustTailCall,
3265 bool InVarArgsFunc) {
3266 if (parseToken(lltok::lparen, "expected '(' in call"))
3267 return true;
3268
3269 while (Lex.getKind() != lltok::rparen) {
3270 // If this isn't the first argument, we need a comma.
3271 if (!ArgList.empty() &&
3272 parseToken(lltok::comma, "expected ',' in argument list"))
3273 return true;
3274
3275 // parse an ellipsis if this is a musttail call in a variadic function.
3276 if (Lex.getKind() == lltok::dotdotdot) {
3277 const char *Msg = "unexpected ellipsis in argument list for ";
3278 if (!IsMustTailCall)
3279 return tokError(Twine(Msg) + "non-musttail call");
3280 if (!InVarArgsFunc)
3281 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3282 Lex.Lex(); // Lex the '...', it is purely for readability.
3283 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3284 }
3285
3286 // parse the argument.
3287 LocTy ArgLoc;
3288 Type *ArgTy = nullptr;
3289 Value *V;
3290 if (parseType(ArgTy, ArgLoc))
3291 return true;
3293 return error(ArgLoc, "invalid type for function argument");
3294
3295 AttrBuilder ArgAttrs(M->getContext());
3296
3297 if (ArgTy->isMetadataTy()) {
3298 if (parseMetadataAsValue(V, PFS))
3299 return true;
3300 } else {
3301 // Otherwise, handle normal operands.
3302 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3303 return true;
3304 }
3305 ArgList.push_back(ParamInfo(
3306 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3307 }
3308
3309 if (IsMustTailCall && InVarArgsFunc)
3310 return tokError("expected '...' at end of argument list for musttail call "
3311 "in varargs function");
3312
3313 Lex.Lex(); // Lex the ')'.
3314 return false;
3315}
3316
3317/// parseRequiredTypeAttr
3318/// ::= attrname(<ty>)
3319bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3320 Attribute::AttrKind AttrKind) {
3321 Type *Ty = nullptr;
3322 if (!EatIfPresent(AttrToken))
3323 return true;
3324 if (!EatIfPresent(lltok::lparen))
3325 return error(Lex.getLoc(), "expected '('");
3326 if (parseType(Ty))
3327 return true;
3328 if (!EatIfPresent(lltok::rparen))
3329 return error(Lex.getLoc(), "expected ')'");
3330
3331 B.addTypeAttr(AttrKind, Ty);
3332 return false;
3333}
3334
3335/// parseRangeAttr
3336/// ::= range(<ty> <n>,<n>)
3337bool LLParser::parseRangeAttr(AttrBuilder &B) {
3338 Lex.Lex();
3339
3340 APInt Lower;
3341 APInt Upper;
3342 Type *Ty = nullptr;
3343 LocTy TyLoc;
3344
3345 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3346 if (Lex.getKind() != lltok::APSInt)
3347 return tokError("expected integer");
3348 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3349 return tokError(
3350 "integer is too large for the bit width of specified type");
3351 Val = Lex.getAPSIntVal().extend(BitWidth);
3352 Lex.Lex();
3353 return false;
3354 };
3355
3356 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3357 return true;
3358 if (!Ty->isIntegerTy())
3359 return error(TyLoc, "the range must have integer type!");
3360
3361 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3362
3363 if (ParseAPSInt(BitWidth, Lower) ||
3364 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3365 return true;
3366 if (Lower == Upper && !Lower.isZero())
3367 return tokError("the range represent the empty set but limits aren't 0!");
3368
3369 if (parseToken(lltok::rparen, "expected ')'"))
3370 return true;
3371
3372 B.addRangeAttr(ConstantRange(Lower, Upper));
3373 return false;
3374}
3375
3376/// parseInitializesAttr
3377/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3378bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3379 Lex.Lex();
3380
3381 auto ParseAPSInt = [&](APInt &Val) {
3382 if (Lex.getKind() != lltok::APSInt)
3383 return tokError("expected integer");
3384 Val = Lex.getAPSIntVal().extend(64);
3385 Lex.Lex();
3386 return false;
3387 };
3388
3389 if (parseToken(lltok::lparen, "expected '('"))
3390 return true;
3391
3393 // Parse each constant range.
3394 do {
3395 APInt Lower, Upper;
3396 if (parseToken(lltok::lparen, "expected '('"))
3397 return true;
3398
3399 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3400 ParseAPSInt(Upper))
3401 return true;
3402
3403 if (Lower == Upper)
3404 return tokError("the range should not represent the full or empty set!");
3405
3406 if (parseToken(lltok::rparen, "expected ')'"))
3407 return true;
3408
3409 RangeList.push_back(ConstantRange(Lower, Upper));
3410 } while (EatIfPresent(lltok::comma));
3411
3412 if (parseToken(lltok::rparen, "expected ')'"))
3413 return true;
3414
3415 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3416 if (!CRLOrNull.has_value())
3417 return tokError("Invalid (unordered or overlapping) range list");
3418 B.addInitializesAttr(*CRLOrNull);
3419 return false;
3420}
3421
3422bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3424 std::optional<CaptureComponents> Ret;
3425
3426 // We use syntax like captures(ret: address, provenance), so the colon
3427 // should not be interpreted as a label terminator.
3428 Lex.setIgnoreColonInIdentifiers(true);
3429 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3430
3431 Lex.Lex();
3432 if (parseToken(lltok::lparen, "expected '('"))
3433 return true;
3434
3435 CaptureComponents *Current = &Other;
3436 bool SeenComponent = false;
3437 while (true) {
3438 if (EatIfPresent(lltok::kw_ret)) {
3439 if (parseToken(lltok::colon, "expected ':'"))
3440 return true;
3441 if (Ret)
3442 return tokError("duplicate 'ret' location");
3444 Current = &*Ret;
3445 SeenComponent = false;
3446 }
3447
3448 if (EatIfPresent(lltok::kw_none)) {
3449 if (SeenComponent)
3450 return tokError("cannot use 'none' with other component");
3451 *Current = CaptureComponents::None;
3452 } else {
3453 if (SeenComponent && capturesNothing(*Current))
3454 return tokError("cannot use 'none' with other component");
3455
3456 if (EatIfPresent(lltok::kw_address_is_null))
3458 else if (EatIfPresent(lltok::kw_address))
3459 *Current |= CaptureComponents::Address;
3460 else if (EatIfPresent(lltok::kw_provenance))
3462 else if (EatIfPresent(lltok::kw_read_provenance))
3464 else
3465 return tokError("expected one of 'none', 'address', 'address_is_null', "
3466 "'provenance' or 'read_provenance'");
3467 }
3468
3469 SeenComponent = true;
3470 if (EatIfPresent(lltok::rparen))
3471 break;
3472
3473 if (parseToken(lltok::comma, "expected ',' or ')'"))
3474 return true;
3475 }
3476
3477 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3478 return false;
3479}
3480
3481/// parseOptionalOperandBundles
3482/// ::= /*empty*/
3483/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3484///
3485/// OperandBundle
3486/// ::= bundle-tag '(' ')'
3487/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3488///
3489/// bundle-tag ::= String Constant
3490bool LLParser::parseOptionalOperandBundles(
3491 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3492 LocTy BeginLoc = Lex.getLoc();
3493 if (!EatIfPresent(lltok::lsquare))
3494 return false;
3495
3496 while (Lex.getKind() != lltok::rsquare) {
3497 // If this isn't the first operand bundle, we need a comma.
3498 if (!BundleList.empty() &&
3499 parseToken(lltok::comma, "expected ',' in input list"))
3500 return true;
3501
3502 std::string Tag;
3503 if (parseStringConstant(Tag))
3504 return true;
3505
3506 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3507 return true;
3508
3509 std::vector<Value *> Inputs;
3510 while (Lex.getKind() != lltok::rparen) {
3511 // If this isn't the first input, we need a comma.
3512 if (!Inputs.empty() &&
3513 parseToken(lltok::comma, "expected ',' in input list"))
3514 return true;
3515
3516 Type *Ty = nullptr;
3517 Value *Input = nullptr;
3518 if (parseType(Ty))
3519 return true;
3520 if (Ty->isMetadataTy()) {
3521 if (parseMetadataAsValue(Input, PFS))
3522 return true;
3523 } else if (parseValue(Ty, Input, PFS)) {
3524 return true;
3525 }
3526 Inputs.push_back(Input);
3527 }
3528
3529 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3530
3531 Lex.Lex(); // Lex the ')'.
3532 }
3533
3534 if (BundleList.empty())
3535 return error(BeginLoc, "operand bundle set must not be empty");
3536
3537 Lex.Lex(); // Lex the ']'.
3538 return false;
3539}
3540
3541bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3542 unsigned NextID, unsigned ID) {
3543 if (ID < NextID)
3544 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3545 Twine(NextID) + "' or greater");
3546
3547 return false;
3548}
3549
3550/// parseArgumentList - parse the argument list for a function type or function
3551/// prototype.
3552/// ::= '(' ArgTypeListI ')'
3553/// ArgTypeListI
3554/// ::= /*empty*/
3555/// ::= '...'
3556/// ::= ArgTypeList ',' '...'
3557/// ::= ArgType (',' ArgType)*
3558///
3559bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3560 SmallVectorImpl<unsigned> &UnnamedArgNums,
3561 bool &IsVarArg) {
3562 unsigned CurValID = 0;
3563 IsVarArg = false;
3564 assert(Lex.getKind() == lltok::lparen);
3565 Lex.Lex(); // eat the (.
3566
3567 if (Lex.getKind() != lltok::rparen) {
3568 do {
3569 // Handle ... at end of arg list.
3570 if (EatIfPresent(lltok::dotdotdot)) {
3571 IsVarArg = true;
3572 break;
3573 }
3574
3575 // Otherwise must be an argument type.
3576 LocTy TypeLoc = Lex.getLoc();
3577 Type *ArgTy = nullptr;
3578 AttrBuilder Attrs(M->getContext());
3579 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3580 return true;
3581
3582 if (ArgTy->isVoidTy())
3583 return error(TypeLoc, "argument can not have void type");
3584
3585 std::string Name;
3586 FileLoc IdentStart;
3587 FileLoc IdentEnd;
3588 bool Unnamed = false;
3589 if (Lex.getKind() == lltok::LocalVar) {
3590 Name = Lex.getStrVal();
3591 IdentStart = getTokLineColumnPos();
3592 Lex.Lex();
3593 IdentEnd = getPrevTokEndLineColumnPos();
3594 } else {
3595 unsigned ArgID;
3596 if (Lex.getKind() == lltok::LocalVarID) {
3597 ArgID = Lex.getUIntVal();
3598 IdentStart = getTokLineColumnPos();
3599 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3600 return true;
3601 Lex.Lex();
3602 IdentEnd = getPrevTokEndLineColumnPos();
3603 } else {
3604 ArgID = CurValID;
3605 Unnamed = true;
3606 }
3607 UnnamedArgNums.push_back(ArgID);
3608 CurValID = ArgID + 1;
3609 }
3610
3612 return error(TypeLoc, "invalid type for function argument");
3613
3614 ArgList.emplace_back(
3615 TypeLoc, ArgTy,
3616 Unnamed ? std::nullopt
3617 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3618 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3619 } while (EatIfPresent(lltok::comma));
3620 }
3621
3622 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3623}
3624
3625/// parseFunctionType
3626/// ::= Type ArgumentList OptionalAttrs
3627bool LLParser::parseFunctionType(Type *&Result) {
3628 assert(Lex.getKind() == lltok::lparen);
3629
3631 return tokError("invalid function return type");
3632
3634 bool IsVarArg;
3635 SmallVector<unsigned> UnnamedArgNums;
3636 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3637 return true;
3638
3639 // Reject names on the arguments lists.
3640 for (const ArgInfo &Arg : ArgList) {
3641 if (!Arg.Name.empty())
3642 return error(Arg.Loc, "argument name invalid in function type");
3643 if (Arg.Attrs.hasAttributes())
3644 return error(Arg.Loc, "argument attributes invalid in function type");
3645 }
3646
3647 SmallVector<Type*, 16> ArgListTy;
3648 for (const ArgInfo &Arg : ArgList)
3649 ArgListTy.push_back(Arg.Ty);
3650
3651 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3652 return false;
3653}
3654
3655/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3656/// other structs.
3657bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3659 if (parseStructBody(Elts))
3660 return true;
3661
3662 Result = StructType::get(Context, Elts, Packed);
3663 return false;
3664}
3665
3666/// parseStructDefinition - parse a struct in a 'type' definition.
3667bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3668 std::pair<Type *, LocTy> &Entry,
3669 Type *&ResultTy) {
3670 // If the type was already defined, diagnose the redefinition.
3671 if (Entry.first && !Entry.second.isValid())
3672 return error(TypeLoc, "redefinition of type");
3673
3674 // If we have opaque, just return without filling in the definition for the
3675 // struct. This counts as a definition as far as the .ll file goes.
3676 if (EatIfPresent(lltok::kw_opaque)) {
3677 // This type is being defined, so clear the location to indicate this.
3678 Entry.second = SMLoc();
3679
3680 // If this type number has never been uttered, create it.
3681 if (!Entry.first)
3682 Entry.first = StructType::create(Context, Name);
3683 ResultTy = Entry.first;
3684 return false;
3685 }
3686
3687 // If the type starts with '<', then it is either a packed struct or a vector.
3688 bool isPacked = EatIfPresent(lltok::less);
3689
3690 // If we don't have a struct, then we have a random type alias, which we
3691 // accept for compatibility with old files. These types are not allowed to be
3692 // forward referenced and not allowed to be recursive.
3693 if (Lex.getKind() != lltok::lbrace) {
3694 if (Entry.first)
3695 return error(TypeLoc, "forward references to non-struct type");
3696
3697 ResultTy = nullptr;
3698 if (isPacked)
3699 return parseArrayVectorType(ResultTy, true);
3700 return parseType(ResultTy);
3701 }
3702
3703 // This type is being defined, so clear the location to indicate this.
3704 Entry.second = SMLoc();
3705
3706 // If this type number has never been uttered, create it.
3707 if (!Entry.first)
3708 Entry.first = StructType::create(Context, Name);
3709
3710 StructType *STy = cast<StructType>(Entry.first);
3711
3713 if (parseStructBody(Body) ||
3714 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3715 return true;
3716
3717 if (auto E = STy->setBodyOrError(Body, isPacked))
3718 return tokError(toString(std::move(E)));
3719
3720 ResultTy = STy;
3721 return false;
3722}
3723
3724/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3725/// StructType
3726/// ::= '{' '}'
3727/// ::= '{' Type (',' Type)* '}'
3728/// ::= '<' '{' '}' '>'
3729/// ::= '<' '{' Type (',' Type)* '}' '>'
3730bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3731 assert(Lex.getKind() == lltok::lbrace);
3732 Lex.Lex(); // Consume the '{'
3733
3734 // Handle the empty struct.
3735 if (EatIfPresent(lltok::rbrace))
3736 return false;
3737
3738 LocTy EltTyLoc = Lex.getLoc();
3739 Type *Ty = nullptr;
3740 if (parseType(Ty))
3741 return true;
3742 Body.push_back(Ty);
3743
3745 return error(EltTyLoc, "invalid element type for struct");
3746
3747 while (EatIfPresent(lltok::comma)) {
3748 EltTyLoc = Lex.getLoc();
3749 if (parseType(Ty))
3750 return true;
3751
3753 return error(EltTyLoc, "invalid element type for struct");
3754
3755 Body.push_back(Ty);
3756 }
3757
3758 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3759}
3760
3761/// parseArrayVectorType - parse an array or vector type, assuming the first
3762/// token has already been consumed.
3763/// Type
3764/// ::= '[' APSINTVAL 'x' Types ']'
3765/// ::= '<' APSINTVAL 'x' Types '>'
3766/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3767bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3768 bool Scalable = false;
3769
3770 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3771 Lex.Lex(); // consume the 'vscale'
3772 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3773 return true;
3774
3775 Scalable = true;
3776 }
3777
3778 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3779 Lex.getAPSIntVal().getBitWidth() > 64)
3780 return tokError("expected number in address space");
3781
3782 LocTy SizeLoc = Lex.getLoc();
3783 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3784 Lex.Lex();
3785
3786 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3787 return true;
3788
3789 LocTy TypeLoc = Lex.getLoc();
3790 Type *EltTy = nullptr;
3791 if (parseType(EltTy))
3792 return true;
3793
3794 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3795 "expected end of sequential type"))
3796 return true;
3797
3798 if (IsVector) {
3799 if (Size == 0)
3800 return error(SizeLoc, "zero element vector is illegal");
3801 if ((unsigned)Size != Size)
3802 return error(SizeLoc, "size too large for vector");
3804 return error(TypeLoc, "invalid vector element type");
3805 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3806 } else {
3808 return error(TypeLoc, "invalid array element type");
3809 Result = ArrayType::get(EltTy, Size);
3810 }
3811 return false;
3812}
3813
3814/// parseTargetExtType - handle target extension type syntax
3815/// TargetExtType
3816/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3817///
3818/// TargetExtTypeParams
3819/// ::= /*empty*/
3820/// ::= ',' Type TargetExtTypeParams
3821///
3822/// TargetExtIntParams
3823/// ::= /*empty*/
3824/// ::= ',' uint32 TargetExtIntParams
3825bool LLParser::parseTargetExtType(Type *&Result) {
3826 Lex.Lex(); // Eat the 'target' keyword.
3827
3828 // Get the mandatory type name.
3829 std::string TypeName;
3830 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3831 parseStringConstant(TypeName))
3832 return true;
3833
3834 // Parse all of the integer and type parameters at the same time; the use of
3835 // SeenInt will allow us to catch cases where type parameters follow integer
3836 // parameters.
3837 SmallVector<Type *> TypeParams;
3838 SmallVector<unsigned> IntParams;
3839 bool SeenInt = false;
3840 while (Lex.getKind() == lltok::comma) {
3841 Lex.Lex(); // Eat the comma.
3842
3843 if (Lex.getKind() == lltok::APSInt) {
3844 SeenInt = true;
3845 unsigned IntVal;
3846 if (parseUInt32(IntVal))
3847 return true;
3848 IntParams.push_back(IntVal);
3849 } else if (SeenInt) {
3850 // The only other kind of parameter we support is type parameters, which
3851 // must precede the integer parameters. This is therefore an error.
3852 return tokError("expected uint32 param");
3853 } else {
3854 Type *TypeParam;
3855 if (parseType(TypeParam, /*AllowVoid=*/true))
3856 return true;
3857 TypeParams.push_back(TypeParam);
3858 }
3859 }
3860
3861 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3862 return true;
3863
3864 auto TTy =
3865 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3866 if (auto E = TTy.takeError())
3867 return tokError(toString(std::move(E)));
3868
3869 Result = *TTy;
3870 return false;
3871}
3872
3873//===----------------------------------------------------------------------===//
3874// Function Semantic Analysis.
3875//===----------------------------------------------------------------------===//
3876
3877LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3878 int functionNumber,
3879 ArrayRef<unsigned> UnnamedArgNums)
3880 : P(p), F(f), FunctionNumber(functionNumber) {
3881
3882 // Insert unnamed arguments into the NumberedVals list.
3883 auto It = UnnamedArgNums.begin();
3884 for (Argument &A : F.args()) {
3885 if (!A.hasName()) {
3886 unsigned ArgNum = *It++;
3887 NumberedVals.add(ArgNum, &A);
3888 }
3889 }
3890}
3891
3892LLParser::PerFunctionState::~PerFunctionState() {
3893 // If there were any forward referenced non-basicblock values, delete them.
3894
3895 for (const auto &P : ForwardRefVals) {
3896 if (isa<BasicBlock>(P.second.first))
3897 continue;
3898 P.second.first->replaceAllUsesWith(
3899 PoisonValue::get(P.second.first->getType()));
3900 P.second.first->deleteValue();
3901 }
3902
3903 for (const auto &P : ForwardRefValIDs) {
3904 if (isa<BasicBlock>(P.second.first))
3905 continue;
3906 P.second.first->replaceAllUsesWith(
3907 PoisonValue::get(P.second.first->getType()));
3908 P.second.first->deleteValue();
3909 }
3910}
3911
3912bool LLParser::PerFunctionState::finishFunction() {
3913 if (!ForwardRefVals.empty())
3914 return P.error(ForwardRefVals.begin()->second.second,
3915 "use of undefined value '%" + ForwardRefVals.begin()->first +
3916 "'");
3917 if (!ForwardRefValIDs.empty())
3918 return P.error(ForwardRefValIDs.begin()->second.second,
3919 "use of undefined value '%" +
3920 Twine(ForwardRefValIDs.begin()->first) + "'");
3921 return false;
3922}
3923
3924/// getVal - Get a value with the specified name or ID, creating a
3925/// forward reference record if needed. This can return null if the value
3926/// exists but does not have the right type.
3927Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3928 LocTy Loc) {
3929 // Look this name up in the normal function symbol table.
3930 Value *Val = F.getValueSymbolTable()->lookup(Name);
3931
3932 // If this is a forward reference for the value, see if we already created a
3933 // forward ref record.
3934 if (!Val) {
3935 auto I = ForwardRefVals.find(Name);
3936 if (I != ForwardRefVals.end())
3937 Val = I->second.first;
3938 }
3939
3940 // If we have the value in the symbol table or fwd-ref table, return it.
3941 if (Val)
3942 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3943
3944 // Don't make placeholders with invalid type.
3945 if (!Ty->isFirstClassType()) {
3946 P.error(Loc, "invalid use of a non-first-class type");
3947 return nullptr;
3948 }
3949
3950 // Otherwise, create a new forward reference for this value and remember it.
3951 Value *FwdVal;
3952 if (Ty->isLabelTy()) {
3953 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3954 } else {
3955 FwdVal = new Argument(Ty, Name);
3956 }
3957 if (FwdVal->getName() != Name) {
3958 P.error(Loc, "name is too long which can result in name collisions, "
3959 "consider making the name shorter or "
3960 "increasing -non-global-value-max-name-size");
3961 return nullptr;
3962 }
3963
3964 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3965 return FwdVal;
3966}
3967
3968Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3969 // Look this name up in the normal function symbol table.
3970 Value *Val = NumberedVals.get(ID);
3971
3972 // If this is a forward reference for the value, see if we already created a
3973 // forward ref record.
3974 if (!Val) {
3975 auto I = ForwardRefValIDs.find(ID);
3976 if (I != ForwardRefValIDs.end())
3977 Val = I->second.first;
3978 }
3979
3980 // If we have the value in the symbol table or fwd-ref table, return it.
3981 if (Val)
3982 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3983
3984 if (!Ty->isFirstClassType()) {
3985 P.error(Loc, "invalid use of a non-first-class type");
3986 return nullptr;
3987 }
3988
3989 // Otherwise, create a new forward reference for this value and remember it.
3990 Value *FwdVal;
3991 if (Ty->isLabelTy()) {
3992 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3993 } else {
3994 FwdVal = new Argument(Ty);
3995 }
3996
3997 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3998 return FwdVal;
3999}
4000
4001/// setInstName - After an instruction is parsed and inserted into its
4002/// basic block, this installs its name.
4003bool LLParser::PerFunctionState::setInstName(int NameID,
4004 const std::string &NameStr,
4005 LocTy NameLoc, Instruction *Inst) {
4006 // If this instruction has void type, it cannot have a name or ID specified.
4007 if (Inst->getType()->isVoidTy()) {
4008 if (NameID != -1 || !NameStr.empty())
4009 return P.error(NameLoc, "instructions returning void cannot have a name");
4010 return false;
4011 }
4012
4013 // If this was a numbered instruction, verify that the instruction is the
4014 // expected value and resolve any forward references.
4015 if (NameStr.empty()) {
4016 // If neither a name nor an ID was specified, just use the next ID.
4017 if (NameID == -1)
4018 NameID = NumberedVals.getNext();
4019
4020 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4021 NameID))
4022 return true;
4023
4024 auto FI = ForwardRefValIDs.find(NameID);
4025 if (FI != ForwardRefValIDs.end()) {
4026 Value *Sentinel = FI->second.first;
4027 if (Sentinel->getType() != Inst->getType())
4028 return P.error(NameLoc, "instruction forward referenced with type '" +
4029 getTypeString(FI->second.first->getType()) +
4030 "'");
4031
4032 Sentinel->replaceAllUsesWith(Inst);
4033 Sentinel->deleteValue();
4034 ForwardRefValIDs.erase(FI);
4035 }
4036
4037 NumberedVals.add(NameID, Inst);
4038 return false;
4039 }
4040
4041 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4042 auto FI = ForwardRefVals.find(NameStr);
4043 if (FI != ForwardRefVals.end()) {
4044 Value *Sentinel = FI->second.first;
4045 if (Sentinel->getType() != Inst->getType())
4046 return P.error(NameLoc, "instruction forward referenced with type '" +
4047 getTypeString(FI->second.first->getType()) +
4048 "'");
4049
4050 Sentinel->replaceAllUsesWith(Inst);
4051 Sentinel->deleteValue();
4052 ForwardRefVals.erase(FI);
4053 }
4054
4055 // Set the name on the instruction.
4056 Inst->setName(NameStr);
4057
4058 if (Inst->getName() != NameStr)
4059 return P.error(NameLoc, "multiple definition of local value named '" +
4060 NameStr + "'");
4061 return false;
4062}
4063
4064/// getBB - Get a basic block with the specified name or ID, creating a
4065/// forward reference record if needed.
4066BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4067 LocTy Loc) {
4069 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4070}
4071
4072BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4074 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4075}
4076
4077/// defineBB - Define the specified basic block, which is either named or
4078/// unnamed. If there is an error, this returns null otherwise it returns
4079/// the block being defined.
4080BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4081 int NameID, LocTy Loc) {
4082 BasicBlock *BB;
4083 if (Name.empty()) {
4084 if (NameID != -1) {
4085 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4086 return nullptr;
4087 } else {
4088 NameID = NumberedVals.getNext();
4089 }
4090 BB = getBB(NameID, Loc);
4091 if (!BB) {
4092 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4093 return nullptr;
4094 }
4095 } else {
4096 BB = getBB(Name, Loc);
4097 if (!BB) {
4098 P.error(Loc, "unable to create block named '" + Name + "'");
4099 return nullptr;
4100 }
4101 }
4102
4103 // Move the block to the end of the function. Forward ref'd blocks are
4104 // inserted wherever they happen to be referenced.
4105 F.splice(F.end(), &F, BB->getIterator());
4106
4107 // Remove the block from forward ref sets.
4108 if (Name.empty()) {
4109 ForwardRefValIDs.erase(NameID);
4110 NumberedVals.add(NameID, BB);
4111 } else {
4112 // BB forward references are already in the function symbol table.
4113 ForwardRefVals.erase(Name);
4114 }
4115
4116 return BB;
4117}
4118
4119//===----------------------------------------------------------------------===//
4120// Constants.
4121//===----------------------------------------------------------------------===//
4122
4123/// parseValID - parse an abstract value that doesn't necessarily have a
4124/// type implied. For example, if we parse "4" we don't know what integer type
4125/// it has. The value will later be combined with its type and checked for
4126/// basic correctness. PFS is used to convert function-local operands of
4127/// metadata (since metadata operands are not just parsed here but also
4128/// converted to values). PFS can be null when we are not parsing metadata
4129/// values inside a function.
4130bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4131 ID.Loc = Lex.getLoc();
4132 switch (Lex.getKind()) {
4133 default:
4134 return tokError("expected value token");
4135 case lltok::GlobalID: // @42
4136 ID.UIntVal = Lex.getUIntVal();
4137 ID.Kind = ValID::t_GlobalID;
4138 break;
4139 case lltok::GlobalVar: // @foo
4140 ID.StrVal = Lex.getStrVal();
4141 ID.Kind = ValID::t_GlobalName;
4142 break;
4143 case lltok::LocalVarID: // %42
4144 ID.UIntVal = Lex.getUIntVal();
4145 ID.Kind = ValID::t_LocalID;
4146 break;
4147 case lltok::LocalVar: // %foo
4148 ID.StrVal = Lex.getStrVal();
4149 ID.Kind = ValID::t_LocalName;
4150 break;
4151 case lltok::APSInt:
4152 ID.APSIntVal = Lex.getAPSIntVal();
4153 ID.Kind = ValID::t_APSInt;
4154 break;
4155 case lltok::APFloat: {
4156 ID.APFloatVal = Lex.getAPFloatVal();
4157 ID.Kind = ValID::t_APFloat;
4158 break;
4159 }
4160 case lltok::FloatLiteral: {
4161 if (!ExpectedTy)
4162 return error(ID.Loc, "unexpected floating-point literal");
4163 if (!ExpectedTy->isFloatingPointTy())
4164 return error(ID.Loc, "floating-point constant invalid for type");
4165 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4166 APFloat::opStatus Except =
4167 cantFail(ID.APFloatVal.convertFromString(
4168 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4169 "Invalid float strings should be caught by the lexer");
4170 // Forbid overflowing and underflowing literals, but permit inexact
4171 // literals. Underflow is thrown when the result is denormal, so to allow
4172 // denormals, only reject underflowing literals that resulted in a zero.
4173 if (Except & APFloat::opOverflow)
4174 return error(ID.Loc, "floating-point constant overflowed type");
4175 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4176 return error(ID.Loc, "floating-point constant underflowed type");
4177 ID.Kind = ValID::t_APFloat;
4178 break;
4179 }
4181 if (!ExpectedTy)
4182 return error(ID.Loc, "unexpected floating-point literal");
4183 const auto &Semantics = ExpectedTy->getFltSemantics();
4184 const APInt &Bits = Lex.getAPSIntVal();
4185 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4186 return error(ID.Loc, "float hex literal has incorrect number of bits");
4187 ID.APFloatVal = APFloat(Semantics, Bits);
4188 ID.Kind = ValID::t_APFloat;
4189 break;
4190 }
4191 case lltok::kw_true:
4192 ID.ConstantVal = ConstantInt::getTrue(Context);
4193 ID.Kind = ValID::t_Constant;
4194 break;
4195 case lltok::kw_false:
4196 ID.ConstantVal = ConstantInt::getFalse(Context);
4197 ID.Kind = ValID::t_Constant;
4198 break;
4199 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4200 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4201 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4202 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4203 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4204
4205 case lltok::lbrace: {
4206 // ValID ::= '{' ConstVector '}'
4207 Lex.Lex();
4209 if (parseGlobalValueVector(Elts) ||
4210 parseToken(lltok::rbrace, "expected end of struct constant"))
4211 return true;
4212
4213 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4214 ID.UIntVal = Elts.size();
4215 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4216 Elts.size() * sizeof(Elts[0]));
4218 return false;
4219 }
4220 case lltok::less: {
4221 // ValID ::= '<' ConstVector '>' --> Vector.
4222 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4223 Lex.Lex();
4224 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4225
4227 LocTy FirstEltLoc = Lex.getLoc();
4228 if (parseGlobalValueVector(Elts) ||
4229 (isPackedStruct &&
4230 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4231 parseToken(lltok::greater, "expected end of constant"))
4232 return true;
4233
4234 if (isPackedStruct) {
4235 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4236 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4237 Elts.size() * sizeof(Elts[0]));
4238 ID.UIntVal = Elts.size();
4240 return false;
4241 }
4242
4243 if (Elts.empty())
4244 return error(ID.Loc, "constant vector must not be empty");
4245
4246 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4247 !Elts[0]->getType()->isFloatingPointTy() &&
4248 !Elts[0]->getType()->isPointerTy())
4249 return error(
4250 FirstEltLoc,
4251 "vector elements must have integer, byte, pointer or floating point "
4252 "type");
4253
4254 // Verify that all the vector elements have the same type.
4255 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4256 if (Elts[i]->getType() != Elts[0]->getType())
4257 return error(FirstEltLoc, "vector element #" + Twine(i) +
4258 " is not of type '" +
4259 getTypeString(Elts[0]->getType()));
4260
4261 ID.ConstantVal = ConstantVector::get(Elts);
4262 ID.Kind = ValID::t_Constant;
4263 return false;
4264 }
4265 case lltok::lsquare: { // Array Constant
4266 Lex.Lex();
4268 LocTy FirstEltLoc = Lex.getLoc();
4269 if (parseGlobalValueVector(Elts) ||
4270 parseToken(lltok::rsquare, "expected end of array constant"))
4271 return true;
4272
4273 // Handle empty element.
4274 if (Elts.empty()) {
4275 // Use undef instead of an array because it's inconvenient to determine
4276 // the element type at this point, there being no elements to examine.
4277 ID.Kind = ValID::t_EmptyArray;
4278 return false;
4279 }
4280
4281 if (!Elts[0]->getType()->isFirstClassType())
4282 return error(FirstEltLoc, "invalid array element type: " +
4283 getTypeString(Elts[0]->getType()));
4284
4285 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4286
4287 // Verify all elements are correct type!
4288 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4289 if (Elts[i]->getType() != Elts[0]->getType())
4290 return error(FirstEltLoc, "array element #" + Twine(i) +
4291 " is not of type '" +
4292 getTypeString(Elts[0]->getType()));
4293 }
4294
4295 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4296 ID.Kind = ValID::t_Constant;
4297 return false;
4298 }
4299 case lltok::kw_c: { // c "foo"
4300 Lex.Lex();
4301 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4302 ID.ConstantVal = ConstantDataArray::getString(
4303 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4304 if (parseToken(lltok::StringConstant, "expected string"))
4305 return true;
4306 ID.Kind = ValID::t_Constant;
4307 return false;
4308 }
4309 case lltok::kw_asm: {
4310 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4311 // STRINGCONSTANT
4312 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4313 Lex.Lex();
4314 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4315 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4316 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4317 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4318 parseStringConstant(ID.StrVal) ||
4319 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4320 parseToken(lltok::StringConstant, "expected constraint string"))
4321 return true;
4322 ID.StrVal2 = Lex.getStrVal();
4323 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4324 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4325 ID.Kind = ValID::t_InlineAsm;
4326 return false;
4327 }
4328
4330 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4331 Lex.Lex();
4332
4333 ValID Fn, Label;
4334
4335 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4336 parseValID(Fn, PFS) ||
4337 parseToken(lltok::comma,
4338 "expected comma in block address expression") ||
4339 parseValID(Label, PFS) ||
4340 parseToken(lltok::rparen, "expected ')' in block address expression"))
4341 return true;
4342
4344 return error(Fn.Loc, "expected function name in blockaddress");
4345 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4346 return error(Label.Loc, "expected basic block name in blockaddress");
4347
4348 // Try to find the function (but skip it if it's forward-referenced).
4349 GlobalValue *GV = nullptr;
4350 if (Fn.Kind == ValID::t_GlobalID) {
4351 GV = NumberedVals.get(Fn.UIntVal);
4352 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4353 GV = M->getNamedValue(Fn.StrVal);
4354 }
4355 Function *F = nullptr;
4356 if (GV) {
4357 // Confirm that it's actually a function with a definition.
4358 if (!isa<Function>(GV))
4359 return error(Fn.Loc, "expected function name in blockaddress");
4360 F = cast<Function>(GV);
4361 if (F->isDeclaration())
4362 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4363 }
4364
4365 if (!F) {
4366 // Make a global variable as a placeholder for this reference.
4367 GlobalValue *&FwdRef =
4368 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4369 if (!FwdRef) {
4370 unsigned FwdDeclAS;
4371 if (ExpectedTy) {
4372 // If we know the type that the blockaddress is being assigned to,
4373 // we can use the address space of that type.
4374 if (!ExpectedTy->isPointerTy())
4375 return error(ID.Loc,
4376 "type of blockaddress must be a pointer and not '" +
4377 getTypeString(ExpectedTy) + "'");
4378 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4379 } else if (PFS) {
4380 // Otherwise, we default the address space of the current function.
4381 FwdDeclAS = PFS->getFunction().getAddressSpace();
4382 } else {
4383 llvm_unreachable("Unknown address space for blockaddress");
4384 }
4385 FwdRef = new GlobalVariable(
4386 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4387 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4388 }
4389
4390 ID.ConstantVal = FwdRef;
4391 ID.Kind = ValID::t_Constant;
4392 return false;
4393 }
4394
4395 // We found the function; now find the basic block. Don't use PFS, since we
4396 // might be inside a constant expression.
4397 BasicBlock *BB;
4398 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4399 if (Label.Kind == ValID::t_LocalID)
4400 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4401 else
4402 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4403 if (!BB)
4404 return error(Label.Loc, "referenced value is not a basic block");
4405 } else {
4406 if (Label.Kind == ValID::t_LocalID)
4407 return error(Label.Loc, "cannot take address of numeric label after "
4408 "the function is defined");
4410 F->getValueSymbolTable()->lookup(Label.StrVal));
4411 if (!BB)
4412 return error(Label.Loc, "referenced value is not a basic block");
4413 }
4414
4415 ID.ConstantVal = BlockAddress::get(F, BB);
4416 ID.Kind = ValID::t_Constant;
4417 return false;
4418 }
4419
4421 // ValID ::= 'dso_local_equivalent' @foo
4422 Lex.Lex();
4423
4424 ValID Fn;
4425
4426 if (parseValID(Fn, PFS))
4427 return true;
4428
4430 return error(Fn.Loc,
4431 "expected global value name in dso_local_equivalent");
4432
4433 // Try to find the function (but skip it if it's forward-referenced).
4434 GlobalValue *GV = nullptr;
4435 if (Fn.Kind == ValID::t_GlobalID) {
4436 GV = NumberedVals.get(Fn.UIntVal);
4437 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4438 GV = M->getNamedValue(Fn.StrVal);
4439 }
4440
4441 if (!GV) {
4442 // Make a placeholder global variable as a placeholder for this reference.
4443 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4444 ? ForwardRefDSOLocalEquivalentIDs
4445 : ForwardRefDSOLocalEquivalentNames;
4446 GlobalValue *&FwdRef = FwdRefMap[Fn];
4447 if (!FwdRef) {
4448 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4449 GlobalValue::InternalLinkage, nullptr, "",
4451 }
4452
4453 ID.ConstantVal = FwdRef;
4454 ID.Kind = ValID::t_Constant;
4455 return false;
4456 }
4457
4458 if (!GV->getValueType()->isFunctionTy())
4459 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4460 "in dso_local_equivalent");
4461
4462 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4463 ID.Kind = ValID::t_Constant;
4464 return false;
4465 }
4466
4467 case lltok::kw_no_cfi: {
4468 // ValID ::= 'no_cfi' @foo
4469 Lex.Lex();
4470
4471 if (parseValID(ID, PFS))
4472 return true;
4473
4474 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4475 return error(ID.Loc, "expected global value name in no_cfi");
4476
4477 ID.NoCFI = true;
4478 return false;
4479 }
4480 case lltok::kw_ptrauth: {
4481 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4482 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4483 // )? )? ')'
4484 Lex.Lex();
4485
4486 Constant *Ptr, *Key;
4487 Constant *Disc = nullptr, *AddrDisc = nullptr,
4488 *DeactivationSymbol = nullptr;
4489
4490 if (parseToken(lltok::lparen,
4491 "expected '(' in constant ptrauth expression") ||
4492 parseGlobalTypeAndValue(Ptr) ||
4493 parseToken(lltok::comma,
4494 "expected comma in constant ptrauth expression") ||
4495 parseGlobalTypeAndValue(Key))
4496 return true;
4497 // If present, parse the optional disc/addrdisc/ds.
4498 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4499 return true;
4500 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4501 return true;
4502 if (EatIfPresent(lltok::comma) &&
4503 parseGlobalTypeAndValue(DeactivationSymbol))
4504 return true;
4505 if (parseToken(lltok::rparen,
4506 "expected ')' in constant ptrauth expression"))
4507 return true;
4508
4509 if (!Ptr->getType()->isPointerTy())
4510 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4511
4512 auto *KeyC = dyn_cast<ConstantInt>(Key);
4513 if (!KeyC || KeyC->getBitWidth() != 32)
4514 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4515
4516 ConstantInt *DiscC = nullptr;
4517 if (Disc) {
4518 DiscC = dyn_cast<ConstantInt>(Disc);
4519 if (!DiscC || DiscC->getBitWidth() != 64)
4520 return error(
4521 ID.Loc,
4522 "constant ptrauth integer discriminator must be i64 constant");
4523 } else {
4524 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4525 }
4526
4527 if (AddrDisc) {
4528 if (!AddrDisc->getType()->isPointerTy())
4529 return error(
4530 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4531 } else {
4532 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4533 }
4534
4535 if (!DeactivationSymbol)
4536 DeactivationSymbol =
4538 if (!DeactivationSymbol->getType()->isPointerTy())
4539 return error(ID.Loc,
4540 "constant ptrauth deactivation symbol must be a pointer");
4541
4542 ID.ConstantVal =
4543 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4544 ID.Kind = ValID::t_Constant;
4545 return false;
4546 }
4547
4548 case lltok::kw_trunc:
4549 case lltok::kw_bitcast:
4551 case lltok::kw_inttoptr:
4553 case lltok::kw_ptrtoint: {
4554 unsigned Opc = Lex.getUIntVal();
4555 Type *DestTy = nullptr;
4556 Constant *SrcVal;
4557 Lex.Lex();
4558 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4559 parseGlobalTypeAndValue(SrcVal) ||
4560 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4561 parseType(DestTy) ||
4562 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4563 return true;
4564 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4565 return error(ID.Loc, "invalid cast opcode for cast from '" +
4566 getTypeString(SrcVal->getType()) + "' to '" +
4567 getTypeString(DestTy) + "'");
4569 SrcVal, DestTy);
4570 ID.Kind = ValID::t_Constant;
4571 return false;
4572 }
4574 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4576 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4577 case lltok::kw_udiv:
4578 return error(ID.Loc, "udiv constexprs are no longer supported");
4579 case lltok::kw_sdiv:
4580 return error(ID.Loc, "sdiv constexprs are no longer supported");
4581 case lltok::kw_urem:
4582 return error(ID.Loc, "urem constexprs are no longer supported");
4583 case lltok::kw_srem:
4584 return error(ID.Loc, "srem constexprs are no longer supported");
4585 case lltok::kw_fadd:
4586 return error(ID.Loc, "fadd constexprs are no longer supported");
4587 case lltok::kw_fsub:
4588 return error(ID.Loc, "fsub constexprs are no longer supported");
4589 case lltok::kw_fmul:
4590 return error(ID.Loc, "fmul constexprs are no longer supported");
4591 case lltok::kw_fdiv:
4592 return error(ID.Loc, "fdiv constexprs are no longer supported");
4593 case lltok::kw_frem:
4594 return error(ID.Loc, "frem constexprs are no longer supported");
4595 case lltok::kw_and:
4596 return error(ID.Loc, "and constexprs are no longer supported");
4597 case lltok::kw_or:
4598 return error(ID.Loc, "or constexprs are no longer supported");
4599 case lltok::kw_lshr:
4600 return error(ID.Loc, "lshr constexprs are no longer supported");
4601 case lltok::kw_ashr:
4602 return error(ID.Loc, "ashr constexprs are no longer supported");
4603 case lltok::kw_shl:
4604 return error(ID.Loc, "shl constexprs are no longer supported");
4605 case lltok::kw_mul:
4606 return error(ID.Loc, "mul constexprs are no longer supported");
4607 case lltok::kw_fneg:
4608 return error(ID.Loc, "fneg constexprs are no longer supported");
4609 case lltok::kw_select:
4610 return error(ID.Loc, "select constexprs are no longer supported");
4611 case lltok::kw_zext:
4612 return error(ID.Loc, "zext constexprs are no longer supported");
4613 case lltok::kw_sext:
4614 return error(ID.Loc, "sext constexprs are no longer supported");
4615 case lltok::kw_fptrunc:
4616 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4617 case lltok::kw_fpext:
4618 return error(ID.Loc, "fpext constexprs are no longer supported");
4619 case lltok::kw_uitofp:
4620 return error(ID.Loc, "uitofp constexprs are no longer supported");
4621 case lltok::kw_sitofp:
4622 return error(ID.Loc, "sitofp constexprs are no longer supported");
4623 case lltok::kw_fptoui:
4624 return error(ID.Loc, "fptoui constexprs are no longer supported");
4625 case lltok::kw_fptosi:
4626 return error(ID.Loc, "fptosi constexprs are no longer supported");
4627 case lltok::kw_icmp:
4628 return error(ID.Loc, "icmp constexprs are no longer supported");
4629 case lltok::kw_fcmp:
4630 return error(ID.Loc, "fcmp constexprs are no longer supported");
4631
4632 // Binary Operators.
4633 case lltok::kw_add:
4634 case lltok::kw_sub:
4635 case lltok::kw_xor: {
4636 bool NUW = false;
4637 bool NSW = false;
4638 unsigned Opc = Lex.getUIntVal();
4639 Constant *Val0, *Val1;
4640 Lex.Lex();
4641 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4642 Opc == Instruction::Mul) {
4643 if (EatIfPresent(lltok::kw_nuw))
4644 NUW = true;
4645 if (EatIfPresent(lltok::kw_nsw)) {
4646 NSW = true;
4647 if (EatIfPresent(lltok::kw_nuw))
4648 NUW = true;
4649 }
4650 }
4651 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4652 parseGlobalTypeAndValue(Val0) ||
4653 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4654 parseGlobalTypeAndValue(Val1) ||
4655 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4656 return true;
4657 if (Val0->getType() != Val1->getType())
4658 return error(ID.Loc, "operands of constexpr must have same type");
4659 // Check that the type is valid for the operator.
4660 if (!Val0->getType()->isIntOrIntVectorTy())
4661 return error(ID.Loc,
4662 "constexpr requires integer or integer vector operands");
4663 unsigned Flags = 0;
4666 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4667 ID.Kind = ValID::t_Constant;
4668 return false;
4669 }
4670
4671 case lltok::kw_splat: {
4672 Lex.Lex();
4673 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4674 return true;
4675 Constant *C;
4676 if (parseGlobalTypeAndValue(C))
4677 return true;
4678 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4679 return true;
4680
4681 ID.ConstantVal = C;
4683 return false;
4684 }
4685
4690 unsigned Opc = Lex.getUIntVal();
4692 GEPNoWrapFlags NW;
4693 bool HasInRange = false;
4694 APSInt InRangeStart;
4695 APSInt InRangeEnd;
4696 Type *Ty;
4697 Lex.Lex();
4698
4699 if (Opc == Instruction::GetElementPtr) {
4700 while (true) {
4701 if (EatIfPresent(lltok::kw_inbounds))
4703 else if (EatIfPresent(lltok::kw_nusw))
4705 else if (EatIfPresent(lltok::kw_nuw))
4707 else
4708 break;
4709 }
4710
4711 if (EatIfPresent(lltok::kw_inrange)) {
4712 if (parseToken(lltok::lparen, "expected '('"))
4713 return true;
4714 if (Lex.getKind() != lltok::APSInt)
4715 return tokError("expected integer");
4716 InRangeStart = Lex.getAPSIntVal();
4717 Lex.Lex();
4718 if (parseToken(lltok::comma, "expected ','"))
4719 return true;
4720 if (Lex.getKind() != lltok::APSInt)
4721 return tokError("expected integer");
4722 InRangeEnd = Lex.getAPSIntVal();
4723 Lex.Lex();
4724 if (parseToken(lltok::rparen, "expected ')'"))
4725 return true;
4726 HasInRange = true;
4727 }
4728 }
4729
4730 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4731 return true;
4732
4733 if (Opc == Instruction::GetElementPtr) {
4734 if (parseType(Ty) ||
4735 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4736 return true;
4737 }
4738
4739 if (parseGlobalValueVector(Elts) ||
4740 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4741 return true;
4742
4743 if (Opc == Instruction::GetElementPtr) {
4744 if (Elts.size() == 0 ||
4745 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4746 return error(ID.Loc, "base of getelementptr must be a pointer");
4747
4748 Type *BaseType = Elts[0]->getType();
4749 std::optional<ConstantRange> InRange;
4750 if (HasInRange) {
4751 unsigned IndexWidth =
4752 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4753 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4754 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4755 if (InRangeStart.sge(InRangeEnd))
4756 return error(ID.Loc, "expected end to be larger than start");
4757 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4758 }
4759
4760 unsigned GEPWidth =
4761 BaseType->isVectorTy()
4762 ? cast<FixedVectorType>(BaseType)->getNumElements()
4763 : 0;
4764
4765 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4766 for (Constant *Val : Indices) {
4767 Type *ValTy = Val->getType();
4768 if (!ValTy->isIntOrIntVectorTy())
4769 return error(ID.Loc, "getelementptr index must be an integer");
4770 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4771 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4772 if (GEPWidth && (ValNumEl != GEPWidth))
4773 return error(
4774 ID.Loc,
4775 "getelementptr vector index has a wrong number of elements");
4776 // GEPWidth may have been unknown because the base is a scalar,
4777 // but it is known now.
4778 GEPWidth = ValNumEl;
4779 }
4780 }
4781
4782 SmallPtrSet<Type*, 4> Visited;
4783 if (!Indices.empty() && !Ty->isSized(&Visited))
4784 return error(ID.Loc, "base element of getelementptr must be sized");
4785
4787 return error(ID.Loc, "invalid base element for constant getelementptr");
4788
4789 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4790 return error(ID.Loc, "invalid getelementptr indices");
4791
4792 ID.ConstantVal =
4793 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4794 } else if (Opc == Instruction::ShuffleVector) {
4795 if (Elts.size() != 3)
4796 return error(ID.Loc, "expected three operands to shufflevector");
4797 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4798 return error(ID.Loc, "invalid operands to shufflevector");
4799 SmallVector<int, 16> Mask;
4801 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4802 } else if (Opc == Instruction::ExtractElement) {
4803 if (Elts.size() != 2)
4804 return error(ID.Loc, "expected two operands to extractelement");
4805 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4806 return error(ID.Loc, "invalid extractelement operands");
4807 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4808 } else {
4809 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4810 if (Elts.size() != 3)
4811 return error(ID.Loc, "expected three operands to insertelement");
4812 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4813 return error(ID.Loc, "invalid insertelement operands");
4814 ID.ConstantVal =
4815 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4816 }
4817
4818 ID.Kind = ValID::t_Constant;
4819 return false;
4820 }
4821 }
4822
4823 Lex.Lex();
4824 return false;
4825}
4826
4827/// parseGlobalValue - parse a global value with the specified type.
4828bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4829 C = nullptr;
4830 ValID ID;
4831 Value *V = nullptr;
4832 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4833 convertValIDToValue(Ty, ID, V, nullptr);
4834 if (V && !(C = dyn_cast<Constant>(V)))
4835 return error(ID.Loc, "global values must be constants");
4836 return Parsed;
4837}
4838
4839bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4840 Type *Ty = nullptr;
4841 return parseType(Ty) || parseGlobalValue(Ty, V);
4842}
4843
4844bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4845 C = nullptr;
4846
4847 LocTy KwLoc = Lex.getLoc();
4848 if (!EatIfPresent(lltok::kw_comdat))
4849 return false;
4850
4851 if (EatIfPresent(lltok::lparen)) {
4852 if (Lex.getKind() != lltok::ComdatVar)
4853 return tokError("expected comdat variable");
4854 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4855 Lex.Lex();
4856 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4857 return true;
4858 } else {
4859 if (GlobalName.empty())
4860 return tokError("comdat cannot be unnamed");
4861 C = getComdat(std::string(GlobalName), KwLoc);
4862 }
4863
4864 return false;
4865}
4866
4867/// parseGlobalValueVector
4868/// ::= /*empty*/
4869/// ::= TypeAndValue (',' TypeAndValue)*
4870bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4871 // Empty list.
4872 if (Lex.getKind() == lltok::rbrace ||
4873 Lex.getKind() == lltok::rsquare ||
4874 Lex.getKind() == lltok::greater ||
4875 Lex.getKind() == lltok::rparen)
4876 return false;
4877
4878 do {
4879 // Let the caller deal with inrange.
4880 if (Lex.getKind() == lltok::kw_inrange)
4881 return false;
4882
4883 Constant *C;
4884 if (parseGlobalTypeAndValue(C))
4885 return true;
4886 Elts.push_back(C);
4887 } while (EatIfPresent(lltok::comma));
4888
4889 return false;
4890}
4891
4892bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4894 if (parseMDNodeVector(Elts))
4895 return true;
4896
4897 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4898 return false;
4899}
4900
4901/// MDNode:
4902/// ::= !{ ... }
4903/// ::= !7
4904/// ::= !DILocation(...)
4905bool LLParser::parseMDNode(MDNode *&N) {
4906 if (Lex.getKind() == lltok::MetadataVar)
4907 return parseSpecializedMDNode(N);
4908
4909 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4910}
4911
4912bool LLParser::parseMDNodeTail(MDNode *&N) {
4913 // !{ ... }
4914 if (Lex.getKind() == lltok::lbrace)
4915 return parseMDTuple(N);
4916
4917 // !42
4918 return parseMDNodeID(N);
4919}
4920
4921namespace {
4922
4923/// Structure to represent an optional metadata field.
4924template <class FieldTy> struct MDFieldImpl {
4925 typedef MDFieldImpl ImplTy;
4926 FieldTy Val;
4927 bool Seen;
4928
4929 void assign(FieldTy Val) {
4930 Seen = true;
4931 this->Val = std::move(Val);
4932 }
4933
4934 explicit MDFieldImpl(FieldTy Default)
4935 : Val(std::move(Default)), Seen(false) {}
4936};
4937
4938/// Structure to represent an optional metadata field that
4939/// can be of either type (A or B) and encapsulates the
4940/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4941/// to reimplement the specifics for representing each Field.
4942template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4943 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4944 FieldTypeA A;
4945 FieldTypeB B;
4946 bool Seen;
4947
4948 enum {
4949 IsInvalid = 0,
4950 IsTypeA = 1,
4951 IsTypeB = 2
4952 } WhatIs;
4953
4954 void assign(FieldTypeA A) {
4955 Seen = true;
4956 this->A = std::move(A);
4957 WhatIs = IsTypeA;
4958 }
4959
4960 void assign(FieldTypeB B) {
4961 Seen = true;
4962 this->B = std::move(B);
4963 WhatIs = IsTypeB;
4964 }
4965
4966 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4967 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4968 WhatIs(IsInvalid) {}
4969};
4970
4971struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4972 uint64_t Max;
4973
4974 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4975 : ImplTy(Default), Max(Max) {}
4976};
4977
4978struct LineField : public MDUnsignedField {
4979 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4980};
4981
4982struct ColumnField : public MDUnsignedField {
4983 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4984};
4985
4986struct DwarfTagField : public MDUnsignedField {
4987 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4988 DwarfTagField(dwarf::Tag DefaultTag)
4989 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4990};
4991
4992struct DwarfMacinfoTypeField : public MDUnsignedField {
4993 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4994 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4995 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4996};
4997
4998struct DwarfAttEncodingField : public MDUnsignedField {
4999 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5000};
5001
5002struct DwarfVirtualityField : public MDUnsignedField {
5003 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5004};
5005
5006struct DwarfLangField : public MDUnsignedField {
5007 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5008};
5009
5010struct DwarfSourceLangNameField : public MDUnsignedField {
5011 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5012};
5013
5014struct DwarfCCField : public MDUnsignedField {
5015 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5016};
5017
5018struct DwarfEnumKindField : public MDUnsignedField {
5019 DwarfEnumKindField()
5020 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5021 dwarf::DW_APPLE_ENUM_KIND_max) {}
5022};
5023
5024struct EmissionKindField : public MDUnsignedField {
5025 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5026};
5027
5028struct FixedPointKindField : public MDUnsignedField {
5029 FixedPointKindField()
5030 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5031};
5032
5033struct NameTableKindField : public MDUnsignedField {
5034 NameTableKindField()
5035 : MDUnsignedField(
5036 0, (unsigned)
5037 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5038};
5039
5040struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5041 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5042};
5043
5044struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5045 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5046};
5047
5048struct MDAPSIntField : public MDFieldImpl<APSInt> {
5049 MDAPSIntField() : ImplTy(APSInt()) {}
5050};
5051
5052struct MDSignedField : public MDFieldImpl<int64_t> {
5053 int64_t Min = INT64_MIN;
5054 int64_t Max = INT64_MAX;
5055
5056 MDSignedField(int64_t Default = 0)
5057 : ImplTy(Default) {}
5058 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5059 : ImplTy(Default), Min(Min), Max(Max) {}
5060};
5061
5062struct MDBoolField : public MDFieldImpl<bool> {
5063 MDBoolField(bool Default = false) : ImplTy(Default) {}
5064};
5065
5066struct MDField : public MDFieldImpl<Metadata *> {
5067 bool AllowNull;
5068
5069 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5070};
5071
5072struct MDStringField : public MDFieldImpl<MDString *> {
5073 enum class EmptyIs {
5074 Null, //< Allow empty input string, map to nullptr
5075 Empty, //< Allow empty input string, map to an empty MDString
5076 Error, //< Disallow empty string, map to an error
5077 } EmptyIs;
5078 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5079 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5080};
5081
5082struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5083 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5084};
5085
5086struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5087 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5088};
5089
5090struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5091 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5092 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5093
5094 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5095 bool AllowNull = true)
5096 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5097
5098 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5099 bool isMDField() const { return WhatIs == IsTypeB; }
5100 int64_t getMDSignedValue() const {
5101 assert(isMDSignedField() && "Wrong field type");
5102 return A.Val;
5103 }
5104 Metadata *getMDFieldValue() const {
5105 assert(isMDField() && "Wrong field type");
5106 return B.Val;
5107 }
5108};
5109
5110struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5111 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5112 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5113
5114 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5115 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5116
5117 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5118 bool isMDField() const { return WhatIs == IsTypeB; }
5119 uint64_t getMDUnsignedValue() const {
5120 assert(isMDUnsignedField() && "Wrong field type");
5121 return A.Val;
5122 }
5123 Metadata *getMDFieldValue() const {
5124 assert(isMDField() && "Wrong field type");
5125 return B.Val;
5126 }
5127
5128 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5129 if (isMDUnsignedField())
5131 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5132 if (isMDField())
5133 return getMDFieldValue();
5134 return nullptr;
5135 }
5136};
5137
5138} // end anonymous namespace
5139
5140namespace llvm {
5141
5142template <>
5143bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5144 if (Lex.getKind() != lltok::APSInt)
5145 return tokError("expected integer");
5146
5147 Result.assign(Lex.getAPSIntVal());
5148 Lex.Lex();
5149 return false;
5150}
5151
5152template <>
5153bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5154 MDUnsignedField &Result) {
5155 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5156 return tokError("expected unsigned integer");
5157
5158 auto &U = Lex.getAPSIntVal();
5159 if (U.ugt(Result.Max))
5160 return tokError("value for '" + Name + "' too large, limit is " +
5161 Twine(Result.Max));
5162 Result.assign(U.getZExtValue());
5163 assert(Result.Val <= Result.Max && "Expected value in range");
5164 Lex.Lex();
5165 return false;
5166}
5167
5168template <>
5169bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5170 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5171}
5172template <>
5173bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5174 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5175}
5176
5177template <>
5178bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5179 if (Lex.getKind() == lltok::APSInt)
5180 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5181
5182 if (Lex.getKind() != lltok::DwarfTag)
5183 return tokError("expected DWARF tag");
5184
5185 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5187 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5188 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5189
5190 Result.assign(Tag);
5191 Lex.Lex();
5192 return false;
5193}
5194
5195template <>
5196bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5197 DwarfMacinfoTypeField &Result) {
5198 if (Lex.getKind() == lltok::APSInt)
5199 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5200
5201 if (Lex.getKind() != lltok::DwarfMacinfo)
5202 return tokError("expected DWARF macinfo type");
5203
5204 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5205 if (Macinfo == dwarf::DW_MACINFO_invalid)
5206 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5207 Lex.getStrVal() + "'");
5208 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5209
5210 Result.assign(Macinfo);
5211 Lex.Lex();
5212 return false;
5213}
5214
5215template <>
5216bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5217 DwarfVirtualityField &Result) {
5218 if (Lex.getKind() == lltok::APSInt)
5219 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5220
5221 if (Lex.getKind() != lltok::DwarfVirtuality)
5222 return tokError("expected DWARF virtuality code");
5223
5224 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5225 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5226 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5227 Lex.getStrVal() + "'");
5228 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5229 Result.assign(Virtuality);
5230 Lex.Lex();
5231 return false;
5232}
5233
5234template <>
5235bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5236 DwarfEnumKindField &Result) {
5237 if (Lex.getKind() == lltok::APSInt)
5238 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5239
5240 if (Lex.getKind() != lltok::DwarfEnumKind)
5241 return tokError("expected DWARF enum kind code");
5242
5243 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5244 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5245 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5246 Lex.getStrVal() + "'");
5247 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5248 Result.assign(EnumKind);
5249 Lex.Lex();
5250 return false;
5251}
5252
5253template <>
5254bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5255 if (Lex.getKind() == lltok::APSInt)
5256 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5257
5258 if (Lex.getKind() != lltok::DwarfLang)
5259 return tokError("expected DWARF language");
5260
5261 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5262 if (!Lang)
5263 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5264 "'");
5265 assert(Lang <= Result.Max && "Expected valid DWARF language");
5266 Result.assign(Lang);
5267 Lex.Lex();
5268 return false;
5269}
5270
5271template <>
5272bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5273 DwarfSourceLangNameField &Result) {
5274 if (Lex.getKind() == lltok::APSInt)
5275 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5276
5277 if (Lex.getKind() != lltok::DwarfSourceLangName)
5278 return tokError("expected DWARF source language name");
5279
5280 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5281 if (!Lang)
5282 return tokError("invalid DWARF source language name" + Twine(" '") +
5283 Lex.getStrVal() + "'");
5284 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5285 Result.assign(Lang);
5286 Lex.Lex();
5287 return false;
5288}
5289
5290template <>
5291bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5292 if (Lex.getKind() == lltok::APSInt)
5293 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5294
5295 if (Lex.getKind() != lltok::DwarfCC)
5296 return tokError("expected DWARF calling convention");
5297
5298 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5299 if (!CC)
5300 return tokError("invalid DWARF calling convention" + Twine(" '") +
5301 Lex.getStrVal() + "'");
5302 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5303 Result.assign(CC);
5304 Lex.Lex();
5305 return false;
5306}
5307
5308template <>
5309bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5310 EmissionKindField &Result) {
5311 if (Lex.getKind() == lltok::APSInt)
5312 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5313
5314 if (Lex.getKind() != lltok::EmissionKind)
5315 return tokError("expected emission kind");
5316
5317 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5318 if (!Kind)
5319 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5320 "'");
5321 assert(*Kind <= Result.Max && "Expected valid emission kind");
5322 Result.assign(*Kind);
5323 Lex.Lex();
5324 return false;
5325}
5326
5327template <>
5328bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5329 FixedPointKindField &Result) {
5330 if (Lex.getKind() == lltok::APSInt)
5331 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5332
5333 if (Lex.getKind() != lltok::FixedPointKind)
5334 return tokError("expected fixed-point kind");
5335
5336 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5337 if (!Kind)
5338 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5339 "'");
5340 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5341 Result.assign(*Kind);
5342 Lex.Lex();
5343 return false;
5344}
5345
5346template <>
5347bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5348 NameTableKindField &Result) {
5349 if (Lex.getKind() == lltok::APSInt)
5350 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5351
5352 if (Lex.getKind() != lltok::NameTableKind)
5353 return tokError("expected nameTable kind");
5354
5355 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5356 if (!Kind)
5357 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5358 "'");
5359 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5360 Result.assign((unsigned)*Kind);
5361 Lex.Lex();
5362 return false;
5363}
5364
5365template <>
5366bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5367 DwarfAttEncodingField &Result) {
5368 if (Lex.getKind() == lltok::APSInt)
5369 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5370
5371 if (Lex.getKind() != lltok::DwarfAttEncoding)
5372 return tokError("expected DWARF type attribute encoding");
5373
5374 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5375 if (!Encoding)
5376 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5377 Lex.getStrVal() + "'");
5378 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5379 Result.assign(Encoding);
5380 Lex.Lex();
5381 return false;
5382}
5383
5384/// DIFlagField
5385/// ::= uint32
5386/// ::= DIFlagVector
5387/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5388template <>
5389bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5390
5391 // parser for a single flag.
5392 auto parseFlag = [&](DINode::DIFlags &Val) {
5393 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5394 uint32_t TempVal = static_cast<uint32_t>(Val);
5395 bool Res = parseUInt32(TempVal);
5396 Val = static_cast<DINode::DIFlags>(TempVal);
5397 return Res;
5398 }
5399
5400 if (Lex.getKind() != lltok::DIFlag)
5401 return tokError("expected debug info flag");
5402
5403 Val = DINode::getFlag(Lex.getStrVal());
5404 if (!Val)
5405 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5406 "'");
5407 Lex.Lex();
5408 return false;
5409 };
5410
5411 // parse the flags and combine them together.
5412 DINode::DIFlags Combined = DINode::FlagZero;
5413 do {
5414 DINode::DIFlags Val;
5415 if (parseFlag(Val))
5416 return true;
5417 Combined |= Val;
5418 } while (EatIfPresent(lltok::bar));
5419
5420 Result.assign(Combined);
5421 return false;
5422}
5423
5424/// DISPFlagField
5425/// ::= uint32
5426/// ::= DISPFlagVector
5427/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5428template <>
5429bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5430
5431 // parser for a single flag.
5432 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5433 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5434 uint32_t TempVal = static_cast<uint32_t>(Val);
5435 bool Res = parseUInt32(TempVal);
5436 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5437 return Res;
5438 }
5439
5440 if (Lex.getKind() != lltok::DISPFlag)
5441 return tokError("expected debug info flag");
5442
5443 Val = DISubprogram::getFlag(Lex.getStrVal());
5444 if (!Val)
5445 return tokError(Twine("invalid subprogram debug info flag '") +
5446 Lex.getStrVal() + "'");
5447 Lex.Lex();
5448 return false;
5449 };
5450
5451 // parse the flags and combine them together.
5452 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5453 do {
5455 if (parseFlag(Val))
5456 return true;
5457 Combined |= Val;
5458 } while (EatIfPresent(lltok::bar));
5459
5460 Result.assign(Combined);
5461 return false;
5462}
5463
5464template <>
5465bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5466 if (Lex.getKind() != lltok::APSInt)
5467 return tokError("expected signed integer");
5468
5469 auto &S = Lex.getAPSIntVal();
5470 if (S < Result.Min)
5471 return tokError("value for '" + Name + "' too small, limit is " +
5472 Twine(Result.Min));
5473 if (S > Result.Max)
5474 return tokError("value for '" + Name + "' too large, limit is " +
5475 Twine(Result.Max));
5476 Result.assign(S.getExtValue());
5477 assert(Result.Val >= Result.Min && "Expected value in range");
5478 assert(Result.Val <= Result.Max && "Expected value in range");
5479 Lex.Lex();
5480 return false;
5481}
5482
5483template <>
5484bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5485 switch (Lex.getKind()) {
5486 default:
5487 return tokError("expected 'true' or 'false'");
5488 case lltok::kw_true:
5489 Result.assign(true);
5490 break;
5491 case lltok::kw_false:
5492 Result.assign(false);
5493 break;
5494 }
5495 Lex.Lex();
5496 return false;
5497}
5498
5499template <>
5500bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5501 if (Lex.getKind() == lltok::kw_null) {
5502 if (!Result.AllowNull)
5503 return tokError("'" + Name + "' cannot be null");
5504 Lex.Lex();
5505 Result.assign(nullptr);
5506 return false;
5507 }
5508
5509 Metadata *MD;
5510 if (parseMetadata(MD, nullptr))
5511 return true;
5512
5513 Result.assign(MD);
5514 return false;
5515}
5516
5517template <>
5518bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5519 MDSignedOrMDField &Result) {
5520 // Try to parse a signed int.
5521 if (Lex.getKind() == lltok::APSInt) {
5522 MDSignedField Res = Result.A;
5523 if (!parseMDField(Loc, Name, Res)) {
5524 Result.assign(Res);
5525 return false;
5526 }
5527 return true;
5528 }
5529
5530 // Otherwise, try to parse as an MDField.
5531 MDField Res = Result.B;
5532 if (!parseMDField(Loc, Name, Res)) {
5533 Result.assign(Res);
5534 return false;
5535 }
5536
5537 return true;
5538}
5539
5540template <>
5541bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5542 MDUnsignedOrMDField &Result) {
5543 // Try to parse an unsigned int.
5544 if (Lex.getKind() == lltok::APSInt) {
5545 MDUnsignedField Res = Result.A;
5546 if (!parseMDField(Loc, Name, Res)) {
5547 Result.assign(Res);
5548 return false;
5549 }
5550 return true;
5551 }
5552
5553 // Otherwise, try to parse as an MDField.
5554 MDField Res = Result.B;
5555 if (!parseMDField(Loc, Name, Res)) {
5556 Result.assign(Res);
5557 return false;
5558 }
5559
5560 return true;
5561}
5562
5563template <>
5564bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5565 LocTy ValueLoc = Lex.getLoc();
5566 std::string S;
5567 if (parseStringConstant(S))
5568 return true;
5569
5570 if (S.empty()) {
5571 switch (Result.EmptyIs) {
5572 case MDStringField::EmptyIs::Null:
5573 Result.assign(nullptr);
5574 return false;
5575 case MDStringField::EmptyIs::Empty:
5576 break;
5577 case MDStringField::EmptyIs::Error:
5578 return error(ValueLoc, "'" + Name + "' cannot be empty");
5579 }
5580 }
5581
5582 Result.assign(MDString::get(Context, S));
5583 return false;
5584}
5585
5586template <>
5587bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5589 if (parseMDNodeVector(MDs))
5590 return true;
5591
5592 Result.assign(std::move(MDs));
5593 return false;
5594}
5595
5596template <>
5597bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5598 ChecksumKindField &Result) {
5599 std::optional<DIFile::ChecksumKind> CSKind =
5600 DIFile::getChecksumKind(Lex.getStrVal());
5601
5602 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5603 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5604 "'");
5605
5606 Result.assign(*CSKind);
5607 Lex.Lex();
5608 return false;
5609}
5610
5611} // end namespace llvm
5612
5613template <class ParserTy>
5614bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5615 do {
5616 if (Lex.getKind() != lltok::LabelStr)
5617 return tokError("expected field label here");
5618
5619 if (ParseField())
5620 return true;
5621 } while (EatIfPresent(lltok::comma));
5622
5623 return false;
5624}
5625
5626template <class ParserTy>
5627bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5628 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5629 Lex.Lex();
5630
5631 if (parseToken(lltok::lparen, "expected '(' here"))
5632 return true;
5633 if (Lex.getKind() != lltok::rparen)
5634 if (parseMDFieldsImplBody(ParseField))
5635 return true;
5636
5637 ClosingLoc = Lex.getLoc();
5638 return parseToken(lltok::rparen, "expected ')' here");
5639}
5640
5641template <class FieldTy>
5642bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5643 if (Result.Seen)
5644 return tokError("field '" + Name + "' cannot be specified more than once");
5645
5646 LocTy Loc = Lex.getLoc();
5647 Lex.Lex();
5648 return parseMDField(Loc, Name, Result);
5649}
5650
5651bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5652 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5653
5654#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5655 if (Lex.getStrVal() == #CLASS) \
5656 return parse##CLASS(N, IsDistinct);
5657#include "llvm/IR/Metadata.def"
5658
5659 return tokError("expected metadata type");
5660}
5661
5662#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5663#define NOP_FIELD(NAME, TYPE, INIT)
5664#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5665 if (!NAME.Seen) \
5666 return error(ClosingLoc, "missing required field '" #NAME "'");
5667#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5668 if (Lex.getStrVal() == #NAME) \
5669 return parseMDField(#NAME, NAME);
5670#define PARSE_MD_FIELDS() \
5671 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5672 do { \
5673 LocTy ClosingLoc; \
5674 if (parseMDFieldsImpl( \
5675 [&]() -> bool { \
5676 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5677 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5678 "'"); \
5679 }, \
5680 ClosingLoc)) \
5681 return true; \
5682 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5683 } while (false)
5684#define GET_OR_DISTINCT(CLASS, ARGS) \
5685 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5686
5687/// parseDILocationFields:
5688/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5689/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5690bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5691#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5692 OPTIONAL(line, LineField, ); \
5693 OPTIONAL(column, ColumnField, ); \
5694 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5695 OPTIONAL(inlinedAt, MDField, ); \
5696 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5697 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5698 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5700#undef VISIT_MD_FIELDS
5701
5702 Result = GET_OR_DISTINCT(
5703 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5704 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5705 return false;
5706}
5707
5708/// parseDIAssignID:
5709/// ::= distinct !DIAssignID()
5710bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5711 if (!IsDistinct)
5712 return tokError("missing 'distinct', required for !DIAssignID()");
5713
5714 Lex.Lex();
5715
5716 // Now eat the parens.
5717 if (parseToken(lltok::lparen, "expected '(' here"))
5718 return true;
5719 if (parseToken(lltok::rparen, "expected ')' here"))
5720 return true;
5721
5723 return false;
5724}
5725
5726/// parseGenericDINode:
5727/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5728bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5729#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5730 REQUIRED(tag, DwarfTagField, ); \
5731 OPTIONAL(header, MDStringField, ); \
5732 OPTIONAL(operands, MDFieldList, );
5734#undef VISIT_MD_FIELDS
5735
5736 Result = GET_OR_DISTINCT(GenericDINode,
5737 (Context, tag.Val, header.Val, operands.Val));
5738 return false;
5739}
5740
5741/// parseDISubrangeType:
5742/// ::= !DISubrangeType(name: "whatever", file: !0,
5743/// line: 7, scope: !1, baseType: !2, size: 32,
5744/// align: 32, flags: 0, lowerBound: !3
5745/// upperBound: !4, stride: !5, bias: !6)
5746bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5747#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5748 OPTIONAL(name, MDStringField, ); \
5749 OPTIONAL(file, MDField, ); \
5750 OPTIONAL(line, LineField, ); \
5751 OPTIONAL(scope, MDField, ); \
5752 OPTIONAL(baseType, MDField, ); \
5753 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5754 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5755 OPTIONAL(flags, DIFlagField, ); \
5756 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5757 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5758 OPTIONAL(stride, MDSignedOrMDField, ); \
5759 OPTIONAL(bias, MDSignedOrMDField, );
5761#undef VISIT_MD_FIELDS
5762
5763 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5764 if (Bound.isMDSignedField())
5766 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5767 if (Bound.isMDField())
5768 return Bound.getMDFieldValue();
5769 return nullptr;
5770 };
5771
5772 Metadata *LowerBound = convToMetadata(lowerBound);
5773 Metadata *UpperBound = convToMetadata(upperBound);
5774 Metadata *Stride = convToMetadata(stride);
5775 Metadata *Bias = convToMetadata(bias);
5776
5778 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5779 size.getValueAsMetadata(Context), align.Val, flags.Val,
5780 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5781
5782 return false;
5783}
5784
5785/// parseDISubrange:
5786/// ::= !DISubrange(count: 30, lowerBound: 2)
5787/// ::= !DISubrange(count: !node, lowerBound: 2)
5788/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5789bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5790#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5791 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5792 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5793 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5794 OPTIONAL(stride, MDSignedOrMDField, );
5796#undef VISIT_MD_FIELDS
5797
5798 Metadata *Count = nullptr;
5799 Metadata *LowerBound = nullptr;
5800 Metadata *UpperBound = nullptr;
5801 Metadata *Stride = nullptr;
5802
5803 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5804 if (Bound.isMDSignedField())
5806 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5807 if (Bound.isMDField())
5808 return Bound.getMDFieldValue();
5809 return nullptr;
5810 };
5811
5812 Count = convToMetadata(count);
5813 LowerBound = convToMetadata(lowerBound);
5814 UpperBound = convToMetadata(upperBound);
5815 Stride = convToMetadata(stride);
5816
5817 Result = GET_OR_DISTINCT(DISubrange,
5818 (Context, Count, LowerBound, UpperBound, Stride));
5819
5820 return false;
5821}
5822
5823/// parseDIGenericSubrange:
5824/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5825/// !node3)
5826bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5827#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5828 OPTIONAL(count, MDSignedOrMDField, ); \
5829 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5830 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5831 OPTIONAL(stride, MDSignedOrMDField, );
5833#undef VISIT_MD_FIELDS
5834
5835 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5836 if (Bound.isMDSignedField())
5837 return DIExpression::get(
5838 Context, {dwarf::DW_OP_consts,
5839 static_cast<uint64_t>(Bound.getMDSignedValue())});
5840 if (Bound.isMDField())
5841 return Bound.getMDFieldValue();
5842 return nullptr;
5843 };
5844
5845 Metadata *Count = ConvToMetadata(count);
5846 Metadata *LowerBound = ConvToMetadata(lowerBound);
5847 Metadata *UpperBound = ConvToMetadata(upperBound);
5848 Metadata *Stride = ConvToMetadata(stride);
5849
5850 Result = GET_OR_DISTINCT(DIGenericSubrange,
5851 (Context, Count, LowerBound, UpperBound, Stride));
5852
5853 return false;
5854}
5855
5856/// parseDIEnumerator:
5857/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5858bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5859#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5860 REQUIRED(name, MDStringField, ); \
5861 REQUIRED(value, MDAPSIntField, ); \
5862 OPTIONAL(isUnsigned, MDBoolField, (false));
5864#undef VISIT_MD_FIELDS
5865
5866 if (isUnsigned.Val && value.Val.isNegative())
5867 return tokError("unsigned enumerator with negative value");
5868
5869 APSInt Value(value.Val);
5870 // Add a leading zero so that unsigned values with the msb set are not
5871 // mistaken for negative values when used for signed enumerators.
5872 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5873 Value = Value.zext(Value.getBitWidth() + 1);
5874
5875 Result =
5876 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5877
5878 return false;
5879}
5880
5881/// parseDIBasicType:
5882/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5883/// encoding: DW_ATE_encoding, flags: 0)
5884bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5885#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5886 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5887 OPTIONAL(name, MDStringField, ); \
5888 OPTIONAL(file, MDField, ); \
5889 OPTIONAL(line, LineField, ); \
5890 OPTIONAL(scope, MDField, ); \
5891 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5892 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5893 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5894 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5895 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5896 OPTIONAL(flags, DIFlagField, );
5898#undef VISIT_MD_FIELDS
5899
5901 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5902 size.getValueAsMetadata(Context), align.Val, encoding.Val,
5903 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5904 return false;
5905}
5906
5907/// parseDIFixedPointType:
5908/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5909/// align: 32, encoding: DW_ATE_signed_fixed,
5910/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5911/// denominator: 8)
5912bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5913#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5914 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5915 OPTIONAL(name, MDStringField, ); \
5916 OPTIONAL(file, MDField, ); \
5917 OPTIONAL(line, LineField, ); \
5918 OPTIONAL(scope, MDField, ); \
5919 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5920 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5921 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5922 OPTIONAL(flags, DIFlagField, ); \
5923 OPTIONAL(kind, FixedPointKindField, ); \
5924 OPTIONAL(factor, MDSignedField, ); \
5925 OPTIONAL(numerator, MDAPSIntField, ); \
5926 OPTIONAL(denominator, MDAPSIntField, );
5928#undef VISIT_MD_FIELDS
5929
5930 Result = GET_OR_DISTINCT(DIFixedPointType,
5931 (Context, tag.Val, name.Val, file.Val, line.Val,
5932 scope.Val, size.getValueAsMetadata(Context),
5933 align.Val, encoding.Val, flags.Val, kind.Val,
5934 factor.Val, numerator.Val, denominator.Val));
5935 return false;
5936}
5937
5938/// parseDIStringType:
5939/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5940bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5943 OPTIONAL(name, MDStringField, ); \
5944 OPTIONAL(stringLength, MDField, ); \
5945 OPTIONAL(stringLengthExpression, MDField, ); \
5946 OPTIONAL(stringLocationExpression, MDField, ); \
5947 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5948 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5949 OPTIONAL(encoding, DwarfAttEncodingField, );
5951#undef VISIT_MD_FIELDS
5952
5954 DIStringType,
5955 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5956 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5957 align.Val, encoding.Val));
5958 return false;
5959}
5960
5961/// parseDIDerivedType:
5962/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5963/// line: 7, scope: !1, baseType: !2, size: 32,
5964/// align: 32, offset: 0, flags: 0, extraData: !3,
5965/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5966/// ptrAuthIsAddressDiscriminated: true,
5967/// ptrAuthExtraDiscriminator: 0x1234,
5968/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5969/// )
5970bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5971#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5972 REQUIRED(tag, DwarfTagField, ); \
5973 OPTIONAL(name, MDStringField, ); \
5974 OPTIONAL(file, MDField, ); \
5975 OPTIONAL(line, LineField, ); \
5976 OPTIONAL(scope, MDField, ); \
5977 REQUIRED(baseType, MDField, ); \
5978 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5979 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5980 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5981 OPTIONAL(flags, DIFlagField, ); \
5982 OPTIONAL(extraData, MDField, ); \
5983 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5984 OPTIONAL(annotations, MDField, ); \
5985 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5986 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5987 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5988 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5989 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5991#undef VISIT_MD_FIELDS
5992
5993 std::optional<unsigned> DWARFAddressSpace;
5994 if (dwarfAddressSpace.Val != UINT32_MAX)
5995 DWARFAddressSpace = dwarfAddressSpace.Val;
5996 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5997 if (ptrAuthKey.Val)
5998 PtrAuthData.emplace(
5999 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6000 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6001 ptrAuthAuthenticatesNullValues.Val);
6002
6004 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6005 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6006 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6007 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6008 return false;
6009}
6010
6011bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6012#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6013 REQUIRED(tag, DwarfTagField, ); \
6014 OPTIONAL(name, MDStringField, ); \
6015 OPTIONAL(file, MDField, ); \
6016 OPTIONAL(line, LineField, ); \
6017 OPTIONAL(scope, MDField, ); \
6018 OPTIONAL(baseType, MDField, ); \
6019 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6020 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6021 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6022 OPTIONAL(flags, DIFlagField, ); \
6023 OPTIONAL(elements, MDField, ); \
6024 OPTIONAL(runtimeLang, DwarfLangField, ); \
6025 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6026 OPTIONAL(vtableHolder, MDField, ); \
6027 OPTIONAL(templateParams, MDField, ); \
6028 OPTIONAL(identifier, MDStringField, ); \
6029 OPTIONAL(discriminator, MDField, ); \
6030 OPTIONAL(dataLocation, MDField, ); \
6031 OPTIONAL(associated, MDField, ); \
6032 OPTIONAL(allocated, MDField, ); \
6033 OPTIONAL(rank, MDSignedOrMDField, ); \
6034 OPTIONAL(annotations, MDField, ); \
6035 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6036 OPTIONAL(specification, MDField, ); \
6037 OPTIONAL(bitStride, MDField, );
6039#undef VISIT_MD_FIELDS
6040
6041 Metadata *Rank = nullptr;
6042 if (rank.isMDSignedField())
6044 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6045 else if (rank.isMDField())
6046 Rank = rank.getMDFieldValue();
6047
6048 std::optional<unsigned> EnumKind;
6049 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6050 EnumKind = enumKind.Val;
6051
6052 // If this has an identifier try to build an ODR type.
6053 if (identifier.Val)
6054 if (auto *CT = DICompositeType::buildODRType(
6055 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6056 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6057 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6058 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6059 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6060 dataLocation.Val, associated.Val, allocated.Val, Rank,
6061 annotations.Val, bitStride.Val)) {
6062 Result = CT;
6063 return false;
6064 }
6065
6066 // Create a new node, and save it in the context if it belongs in the type
6067 // map.
6069 DICompositeType,
6070 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6071 size.getValueAsMetadata(Context), align.Val,
6072 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6073 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6074 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6075 allocated.Val, Rank, annotations.Val, specification.Val,
6076 num_extra_inhabitants.Val, bitStride.Val));
6077 return false;
6078}
6079
6080bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6081#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6082 OPTIONAL(flags, DIFlagField, ); \
6083 OPTIONAL(cc, DwarfCCField, ); \
6084 REQUIRED(types, MDField, );
6086#undef VISIT_MD_FIELDS
6087
6088 Result = GET_OR_DISTINCT(DISubroutineType,
6089 (Context, flags.Val, cc.Val, types.Val));
6090 return false;
6091}
6092
6093/// parseDIFileType:
6094/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6095/// checksumkind: CSK_MD5,
6096/// checksum: "000102030405060708090a0b0c0d0e0f",
6097/// source: "source file contents")
6098bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6099 // The default constructed value for checksumkind is required, but will never
6100 // be used, as the parser checks if the field was actually Seen before using
6101 // the Val.
6102#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6103 REQUIRED(filename, MDStringField, ); \
6104 REQUIRED(directory, MDStringField, ); \
6105 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6106 OPTIONAL(checksum, MDStringField, ); \
6107 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6109#undef VISIT_MD_FIELDS
6110
6111 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6112 if (checksumkind.Seen && checksum.Seen)
6113 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6114 else if (checksumkind.Seen || checksum.Seen)
6115 return tokError("'checksumkind' and 'checksum' must be provided together");
6116
6117 MDString *Source = nullptr;
6118 if (source.Seen)
6119 Source = source.Val;
6121 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6122 return false;
6123}
6124
6125/// parseDICompileUnit:
6126/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6127/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6128/// splitDebugFilename: "abc.debug",
6129/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6130/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6131/// sysroot: "/", sdk: "MacOSX.sdk")
6132bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6133 if (!IsDistinct)
6134 return tokError("missing 'distinct', required for !DICompileUnit");
6135
6136 LocTy Loc = Lex.getLoc();
6137
6138#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6139 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6140 OPTIONAL(language, DwarfLangField, ); \
6141 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6142 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6143 OPTIONAL(producer, MDStringField, ); \
6144 OPTIONAL(isOptimized, MDBoolField, ); \
6145 OPTIONAL(flags, MDStringField, ); \
6146 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6147 OPTIONAL(splitDebugFilename, MDStringField, ); \
6148 OPTIONAL(emissionKind, EmissionKindField, ); \
6149 OPTIONAL(enums, MDField, ); \
6150 OPTIONAL(retainedTypes, MDField, ); \
6151 OPTIONAL(globals, MDField, ); \
6152 OPTIONAL(imports, MDField, ); \
6153 OPTIONAL(macros, MDField, ); \
6154 OPTIONAL(dwoId, MDUnsignedField, ); \
6155 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6156 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6157 OPTIONAL(nameTableKind, NameTableKindField, ); \
6158 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6159 OPTIONAL(sysroot, MDStringField, ); \
6160 OPTIONAL(sdk, MDStringField, );
6162#undef VISIT_MD_FIELDS
6163
6164 if (!language.Seen && !sourceLanguageName.Seen)
6165 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6166 "required for !DICompileUnit");
6167
6168 if (language.Seen && sourceLanguageName.Seen)
6169 return error(Loc, "can only specify one of 'language' and "
6170 "'sourceLanguageName' on !DICompileUnit");
6171
6172 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6173 return error(Loc, "'sourceLanguageVersion' requires an associated "
6174 "'sourceLanguageName' on !DICompileUnit");
6175
6177 Context,
6178 language.Seen ? DISourceLanguageName(language.Val)
6179 : DISourceLanguageName(sourceLanguageName.Val,
6180 sourceLanguageVersion.Val),
6181 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
6182 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
6183 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
6184 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
6185 sysroot.Val, sdk.Val);
6186 return false;
6187}
6188
6189/// parseDISubprogram:
6190/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6191/// file: !1, line: 7, type: !2, isLocal: false,
6192/// isDefinition: true, scopeLine: 8, containingType: !3,
6193/// virtuality: DW_VIRTUALTIY_pure_virtual,
6194/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6195/// spFlags: 10, isOptimized: false, templateParams: !4,
6196/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6197/// annotations: !8)
6198bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6199 auto Loc = Lex.getLoc();
6200#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6201 OPTIONAL(scope, MDField, ); \
6202 OPTIONAL(name, MDStringField, ); \
6203 OPTIONAL(linkageName, MDStringField, ); \
6204 OPTIONAL(file, MDField, ); \
6205 OPTIONAL(line, LineField, ); \
6206 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6207 OPTIONAL(isLocal, MDBoolField, ); \
6208 OPTIONAL(isDefinition, MDBoolField, (true)); \
6209 OPTIONAL(scopeLine, LineField, ); \
6210 OPTIONAL(containingType, MDField, ); \
6211 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6212 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6213 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6214 OPTIONAL(flags, DIFlagField, ); \
6215 OPTIONAL(spFlags, DISPFlagField, ); \
6216 OPTIONAL(isOptimized, MDBoolField, ); \
6217 OPTIONAL(unit, MDField, ); \
6218 OPTIONAL(templateParams, MDField, ); \
6219 OPTIONAL(declaration, MDField, ); \
6220 OPTIONAL(retainedNodes, MDField, ); \
6221 OPTIONAL(thrownTypes, MDField, ); \
6222 OPTIONAL(annotations, MDField, ); \
6223 OPTIONAL(targetFuncName, MDStringField, ); \
6224 OPTIONAL(keyInstructions, MDBoolField, );
6226#undef VISIT_MD_FIELDS
6227
6228 // An explicit spFlags field takes precedence over individual fields in
6229 // older IR versions.
6230 DISubprogram::DISPFlags SPFlags =
6231 spFlags.Seen ? spFlags.Val
6232 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6233 isOptimized.Val, virtuality.Val);
6234 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6235 return error(
6236 Loc,
6237 "missing 'distinct', required for !DISubprogram that is a Definition");
6239 DISubprogram,
6240 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6241 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6242 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6243 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6244 targetFuncName.Val, keyInstructions.Val));
6245
6246 if (IsDistinct)
6247 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6248
6249 return false;
6250}
6251
6252/// parseDILexicalBlock:
6253/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6254bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6255#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6256 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6257 OPTIONAL(file, MDField, ); \
6258 OPTIONAL(line, LineField, ); \
6259 OPTIONAL(column, ColumnField, );
6261#undef VISIT_MD_FIELDS
6262
6264 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6265 return false;
6266}
6267
6268/// parseDILexicalBlockFile:
6269/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6270bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6271#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6272 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6273 OPTIONAL(file, MDField, ); \
6274 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6276#undef VISIT_MD_FIELDS
6277
6278 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6279 (Context, scope.Val, file.Val, discriminator.Val));
6280 return false;
6281}
6282
6283/// parseDICommonBlock:
6284/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6285bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6286#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6287 REQUIRED(scope, MDField, ); \
6288 OPTIONAL(declaration, MDField, ); \
6289 OPTIONAL(name, MDStringField, ); \
6290 OPTIONAL(file, MDField, ); \
6291 OPTIONAL(line, LineField, );
6293#undef VISIT_MD_FIELDS
6294
6295 Result = GET_OR_DISTINCT(DICommonBlock,
6296 (Context, scope.Val, declaration.Val, name.Val,
6297 file.Val, line.Val));
6298 return false;
6299}
6300
6301/// parseDINamespace:
6302/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6303bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6304#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6305 REQUIRED(scope, MDField, ); \
6306 OPTIONAL(name, MDStringField, ); \
6307 OPTIONAL(exportSymbols, MDBoolField, );
6309#undef VISIT_MD_FIELDS
6310
6311 Result = GET_OR_DISTINCT(DINamespace,
6312 (Context, scope.Val, name.Val, exportSymbols.Val));
6313 return false;
6314}
6315
6316/// parseDIMacro:
6317/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6318/// "SomeValue")
6319bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6320#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6321 REQUIRED(type, DwarfMacinfoTypeField, ); \
6322 OPTIONAL(line, LineField, ); \
6323 REQUIRED(name, MDStringField, ); \
6324 OPTIONAL(value, MDStringField, );
6326#undef VISIT_MD_FIELDS
6327
6328 Result = GET_OR_DISTINCT(DIMacro,
6329 (Context, type.Val, line.Val, name.Val, value.Val));
6330 return false;
6331}
6332
6333/// parseDIMacroFile:
6334/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6335bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6336#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6337 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6338 OPTIONAL(line, LineField, ); \
6339 REQUIRED(file, MDField, ); \
6340 OPTIONAL(nodes, MDField, );
6342#undef VISIT_MD_FIELDS
6343
6344 Result = GET_OR_DISTINCT(DIMacroFile,
6345 (Context, type.Val, line.Val, file.Val, nodes.Val));
6346 return false;
6347}
6348
6349/// parseDIModule:
6350/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6351/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6352/// file: !1, line: 4, isDecl: false)
6353bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6354#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6355 REQUIRED(scope, MDField, ); \
6356 REQUIRED(name, MDStringField, ); \
6357 OPTIONAL(configMacros, MDStringField, ); \
6358 OPTIONAL(includePath, MDStringField, ); \
6359 OPTIONAL(apinotes, MDStringField, ); \
6360 OPTIONAL(file, MDField, ); \
6361 OPTIONAL(line, LineField, ); \
6362 OPTIONAL(isDecl, MDBoolField, );
6364#undef VISIT_MD_FIELDS
6365
6366 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6367 configMacros.Val, includePath.Val,
6368 apinotes.Val, line.Val, isDecl.Val));
6369 return false;
6370}
6371
6372/// parseDITemplateTypeParameter:
6373/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6374bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6375#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6376 OPTIONAL(name, MDStringField, ); \
6377 REQUIRED(type, MDField, ); \
6378 OPTIONAL(defaulted, MDBoolField, );
6380#undef VISIT_MD_FIELDS
6381
6382 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6383 (Context, name.Val, type.Val, defaulted.Val));
6384 return false;
6385}
6386
6387/// parseDITemplateValueParameter:
6388/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6389/// name: "V", type: !1, defaulted: false,
6390/// value: i32 7)
6391bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6392#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6393 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6394 OPTIONAL(name, MDStringField, ); \
6395 OPTIONAL(type, MDField, ); \
6396 OPTIONAL(defaulted, MDBoolField, ); \
6397 REQUIRED(value, MDField, );
6398
6400#undef VISIT_MD_FIELDS
6401
6403 DITemplateValueParameter,
6404 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6405 return false;
6406}
6407
6408/// parseDIGlobalVariable:
6409/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6410/// file: !1, line: 7, type: !2, isLocal: false,
6411/// isDefinition: true, templateParams: !3,
6412/// declaration: !4, align: 8)
6413bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6414#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6415 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6416 OPTIONAL(scope, MDField, ); \
6417 OPTIONAL(linkageName, MDStringField, ); \
6418 OPTIONAL(file, MDField, ); \
6419 OPTIONAL(line, LineField, ); \
6420 OPTIONAL(type, MDField, ); \
6421 OPTIONAL(isLocal, MDBoolField, ); \
6422 OPTIONAL(isDefinition, MDBoolField, (true)); \
6423 OPTIONAL(templateParams, MDField, ); \
6424 OPTIONAL(declaration, MDField, ); \
6425 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6426 OPTIONAL(annotations, MDField, );
6428#undef VISIT_MD_FIELDS
6429
6430 Result =
6431 GET_OR_DISTINCT(DIGlobalVariable,
6432 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6433 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6434 declaration.Val, templateParams.Val, align.Val,
6435 annotations.Val));
6436 return false;
6437}
6438
6439/// parseDILocalVariable:
6440/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6441/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6442/// align: 8)
6443/// ::= !DILocalVariable(scope: !0, name: "foo",
6444/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6445/// align: 8)
6446bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6447#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6448 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6449 OPTIONAL(name, MDStringField, ); \
6450 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6451 OPTIONAL(file, MDField, ); \
6452 OPTIONAL(line, LineField, ); \
6453 OPTIONAL(type, MDField, ); \
6454 OPTIONAL(flags, DIFlagField, ); \
6455 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6456 OPTIONAL(annotations, MDField, );
6458#undef VISIT_MD_FIELDS
6459
6460 Result = GET_OR_DISTINCT(DILocalVariable,
6461 (Context, scope.Val, name.Val, file.Val, line.Val,
6462 type.Val, arg.Val, flags.Val, align.Val,
6463 annotations.Val));
6464 return false;
6465}
6466
6467/// parseDILabel:
6468/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6469bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6470#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6471 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6472 REQUIRED(name, MDStringField, ); \
6473 REQUIRED(file, MDField, ); \
6474 REQUIRED(line, LineField, ); \
6475 OPTIONAL(column, ColumnField, ); \
6476 OPTIONAL(isArtificial, MDBoolField, ); \
6477 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6479#undef VISIT_MD_FIELDS
6480
6481 std::optional<unsigned> CoroSuspendIdx =
6482 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6483 : std::nullopt;
6484
6485 Result = GET_OR_DISTINCT(DILabel,
6486 (Context, scope.Val, name.Val, file.Val, line.Val,
6487 column.Val, isArtificial.Val, CoroSuspendIdx));
6488 return false;
6489}
6490
6491/// parseDIExpressionBody:
6492/// ::= (0, 7, -1)
6493bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6494 if (parseToken(lltok::lparen, "expected '(' here"))
6495 return true;
6496
6497 SmallVector<uint64_t, 8> Elements;
6498 if (Lex.getKind() != lltok::rparen)
6499 do {
6500 if (Lex.getKind() == lltok::DwarfOp) {
6501 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6502 Lex.Lex();
6503 Elements.push_back(Op);
6504 continue;
6505 }
6506 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6507 }
6508
6509 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6510 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6511 Lex.Lex();
6512 Elements.push_back(Op);
6513 continue;
6514 }
6515 return tokError(Twine("invalid DWARF attribute encoding '") +
6516 Lex.getStrVal() + "'");
6517 }
6518
6519 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6520 return tokError("expected unsigned integer");
6521
6522 auto &U = Lex.getAPSIntVal();
6523 if (U.ugt(UINT64_MAX))
6524 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6525 Elements.push_back(U.getZExtValue());
6526 Lex.Lex();
6527 } while (EatIfPresent(lltok::comma));
6528
6529 if (parseToken(lltok::rparen, "expected ')' here"))
6530 return true;
6531
6532 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6533 return false;
6534}
6535
6536/// parseDIExpression:
6537/// ::= !DIExpression(0, 7, -1)
6538bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6539 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6540 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6541 Lex.Lex();
6542
6543 return parseDIExpressionBody(Result, IsDistinct);
6544}
6545
6546/// ParseDIArgList:
6547/// ::= !DIArgList(i32 7, i64 %0)
6548bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6549 assert(PFS && "Expected valid function state");
6550 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6551 Lex.Lex();
6552
6553 if (parseToken(lltok::lparen, "expected '(' here"))
6554 return true;
6555
6557 if (Lex.getKind() != lltok::rparen)
6558 do {
6559 Metadata *MD;
6560 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6561 return true;
6562 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6563 } while (EatIfPresent(lltok::comma));
6564
6565 if (parseToken(lltok::rparen, "expected ')' here"))
6566 return true;
6567
6568 MD = DIArgList::get(Context, Args);
6569 return false;
6570}
6571
6572/// parseDIGlobalVariableExpression:
6573/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6574bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6575 bool IsDistinct) {
6576#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6577 REQUIRED(var, MDField, ); \
6578 REQUIRED(expr, MDField, );
6580#undef VISIT_MD_FIELDS
6581
6582 Result =
6583 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6584 return false;
6585}
6586
6587/// parseDIObjCProperty:
6588/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6589/// getter: "getFoo", attributes: 7, type: !2)
6590bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6591#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6592 OPTIONAL(name, MDStringField, ); \
6593 OPTIONAL(file, MDField, ); \
6594 OPTIONAL(line, LineField, ); \
6595 OPTIONAL(setter, MDStringField, ); \
6596 OPTIONAL(getter, MDStringField, ); \
6597 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6598 OPTIONAL(type, MDField, );
6600#undef VISIT_MD_FIELDS
6601
6602 Result = GET_OR_DISTINCT(DIObjCProperty,
6603 (Context, name.Val, file.Val, line.Val, getter.Val,
6604 setter.Val, attributes.Val, type.Val));
6605 return false;
6606}
6607
6608/// parseDIImportedEntity:
6609/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6610/// line: 7, name: "foo", elements: !2)
6611bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6612#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6613 REQUIRED(tag, DwarfTagField, ); \
6614 REQUIRED(scope, MDField, ); \
6615 OPTIONAL(entity, MDField, ); \
6616 OPTIONAL(file, MDField, ); \
6617 OPTIONAL(line, LineField, ); \
6618 OPTIONAL(name, MDStringField, ); \
6619 OPTIONAL(elements, MDField, );
6621#undef VISIT_MD_FIELDS
6622
6623 Result = GET_OR_DISTINCT(DIImportedEntity,
6624 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6625 line.Val, name.Val, elements.Val));
6626 return false;
6627}
6628
6629#undef PARSE_MD_FIELD
6630#undef NOP_FIELD
6631#undef REQUIRE_FIELD
6632#undef DECLARE_FIELD
6633
6634/// parseMetadataAsValue
6635/// ::= metadata i32 %local
6636/// ::= metadata i32 @global
6637/// ::= metadata i32 7
6638/// ::= metadata !0
6639/// ::= metadata !{...}
6640/// ::= metadata !"string"
6641bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6642 // Note: the type 'metadata' has already been parsed.
6643 Metadata *MD;
6644 if (parseMetadata(MD, &PFS))
6645 return true;
6646
6647 V = MetadataAsValue::get(Context, MD);
6648 return false;
6649}
6650
6651/// parseValueAsMetadata
6652/// ::= i32 %local
6653/// ::= i32 @global
6654/// ::= i32 7
6655bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6656 PerFunctionState *PFS) {
6657 Type *Ty;
6658 LocTy Loc;
6659 if (parseType(Ty, TypeMsg, Loc))
6660 return true;
6661 if (Ty->isMetadataTy())
6662 return error(Loc, "invalid metadata-value-metadata roundtrip");
6663
6664 Value *V;
6665 if (parseValue(Ty, V, PFS))
6666 return true;
6667
6668 MD = ValueAsMetadata::get(V);
6669 return false;
6670}
6671
6672/// parseMetadata
6673/// ::= i32 %local
6674/// ::= i32 @global
6675/// ::= i32 7
6676/// ::= !42
6677/// ::= !{...}
6678/// ::= !"string"
6679/// ::= !DILocation(...)
6680bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6681 if (Lex.getKind() == lltok::MetadataVar) {
6682 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6683 // so parsing this requires a Function State.
6684 if (Lex.getStrVal() == "DIArgList") {
6685 Metadata *AL;
6686 if (parseDIArgList(AL, PFS))
6687 return true;
6688 MD = AL;
6689 return false;
6690 }
6691 MDNode *N;
6692 if (parseSpecializedMDNode(N)) {
6693 return true;
6694 }
6695 MD = N;
6696 return false;
6697 }
6698
6699 // ValueAsMetadata:
6700 // <type> <value>
6701 if (Lex.getKind() != lltok::exclaim)
6702 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6703
6704 // '!'.
6705 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6706 Lex.Lex();
6707
6708 // MDString:
6709 // ::= '!' STRINGCONSTANT
6710 if (Lex.getKind() == lltok::StringConstant) {
6711 MDString *S;
6712 if (parseMDString(S))
6713 return true;
6714 MD = S;
6715 return false;
6716 }
6717
6718 // MDNode:
6719 // !{ ... }
6720 // !7
6721 MDNode *N;
6722 if (parseMDNodeTail(N))
6723 return true;
6724 MD = N;
6725 return false;
6726}
6727
6728//===----------------------------------------------------------------------===//
6729// Function Parsing.
6730//===----------------------------------------------------------------------===//
6731
6732bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6733 PerFunctionState *PFS) {
6734 if (Ty->isFunctionTy())
6735 return error(ID.Loc, "functions are not values, refer to them as pointers");
6736
6737 switch (ID.Kind) {
6738 case ValID::t_LocalID:
6739 if (!PFS)
6740 return error(ID.Loc, "invalid use of function-local name");
6741 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6742 return V == nullptr;
6743 case ValID::t_LocalName:
6744 if (!PFS)
6745 return error(ID.Loc, "invalid use of function-local name");
6746 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6747 return V == nullptr;
6748 case ValID::t_InlineAsm: {
6749 if (!ID.FTy)
6750 return error(ID.Loc, "invalid type for inline asm constraint string");
6751 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6752 return error(ID.Loc, toString(std::move(Err)));
6753 V = InlineAsm::get(
6754 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6755 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6756 return false;
6757 }
6759 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6760 if (V && ID.NoCFI)
6762 return V == nullptr;
6763 case ValID::t_GlobalID:
6764 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6765 if (V && ID.NoCFI)
6767 return V == nullptr;
6768 case ValID::t_APSInt:
6769 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6770 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6771 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6772 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6773 : V = ConstantByte::get(Context, ID.APSIntVal);
6774 return false;
6775 case ValID::t_APFloat:
6776 if (!Ty->isFloatingPointTy() ||
6777 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6778 return error(ID.Loc, "floating point constant invalid for type");
6779
6780 // The lexer has no type info, so builds all half, bfloat, float, and double
6781 // FP constants as double. Fix this here. Long double does not need this.
6782 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6783 // Check for signaling before potentially converting and losing that info.
6784 bool IsSNAN = ID.APFloatVal.isSignaling();
6785 bool Ignored;
6786 if (Ty->isHalfTy())
6787 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6788 &Ignored);
6789 else if (Ty->isBFloatTy())
6790 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6791 &Ignored);
6792 else if (Ty->isFloatTy())
6793 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6794 &Ignored);
6795 if (IsSNAN) {
6796 // The convert call above may quiet an SNaN, so manufacture another
6797 // SNaN. The bitcast works because the payload (significand) parameter
6798 // is truncated to fit.
6799 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6800 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6801 ID.APFloatVal.isNegative(), &Payload);
6802 }
6803 }
6804 V = ConstantFP::get(Context, ID.APFloatVal);
6805
6806 if (V->getType() != Ty)
6807 return error(ID.Loc, "floating point constant does not have type '" +
6808 getTypeString(Ty) + "'");
6809
6810 return false;
6811 case ValID::t_Null:
6812 if (!Ty->isPointerTy())
6813 return error(ID.Loc, "null must be a pointer type");
6815 return false;
6816 case ValID::t_Undef:
6817 // FIXME: LabelTy should not be a first-class type.
6818 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6819 return error(ID.Loc, "invalid type for undef constant");
6820 V = UndefValue::get(Ty);
6821 return false;
6823 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6824 return error(ID.Loc, "invalid empty array initializer");
6825 V = PoisonValue::get(Ty);
6826 return false;
6827 case ValID::t_Zero:
6828 // FIXME: LabelTy should not be a first-class type.
6829 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6830 return error(ID.Loc, "invalid type for null constant");
6831 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6832 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6833 return error(ID.Loc, "invalid type for null constant");
6835 return false;
6836 case ValID::t_None:
6837 if (!Ty->isTokenTy())
6838 return error(ID.Loc, "invalid type for none constant");
6840 return false;
6841 case ValID::t_Poison:
6842 // FIXME: LabelTy should not be a first-class type.
6843 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6844 return error(ID.Loc, "invalid type for poison constant");
6845 V = PoisonValue::get(Ty);
6846 return false;
6847 case ValID::t_Constant:
6848 if (ID.ConstantVal->getType() != Ty)
6849 return error(ID.Loc, "constant expression type mismatch: got type '" +
6850 getTypeString(ID.ConstantVal->getType()) +
6851 "' but expected '" + getTypeString(Ty) + "'");
6852 V = ID.ConstantVal;
6853 return false;
6855 if (!Ty->isVectorTy())
6856 return error(ID.Loc, "vector constant must have vector type");
6857 if (ID.ConstantVal->getType() != Ty->getScalarType())
6858 return error(ID.Loc, "constant expression type mismatch: got type '" +
6859 getTypeString(ID.ConstantVal->getType()) +
6860 "' but expected '" +
6861 getTypeString(Ty->getScalarType()) + "'");
6862 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6863 ID.ConstantVal);
6864 return false;
6867 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6868 if (ST->getNumElements() != ID.UIntVal)
6869 return error(ID.Loc,
6870 "initializer with struct type has wrong # elements");
6871 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6872 return error(ID.Loc, "packed'ness of initializer and type don't match");
6873
6874 // Verify that the elements are compatible with the structtype.
6875 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6876 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6877 return error(
6878 ID.Loc,
6879 "element " + Twine(i) +
6880 " of struct initializer doesn't match struct element type");
6881
6883 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6884 } else
6885 return error(ID.Loc, "constant expression type mismatch");
6886 return false;
6887 }
6888 llvm_unreachable("Invalid ValID");
6889}
6890
6891bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6892 C = nullptr;
6893 ValID ID;
6894 auto Loc = Lex.getLoc();
6895 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
6896 return true;
6897 switch (ID.Kind) {
6898 case ValID::t_APSInt:
6899 case ValID::t_APFloat:
6900 case ValID::t_Undef:
6901 case ValID::t_Poison:
6902 case ValID::t_Zero:
6903 case ValID::t_Constant:
6907 Value *V;
6908 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6909 return true;
6910 assert(isa<Constant>(V) && "Expected a constant value");
6911 C = cast<Constant>(V);
6912 return false;
6913 }
6914 case ValID::t_Null:
6916 return false;
6917 default:
6918 return error(Loc, "expected a constant value");
6919 }
6920}
6921
6922bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6923 V = nullptr;
6924 ValID ID;
6925
6926 FileLoc Start = getTokLineColumnPos();
6927 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
6928 if (!Ret && ParserContext) {
6929 FileLoc End = getPrevTokEndLineColumnPos();
6930 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6931 }
6932 return Ret;
6933}
6934
6935bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6936 Type *Ty = nullptr;
6937 return parseType(Ty) || parseValue(Ty, V, PFS);
6938}
6939
6940bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6941 PerFunctionState &PFS) {
6942 Value *V;
6943 Loc = Lex.getLoc();
6944 if (parseTypeAndValue(V, PFS))
6945 return true;
6946 if (!isa<BasicBlock>(V))
6947 return error(Loc, "expected a basic block");
6948 BB = cast<BasicBlock>(V);
6949 return false;
6950}
6951
6953 // Exit early for the common (non-debug-intrinsic) case.
6954 // We can make this the only check when we begin supporting all "llvm.dbg"
6955 // intrinsics in the new debug info format.
6956 if (!Name.starts_with("llvm.dbg."))
6957 return false;
6959 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6960 FnID == Intrinsic::dbg_assign;
6961}
6962
6963/// FunctionHeader
6964/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6965/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6966/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6967/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6968bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6969 unsigned &FunctionNumber,
6970 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6971 // parse the linkage.
6972 LocTy LinkageLoc = Lex.getLoc();
6973 unsigned Linkage;
6974 unsigned Visibility;
6975 unsigned DLLStorageClass;
6976 bool DSOLocal;
6977 AttrBuilder RetAttrs(M->getContext());
6978 unsigned CC;
6979 bool HasLinkage;
6980 Type *RetType = nullptr;
6981 LocTy RetTypeLoc = Lex.getLoc();
6982 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6983 DSOLocal) ||
6984 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6985 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6986 return true;
6987
6988 // Verify that the linkage is ok.
6991 break; // always ok.
6993 if (IsDefine)
6994 return error(LinkageLoc, "invalid linkage for function definition");
6995 break;
7003 if (!IsDefine)
7004 return error(LinkageLoc, "invalid linkage for function declaration");
7005 break;
7008 return error(LinkageLoc, "invalid function linkage type");
7009 }
7010
7011 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7012 return error(LinkageLoc,
7013 "symbol with local linkage must have default visibility");
7014
7015 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7016 return error(LinkageLoc,
7017 "symbol with local linkage cannot have a DLL storage class");
7018
7019 if (!FunctionType::isValidReturnType(RetType))
7020 return error(RetTypeLoc, "invalid function return type");
7021
7022 LocTy NameLoc = Lex.getLoc();
7023
7024 std::string FunctionName;
7025 if (Lex.getKind() == lltok::GlobalVar) {
7026 FunctionName = Lex.getStrVal();
7027 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7028 FunctionNumber = Lex.getUIntVal();
7029 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7030 FunctionNumber))
7031 return true;
7032 } else {
7033 return tokError("expected function name");
7034 }
7035
7036 Lex.Lex();
7037
7038 if (Lex.getKind() != lltok::lparen)
7039 return tokError("expected '(' in function argument list");
7040
7042 bool IsVarArg;
7043 AttrBuilder FuncAttrs(M->getContext());
7044 std::vector<unsigned> FwdRefAttrGrps;
7045 LocTy BuiltinLoc;
7046 std::string Section;
7047 std::string Partition;
7048 MaybeAlign Alignment, PrefAlignment;
7049 std::string GC;
7051 unsigned AddrSpace = 0;
7052 Constant *Prefix = nullptr;
7053 Constant *Prologue = nullptr;
7054 Constant *PersonalityFn = nullptr;
7055 Comdat *C;
7056
7057 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7058 parseOptionalUnnamedAddr(UnnamedAddr) ||
7059 parseOptionalProgramAddrSpace(AddrSpace) ||
7060 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7061 BuiltinLoc) ||
7062 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7063 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7064 parseOptionalComdat(FunctionName, C) ||
7065 parseOptionalAlignment(Alignment) ||
7066 parseOptionalPrefAlignment(PrefAlignment) ||
7067 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7068 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7069 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7070 (EatIfPresent(lltok::kw_personality) &&
7071 parseGlobalTypeAndValue(PersonalityFn)))
7072 return true;
7073
7074 if (FuncAttrs.contains(Attribute::Builtin))
7075 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7076
7077 // If the alignment was parsed as an attribute, move to the alignment field.
7078 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7079 Alignment = A;
7080 FuncAttrs.removeAttribute(Attribute::Alignment);
7081 }
7082
7083 // Okay, if we got here, the function is syntactically valid. Convert types
7084 // and do semantic checks.
7085 std::vector<Type*> ParamTypeList;
7087
7088 for (const ArgInfo &Arg : ArgList) {
7089 ParamTypeList.push_back(Arg.Ty);
7090 Attrs.push_back(Arg.Attrs);
7091 }
7092
7093 AttributeList PAL =
7094 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7095 AttributeSet::get(Context, RetAttrs), Attrs);
7096
7097 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7098 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7099
7100 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7101 PointerType *PFT = PointerType::get(Context, AddrSpace);
7102
7103 Fn = nullptr;
7104 GlobalValue *FwdFn = nullptr;
7105 if (!FunctionName.empty()) {
7106 // If this was a definition of a forward reference, remove the definition
7107 // from the forward reference table and fill in the forward ref.
7108 auto FRVI = ForwardRefVals.find(FunctionName);
7109 if (FRVI != ForwardRefVals.end()) {
7110 FwdFn = FRVI->second.first;
7111 if (FwdFn->getType() != PFT)
7112 return error(FRVI->second.second,
7113 "invalid forward reference to "
7114 "function '" +
7115 FunctionName +
7116 "' with wrong type: "
7117 "expected '" +
7118 getTypeString(PFT) + "' but was '" +
7119 getTypeString(FwdFn->getType()) + "'");
7120 ForwardRefVals.erase(FRVI);
7121 } else if ((Fn = M->getFunction(FunctionName))) {
7122 // Reject redefinitions.
7123 return error(NameLoc,
7124 "invalid redefinition of function '" + FunctionName + "'");
7125 } else if (M->getNamedValue(FunctionName)) {
7126 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7127 }
7128
7129 } else {
7130 // Handle @"", where a name is syntactically specified, but semantically
7131 // missing.
7132 if (FunctionNumber == (unsigned)-1)
7133 FunctionNumber = NumberedVals.getNext();
7134
7135 // If this is a definition of a forward referenced function, make sure the
7136 // types agree.
7137 auto I = ForwardRefValIDs.find(FunctionNumber);
7138 if (I != ForwardRefValIDs.end()) {
7139 FwdFn = I->second.first;
7140 if (FwdFn->getType() != PFT)
7141 return error(NameLoc, "type of definition and forward reference of '@" +
7142 Twine(FunctionNumber) +
7143 "' disagree: "
7144 "expected '" +
7145 getTypeString(PFT) + "' but was '" +
7146 getTypeString(FwdFn->getType()) + "'");
7147 ForwardRefValIDs.erase(I);
7148 }
7149 }
7150
7152 FunctionName, M);
7153
7154 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7155
7156 if (FunctionName.empty())
7157 NumberedVals.add(FunctionNumber, Fn);
7158
7160 maybeSetDSOLocal(DSOLocal, *Fn);
7163 Fn->setCallingConv(CC);
7164 Fn->setAttributes(PAL);
7165 Fn->setUnnamedAddr(UnnamedAddr);
7166 if (Alignment)
7167 Fn->setAlignment(*Alignment);
7168 Fn->setPreferredAlignment(PrefAlignment);
7169 Fn->setSection(Section);
7170 Fn->setPartition(Partition);
7171 Fn->setComdat(C);
7172 Fn->setPersonalityFn(PersonalityFn);
7173 if (!GC.empty()) Fn->setGC(GC);
7174 Fn->setPrefixData(Prefix);
7175 Fn->setPrologueData(Prologue);
7176 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7177
7178 // Add all of the arguments we parsed to the function.
7179 Function::arg_iterator ArgIt = Fn->arg_begin();
7180 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7181 if (ParserContext && ArgList[i].IdentLoc)
7182 ParserContext->addInstructionOrArgumentLocation(
7183 &*ArgIt, ArgList[i].IdentLoc.value());
7184 // If the argument has a name, insert it into the argument symbol table.
7185 if (ArgList[i].Name.empty()) continue;
7186
7187 // Set the name, if it conflicted, it will be auto-renamed.
7188 ArgIt->setName(ArgList[i].Name);
7189
7190 if (ArgIt->getName() != ArgList[i].Name)
7191 return error(ArgList[i].Loc,
7192 "redefinition of argument '%" + ArgList[i].Name + "'");
7193 }
7194
7195 if (FwdFn) {
7196 FwdFn->replaceAllUsesWith(Fn);
7197 FwdFn->eraseFromParent();
7198 }
7199
7200 if (IsDefine)
7201 return false;
7202
7203 // Check the declaration has no block address forward references.
7204 ValID ID;
7205 if (FunctionName.empty()) {
7206 ID.Kind = ValID::t_GlobalID;
7207 ID.UIntVal = FunctionNumber;
7208 } else {
7209 ID.Kind = ValID::t_GlobalName;
7210 ID.StrVal = FunctionName;
7211 }
7212 auto Blocks = ForwardRefBlockAddresses.find(ID);
7213 if (Blocks != ForwardRefBlockAddresses.end())
7214 return error(Blocks->first.Loc,
7215 "cannot take blockaddress inside a declaration");
7216 return false;
7217}
7218
7219bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7220 ValID ID;
7221 if (FunctionNumber == -1) {
7222 ID.Kind = ValID::t_GlobalName;
7223 ID.StrVal = std::string(F.getName());
7224 } else {
7225 ID.Kind = ValID::t_GlobalID;
7226 ID.UIntVal = FunctionNumber;
7227 }
7228
7229 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7230 if (Blocks == P.ForwardRefBlockAddresses.end())
7231 return false;
7232
7233 for (const auto &I : Blocks->second) {
7234 const ValID &BBID = I.first;
7235 GlobalValue *GV = I.second;
7236
7237 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7238 "Expected local id or name");
7239 BasicBlock *BB;
7240 if (BBID.Kind == ValID::t_LocalName)
7241 BB = getBB(BBID.StrVal, BBID.Loc);
7242 else
7243 BB = getBB(BBID.UIntVal, BBID.Loc);
7244 if (!BB)
7245 return P.error(BBID.Loc, "referenced value is not a basic block");
7246
7247 Value *ResolvedVal = BlockAddress::get(&F, BB);
7248 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7249 ResolvedVal);
7250 if (!ResolvedVal)
7251 return true;
7252 GV->replaceAllUsesWith(ResolvedVal);
7253 GV->eraseFromParent();
7254 }
7255
7256 P.ForwardRefBlockAddresses.erase(Blocks);
7257 return false;
7258}
7259
7260/// parseFunctionBody
7261/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7262bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7263 ArrayRef<unsigned> UnnamedArgNums) {
7264 if (Lex.getKind() != lltok::lbrace)
7265 return tokError("expected '{' in function body");
7266 Lex.Lex(); // eat the {.
7267
7268 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7269
7270 // Resolve block addresses and allow basic blocks to be forward-declared
7271 // within this function.
7272 if (PFS.resolveForwardRefBlockAddresses())
7273 return true;
7274 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7275
7276 // We need at least one basic block.
7277 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7278 return tokError("function body requires at least one basic block");
7279
7280 while (Lex.getKind() != lltok::rbrace &&
7281 Lex.getKind() != lltok::kw_uselistorder)
7282 if (parseBasicBlock(PFS))
7283 return true;
7284
7285 while (Lex.getKind() != lltok::rbrace)
7286 if (parseUseListOrder(&PFS))
7287 return true;
7288
7289 // Eat the }.
7290 Lex.Lex();
7291
7292 // Verify function is ok.
7293 return PFS.finishFunction();
7294}
7295
7296/// parseBasicBlock
7297/// ::= (LabelStr|LabelID)? Instruction*
7298bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7299 FileLoc BBStart = getTokLineColumnPos();
7300
7301 // If this basic block starts out with a name, remember it.
7302 std::string Name;
7303 int NameID = -1;
7304 LocTy NameLoc = Lex.getLoc();
7305 if (Lex.getKind() == lltok::LabelStr) {
7306 Name = Lex.getStrVal();
7307 Lex.Lex();
7308 } else if (Lex.getKind() == lltok::LabelID) {
7309 NameID = Lex.getUIntVal();
7310 Lex.Lex();
7311 }
7312
7313 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7314 if (!BB)
7315 return true;
7316
7317 std::string NameStr;
7318
7319 // Parse the instructions and debug values in this block until we get a
7320 // terminator.
7321 Instruction *Inst;
7322 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7323 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7324 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7325 do {
7326 // Handle debug records first - there should always be an instruction
7327 // following the debug records, i.e. they cannot appear after the block
7328 // terminator.
7329 while (Lex.getKind() == lltok::hash) {
7330 if (SeenOldDbgInfoFormat)
7331 return error(Lex.getLoc(), "debug record should not appear in a module "
7332 "containing debug info intrinsics");
7333 SeenNewDbgInfoFormat = true;
7334 Lex.Lex();
7335
7336 DbgRecord *DR;
7337 if (parseDebugRecord(DR, PFS))
7338 return true;
7339 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7340 }
7341
7342 FileLoc InstStart = getTokLineColumnPos();
7343 // This instruction may have three possibilities for a name: a) none
7344 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7345 LocTy NameLoc = Lex.getLoc();
7346 int NameID = -1;
7347 NameStr = "";
7348
7349 if (Lex.getKind() == lltok::LocalVarID) {
7350 NameID = Lex.getUIntVal();
7351 Lex.Lex();
7352 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7353 return true;
7354 } else if (Lex.getKind() == lltok::LocalVar) {
7355 NameStr = Lex.getStrVal();
7356 Lex.Lex();
7357 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7358 return true;
7359 }
7360
7361 switch (parseInstruction(Inst, BB, PFS)) {
7362 default:
7363 llvm_unreachable("Unknown parseInstruction result!");
7364 case InstError: return true;
7365 case InstNormal:
7366 Inst->insertInto(BB, BB->end());
7367
7368 // With a normal result, we check to see if the instruction is followed by
7369 // a comma and metadata.
7370 if (EatIfPresent(lltok::comma))
7371 if (parseInstructionMetadata(*Inst))
7372 return true;
7373 break;
7374 case InstExtraComma:
7375 Inst->insertInto(BB, BB->end());
7376
7377 // If the instruction parser ate an extra comma at the end of it, it
7378 // *must* be followed by metadata.
7379 if (parseInstructionMetadata(*Inst))
7380 return true;
7381 break;
7382 }
7383
7384 // Set the name on the instruction.
7385 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7386 return true;
7387
7388 // Attach any preceding debug values to this instruction.
7389 for (DbgRecordPtr &DR : TrailingDbgRecord)
7390 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7391 TrailingDbgRecord.clear();
7392 if (ParserContext) {
7393 ParserContext->addInstructionOrArgumentLocation(
7394 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7395 }
7396 } while (!Inst->isTerminator());
7397
7398 if (ParserContext)
7399 ParserContext->addBlockLocation(
7400 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7401
7402 assert(TrailingDbgRecord.empty() &&
7403 "All debug values should have been attached to an instruction.");
7404
7405 return false;
7406}
7407
7408/// parseDebugRecord
7409/// ::= #dbg_label '(' MDNode ')'
7410/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7411/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7412bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7413 using RecordKind = DbgRecord::Kind;
7414 using LocType = DbgVariableRecord::LocationType;
7415 LocTy DVRLoc = Lex.getLoc();
7416 if (Lex.getKind() != lltok::DbgRecordType)
7417 return error(DVRLoc, "expected debug record type here");
7418 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7419 .Case("declare", RecordKind::ValueKind)
7420 .Case("value", RecordKind::ValueKind)
7421 .Case("assign", RecordKind::ValueKind)
7422 .Case("label", RecordKind::LabelKind)
7423 .Case("declare_value", RecordKind::ValueKind);
7424
7425 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7426 // full DbgVariableRecord processing stage.
7427 if (RecordType == RecordKind::LabelKind) {
7428 Lex.Lex();
7429 if (parseToken(lltok::lparen, "Expected '(' here"))
7430 return true;
7431 MDNode *Label;
7432 if (parseMDNode(Label))
7433 return true;
7434 if (parseToken(lltok::comma, "Expected ',' here"))
7435 return true;
7436 MDNode *DbgLoc;
7437 if (parseMDNode(DbgLoc))
7438 return true;
7439 if (parseToken(lltok::rparen, "Expected ')' here"))
7440 return true;
7442 return false;
7443 }
7444
7445 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7446 .Case("declare", LocType::Declare)
7447 .Case("value", LocType::Value)
7448 .Case("assign", LocType::Assign)
7449 .Case("declare_value", LocType::DeclareValue);
7450
7451 Lex.Lex();
7452 if (parseToken(lltok::lparen, "Expected '(' here"))
7453 return true;
7454
7455 // Parse Value field.
7456 Metadata *ValLocMD;
7457 if (parseMetadata(ValLocMD, &PFS))
7458 return true;
7459 if (parseToken(lltok::comma, "Expected ',' here"))
7460 return true;
7461
7462 // Parse Variable field.
7463 MDNode *Variable;
7464 if (parseMDNode(Variable))
7465 return true;
7466 if (parseToken(lltok::comma, "Expected ',' here"))
7467 return true;
7468
7469 // Parse Expression field.
7470 MDNode *Expression;
7471 if (parseMDNode(Expression))
7472 return true;
7473 if (parseToken(lltok::comma, "Expected ',' here"))
7474 return true;
7475
7476 // Parse additional fields for #dbg_assign.
7477 MDNode *AssignID = nullptr;
7478 Metadata *AddressLocation = nullptr;
7479 MDNode *AddressExpression = nullptr;
7480 if (ValueType == LocType::Assign) {
7481 // Parse DIAssignID.
7482 if (parseMDNode(AssignID))
7483 return true;
7484 if (parseToken(lltok::comma, "Expected ',' here"))
7485 return true;
7486
7487 // Parse address ValueAsMetadata.
7488 if (parseMetadata(AddressLocation, &PFS))
7489 return true;
7490 if (parseToken(lltok::comma, "Expected ',' here"))
7491 return true;
7492
7493 // Parse address DIExpression.
7494 if (parseMDNode(AddressExpression))
7495 return true;
7496 if (parseToken(lltok::comma, "Expected ',' here"))
7497 return true;
7498 }
7499
7500 /// Parse DILocation.
7501 MDNode *DebugLoc;
7502 if (parseMDNode(DebugLoc))
7503 return true;
7504
7505 if (parseToken(lltok::rparen, "Expected ')' here"))
7506 return true;
7508 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7509 AddressExpression, DebugLoc);
7510 return false;
7511}
7512//===----------------------------------------------------------------------===//
7513// Instruction Parsing.
7514//===----------------------------------------------------------------------===//
7515
7516/// parseInstruction - parse one of the many different instructions.
7517///
7518int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7519 PerFunctionState &PFS) {
7520 lltok::Kind Token = Lex.getKind();
7521 if (Token == lltok::Eof)
7522 return tokError("found end of file when expecting more instructions");
7523 LocTy Loc = Lex.getLoc();
7524 unsigned KeywordVal = Lex.getUIntVal();
7525 Lex.Lex(); // Eat the keyword.
7526
7527 switch (Token) {
7528 default:
7529 return error(Loc, "expected instruction opcode");
7530 // Terminator Instructions.
7531 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7532 case lltok::kw_ret:
7533 return parseRet(Inst, BB, PFS);
7534 case lltok::kw_br:
7535 return parseBr(Inst, PFS);
7536 case lltok::kw_switch:
7537 return parseSwitch(Inst, PFS);
7539 return parseIndirectBr(Inst, PFS);
7540 case lltok::kw_invoke:
7541 return parseInvoke(Inst, PFS);
7542 case lltok::kw_resume:
7543 return parseResume(Inst, PFS);
7545 return parseCleanupRet(Inst, PFS);
7546 case lltok::kw_catchret:
7547 return parseCatchRet(Inst, PFS);
7549 return parseCatchSwitch(Inst, PFS);
7550 case lltok::kw_catchpad:
7551 return parseCatchPad(Inst, PFS);
7553 return parseCleanupPad(Inst, PFS);
7554 case lltok::kw_callbr:
7555 return parseCallBr(Inst, PFS);
7556 // Unary Operators.
7557 case lltok::kw_fneg: {
7558 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7559 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7560 if (Res != 0)
7561 return Res;
7562 if (FMF.any())
7563 Inst->setFastMathFlags(FMF);
7564 return false;
7565 }
7566 // Binary Operators.
7567 case lltok::kw_add:
7568 case lltok::kw_sub:
7569 case lltok::kw_mul:
7570 case lltok::kw_shl: {
7571 bool NUW = EatIfPresent(lltok::kw_nuw);
7572 bool NSW = EatIfPresent(lltok::kw_nsw);
7573 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7574
7575 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7576 return true;
7577
7578 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7579 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7580 return false;
7581 }
7582 case lltok::kw_fadd:
7583 case lltok::kw_fsub:
7584 case lltok::kw_fmul:
7585 case lltok::kw_fdiv:
7586 case lltok::kw_frem: {
7587 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7588 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7589 if (Res != 0)
7590 return Res;
7591 if (FMF.any())
7592 Inst->setFastMathFlags(FMF);
7593 return 0;
7594 }
7595
7596 case lltok::kw_sdiv:
7597 case lltok::kw_udiv:
7598 case lltok::kw_lshr:
7599 case lltok::kw_ashr: {
7600 bool Exact = EatIfPresent(lltok::kw_exact);
7601
7602 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7603 return true;
7604 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7605 return false;
7606 }
7607
7608 case lltok::kw_urem:
7609 case lltok::kw_srem:
7610 return parseArithmetic(Inst, PFS, KeywordVal,
7611 /*IsFP*/ false);
7612 case lltok::kw_or: {
7613 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7614 if (parseLogical(Inst, PFS, KeywordVal))
7615 return true;
7616 if (Disjoint)
7617 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7618 return false;
7619 }
7620 case lltok::kw_and:
7621 case lltok::kw_xor:
7622 return parseLogical(Inst, PFS, KeywordVal);
7623 case lltok::kw_icmp: {
7624 bool SameSign = EatIfPresent(lltok::kw_samesign);
7625 if (parseCompare(Inst, PFS, KeywordVal))
7626 return true;
7627 if (SameSign)
7628 cast<ICmpInst>(Inst)->setSameSign();
7629 return false;
7630 }
7631 case lltok::kw_fcmp: {
7632 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7633 int Res = parseCompare(Inst, PFS, KeywordVal);
7634 if (Res != 0)
7635 return Res;
7636 if (FMF.any())
7637 Inst->setFastMathFlags(FMF);
7638 return 0;
7639 }
7640
7641 // Casts.
7642 case lltok::kw_uitofp:
7643 case lltok::kw_zext: {
7644 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7645 bool Res = parseCast(Inst, PFS, KeywordVal);
7646 if (Res != 0)
7647 return Res;
7648 if (NonNeg)
7649 Inst->setNonNeg();
7650 return 0;
7651 }
7652 case lltok::kw_trunc: {
7653 bool NUW = EatIfPresent(lltok::kw_nuw);
7654 bool NSW = EatIfPresent(lltok::kw_nsw);
7655 if (!NUW)
7656 NUW = EatIfPresent(lltok::kw_nuw);
7657 if (parseCast(Inst, PFS, KeywordVal))
7658 return true;
7659 if (NUW)
7660 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7661 if (NSW)
7662 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7663 return false;
7664 }
7665 case lltok::kw_sext:
7666 case lltok::kw_bitcast:
7668 case lltok::kw_sitofp:
7669 case lltok::kw_fptoui:
7670 case lltok::kw_fptosi:
7671 case lltok::kw_inttoptr:
7673 case lltok::kw_ptrtoint:
7674 return parseCast(Inst, PFS, KeywordVal);
7675 case lltok::kw_fptrunc:
7676 case lltok::kw_fpext: {
7677 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7678 if (parseCast(Inst, PFS, KeywordVal))
7679 return true;
7680 if (FMF.any())
7681 Inst->setFastMathFlags(FMF);
7682 return false;
7683 }
7684
7685 // Other.
7686 case lltok::kw_select: {
7687 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7688 int Res = parseSelect(Inst, PFS);
7689 if (Res != 0)
7690 return Res;
7691 if (FMF.any()) {
7692 if (!isa<FPMathOperator>(Inst))
7693 return error(Loc, "fast-math-flags specified for select without "
7694 "floating-point scalar or vector return type");
7695 Inst->setFastMathFlags(FMF);
7696 }
7697 return 0;
7698 }
7699 case lltok::kw_va_arg:
7700 return parseVAArg(Inst, PFS);
7702 return parseExtractElement(Inst, PFS);
7704 return parseInsertElement(Inst, PFS);
7706 return parseShuffleVector(Inst, PFS);
7707 case lltok::kw_phi: {
7708 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7709 int Res = parsePHI(Inst, PFS);
7710 if (Res != 0)
7711 return Res;
7712 if (FMF.any()) {
7713 if (!isa<FPMathOperator>(Inst))
7714 return error(Loc, "fast-math-flags specified for phi without "
7715 "floating-point scalar or vector return type");
7716 Inst->setFastMathFlags(FMF);
7717 }
7718 return 0;
7719 }
7721 return parseLandingPad(Inst, PFS);
7722 case lltok::kw_freeze:
7723 return parseFreeze(Inst, PFS);
7724 // Call.
7725 case lltok::kw_call:
7726 return parseCall(Inst, PFS, CallInst::TCK_None);
7727 case lltok::kw_tail:
7728 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7729 case lltok::kw_musttail:
7730 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7731 case lltok::kw_notail:
7732 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7733 // Memory.
7734 case lltok::kw_alloca:
7735 return parseAlloc(Inst, PFS);
7736 case lltok::kw_load:
7737 return parseLoad(Inst, PFS);
7738 case lltok::kw_store:
7739 return parseStore(Inst, PFS);
7740 case lltok::kw_cmpxchg:
7741 return parseCmpXchg(Inst, PFS);
7743 return parseAtomicRMW(Inst, PFS);
7744 case lltok::kw_fence:
7745 return parseFence(Inst, PFS);
7747 return parseGetElementPtr(Inst, PFS);
7749 return parseExtractValue(Inst, PFS);
7751 return parseInsertValue(Inst, PFS);
7752 }
7753}
7754
7755/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7756bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7757 if (Opc == Instruction::FCmp) {
7758 switch (Lex.getKind()) {
7759 default:
7760 return tokError("expected fcmp predicate (e.g. 'oeq')");
7761 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7762 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7763 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7764 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7765 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7766 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7767 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7768 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7769 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7770 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7771 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7772 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7773 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7774 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7775 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7776 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7777 }
7778 } else {
7779 switch (Lex.getKind()) {
7780 default:
7781 return tokError("expected icmp predicate (e.g. 'eq')");
7782 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7783 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7784 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7785 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7786 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7787 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7788 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7789 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7790 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7791 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7792 }
7793 }
7794 Lex.Lex();
7795 return false;
7796}
7797
7798//===----------------------------------------------------------------------===//
7799// Terminator Instructions.
7800//===----------------------------------------------------------------------===//
7801
7802/// parseRet - parse a return instruction.
7803/// ::= 'ret' void (',' !dbg, !1)*
7804/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7805bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7806 PerFunctionState &PFS) {
7807 SMLoc TypeLoc = Lex.getLoc();
7808 Type *Ty = nullptr;
7809 if (parseType(Ty, true /*void allowed*/))
7810 return true;
7811
7812 Type *ResType = PFS.getFunction().getReturnType();
7813
7814 if (Ty->isVoidTy()) {
7815 if (!ResType->isVoidTy())
7816 return error(TypeLoc, "value doesn't match function result type '" +
7817 getTypeString(ResType) + "'");
7818
7819 Inst = ReturnInst::Create(Context);
7820 return false;
7821 }
7822
7823 Value *RV;
7824 if (parseValue(Ty, RV, PFS))
7825 return true;
7826
7827 if (ResType != RV->getType())
7828 return error(TypeLoc, "value doesn't match function result type '" +
7829 getTypeString(ResType) + "'");
7830
7831 Inst = ReturnInst::Create(Context, RV);
7832 return false;
7833}
7834
7835/// parseBr
7836/// ::= 'br' TypeAndValue
7837/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7838bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7839 LocTy Loc, Loc2;
7840 Value *Op0;
7841 BasicBlock *Op1, *Op2;
7842 if (parseTypeAndValue(Op0, Loc, PFS))
7843 return true;
7844
7845 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7846 Inst = UncondBrInst::Create(BB);
7847 return false;
7848 }
7849
7850 if (Op0->getType() != Type::getInt1Ty(Context))
7851 return error(Loc, "branch condition must have 'i1' type");
7852
7853 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7854 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7855 parseToken(lltok::comma, "expected ',' after true destination") ||
7856 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7857 return true;
7858
7859 Inst = CondBrInst::Create(Op0, Op1, Op2);
7860 return false;
7861}
7862
7863/// parseSwitch
7864/// Instruction
7865/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7866/// JumpTable
7867/// ::= (TypeAndValue ',' TypeAndValue)*
7868bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7869 LocTy CondLoc, BBLoc;
7870 Value *Cond;
7871 BasicBlock *DefaultBB;
7872 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7873 parseToken(lltok::comma, "expected ',' after switch condition") ||
7874 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7875 parseToken(lltok::lsquare, "expected '[' with switch table"))
7876 return true;
7877
7878 if (!Cond->getType()->isIntegerTy())
7879 return error(CondLoc, "switch condition must have integer type");
7880
7881 // parse the jump table pairs.
7882 SmallPtrSet<Value*, 32> SeenCases;
7884 while (Lex.getKind() != lltok::rsquare) {
7885 Value *Constant;
7886 BasicBlock *DestBB;
7887
7888 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7889 parseToken(lltok::comma, "expected ',' after case value") ||
7890 parseTypeAndBasicBlock(DestBB, PFS))
7891 return true;
7892
7893 if (!SeenCases.insert(Constant).second)
7894 return error(CondLoc, "duplicate case value in switch");
7895 if (!isa<ConstantInt>(Constant))
7896 return error(CondLoc, "case value is not a constant integer");
7897
7898 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7899 }
7900
7901 Lex.Lex(); // Eat the ']'.
7902
7903 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7904 for (const auto &[OnVal, Dest] : Table)
7905 SI->addCase(OnVal, Dest);
7906 Inst = SI;
7907 return false;
7908}
7909
7910/// parseIndirectBr
7911/// Instruction
7912/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7913bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7914 LocTy AddrLoc;
7915 Value *Address;
7916 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7917 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7918 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7919 return true;
7920
7921 if (!Address->getType()->isPointerTy())
7922 return error(AddrLoc, "indirectbr address must have pointer type");
7923
7924 // parse the destination list.
7925 SmallVector<BasicBlock*, 16> DestList;
7926
7927 if (Lex.getKind() != lltok::rsquare) {
7928 BasicBlock *DestBB;
7929 if (parseTypeAndBasicBlock(DestBB, PFS))
7930 return true;
7931 DestList.push_back(DestBB);
7932
7933 while (EatIfPresent(lltok::comma)) {
7934 if (parseTypeAndBasicBlock(DestBB, PFS))
7935 return true;
7936 DestList.push_back(DestBB);
7937 }
7938 }
7939
7940 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7941 return true;
7942
7943 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7944 for (BasicBlock *Dest : DestList)
7945 IBI->addDestination(Dest);
7946 Inst = IBI;
7947 return false;
7948}
7949
7950// If RetType is a non-function pointer type, then this is the short syntax
7951// for the call, which means that RetType is just the return type. Infer the
7952// rest of the function argument types from the arguments that are present.
7953bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7954 FunctionType *&FuncTy) {
7955 FuncTy = dyn_cast<FunctionType>(RetType);
7956 if (!FuncTy) {
7957 // Pull out the types of all of the arguments...
7958 SmallVector<Type *, 8> ParamTypes;
7959 ParamTypes.reserve(ArgList.size());
7960 for (const ParamInfo &Arg : ArgList)
7961 ParamTypes.push_back(Arg.V->getType());
7962
7963 if (!FunctionType::isValidReturnType(RetType))
7964 return true;
7965
7966 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7967 }
7968 return false;
7969}
7970
7971/// parseInvoke
7972/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7973/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7974bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7975 LocTy CallLoc = Lex.getLoc();
7976 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7977 std::vector<unsigned> FwdRefAttrGrps;
7978 LocTy NoBuiltinLoc;
7979 unsigned CC;
7980 unsigned InvokeAddrSpace;
7981 Type *RetType = nullptr;
7982 LocTy RetTypeLoc;
7983 ValID CalleeID;
7986
7987 BasicBlock *NormalBB, *UnwindBB;
7988 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7989 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7990 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7991 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7992 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7993 NoBuiltinLoc) ||
7994 parseOptionalOperandBundles(BundleList, PFS) ||
7995 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7996 parseTypeAndBasicBlock(NormalBB, PFS) ||
7997 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7998 parseTypeAndBasicBlock(UnwindBB, PFS))
7999 return true;
8000
8001 // If RetType is a non-function pointer type, then this is the short syntax
8002 // for the call, which means that RetType is just the return type. Infer the
8003 // rest of the function argument types from the arguments that are present.
8004 FunctionType *Ty;
8005 if (resolveFunctionType(RetType, ArgList, Ty))
8006 return error(RetTypeLoc, "Invalid result type for LLVM function");
8007
8008 CalleeID.FTy = Ty;
8009
8010 // Look up the callee.
8011 Value *Callee;
8012 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8013 Callee, &PFS))
8014 return true;
8015
8016 // Set up the Attribute for the function.
8017 SmallVector<Value *, 8> Args;
8019
8020 // Loop through FunctionType's arguments and ensure they are specified
8021 // correctly. Also, gather any parameter attributes.
8022 FunctionType::param_iterator I = Ty->param_begin();
8023 FunctionType::param_iterator E = Ty->param_end();
8024 for (const ParamInfo &Arg : ArgList) {
8025 Type *ExpectedTy = nullptr;
8026 if (I != E) {
8027 ExpectedTy = *I++;
8028 } else if (!Ty->isVarArg()) {
8029 return error(Arg.Loc, "too many arguments specified");
8030 }
8031
8032 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8033 return error(Arg.Loc, "argument is not of expected type '" +
8034 getTypeString(ExpectedTy) + "'");
8035 Args.push_back(Arg.V);
8036 ArgAttrs.push_back(Arg.Attrs);
8037 }
8038
8039 if (I != E)
8040 return error(CallLoc, "not enough parameters specified for call");
8041
8042 // Finish off the Attribute and check them
8043 AttributeList PAL =
8044 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8045 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8046
8047 InvokeInst *II =
8048 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8049 II->setCallingConv(CC);
8050 II->setAttributes(PAL);
8051 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8052 Inst = II;
8053 return false;
8054}
8055
8056/// parseResume
8057/// ::= 'resume' TypeAndValue
8058bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8059 Value *Exn; LocTy ExnLoc;
8060 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8061 return true;
8062
8063 ResumeInst *RI = ResumeInst::Create(Exn);
8064 Inst = RI;
8065 return false;
8066}
8067
8068bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8069 PerFunctionState &PFS) {
8070 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8071 return true;
8072
8073 while (Lex.getKind() != lltok::rsquare) {
8074 // If this isn't the first argument, we need a comma.
8075 if (!Args.empty() &&
8076 parseToken(lltok::comma, "expected ',' in argument list"))
8077 return true;
8078
8079 // parse the argument.
8080 LocTy ArgLoc;
8081 Type *ArgTy = nullptr;
8082 if (parseType(ArgTy, ArgLoc))
8083 return true;
8084
8085 Value *V;
8086 if (ArgTy->isMetadataTy()) {
8087 if (parseMetadataAsValue(V, PFS))
8088 return true;
8089 } else {
8090 if (parseValue(ArgTy, V, PFS))
8091 return true;
8092 }
8093 Args.push_back(V);
8094 }
8095
8096 Lex.Lex(); // Lex the ']'.
8097 return false;
8098}
8099
8100/// parseCleanupRet
8101/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8102bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8103 Value *CleanupPad = nullptr;
8104
8105 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8106 return true;
8107
8108 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8109 return true;
8110
8111 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8112 return true;
8113
8114 BasicBlock *UnwindBB = nullptr;
8115 if (Lex.getKind() == lltok::kw_to) {
8116 Lex.Lex();
8117 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8118 return true;
8119 } else {
8120 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8121 return true;
8122 }
8123 }
8124
8125 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8126 return false;
8127}
8128
8129/// parseCatchRet
8130/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8131bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8132 Value *CatchPad = nullptr;
8133
8134 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8135 return true;
8136
8137 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8138 return true;
8139
8140 BasicBlock *BB;
8141 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8142 parseTypeAndBasicBlock(BB, PFS))
8143 return true;
8144
8145 Inst = CatchReturnInst::Create(CatchPad, BB);
8146 return false;
8147}
8148
8149/// parseCatchSwitch
8150/// ::= 'catchswitch' within Parent
8151bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8152 Value *ParentPad;
8153
8154 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8155 return true;
8156
8157 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8158 Lex.getKind() != lltok::LocalVarID)
8159 return tokError("expected scope value for catchswitch");
8160
8161 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8162 return true;
8163
8164 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8165 return true;
8166
8168 do {
8169 BasicBlock *DestBB;
8170 if (parseTypeAndBasicBlock(DestBB, PFS))
8171 return true;
8172 Table.push_back(DestBB);
8173 } while (EatIfPresent(lltok::comma));
8174
8175 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8176 return true;
8177
8178 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8179 return true;
8180
8181 BasicBlock *UnwindBB = nullptr;
8182 if (EatIfPresent(lltok::kw_to)) {
8183 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8184 return true;
8185 } else {
8186 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8187 return true;
8188 }
8189
8190 auto *CatchSwitch =
8191 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8192 for (BasicBlock *DestBB : Table)
8193 CatchSwitch->addHandler(DestBB);
8194 Inst = CatchSwitch;
8195 return false;
8196}
8197
8198/// parseCatchPad
8199/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8200bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8201 Value *CatchSwitch = nullptr;
8202
8203 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8204 return true;
8205
8206 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8207 return tokError("expected scope value for catchpad");
8208
8209 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8210 return true;
8211
8212 SmallVector<Value *, 8> Args;
8213 if (parseExceptionArgs(Args, PFS))
8214 return true;
8215
8216 Inst = CatchPadInst::Create(CatchSwitch, Args);
8217 return false;
8218}
8219
8220/// parseCleanupPad
8221/// ::= 'cleanuppad' within Parent ParamList
8222bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8223 Value *ParentPad = nullptr;
8224
8225 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8226 return true;
8227
8228 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8229 Lex.getKind() != lltok::LocalVarID)
8230 return tokError("expected scope value for cleanuppad");
8231
8232 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8233 return true;
8234
8235 SmallVector<Value *, 8> Args;
8236 if (parseExceptionArgs(Args, PFS))
8237 return true;
8238
8239 Inst = CleanupPadInst::Create(ParentPad, Args);
8240 return false;
8241}
8242
8243//===----------------------------------------------------------------------===//
8244// Unary Operators.
8245//===----------------------------------------------------------------------===//
8246
8247/// parseUnaryOp
8248/// ::= UnaryOp TypeAndValue ',' Value
8249///
8250/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8251/// operand is allowed.
8252bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8253 unsigned Opc, bool IsFP) {
8254 LocTy Loc; Value *LHS;
8255 if (parseTypeAndValue(LHS, Loc, PFS))
8256 return true;
8257
8258 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8260
8261 if (!Valid)
8262 return error(Loc, "invalid operand type for instruction");
8263
8265 return false;
8266}
8267
8268/// parseCallBr
8269/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8270/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8271/// '[' LabelList ']'
8272bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8273 LocTy CallLoc = Lex.getLoc();
8274 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8275 std::vector<unsigned> FwdRefAttrGrps;
8276 LocTy NoBuiltinLoc;
8277 unsigned CC;
8278 Type *RetType = nullptr;
8279 LocTy RetTypeLoc;
8280 ValID CalleeID;
8283
8284 BasicBlock *DefaultDest;
8285 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8286 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8287 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8288 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8289 NoBuiltinLoc) ||
8290 parseOptionalOperandBundles(BundleList, PFS) ||
8291 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8292 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8293 parseToken(lltok::lsquare, "expected '[' in callbr"))
8294 return true;
8295
8296 // parse the destination list.
8297 SmallVector<BasicBlock *, 16> IndirectDests;
8298
8299 if (Lex.getKind() != lltok::rsquare) {
8300 BasicBlock *DestBB;
8301 if (parseTypeAndBasicBlock(DestBB, PFS))
8302 return true;
8303 IndirectDests.push_back(DestBB);
8304
8305 while (EatIfPresent(lltok::comma)) {
8306 if (parseTypeAndBasicBlock(DestBB, PFS))
8307 return true;
8308 IndirectDests.push_back(DestBB);
8309 }
8310 }
8311
8312 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8313 return true;
8314
8315 // If RetType is a non-function pointer type, then this is the short syntax
8316 // for the call, which means that RetType is just the return type. Infer the
8317 // rest of the function argument types from the arguments that are present.
8318 FunctionType *Ty;
8319 if (resolveFunctionType(RetType, ArgList, Ty))
8320 return error(RetTypeLoc, "Invalid result type for LLVM function");
8321
8322 CalleeID.FTy = Ty;
8323
8324 // Look up the callee.
8325 Value *Callee;
8326 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8327 &PFS))
8328 return true;
8329
8330 // Set up the Attribute for the function.
8331 SmallVector<Value *, 8> Args;
8333
8334 // Loop through FunctionType's arguments and ensure they are specified
8335 // correctly. Also, gather any parameter attributes.
8336 FunctionType::param_iterator I = Ty->param_begin();
8337 FunctionType::param_iterator E = Ty->param_end();
8338 for (const ParamInfo &Arg : ArgList) {
8339 Type *ExpectedTy = nullptr;
8340 if (I != E) {
8341 ExpectedTy = *I++;
8342 } else if (!Ty->isVarArg()) {
8343 return error(Arg.Loc, "too many arguments specified");
8344 }
8345
8346 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8347 return error(Arg.Loc, "argument is not of expected type '" +
8348 getTypeString(ExpectedTy) + "'");
8349 Args.push_back(Arg.V);
8350 ArgAttrs.push_back(Arg.Attrs);
8351 }
8352
8353 if (I != E)
8354 return error(CallLoc, "not enough parameters specified for call");
8355
8356 // Finish off the Attribute and check them
8357 AttributeList PAL =
8358 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8359 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8360
8361 CallBrInst *CBI =
8362 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8363 BundleList);
8364 CBI->setCallingConv(CC);
8365 CBI->setAttributes(PAL);
8366 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8367 Inst = CBI;
8368 return false;
8369}
8370
8371//===----------------------------------------------------------------------===//
8372// Binary Operators.
8373//===----------------------------------------------------------------------===//
8374
8375/// parseArithmetic
8376/// ::= ArithmeticOps TypeAndValue ',' Value
8377///
8378/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8379/// operand is allowed.
8380bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8381 unsigned Opc, bool IsFP) {
8382 LocTy Loc; Value *LHS, *RHS;
8383 if (parseTypeAndValue(LHS, Loc, PFS) ||
8384 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8385 parseValue(LHS->getType(), RHS, PFS))
8386 return true;
8387
8388 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8390
8391 if (!Valid)
8392 return error(Loc, "invalid operand type for instruction");
8393
8395 return false;
8396}
8397
8398/// parseLogical
8399/// ::= ArithmeticOps TypeAndValue ',' Value {
8400bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8401 unsigned Opc) {
8402 LocTy Loc; Value *LHS, *RHS;
8403 if (parseTypeAndValue(LHS, Loc, PFS) ||
8404 parseToken(lltok::comma, "expected ',' in logical operation") ||
8405 parseValue(LHS->getType(), RHS, PFS))
8406 return true;
8407
8408 if (!LHS->getType()->isIntOrIntVectorTy())
8409 return error(Loc,
8410 "instruction requires integer or integer vector operands");
8411
8413 return false;
8414}
8415
8416/// parseCompare
8417/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8418/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8419bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8420 unsigned Opc) {
8421 // parse the integer/fp comparison predicate.
8422 LocTy Loc;
8423 unsigned Pred;
8424 Value *LHS, *RHS;
8425 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8426 parseToken(lltok::comma, "expected ',' after compare value") ||
8427 parseValue(LHS->getType(), RHS, PFS))
8428 return true;
8429
8430 if (Opc == Instruction::FCmp) {
8431 if (!LHS->getType()->isFPOrFPVectorTy())
8432 return error(Loc, "fcmp requires floating point operands");
8433 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8434 } else {
8435 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8436 if (!LHS->getType()->isIntOrIntVectorTy() &&
8438 return error(Loc, "icmp requires integer operands");
8439 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8440 }
8441 return false;
8442}
8443
8444//===----------------------------------------------------------------------===//
8445// Other Instructions.
8446//===----------------------------------------------------------------------===//
8447
8448/// parseCast
8449/// ::= CastOpc TypeAndValue 'to' Type
8450bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8451 unsigned Opc) {
8452 LocTy Loc;
8453 Value *Op;
8454 Type *DestTy = nullptr;
8455 if (parseTypeAndValue(Op, Loc, PFS) ||
8456 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8457 parseType(DestTy))
8458 return true;
8459
8461 return error(Loc, "invalid cast opcode for cast from '" +
8462 getTypeString(Op->getType()) + "' to '" +
8463 getTypeString(DestTy) + "'");
8464 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8465 return false;
8466}
8467
8468/// parseSelect
8469/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8470bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8471 LocTy Loc;
8472 Value *Op0, *Op1, *Op2;
8473 if (parseTypeAndValue(Op0, Loc, PFS) ||
8474 parseToken(lltok::comma, "expected ',' after select condition") ||
8475 parseTypeAndValue(Op1, PFS) ||
8476 parseToken(lltok::comma, "expected ',' after select value") ||
8477 parseTypeAndValue(Op2, PFS))
8478 return true;
8479
8480 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8481 return error(Loc, Reason);
8482
8483 Inst = SelectInst::Create(Op0, Op1, Op2);
8484 return false;
8485}
8486
8487/// parseVAArg
8488/// ::= 'va_arg' TypeAndValue ',' Type
8489bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8490 Value *Op;
8491 Type *EltTy = nullptr;
8492 LocTy TypeLoc;
8493 if (parseTypeAndValue(Op, PFS) ||
8494 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8495 parseType(EltTy, TypeLoc))
8496 return true;
8497
8498 if (!EltTy->isFirstClassType())
8499 return error(TypeLoc, "va_arg requires operand with first class type");
8500
8501 Inst = new VAArgInst(Op, EltTy);
8502 return false;
8503}
8504
8505/// parseExtractElement
8506/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8507bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8508 LocTy Loc;
8509 Value *Op0, *Op1;
8510 if (parseTypeAndValue(Op0, Loc, PFS) ||
8511 parseToken(lltok::comma, "expected ',' after extract value") ||
8512 parseTypeAndValue(Op1, PFS))
8513 return true;
8514
8516 return error(Loc, "invalid extractelement operands");
8517
8518 Inst = ExtractElementInst::Create(Op0, Op1);
8519 return false;
8520}
8521
8522/// parseInsertElement
8523/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8524bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8525 LocTy Loc;
8526 Value *Op0, *Op1, *Op2;
8527 if (parseTypeAndValue(Op0, Loc, PFS) ||
8528 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8529 parseTypeAndValue(Op1, PFS) ||
8530 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8531 parseTypeAndValue(Op2, PFS))
8532 return true;
8533
8534 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8535 return error(Loc, "invalid insertelement operands");
8536
8537 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8538 return false;
8539}
8540
8541/// parseShuffleVector
8542/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8543bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8544 LocTy Loc;
8545 Value *Op0, *Op1, *Op2;
8546 if (parseTypeAndValue(Op0, Loc, PFS) ||
8547 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8548 parseTypeAndValue(Op1, PFS) ||
8549 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8550 parseTypeAndValue(Op2, PFS))
8551 return true;
8552
8553 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8554 return error(Loc, "invalid shufflevector operands");
8555
8556 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8557 return false;
8558}
8559
8560/// parsePHI
8561/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8562int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8563 Type *Ty = nullptr; LocTy TypeLoc;
8564 Value *Op0, *Op1;
8565
8566 if (parseType(Ty, TypeLoc))
8567 return true;
8568
8569 if (!Ty->isFirstClassType())
8570 return error(TypeLoc, "phi node must have first class type");
8571
8572 bool First = true;
8573 bool AteExtraComma = false;
8575
8576 while (true) {
8577 if (First) {
8578 if (Lex.getKind() != lltok::lsquare)
8579 break;
8580 First = false;
8581 } else if (!EatIfPresent(lltok::comma))
8582 break;
8583
8584 if (Lex.getKind() == lltok::MetadataVar) {
8585 AteExtraComma = true;
8586 break;
8587 }
8588
8589 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8590 parseValue(Ty, Op0, PFS) ||
8591 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8592 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8593 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8594 return true;
8595
8596 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8597 }
8598
8599 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8600 for (const auto &[Val, BB] : PHIVals)
8601 PN->addIncoming(Val, BB);
8602 Inst = PN;
8603 return AteExtraComma ? InstExtraComma : InstNormal;
8604}
8605
8606/// parseLandingPad
8607/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8608/// Clause
8609/// ::= 'catch' TypeAndValue
8610/// ::= 'filter'
8611/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8612bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8613 Type *Ty = nullptr; LocTy TyLoc;
8614
8615 if (parseType(Ty, TyLoc))
8616 return true;
8617
8618 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8619 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8620
8621 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8623 if (EatIfPresent(lltok::kw_catch))
8625 else if (EatIfPresent(lltok::kw_filter))
8627 else
8628 return tokError("expected 'catch' or 'filter' clause type");
8629
8630 Value *V;
8631 LocTy VLoc;
8632 if (parseTypeAndValue(V, VLoc, PFS))
8633 return true;
8634
8635 // A 'catch' type expects a non-array constant. A filter clause expects an
8636 // array constant.
8637 if (CT == LandingPadInst::Catch) {
8638 if (isa<ArrayType>(V->getType()))
8639 return error(VLoc, "'catch' clause has an invalid type");
8640 } else {
8641 if (!isa<ArrayType>(V->getType()))
8642 return error(VLoc, "'filter' clause has an invalid type");
8643 }
8644
8646 if (!CV)
8647 return error(VLoc, "clause argument must be a constant");
8648 LP->addClause(CV);
8649 }
8650
8651 Inst = LP.release();
8652 return false;
8653}
8654
8655/// parseFreeze
8656/// ::= 'freeze' Type Value
8657bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8658 LocTy Loc;
8659 Value *Op;
8660 if (parseTypeAndValue(Op, Loc, PFS))
8661 return true;
8662
8663 Inst = new FreezeInst(Op);
8664 return false;
8665}
8666
8667/// parseCall
8668/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8669/// OptionalAttrs Type Value ParameterList OptionalAttrs
8670/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8671/// OptionalAttrs Type Value ParameterList OptionalAttrs
8672/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8673/// OptionalAttrs Type Value ParameterList OptionalAttrs
8674/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8675/// OptionalAttrs Type Value ParameterList OptionalAttrs
8676bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8678 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8679 std::vector<unsigned> FwdRefAttrGrps;
8680 LocTy BuiltinLoc;
8681 unsigned CallAddrSpace;
8682 unsigned CC;
8683 Type *RetType = nullptr;
8684 LocTy RetTypeLoc;
8685 ValID CalleeID;
8688 LocTy CallLoc = Lex.getLoc();
8689
8690 if (TCK != CallInst::TCK_None &&
8691 parseToken(lltok::kw_call,
8692 "expected 'tail call', 'musttail call', or 'notail call'"))
8693 return true;
8694
8695 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8696
8697 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8698 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8699 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8700 parseValID(CalleeID, &PFS) ||
8701 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8702 PFS.getFunction().isVarArg()) ||
8703 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8704 parseOptionalOperandBundles(BundleList, PFS))
8705 return true;
8706
8707 // If RetType is a non-function pointer type, then this is the short syntax
8708 // for the call, which means that RetType is just the return type. Infer the
8709 // rest of the function argument types from the arguments that are present.
8710 FunctionType *Ty;
8711 if (resolveFunctionType(RetType, ArgList, Ty))
8712 return error(RetTypeLoc, "Invalid result type for LLVM function");
8713
8714 CalleeID.FTy = Ty;
8715
8716 // Look up the callee.
8717 Value *Callee;
8718 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8719 Callee, &PFS))
8720 return true;
8721
8722 // Set up the Attribute for the function.
8724
8725 SmallVector<Value*, 8> Args;
8726
8727 // Loop through FunctionType's arguments and ensure they are specified
8728 // correctly. Also, gather any parameter attributes.
8729 FunctionType::param_iterator I = Ty->param_begin();
8730 FunctionType::param_iterator E = Ty->param_end();
8731 for (const ParamInfo &Arg : ArgList) {
8732 Type *ExpectedTy = nullptr;
8733 if (I != E) {
8734 ExpectedTy = *I++;
8735 } else if (!Ty->isVarArg()) {
8736 return error(Arg.Loc, "too many arguments specified");
8737 }
8738
8739 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8740 return error(Arg.Loc, "argument is not of expected type '" +
8741 getTypeString(ExpectedTy) + "'");
8742 Args.push_back(Arg.V);
8743 Attrs.push_back(Arg.Attrs);
8744 }
8745
8746 if (I != E)
8747 return error(CallLoc, "not enough parameters specified for call");
8748
8749 // Finish off the Attribute and check them
8750 AttributeList PAL =
8751 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8752 AttributeSet::get(Context, RetAttrs), Attrs);
8753
8754 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8755 CI->setTailCallKind(TCK);
8756 CI->setCallingConv(CC);
8757 if (FMF.any()) {
8758 if (!isa<FPMathOperator>(CI)) {
8759 CI->deleteValue();
8760 return error(CallLoc, "fast-math-flags specified for call without "
8761 "floating-point scalar or vector return type");
8762 }
8763 CI->setFastMathFlags(FMF);
8764 }
8765
8766 if (CalleeID.Kind == ValID::t_GlobalName &&
8767 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8768 if (SeenNewDbgInfoFormat) {
8769 CI->deleteValue();
8770 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8771 "using non-intrinsic debug info");
8772 }
8773 SeenOldDbgInfoFormat = true;
8774 }
8775 CI->setAttributes(PAL);
8776 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8777 Inst = CI;
8778 return false;
8779}
8780
8781//===----------------------------------------------------------------------===//
8782// Memory Instructions.
8783//===----------------------------------------------------------------------===//
8784
8785/// parseAlloc
8786/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8787/// (',' 'align' i32)? (',', 'addrspace(n))?
8788int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8789 Value *Size = nullptr;
8790 LocTy SizeLoc, TyLoc, ASLoc;
8791 MaybeAlign Alignment;
8792 unsigned AddrSpace = 0;
8793 Type *Ty = nullptr;
8794
8795 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8796 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8797
8798 if (parseType(Ty, TyLoc))
8799 return true;
8800
8802 return error(TyLoc, "invalid type for alloca");
8803
8804 bool AteExtraComma = false;
8805 if (EatIfPresent(lltok::comma)) {
8806 if (Lex.getKind() == lltok::kw_align) {
8807 if (parseOptionalAlignment(Alignment))
8808 return true;
8809 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8810 return true;
8811 } else if (Lex.getKind() == lltok::kw_addrspace) {
8812 ASLoc = Lex.getLoc();
8813 if (parseOptionalAddrSpace(AddrSpace))
8814 return true;
8815 } else if (Lex.getKind() == lltok::MetadataVar) {
8816 AteExtraComma = true;
8817 } else {
8818 if (parseTypeAndValue(Size, SizeLoc, PFS))
8819 return true;
8820 if (EatIfPresent(lltok::comma)) {
8821 if (Lex.getKind() == lltok::kw_align) {
8822 if (parseOptionalAlignment(Alignment))
8823 return true;
8824 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8825 return true;
8826 } else if (Lex.getKind() == lltok::kw_addrspace) {
8827 ASLoc = Lex.getLoc();
8828 if (parseOptionalAddrSpace(AddrSpace))
8829 return true;
8830 } else if (Lex.getKind() == lltok::MetadataVar) {
8831 AteExtraComma = true;
8832 }
8833 }
8834 }
8835 }
8836
8837 if (Size && !Size->getType()->isIntegerTy())
8838 return error(SizeLoc, "element count must have integer type");
8839
8840 SmallPtrSet<Type *, 4> Visited;
8841 if (!Alignment && !Ty->isSized(&Visited))
8842 return error(TyLoc, "Cannot allocate unsized type");
8843 if (!Alignment)
8844 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8845 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8846 AI->setUsedWithInAlloca(IsInAlloca);
8847 AI->setSwiftError(IsSwiftError);
8848 Inst = AI;
8849 return AteExtraComma ? InstExtraComma : InstNormal;
8850}
8851
8852/// parseLoad
8853/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8854/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8855/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8856int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8857 Value *Val; LocTy Loc;
8858 MaybeAlign Alignment;
8859 bool AteExtraComma = false;
8860 bool isAtomic = false;
8863
8864 if (Lex.getKind() == lltok::kw_atomic) {
8865 isAtomic = true;
8866 Lex.Lex();
8867 }
8868
8869 bool isVolatile = false;
8870 if (Lex.getKind() == lltok::kw_volatile) {
8871 isVolatile = true;
8872 Lex.Lex();
8873 }
8874
8875 Type *Ty;
8876 LocTy ExplicitTypeLoc = Lex.getLoc();
8877 if (parseType(Ty) ||
8878 parseToken(lltok::comma, "expected comma after load's type") ||
8879 parseTypeAndValue(Val, Loc, PFS) ||
8880 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8881 parseOptionalCommaAlign(Alignment, AteExtraComma))
8882 return true;
8883
8884 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8885 return error(Loc, "load operand must be a pointer to a first class type");
8886 if (isAtomic && !Alignment)
8887 return error(Loc, "atomic load must have explicit non-zero alignment");
8888 if (Ordering == AtomicOrdering::Release ||
8890 return error(Loc, "atomic load cannot use Release ordering");
8891
8892 SmallPtrSet<Type *, 4> Visited;
8893 if (!Alignment && !Ty->isSized(&Visited))
8894 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8895 if (!Alignment)
8896 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8897 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8898 return AteExtraComma ? InstExtraComma : InstNormal;
8899}
8900
8901/// parseStore
8902
8903/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8904/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8905/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8906int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8907 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8908 MaybeAlign Alignment;
8909 bool AteExtraComma = false;
8910 bool isAtomic = false;
8913
8914 if (Lex.getKind() == lltok::kw_atomic) {
8915 isAtomic = true;
8916 Lex.Lex();
8917 }
8918
8919 bool isVolatile = false;
8920 if (Lex.getKind() == lltok::kw_volatile) {
8921 isVolatile = true;
8922 Lex.Lex();
8923 }
8924
8925 if (parseTypeAndValue(Val, Loc, PFS) ||
8926 parseToken(lltok::comma, "expected ',' after store operand") ||
8927 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8928 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8929 parseOptionalCommaAlign(Alignment, AteExtraComma))
8930 return true;
8931
8932 if (!Ptr->getType()->isPointerTy())
8933 return error(PtrLoc, "store operand must be a pointer");
8934 if (!Val->getType()->isFirstClassType())
8935 return error(Loc, "store operand must be a first class value");
8936 if (isAtomic && !Alignment)
8937 return error(Loc, "atomic store must have explicit non-zero alignment");
8938 if (Ordering == AtomicOrdering::Acquire ||
8940 return error(Loc, "atomic store cannot use Acquire ordering");
8941 SmallPtrSet<Type *, 4> Visited;
8942 if (!Alignment && !Val->getType()->isSized(&Visited))
8943 return error(Loc, "storing unsized types is not allowed");
8944 if (!Alignment)
8945 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8946
8947 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8948 return AteExtraComma ? InstExtraComma : InstNormal;
8949}
8950
8951/// parseCmpXchg
8952/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8953/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8954/// 'Align'?
8955int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8956 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8957 bool AteExtraComma = false;
8958 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8959 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8961 bool isVolatile = false;
8962 bool isWeak = false;
8963 MaybeAlign Alignment;
8964
8965 if (EatIfPresent(lltok::kw_weak))
8966 isWeak = true;
8967
8968 if (EatIfPresent(lltok::kw_volatile))
8969 isVolatile = true;
8970
8971 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8972 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8973 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8974 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8975 parseTypeAndValue(New, NewLoc, PFS) ||
8976 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8977 parseOrdering(FailureOrdering) ||
8978 parseOptionalCommaAlign(Alignment, AteExtraComma))
8979 return true;
8980
8981 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8982 return tokError("invalid cmpxchg success ordering");
8983 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8984 return tokError("invalid cmpxchg failure ordering");
8985 if (!Ptr->getType()->isPointerTy())
8986 return error(PtrLoc, "cmpxchg operand must be a pointer");
8987 if (Cmp->getType() != New->getType())
8988 return error(NewLoc, "compare value and new value type do not match");
8989 if (!New->getType()->isFirstClassType())
8990 return error(NewLoc, "cmpxchg operand must be a first class value");
8991
8992 const Align DefaultAlignment(
8993 PFS.getFunction().getDataLayout().getTypeStoreSize(
8994 Cmp->getType()));
8995
8996 AtomicCmpXchgInst *CXI =
8997 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8998 SuccessOrdering, FailureOrdering, SSID);
8999 CXI->setVolatile(isVolatile);
9000 CXI->setWeak(isWeak);
9001
9002 Inst = CXI;
9003 return AteExtraComma ? InstExtraComma : InstNormal;
9004}
9005
9006/// parseAtomicRMW
9007/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9008/// TypeAndValue
9009/// 'singlethread'? AtomicOrdering
9010int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9011 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9012 bool AteExtraComma = false;
9015 bool IsVolatile = false;
9016 bool IsElementwise = false;
9017 bool IsFP = false;
9019 MaybeAlign Alignment;
9020
9021 if (EatIfPresent(lltok::kw_volatile))
9022 IsVolatile = true;
9023 if (EatIfPresent(lltok::kw_elementwise))
9024 IsElementwise = true;
9025
9026 switch (Lex.getKind()) {
9027 default:
9028 return tokError("expected binary operation in atomicrmw");
9042 break;
9045 break;
9048 break;
9049 case lltok::kw_usub_sat:
9051 break;
9052 case lltok::kw_fadd:
9054 IsFP = true;
9055 break;
9056 case lltok::kw_fsub:
9058 IsFP = true;
9059 break;
9060 case lltok::kw_fmax:
9062 IsFP = true;
9063 break;
9064 case lltok::kw_fmin:
9066 IsFP = true;
9067 break;
9068 case lltok::kw_fmaximum:
9070 IsFP = true;
9071 break;
9072 case lltok::kw_fminimum:
9074 IsFP = true;
9075 break;
9078 IsFP = true;
9079 break;
9082 IsFP = true;
9083 break;
9084 }
9085 Lex.Lex(); // Eat the operation.
9086
9087 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9088 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9089 parseTypeAndValue(Val, ValLoc, PFS) ||
9090 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9091 parseOptionalCommaAlign(Alignment, AteExtraComma))
9092 return true;
9093
9094 if (Ordering == AtomicOrdering::Unordered)
9095 return tokError("atomicrmw cannot be unordered");
9096 if (!Ptr->getType()->isPointerTy())
9097 return error(PtrLoc, "atomicrmw operand must be a pointer");
9098 if (Val->getType()->isScalableTy())
9099 return error(ValLoc, "atomicrmw operand may not be scalable");
9100
9101 // For elementwise ops, the value must be a fixed vector type whose element
9102 // type is legal for the corresponding scalar atomicrmw operation. So assign
9103 // ScalarTy the element type for elementwise ops so we can check this.
9104 Type *ScalarTy = Val->getType();
9105 if (IsElementwise) {
9106 auto *VecTy = dyn_cast<FixedVectorType>(Val->getType());
9107 if (!VecTy)
9108 return error(ValLoc,
9109 "atomicrmw elementwise operand must be a fixed vector type");
9110 ScalarTy = VecTy->getElementType();
9111 }
9112
9114 if (!ScalarTy->isIntegerTy() && !ScalarTy->isFloatingPointTy() &&
9115 !ScalarTy->isPointerTy()) {
9116 return error(
9117 ValLoc,
9119 " operand must be an integer, floating point, or pointer type");
9120 }
9121 } else if (IsFP) {
9122 if (!ScalarTy->isFPOrFPVectorTy()) {
9123 return error(ValLoc, "atomicrmw " +
9125 " operand must be a floating point type");
9126 }
9127 } else {
9128 if (!ScalarTy->isIntegerTy()) {
9129 return error(ValLoc, "atomicrmw " +
9131 " operand must be an integer");
9132 }
9133 }
9134
9135 unsigned Size =
9136 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(Val->getType());
9137 if (Size < 8 || (Size & (Size - 1)))
9138 return error(ValLoc,
9139 "atomicrmw operand must have a power-of-two byte size");
9140 const Align DefaultAlignment(
9141 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9142 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9143 Alignment.value_or(DefaultAlignment),
9144 Ordering, SSID, IsElementwise);
9145 RMWI->setVolatile(IsVolatile);
9146 Inst = RMWI;
9147 return AteExtraComma ? InstExtraComma : InstNormal;
9148}
9149
9150/// parseFence
9151/// ::= 'fence' 'singlethread'? AtomicOrdering
9152int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9155 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9156 return true;
9157
9158 if (Ordering == AtomicOrdering::Unordered)
9159 return tokError("fence cannot be unordered");
9160 if (Ordering == AtomicOrdering::Monotonic)
9161 return tokError("fence cannot be monotonic");
9162
9163 Inst = new FenceInst(Context, Ordering, SSID);
9164 return InstNormal;
9165}
9166
9167/// parseGetElementPtr
9168/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9169int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9170 Value *Ptr = nullptr;
9171 Value *Val = nullptr;
9172 LocTy Loc, EltLoc;
9173 GEPNoWrapFlags NW;
9174
9175 while (true) {
9176 if (EatIfPresent(lltok::kw_inbounds))
9178 else if (EatIfPresent(lltok::kw_nusw))
9180 else if (EatIfPresent(lltok::kw_nuw))
9182 else
9183 break;
9184 }
9185
9186 Type *Ty = nullptr;
9187 if (parseType(Ty) ||
9188 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9189 parseTypeAndValue(Ptr, Loc, PFS))
9190 return true;
9191
9192 Type *BaseType = Ptr->getType();
9193 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9194 if (!BasePointerType)
9195 return error(Loc, "base of getelementptr must be a pointer");
9196
9197 SmallVector<Value*, 16> Indices;
9198 bool AteExtraComma = false;
9199 // GEP returns a vector of pointers if at least one of parameters is a vector.
9200 // All vector parameters should have the same vector width.
9201 ElementCount GEPWidth = BaseType->isVectorTy()
9202 ? cast<VectorType>(BaseType)->getElementCount()
9204
9205 while (EatIfPresent(lltok::comma)) {
9206 if (Lex.getKind() == lltok::MetadataVar) {
9207 AteExtraComma = true;
9208 break;
9209 }
9210 if (parseTypeAndValue(Val, EltLoc, PFS))
9211 return true;
9212 if (!Val->getType()->isIntOrIntVectorTy())
9213 return error(EltLoc, "getelementptr index must be an integer");
9214
9215 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9216 ElementCount ValNumEl = ValVTy->getElementCount();
9217 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9218 return error(
9219 EltLoc,
9220 "getelementptr vector index has a wrong number of elements");
9221 GEPWidth = ValNumEl;
9222 }
9223 Indices.push_back(Val);
9224 }
9225
9226 SmallPtrSet<Type*, 4> Visited;
9227 if (!Indices.empty() && !Ty->isSized(&Visited))
9228 return error(Loc, "base element of getelementptr must be sized");
9229
9230 auto *STy = dyn_cast<StructType>(Ty);
9231 if (STy && STy->isScalableTy())
9232 return error(Loc, "getelementptr cannot target structure that contains "
9233 "scalable vector type");
9234
9235 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9236 return error(Loc, "invalid getelementptr indices");
9237 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9238 Inst = GEP;
9239 GEP->setNoWrapFlags(NW);
9240 return AteExtraComma ? InstExtraComma : InstNormal;
9241}
9242
9243/// parseExtractValue
9244/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9245int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9246 Value *Val; LocTy Loc;
9247 SmallVector<unsigned, 4> Indices;
9248 bool AteExtraComma;
9249 if (parseTypeAndValue(Val, Loc, PFS) ||
9250 parseIndexList(Indices, AteExtraComma))
9251 return true;
9252
9253 if (!Val->getType()->isAggregateType())
9254 return error(Loc, "extractvalue operand must be aggregate type");
9255
9256 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9257 return error(Loc, "invalid indices for extractvalue");
9258 Inst = ExtractValueInst::Create(Val, Indices);
9259 return AteExtraComma ? InstExtraComma : InstNormal;
9260}
9261
9262/// parseInsertValue
9263/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9264int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9265 Value *Val0, *Val1; LocTy Loc0, Loc1;
9266 SmallVector<unsigned, 4> Indices;
9267 bool AteExtraComma;
9268 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9269 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9270 parseTypeAndValue(Val1, Loc1, PFS) ||
9271 parseIndexList(Indices, AteExtraComma))
9272 return true;
9273
9274 if (!Val0->getType()->isAggregateType())
9275 return error(Loc0, "insertvalue operand must be aggregate type");
9276
9277 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9278 if (!IndexedType)
9279 return error(Loc0, "invalid indices for insertvalue");
9280 if (IndexedType != Val1->getType())
9281 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9282 getTypeString(Val1->getType()) + "' instead of '" +
9283 getTypeString(IndexedType) + "'");
9284 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9285 return AteExtraComma ? InstExtraComma : InstNormal;
9286}
9287
9288//===----------------------------------------------------------------------===//
9289// Embedded metadata.
9290//===----------------------------------------------------------------------===//
9291
9292/// parseMDNodeVector
9293/// ::= { Element (',' Element)* }
9294/// Element
9295/// ::= 'null' | Metadata
9296bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9297 if (parseToken(lltok::lbrace, "expected '{' here"))
9298 return true;
9299
9300 // Check for an empty list.
9301 if (EatIfPresent(lltok::rbrace))
9302 return false;
9303
9304 do {
9305 if (EatIfPresent(lltok::kw_null)) {
9306 Elts.push_back(nullptr);
9307 continue;
9308 }
9309
9310 Metadata *MD;
9311 if (parseMetadata(MD, nullptr))
9312 return true;
9313 Elts.push_back(MD);
9314 } while (EatIfPresent(lltok::comma));
9315
9316 return parseToken(lltok::rbrace, "expected end of metadata node");
9317}
9318
9319//===----------------------------------------------------------------------===//
9320// Use-list order directives.
9321//===----------------------------------------------------------------------===//
9322bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9323 SMLoc Loc) {
9324 if (!V->hasUseList())
9325 return false;
9326 if (V->use_empty())
9327 return error(Loc, "value has no uses");
9328
9329 unsigned NumUses = 0;
9330 SmallDenseMap<const Use *, unsigned, 16> Order;
9331 for (const Use &U : V->uses()) {
9332 if (++NumUses > Indexes.size())
9333 break;
9334 Order[&U] = Indexes[NumUses - 1];
9335 }
9336 if (NumUses < 2)
9337 return error(Loc, "value only has one use");
9338 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9339 return error(Loc,
9340 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9341
9342 V->sortUseList([&](const Use &L, const Use &R) {
9343 return Order.lookup(&L) < Order.lookup(&R);
9344 });
9345 return false;
9346}
9347
9348/// parseUseListOrderIndexes
9349/// ::= '{' uint32 (',' uint32)+ '}'
9350bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9351 SMLoc Loc = Lex.getLoc();
9352 if (parseToken(lltok::lbrace, "expected '{' here"))
9353 return true;
9354 if (Lex.getKind() == lltok::rbrace)
9355 return tokError("expected non-empty list of uselistorder indexes");
9356
9357 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9358 // indexes should be distinct numbers in the range [0, size-1], and should
9359 // not be in order.
9360 unsigned Offset = 0;
9361 unsigned Max = 0;
9362 bool IsOrdered = true;
9363 assert(Indexes.empty() && "Expected empty order vector");
9364 do {
9365 unsigned Index;
9366 if (parseUInt32(Index))
9367 return true;
9368
9369 // Update consistency checks.
9370 Offset += Index - Indexes.size();
9371 Max = std::max(Max, Index);
9372 IsOrdered &= Index == Indexes.size();
9373
9374 Indexes.push_back(Index);
9375 } while (EatIfPresent(lltok::comma));
9376
9377 if (parseToken(lltok::rbrace, "expected '}' here"))
9378 return true;
9379
9380 if (Indexes.size() < 2)
9381 return error(Loc, "expected >= 2 uselistorder indexes");
9382 if (Offset != 0 || Max >= Indexes.size())
9383 return error(Loc,
9384 "expected distinct uselistorder indexes in range [0, size)");
9385 if (IsOrdered)
9386 return error(Loc, "expected uselistorder indexes to change the order");
9387
9388 return false;
9389}
9390
9391/// parseUseListOrder
9392/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9393bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9394 SMLoc Loc = Lex.getLoc();
9395 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9396 return true;
9397
9398 Value *V;
9399 SmallVector<unsigned, 16> Indexes;
9400 if (parseTypeAndValue(V, PFS) ||
9401 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9402 parseUseListOrderIndexes(Indexes))
9403 return true;
9404
9405 return sortUseListOrder(V, Indexes, Loc);
9406}
9407
9408/// parseUseListOrderBB
9409/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9410bool LLParser::parseUseListOrderBB() {
9411 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9412 SMLoc Loc = Lex.getLoc();
9413 Lex.Lex();
9414
9415 ValID Fn, Label;
9416 SmallVector<unsigned, 16> Indexes;
9417 if (parseValID(Fn, /*PFS=*/nullptr) ||
9418 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9419 parseValID(Label, /*PFS=*/nullptr) ||
9420 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9421 parseUseListOrderIndexes(Indexes))
9422 return true;
9423
9424 // Check the function.
9425 GlobalValue *GV;
9426 if (Fn.Kind == ValID::t_GlobalName)
9427 GV = M->getNamedValue(Fn.StrVal);
9428 else if (Fn.Kind == ValID::t_GlobalID)
9429 GV = NumberedVals.get(Fn.UIntVal);
9430 else
9431 return error(Fn.Loc, "expected function name in uselistorder_bb");
9432 if (!GV)
9433 return error(Fn.Loc,
9434 "invalid function forward reference in uselistorder_bb");
9435 auto *F = dyn_cast<Function>(GV);
9436 if (!F)
9437 return error(Fn.Loc, "expected function name in uselistorder_bb");
9438 if (F->isDeclaration())
9439 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9440
9441 // Check the basic block.
9442 if (Label.Kind == ValID::t_LocalID)
9443 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9444 if (Label.Kind != ValID::t_LocalName)
9445 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9446 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9447 if (!V)
9448 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9449 if (!isa<BasicBlock>(V))
9450 return error(Label.Loc, "expected basic block in uselistorder_bb");
9451
9452 return sortUseListOrder(V, Indexes, Loc);
9453}
9454
9455/// ModuleEntry
9456/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9457/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9458bool LLParser::parseModuleEntry(unsigned ID) {
9459 assert(Lex.getKind() == lltok::kw_module);
9460 Lex.Lex();
9461
9462 std::string Path;
9463 if (parseToken(lltok::colon, "expected ':' here") ||
9464 parseToken(lltok::lparen, "expected '(' here") ||
9465 parseToken(lltok::kw_path, "expected 'path' here") ||
9466 parseToken(lltok::colon, "expected ':' here") ||
9467 parseStringConstant(Path) ||
9468 parseToken(lltok::comma, "expected ',' here") ||
9469 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9470 parseToken(lltok::colon, "expected ':' here") ||
9471 parseToken(lltok::lparen, "expected '(' here"))
9472 return true;
9473
9474 ModuleHash Hash;
9475 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9476 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9477 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9478 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9479 parseUInt32(Hash[4]))
9480 return true;
9481
9482 if (parseToken(lltok::rparen, "expected ')' here") ||
9483 parseToken(lltok::rparen, "expected ')' here"))
9484 return true;
9485
9486 auto ModuleEntry = Index->addModule(Path, Hash);
9487 ModuleIdMap[ID] = ModuleEntry->first();
9488
9489 return false;
9490}
9491
9492/// TypeIdEntry
9493/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9494bool LLParser::parseTypeIdEntry(unsigned ID) {
9495 assert(Lex.getKind() == lltok::kw_typeid);
9496 Lex.Lex();
9497
9498 std::string Name;
9499 if (parseToken(lltok::colon, "expected ':' here") ||
9500 parseToken(lltok::lparen, "expected '(' here") ||
9501 parseToken(lltok::kw_name, "expected 'name' here") ||
9502 parseToken(lltok::colon, "expected ':' here") ||
9503 parseStringConstant(Name))
9504 return true;
9505
9506 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9507 if (parseToken(lltok::comma, "expected ',' here") ||
9508 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9509 return true;
9510
9511 // Check if this ID was forward referenced, and if so, update the
9512 // corresponding GUIDs.
9513 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9514 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9515 for (auto TIDRef : FwdRefTIDs->second) {
9516 assert(!*TIDRef.first &&
9517 "Forward referenced type id GUID expected to be 0");
9518 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9519 }
9520 ForwardRefTypeIds.erase(FwdRefTIDs);
9521 }
9522
9523 return false;
9524}
9525
9526/// TypeIdSummary
9527/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9528bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9529 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9530 parseToken(lltok::colon, "expected ':' here") ||
9531 parseToken(lltok::lparen, "expected '(' here") ||
9532 parseTypeTestResolution(TIS.TTRes))
9533 return true;
9534
9535 if (EatIfPresent(lltok::comma)) {
9536 // Expect optional wpdResolutions field
9537 if (parseOptionalWpdResolutions(TIS.WPDRes))
9538 return true;
9539 }
9540
9541 if (parseToken(lltok::rparen, "expected ')' here"))
9542 return true;
9543
9544 return false;
9545}
9546
9548 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9549
9550/// TypeIdCompatibleVtableEntry
9551/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9552/// TypeIdCompatibleVtableInfo
9553/// ')'
9554bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9556 Lex.Lex();
9557
9558 std::string Name;
9559 if (parseToken(lltok::colon, "expected ':' here") ||
9560 parseToken(lltok::lparen, "expected '(' here") ||
9561 parseToken(lltok::kw_name, "expected 'name' here") ||
9562 parseToken(lltok::colon, "expected ':' here") ||
9563 parseStringConstant(Name))
9564 return true;
9565
9567 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9568 if (parseToken(lltok::comma, "expected ',' here") ||
9569 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9570 parseToken(lltok::colon, "expected ':' here") ||
9571 parseToken(lltok::lparen, "expected '(' here"))
9572 return true;
9573
9574 IdToIndexMapType IdToIndexMap;
9575 // parse each call edge
9576 do {
9578 if (parseToken(lltok::lparen, "expected '(' here") ||
9579 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9580 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9581 parseToken(lltok::comma, "expected ',' here"))
9582 return true;
9583
9584 LocTy Loc = Lex.getLoc();
9585 unsigned GVId;
9586 ValueInfo VI;
9587 if (parseGVReference(VI, GVId))
9588 return true;
9589
9590 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9591 // forward reference. We will save the location of the ValueInfo needing an
9592 // update, but can only do so once the std::vector is finalized.
9593 if (VI == EmptyVI)
9594 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9595 TI.push_back({Offset, VI});
9596
9597 if (parseToken(lltok::rparen, "expected ')' in call"))
9598 return true;
9599 } while (EatIfPresent(lltok::comma));
9600
9601 // Now that the TI vector is finalized, it is safe to save the locations
9602 // of any forward GV references that need updating later.
9603 for (auto I : IdToIndexMap) {
9604 auto &Infos = ForwardRefValueInfos[I.first];
9605 for (auto P : I.second) {
9606 assert(TI[P.first].VTableVI == EmptyVI &&
9607 "Forward referenced ValueInfo expected to be empty");
9608 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9609 }
9610 }
9611
9612 if (parseToken(lltok::rparen, "expected ')' here") ||
9613 parseToken(lltok::rparen, "expected ')' here"))
9614 return true;
9615
9616 // Check if this ID was forward referenced, and if so, update the
9617 // corresponding GUIDs.
9618 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9619 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9620 for (auto TIDRef : FwdRefTIDs->second) {
9621 assert(!*TIDRef.first &&
9622 "Forward referenced type id GUID expected to be 0");
9623 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9624 }
9625 ForwardRefTypeIds.erase(FwdRefTIDs);
9626 }
9627
9628 return false;
9629}
9630
9631/// TypeTestResolution
9632/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9633/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9634/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9635/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9636/// [',' 'inlinesBits' ':' UInt64]? ')'
9637bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9638 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9639 parseToken(lltok::colon, "expected ':' here") ||
9640 parseToken(lltok::lparen, "expected '(' here") ||
9641 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9642 parseToken(lltok::colon, "expected ':' here"))
9643 return true;
9644
9645 switch (Lex.getKind()) {
9646 case lltok::kw_unknown:
9648 break;
9649 case lltok::kw_unsat:
9651 break;
9654 break;
9655 case lltok::kw_inline:
9657 break;
9658 case lltok::kw_single:
9660 break;
9661 case lltok::kw_allOnes:
9663 break;
9664 default:
9665 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9666 }
9667 Lex.Lex();
9668
9669 if (parseToken(lltok::comma, "expected ',' here") ||
9670 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9671 parseToken(lltok::colon, "expected ':' here") ||
9672 parseUInt32(TTRes.SizeM1BitWidth))
9673 return true;
9674
9675 // parse optional fields
9676 while (EatIfPresent(lltok::comma)) {
9677 switch (Lex.getKind()) {
9679 Lex.Lex();
9680 if (parseToken(lltok::colon, "expected ':'") ||
9681 parseUInt64(TTRes.AlignLog2))
9682 return true;
9683 break;
9684 case lltok::kw_sizeM1:
9685 Lex.Lex();
9686 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9687 return true;
9688 break;
9689 case lltok::kw_bitMask: {
9690 unsigned Val;
9691 Lex.Lex();
9692 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9693 return true;
9694 assert(Val <= 0xff);
9695 TTRes.BitMask = (uint8_t)Val;
9696 break;
9697 }
9699 Lex.Lex();
9700 if (parseToken(lltok::colon, "expected ':'") ||
9701 parseUInt64(TTRes.InlineBits))
9702 return true;
9703 break;
9704 default:
9705 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9706 }
9707 }
9708
9709 if (parseToken(lltok::rparen, "expected ')' here"))
9710 return true;
9711
9712 return false;
9713}
9714
9715/// OptionalWpdResolutions
9716/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9717/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9718bool LLParser::parseOptionalWpdResolutions(
9719 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9720 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9721 parseToken(lltok::colon, "expected ':' here") ||
9722 parseToken(lltok::lparen, "expected '(' here"))
9723 return true;
9724
9725 do {
9726 uint64_t Offset;
9727 WholeProgramDevirtResolution WPDRes;
9728 if (parseToken(lltok::lparen, "expected '(' here") ||
9729 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9730 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9731 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9732 parseToken(lltok::rparen, "expected ')' here"))
9733 return true;
9734 WPDResMap[Offset] = WPDRes;
9735 } while (EatIfPresent(lltok::comma));
9736
9737 if (parseToken(lltok::rparen, "expected ')' here"))
9738 return true;
9739
9740 return false;
9741}
9742
9743/// WpdRes
9744/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9745/// [',' OptionalResByArg]? ')'
9746/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9747/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9748/// [',' OptionalResByArg]? ')'
9749/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9750/// [',' OptionalResByArg]? ')'
9751bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9752 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9753 parseToken(lltok::colon, "expected ':' here") ||
9754 parseToken(lltok::lparen, "expected '(' here") ||
9755 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9756 parseToken(lltok::colon, "expected ':' here"))
9757 return true;
9758
9759 switch (Lex.getKind()) {
9760 case lltok::kw_indir:
9762 break;
9765 break;
9768 break;
9769 default:
9770 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9771 }
9772 Lex.Lex();
9773
9774 // parse optional fields
9775 while (EatIfPresent(lltok::comma)) {
9776 switch (Lex.getKind()) {
9778 Lex.Lex();
9779 if (parseToken(lltok::colon, "expected ':' here") ||
9780 parseStringConstant(WPDRes.SingleImplName))
9781 return true;
9782 break;
9783 case lltok::kw_resByArg:
9784 if (parseOptionalResByArg(WPDRes.ResByArg))
9785 return true;
9786 break;
9787 default:
9788 return error(Lex.getLoc(),
9789 "expected optional WholeProgramDevirtResolution field");
9790 }
9791 }
9792
9793 if (parseToken(lltok::rparen, "expected ')' here"))
9794 return true;
9795
9796 return false;
9797}
9798
9799/// OptionalResByArg
9800/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9801/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9802/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9803/// 'virtualConstProp' )
9804/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9805/// [',' 'bit' ':' UInt32]? ')'
9806bool LLParser::parseOptionalResByArg(
9807 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9808 &ResByArg) {
9809 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9810 parseToken(lltok::colon, "expected ':' here") ||
9811 parseToken(lltok::lparen, "expected '(' here"))
9812 return true;
9813
9814 do {
9815 std::vector<uint64_t> Args;
9816 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9817 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9818 parseToken(lltok::colon, "expected ':' here") ||
9819 parseToken(lltok::lparen, "expected '(' here") ||
9820 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9821 parseToken(lltok::colon, "expected ':' here"))
9822 return true;
9823
9824 WholeProgramDevirtResolution::ByArg ByArg;
9825 switch (Lex.getKind()) {
9826 case lltok::kw_indir:
9828 break;
9831 break;
9834 break;
9837 break;
9838 default:
9839 return error(Lex.getLoc(),
9840 "unexpected WholeProgramDevirtResolution::ByArg kind");
9841 }
9842 Lex.Lex();
9843
9844 // parse optional fields
9845 while (EatIfPresent(lltok::comma)) {
9846 switch (Lex.getKind()) {
9847 case lltok::kw_info:
9848 Lex.Lex();
9849 if (parseToken(lltok::colon, "expected ':' here") ||
9850 parseUInt64(ByArg.Info))
9851 return true;
9852 break;
9853 case lltok::kw_byte:
9854 Lex.Lex();
9855 if (parseToken(lltok::colon, "expected ':' here") ||
9856 parseUInt32(ByArg.Byte))
9857 return true;
9858 break;
9859 case lltok::kw_bit:
9860 Lex.Lex();
9861 if (parseToken(lltok::colon, "expected ':' here") ||
9862 parseUInt32(ByArg.Bit))
9863 return true;
9864 break;
9865 default:
9866 return error(Lex.getLoc(),
9867 "expected optional whole program devirt field");
9868 }
9869 }
9870
9871 if (parseToken(lltok::rparen, "expected ')' here"))
9872 return true;
9873
9874 ResByArg[Args] = ByArg;
9875 } while (EatIfPresent(lltok::comma));
9876
9877 if (parseToken(lltok::rparen, "expected ')' here"))
9878 return true;
9879
9880 return false;
9881}
9882
9883/// OptionalResByArg
9884/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9885bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9886 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9887 parseToken(lltok::colon, "expected ':' here") ||
9888 parseToken(lltok::lparen, "expected '(' here"))
9889 return true;
9890
9891 do {
9892 uint64_t Val;
9893 if (parseUInt64(Val))
9894 return true;
9895 Args.push_back(Val);
9896 } while (EatIfPresent(lltok::comma));
9897
9898 if (parseToken(lltok::rparen, "expected ')' here"))
9899 return true;
9900
9901 return false;
9902}
9903
9904static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9905
9906static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9907 bool ReadOnly = Fwd->isReadOnly();
9908 bool WriteOnly = Fwd->isWriteOnly();
9909 assert(!(ReadOnly && WriteOnly));
9910 *Fwd = Resolved;
9911 if (ReadOnly)
9912 Fwd->setReadOnly();
9913 if (WriteOnly)
9914 Fwd->setWriteOnly();
9915}
9916
9917/// Stores the given Name/GUID and associated summary into the Index.
9918/// Also updates any forward references to the associated entry ID.
9919bool LLParser::addGlobalValueToIndex(
9920 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9921 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9922 // First create the ValueInfo utilizing the Name or GUID.
9923 ValueInfo VI;
9924 if (GUID != 0) {
9925 assert(Name.empty());
9926 VI = Index->getOrInsertValueInfo(GUID);
9927 } else {
9928 assert(!Name.empty());
9929 if (M) {
9930 auto *GV = M->getNamedValue(Name);
9931 if (!GV)
9932 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9933
9934 VI = Index->getOrInsertValueInfo(GV);
9935 } else {
9936 assert(
9937 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9938 "Need a source_filename to compute GUID for local");
9940 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9941 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9942 }
9943 }
9944
9945 // Resolve forward references from calls/refs
9946 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9947 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9948 for (auto VIRef : FwdRefVIs->second) {
9949 assert(VIRef.first->getRef() == FwdVIRef &&
9950 "Forward referenced ValueInfo expected to be empty");
9951 resolveFwdRef(VIRef.first, VI);
9952 }
9953 ForwardRefValueInfos.erase(FwdRefVIs);
9954 }
9955
9956 // Resolve forward references from aliases
9957 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9958 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9959 for (auto AliaseeRef : FwdRefAliasees->second) {
9960 assert(!AliaseeRef.first->hasAliasee() &&
9961 "Forward referencing alias already has aliasee");
9962 assert(Summary && "Aliasee must be a definition");
9963 AliaseeRef.first->setAliasee(VI, Summary.get());
9964 }
9965 ForwardRefAliasees.erase(FwdRefAliasees);
9966 }
9967
9968 // Add the summary if one was provided.
9969 if (Summary)
9970 Index->addGlobalValueSummary(VI, std::move(Summary));
9971
9972 // Save the associated ValueInfo for use in later references by ID.
9973 if (ID == NumberedValueInfos.size())
9974 NumberedValueInfos.push_back(VI);
9975 else {
9976 // Handle non-continuous numbers (to make test simplification easier).
9977 if (ID > NumberedValueInfos.size())
9978 NumberedValueInfos.resize(ID + 1);
9979 NumberedValueInfos[ID] = VI;
9980 }
9981
9982 return false;
9983}
9984
9985/// parseSummaryIndexFlags
9986/// ::= 'flags' ':' UInt64
9987bool LLParser::parseSummaryIndexFlags() {
9988 assert(Lex.getKind() == lltok::kw_flags);
9989 Lex.Lex();
9990
9991 if (parseToken(lltok::colon, "expected ':' here"))
9992 return true;
9993 uint64_t Flags;
9994 if (parseUInt64(Flags))
9995 return true;
9996 if (Index)
9997 Index->setFlags(Flags);
9998 return false;
9999}
10000
10001/// parseBlockCount
10002/// ::= 'blockcount' ':' UInt64
10003bool LLParser::parseBlockCount() {
10004 assert(Lex.getKind() == lltok::kw_blockcount);
10005 Lex.Lex();
10006
10007 if (parseToken(lltok::colon, "expected ':' here"))
10008 return true;
10009 uint64_t BlockCount;
10010 if (parseUInt64(BlockCount))
10011 return true;
10012 if (Index)
10013 Index->setBlockCount(BlockCount);
10014 return false;
10015}
10016
10017/// parseGVEntry
10018/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10019/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10020/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10021bool LLParser::parseGVEntry(unsigned ID) {
10022 assert(Lex.getKind() == lltok::kw_gv);
10023 Lex.Lex();
10024
10025 if (parseToken(lltok::colon, "expected ':' here") ||
10026 parseToken(lltok::lparen, "expected '(' here"))
10027 return true;
10028
10029 LocTy Loc = Lex.getLoc();
10030 std::string Name;
10032 switch (Lex.getKind()) {
10033 case lltok::kw_name:
10034 Lex.Lex();
10035 if (parseToken(lltok::colon, "expected ':' here") ||
10036 parseStringConstant(Name))
10037 return true;
10038 // Can't create GUID/ValueInfo until we have the linkage.
10039 break;
10040 case lltok::kw_guid:
10041 Lex.Lex();
10042 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10043 return true;
10044 break;
10045 default:
10046 return error(Lex.getLoc(), "expected name or guid tag");
10047 }
10048
10049 if (!EatIfPresent(lltok::comma)) {
10050 // No summaries. Wrap up.
10051 if (parseToken(lltok::rparen, "expected ')' here"))
10052 return true;
10053 // This was created for a call to an external or indirect target.
10054 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10055 // created for indirect calls with VP. A Name with no GUID came from
10056 // an external definition. We pass ExternalLinkage since that is only
10057 // used when the GUID must be computed from Name, and in that case
10058 // the symbol must have external linkage.
10059 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10060 nullptr, Loc);
10061 }
10062
10063 // Have a list of summaries
10064 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10065 parseToken(lltok::colon, "expected ':' here") ||
10066 parseToken(lltok::lparen, "expected '(' here"))
10067 return true;
10068 do {
10069 switch (Lex.getKind()) {
10070 case lltok::kw_function:
10071 if (parseFunctionSummary(Name, GUID, ID))
10072 return true;
10073 break;
10074 case lltok::kw_variable:
10075 if (parseVariableSummary(Name, GUID, ID))
10076 return true;
10077 break;
10078 case lltok::kw_alias:
10079 if (parseAliasSummary(Name, GUID, ID))
10080 return true;
10081 break;
10082 default:
10083 return error(Lex.getLoc(), "expected summary type");
10084 }
10085 } while (EatIfPresent(lltok::comma));
10086
10087 if (parseToken(lltok::rparen, "expected ')' here") ||
10088 parseToken(lltok::rparen, "expected ')' here"))
10089 return true;
10090
10091 return false;
10092}
10093
10094/// FunctionSummary
10095/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10096/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10097/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10098/// [',' OptionalRefs]? ')'
10099bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10100 unsigned ID) {
10101 LocTy Loc = Lex.getLoc();
10102 assert(Lex.getKind() == lltok::kw_function);
10103 Lex.Lex();
10104
10105 StringRef ModulePath;
10106 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10108 /*NotEligibleToImport=*/false,
10109 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10110 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10111 unsigned InstCount;
10113 FunctionSummary::TypeIdInfo TypeIdInfo;
10114 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10116 std::vector<CallsiteInfo> Callsites;
10117 std::vector<AllocInfo> Allocs;
10118 // Default is all-zeros (conservative values).
10119 FunctionSummary::FFlags FFlags = {};
10120 if (parseToken(lltok::colon, "expected ':' here") ||
10121 parseToken(lltok::lparen, "expected '(' here") ||
10122 parseModuleReference(ModulePath) ||
10123 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10124 parseToken(lltok::comma, "expected ',' here") ||
10125 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10126 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10127 return true;
10128
10129 // parse optional fields
10130 while (EatIfPresent(lltok::comma)) {
10131 switch (Lex.getKind()) {
10133 if (parseOptionalFFlags(FFlags))
10134 return true;
10135 break;
10136 case lltok::kw_calls:
10137 if (parseOptionalCalls(Calls))
10138 return true;
10139 break;
10141 if (parseOptionalTypeIdInfo(TypeIdInfo))
10142 return true;
10143 break;
10144 case lltok::kw_refs:
10145 if (parseOptionalRefs(Refs))
10146 return true;
10147 break;
10148 case lltok::kw_params:
10149 if (parseOptionalParamAccesses(ParamAccesses))
10150 return true;
10151 break;
10152 case lltok::kw_allocs:
10153 if (parseOptionalAllocs(Allocs))
10154 return true;
10155 break;
10157 if (parseOptionalCallsites(Callsites))
10158 return true;
10159 break;
10160 default:
10161 return error(Lex.getLoc(), "expected optional function summary field");
10162 }
10163 }
10164
10165 if (parseToken(lltok::rparen, "expected ')' here"))
10166 return true;
10167
10168 auto FS = std::make_unique<FunctionSummary>(
10169 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10170 std::move(TypeIdInfo.TypeTests),
10171 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10172 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10173 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10174 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10175 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10176
10177 FS->setModulePath(ModulePath);
10178
10179 return addGlobalValueToIndex(Name, GUID,
10181 std::move(FS), Loc);
10182}
10183
10184/// VariableSummary
10185/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10186/// [',' OptionalRefs]? ')'
10187bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10188 unsigned ID) {
10189 LocTy Loc = Lex.getLoc();
10190 assert(Lex.getKind() == lltok::kw_variable);
10191 Lex.Lex();
10192
10193 StringRef ModulePath;
10194 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10196 /*NotEligibleToImport=*/false,
10197 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10198 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10199 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10200 /* WriteOnly */ false,
10201 /* Constant */ false,
10204 VTableFuncList VTableFuncs;
10205 if (parseToken(lltok::colon, "expected ':' here") ||
10206 parseToken(lltok::lparen, "expected '(' here") ||
10207 parseModuleReference(ModulePath) ||
10208 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10209 parseToken(lltok::comma, "expected ',' here") ||
10210 parseGVarFlags(GVarFlags))
10211 return true;
10212
10213 // parse optional fields
10214 while (EatIfPresent(lltok::comma)) {
10215 switch (Lex.getKind()) {
10217 if (parseOptionalVTableFuncs(VTableFuncs))
10218 return true;
10219 break;
10220 case lltok::kw_refs:
10221 if (parseOptionalRefs(Refs))
10222 return true;
10223 break;
10224 default:
10225 return error(Lex.getLoc(), "expected optional variable summary field");
10226 }
10227 }
10228
10229 if (parseToken(lltok::rparen, "expected ')' here"))
10230 return true;
10231
10232 auto GS =
10233 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10234
10235 GS->setModulePath(ModulePath);
10236 GS->setVTableFuncs(std::move(VTableFuncs));
10237
10238 return addGlobalValueToIndex(Name, GUID,
10240 std::move(GS), Loc);
10241}
10242
10243/// AliasSummary
10244/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10245/// 'aliasee' ':' GVReference ')'
10246bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10247 unsigned ID) {
10248 assert(Lex.getKind() == lltok::kw_alias);
10249 LocTy Loc = Lex.getLoc();
10250 Lex.Lex();
10251
10252 StringRef ModulePath;
10253 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10255 /*NotEligibleToImport=*/false,
10256 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10257 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10258 if (parseToken(lltok::colon, "expected ':' here") ||
10259 parseToken(lltok::lparen, "expected '(' here") ||
10260 parseModuleReference(ModulePath) ||
10261 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10262 parseToken(lltok::comma, "expected ',' here") ||
10263 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10264 parseToken(lltok::colon, "expected ':' here"))
10265 return true;
10266
10267 ValueInfo AliaseeVI;
10268 unsigned GVId;
10269 auto AS = std::make_unique<AliasSummary>(GVFlags);
10270 AS->setModulePath(ModulePath);
10271
10272 if (!EatIfPresent(lltok::kw_null)) {
10273 if (parseGVReference(AliaseeVI, GVId))
10274 return true;
10275
10276 // Record forward reference if the aliasee is not parsed yet.
10277 if (AliaseeVI.getRef() == FwdVIRef) {
10278 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10279 } else {
10280 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10281 assert(Summary && "Aliasee must be a definition");
10282 AS->setAliasee(AliaseeVI, Summary);
10283 }
10284 }
10285
10286 if (parseToken(lltok::rparen, "expected ')' here"))
10287 return true;
10288
10289 return addGlobalValueToIndex(Name, GUID,
10291 std::move(AS), Loc);
10292}
10293
10294/// Flag
10295/// ::= [0|1]
10296bool LLParser::parseFlag(unsigned &Val) {
10297 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10298 return tokError("expected integer");
10299 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10300 Lex.Lex();
10301 return false;
10302}
10303
10304/// OptionalFFlags
10305/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10306/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10307/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10308/// [',' 'noInline' ':' Flag]? ')'
10309/// [',' 'alwaysInline' ':' Flag]? ')'
10310/// [',' 'noUnwind' ':' Flag]? ')'
10311/// [',' 'mayThrow' ':' Flag]? ')'
10312/// [',' 'hasUnknownCall' ':' Flag]? ')'
10313/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10314
10315bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10316 assert(Lex.getKind() == lltok::kw_funcFlags);
10317 Lex.Lex();
10318
10319 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10320 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10321 return true;
10322
10323 do {
10324 unsigned Val = 0;
10325 switch (Lex.getKind()) {
10326 case lltok::kw_readNone:
10327 Lex.Lex();
10328 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10329 return true;
10330 FFlags.ReadNone = Val;
10331 break;
10332 case lltok::kw_readOnly:
10333 Lex.Lex();
10334 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10335 return true;
10336 FFlags.ReadOnly = Val;
10337 break;
10339 Lex.Lex();
10340 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10341 return true;
10342 FFlags.NoRecurse = Val;
10343 break;
10345 Lex.Lex();
10346 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10347 return true;
10348 FFlags.ReturnDoesNotAlias = Val;
10349 break;
10350 case lltok::kw_noInline:
10351 Lex.Lex();
10352 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10353 return true;
10354 FFlags.NoInline = Val;
10355 break;
10357 Lex.Lex();
10358 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10359 return true;
10360 FFlags.AlwaysInline = Val;
10361 break;
10362 case lltok::kw_noUnwind:
10363 Lex.Lex();
10364 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10365 return true;
10366 FFlags.NoUnwind = Val;
10367 break;
10368 case lltok::kw_mayThrow:
10369 Lex.Lex();
10370 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10371 return true;
10372 FFlags.MayThrow = Val;
10373 break;
10375 Lex.Lex();
10376 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10377 return true;
10378 FFlags.HasUnknownCall = Val;
10379 break;
10381 Lex.Lex();
10382 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10383 return true;
10384 FFlags.MustBeUnreachable = Val;
10385 break;
10386 default:
10387 return error(Lex.getLoc(), "expected function flag type");
10388 }
10389 } while (EatIfPresent(lltok::comma));
10390
10391 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10392 return true;
10393
10394 return false;
10395}
10396
10397/// OptionalCalls
10398/// := 'calls' ':' '(' Call [',' Call]* ')'
10399/// Call ::= '(' 'callee' ':' GVReference
10400/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10401/// [ ',' 'tail' ]? ')'
10402bool LLParser::parseOptionalCalls(
10403 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10404 assert(Lex.getKind() == lltok::kw_calls);
10405 Lex.Lex();
10406
10407 if (parseToken(lltok::colon, "expected ':' in calls") ||
10408 parseToken(lltok::lparen, "expected '(' in calls"))
10409 return true;
10410
10411 IdToIndexMapType IdToIndexMap;
10412 // parse each call edge
10413 do {
10414 ValueInfo VI;
10415 if (parseToken(lltok::lparen, "expected '(' in call") ||
10416 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10417 parseToken(lltok::colon, "expected ':'"))
10418 return true;
10419
10420 LocTy Loc = Lex.getLoc();
10421 unsigned GVId;
10422 if (parseGVReference(VI, GVId))
10423 return true;
10424
10426 unsigned RelBF = 0;
10427 unsigned HasTailCall = false;
10428
10429 // parse optional fields
10430 while (EatIfPresent(lltok::comma)) {
10431 switch (Lex.getKind()) {
10432 case lltok::kw_hotness:
10433 Lex.Lex();
10434 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10435 return true;
10436 break;
10437 // Deprecated, keep in order to support old files.
10438 case lltok::kw_relbf:
10439 Lex.Lex();
10440 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10441 return true;
10442 break;
10443 case lltok::kw_tail:
10444 Lex.Lex();
10445 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10446 return true;
10447 break;
10448 default:
10449 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10450 }
10451 }
10452 // Keep track of the Call array index needing a forward reference.
10453 // We will save the location of the ValueInfo needing an update, but
10454 // can only do so once the std::vector is finalized.
10455 if (VI.getRef() == FwdVIRef)
10456 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10457 Calls.push_back(
10458 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10459
10460 if (parseToken(lltok::rparen, "expected ')' in call"))
10461 return true;
10462 } while (EatIfPresent(lltok::comma));
10463
10464 // Now that the Calls vector is finalized, it is safe to save the locations
10465 // of any forward GV references that need updating later.
10466 for (auto I : IdToIndexMap) {
10467 auto &Infos = ForwardRefValueInfos[I.first];
10468 for (auto P : I.second) {
10469 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10470 "Forward referenced ValueInfo expected to be empty");
10471 Infos.emplace_back(&Calls[P.first].first, P.second);
10472 }
10473 }
10474
10475 if (parseToken(lltok::rparen, "expected ')' in calls"))
10476 return true;
10477
10478 return false;
10479}
10480
10481/// Hotness
10482/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10483bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10484 switch (Lex.getKind()) {
10485 case lltok::kw_unknown:
10487 break;
10488 case lltok::kw_cold:
10490 break;
10491 case lltok::kw_none:
10493 break;
10494 case lltok::kw_hot:
10496 break;
10497 case lltok::kw_critical:
10499 break;
10500 default:
10501 return error(Lex.getLoc(), "invalid call edge hotness");
10502 }
10503 Lex.Lex();
10504 return false;
10505}
10506
10507/// OptionalVTableFuncs
10508/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10509/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10510bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10511 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10512 Lex.Lex();
10513
10514 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10515 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10516 return true;
10517
10518 IdToIndexMapType IdToIndexMap;
10519 // parse each virtual function pair
10520 do {
10521 ValueInfo VI;
10522 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10523 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10524 parseToken(lltok::colon, "expected ':'"))
10525 return true;
10526
10527 LocTy Loc = Lex.getLoc();
10528 unsigned GVId;
10529 if (parseGVReference(VI, GVId))
10530 return true;
10531
10532 uint64_t Offset;
10533 if (parseToken(lltok::comma, "expected comma") ||
10534 parseToken(lltok::kw_offset, "expected offset") ||
10535 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10536 return true;
10537
10538 // Keep track of the VTableFuncs array index needing a forward reference.
10539 // We will save the location of the ValueInfo needing an update, but
10540 // can only do so once the std::vector is finalized.
10541 if (VI == EmptyVI)
10542 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10543 VTableFuncs.push_back({VI, Offset});
10544
10545 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10546 return true;
10547 } while (EatIfPresent(lltok::comma));
10548
10549 // Now that the VTableFuncs vector is finalized, it is safe to save the
10550 // locations of any forward GV references that need updating later.
10551 for (auto I : IdToIndexMap) {
10552 auto &Infos = ForwardRefValueInfos[I.first];
10553 for (auto P : I.second) {
10554 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10555 "Forward referenced ValueInfo expected to be empty");
10556 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10557 }
10558 }
10559
10560 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10561 return true;
10562
10563 return false;
10564}
10565
10566/// ParamNo := 'param' ':' UInt64
10567bool LLParser::parseParamNo(uint64_t &ParamNo) {
10568 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10569 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10570 return true;
10571 return false;
10572}
10573
10574/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10575bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10576 APSInt Lower;
10577 APSInt Upper;
10578 auto ParseAPSInt = [&](APSInt &Val) {
10579 if (Lex.getKind() != lltok::APSInt)
10580 return tokError("expected integer");
10581 Val = Lex.getAPSIntVal();
10582 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10583 Val.setIsSigned(true);
10584 Lex.Lex();
10585 return false;
10586 };
10587 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10588 parseToken(lltok::colon, "expected ':' here") ||
10589 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10590 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10591 parseToken(lltok::rsquare, "expected ']' here"))
10592 return true;
10593
10594 ++Upper;
10595 Range =
10596 (Lower == Upper && !Lower.isMaxValue())
10597 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10598 : ConstantRange(Lower, Upper);
10599
10600 return false;
10601}
10602
10603/// ParamAccessCall
10604/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10605bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10606 IdLocListType &IdLocList) {
10607 if (parseToken(lltok::lparen, "expected '(' here") ||
10608 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10609 parseToken(lltok::colon, "expected ':' here"))
10610 return true;
10611
10612 unsigned GVId;
10613 ValueInfo VI;
10614 LocTy Loc = Lex.getLoc();
10615 if (parseGVReference(VI, GVId))
10616 return true;
10617
10618 Call.Callee = VI;
10619 IdLocList.emplace_back(GVId, Loc);
10620
10621 if (parseToken(lltok::comma, "expected ',' here") ||
10622 parseParamNo(Call.ParamNo) ||
10623 parseToken(lltok::comma, "expected ',' here") ||
10624 parseParamAccessOffset(Call.Offsets))
10625 return true;
10626
10627 if (parseToken(lltok::rparen, "expected ')' here"))
10628 return true;
10629
10630 return false;
10631}
10632
10633/// ParamAccess
10634/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10635/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10636bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10637 IdLocListType &IdLocList) {
10638 if (parseToken(lltok::lparen, "expected '(' here") ||
10639 parseParamNo(Param.ParamNo) ||
10640 parseToken(lltok::comma, "expected ',' here") ||
10641 parseParamAccessOffset(Param.Use))
10642 return true;
10643
10644 if (EatIfPresent(lltok::comma)) {
10645 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10646 parseToken(lltok::colon, "expected ':' here") ||
10647 parseToken(lltok::lparen, "expected '(' here"))
10648 return true;
10649 do {
10650 FunctionSummary::ParamAccess::Call Call;
10651 if (parseParamAccessCall(Call, IdLocList))
10652 return true;
10653 Param.Calls.push_back(Call);
10654 } while (EatIfPresent(lltok::comma));
10655
10656 if (parseToken(lltok::rparen, "expected ')' here"))
10657 return true;
10658 }
10659
10660 if (parseToken(lltok::rparen, "expected ')' here"))
10661 return true;
10662
10663 return false;
10664}
10665
10666/// OptionalParamAccesses
10667/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10668bool LLParser::parseOptionalParamAccesses(
10669 std::vector<FunctionSummary::ParamAccess> &Params) {
10670 assert(Lex.getKind() == lltok::kw_params);
10671 Lex.Lex();
10672
10673 if (parseToken(lltok::colon, "expected ':' here") ||
10674 parseToken(lltok::lparen, "expected '(' here"))
10675 return true;
10676
10677 IdLocListType VContexts;
10678 size_t CallsNum = 0;
10679 do {
10680 FunctionSummary::ParamAccess ParamAccess;
10681 if (parseParamAccess(ParamAccess, VContexts))
10682 return true;
10683 CallsNum += ParamAccess.Calls.size();
10684 assert(VContexts.size() == CallsNum);
10685 (void)CallsNum;
10686 Params.emplace_back(std::move(ParamAccess));
10687 } while (EatIfPresent(lltok::comma));
10688
10689 if (parseToken(lltok::rparen, "expected ')' here"))
10690 return true;
10691
10692 // Now that the Params is finalized, it is safe to save the locations
10693 // of any forward GV references that need updating later.
10694 IdLocListType::const_iterator ItContext = VContexts.begin();
10695 for (auto &PA : Params) {
10696 for (auto &C : PA.Calls) {
10697 if (C.Callee.getRef() == FwdVIRef)
10698 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10699 ItContext->second);
10700 ++ItContext;
10701 }
10702 }
10703 assert(ItContext == VContexts.end());
10704
10705 return false;
10706}
10707
10708/// OptionalRefs
10709/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10710bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10711 assert(Lex.getKind() == lltok::kw_refs);
10712 Lex.Lex();
10713
10714 if (parseToken(lltok::colon, "expected ':' in refs") ||
10715 parseToken(lltok::lparen, "expected '(' in refs"))
10716 return true;
10717
10718 struct ValueContext {
10719 ValueInfo VI;
10720 unsigned GVId;
10721 LocTy Loc;
10722 };
10723 std::vector<ValueContext> VContexts;
10724 // parse each ref edge
10725 do {
10726 ValueContext VC;
10727 VC.Loc = Lex.getLoc();
10728 if (parseGVReference(VC.VI, VC.GVId))
10729 return true;
10730 VContexts.push_back(VC);
10731 } while (EatIfPresent(lltok::comma));
10732
10733 // Sort value contexts so that ones with writeonly
10734 // and readonly ValueInfo are at the end of VContexts vector.
10735 // See FunctionSummary::specialRefCounts()
10736 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10737 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10738 });
10739
10740 IdToIndexMapType IdToIndexMap;
10741 for (auto &VC : VContexts) {
10742 // Keep track of the Refs array index needing a forward reference.
10743 // We will save the location of the ValueInfo needing an update, but
10744 // can only do so once the std::vector is finalized.
10745 if (VC.VI.getRef() == FwdVIRef)
10746 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10747 Refs.push_back(VC.VI);
10748 }
10749
10750 // Now that the Refs vector is finalized, it is safe to save the locations
10751 // of any forward GV references that need updating later.
10752 for (auto I : IdToIndexMap) {
10753 auto &Infos = ForwardRefValueInfos[I.first];
10754 for (auto P : I.second) {
10755 assert(Refs[P.first].getRef() == FwdVIRef &&
10756 "Forward referenced ValueInfo expected to be empty");
10757 Infos.emplace_back(&Refs[P.first], P.second);
10758 }
10759 }
10760
10761 if (parseToken(lltok::rparen, "expected ')' in refs"))
10762 return true;
10763
10764 return false;
10765}
10766
10767/// OptionalTypeIdInfo
10768/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10769/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10770/// [',' TypeCheckedLoadConstVCalls]? ')'
10771bool LLParser::parseOptionalTypeIdInfo(
10772 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10773 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10774 Lex.Lex();
10775
10776 if (parseToken(lltok::colon, "expected ':' here") ||
10777 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10778 return true;
10779
10780 do {
10781 switch (Lex.getKind()) {
10783 if (parseTypeTests(TypeIdInfo.TypeTests))
10784 return true;
10785 break;
10787 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10788 TypeIdInfo.TypeTestAssumeVCalls))
10789 return true;
10790 break;
10792 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10793 TypeIdInfo.TypeCheckedLoadVCalls))
10794 return true;
10795 break;
10797 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10798 TypeIdInfo.TypeTestAssumeConstVCalls))
10799 return true;
10800 break;
10802 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10803 TypeIdInfo.TypeCheckedLoadConstVCalls))
10804 return true;
10805 break;
10806 default:
10807 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10808 }
10809 } while (EatIfPresent(lltok::comma));
10810
10811 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10812 return true;
10813
10814 return false;
10815}
10816
10817/// TypeTests
10818/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10819/// [',' (SummaryID | UInt64)]* ')'
10820bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10821 assert(Lex.getKind() == lltok::kw_typeTests);
10822 Lex.Lex();
10823
10824 if (parseToken(lltok::colon, "expected ':' here") ||
10825 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10826 return true;
10827
10828 IdToIndexMapType IdToIndexMap;
10829 do {
10831 if (Lex.getKind() == lltok::SummaryID) {
10832 unsigned ID = Lex.getUIntVal();
10833 LocTy Loc = Lex.getLoc();
10834 // Keep track of the TypeTests array index needing a forward reference.
10835 // We will save the location of the GUID needing an update, but
10836 // can only do so once the std::vector is finalized.
10837 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10838 Lex.Lex();
10839 } else if (parseUInt64(GUID))
10840 return true;
10841 TypeTests.push_back(GUID);
10842 } while (EatIfPresent(lltok::comma));
10843
10844 // Now that the TypeTests vector is finalized, it is safe to save the
10845 // locations of any forward GV references that need updating later.
10846 for (auto I : IdToIndexMap) {
10847 auto &Ids = ForwardRefTypeIds[I.first];
10848 for (auto P : I.second) {
10849 assert(TypeTests[P.first] == 0 &&
10850 "Forward referenced type id GUID expected to be 0");
10851 Ids.emplace_back(&TypeTests[P.first], P.second);
10852 }
10853 }
10854
10855 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10856 return true;
10857
10858 return false;
10859}
10860
10861/// VFuncIdList
10862/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10863bool LLParser::parseVFuncIdList(
10864 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10865 assert(Lex.getKind() == Kind);
10866 Lex.Lex();
10867
10868 if (parseToken(lltok::colon, "expected ':' here") ||
10869 parseToken(lltok::lparen, "expected '(' here"))
10870 return true;
10871
10872 IdToIndexMapType IdToIndexMap;
10873 do {
10874 FunctionSummary::VFuncId VFuncId;
10875 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10876 return true;
10877 VFuncIdList.push_back(VFuncId);
10878 } while (EatIfPresent(lltok::comma));
10879
10880 if (parseToken(lltok::rparen, "expected ')' here"))
10881 return true;
10882
10883 // Now that the VFuncIdList vector is finalized, it is safe to save the
10884 // locations of any forward GV references that need updating later.
10885 for (auto I : IdToIndexMap) {
10886 auto &Ids = ForwardRefTypeIds[I.first];
10887 for (auto P : I.second) {
10888 assert(VFuncIdList[P.first].GUID == 0 &&
10889 "Forward referenced type id GUID expected to be 0");
10890 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10891 }
10892 }
10893
10894 return false;
10895}
10896
10897/// ConstVCallList
10898/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10899bool LLParser::parseConstVCallList(
10900 lltok::Kind Kind,
10901 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10902 assert(Lex.getKind() == Kind);
10903 Lex.Lex();
10904
10905 if (parseToken(lltok::colon, "expected ':' here") ||
10906 parseToken(lltok::lparen, "expected '(' here"))
10907 return true;
10908
10909 IdToIndexMapType IdToIndexMap;
10910 do {
10911 FunctionSummary::ConstVCall ConstVCall;
10912 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10913 return true;
10914 ConstVCallList.push_back(ConstVCall);
10915 } while (EatIfPresent(lltok::comma));
10916
10917 if (parseToken(lltok::rparen, "expected ')' here"))
10918 return true;
10919
10920 // Now that the ConstVCallList vector is finalized, it is safe to save the
10921 // locations of any forward GV references that need updating later.
10922 for (auto I : IdToIndexMap) {
10923 auto &Ids = ForwardRefTypeIds[I.first];
10924 for (auto P : I.second) {
10925 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10926 "Forward referenced type id GUID expected to be 0");
10927 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10928 }
10929 }
10930
10931 return false;
10932}
10933
10934/// ConstVCall
10935/// ::= '(' VFuncId ',' Args ')'
10936bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10937 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10938 if (parseToken(lltok::lparen, "expected '(' here") ||
10939 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10940 return true;
10941
10942 if (EatIfPresent(lltok::comma))
10943 if (parseArgs(ConstVCall.Args))
10944 return true;
10945
10946 if (parseToken(lltok::rparen, "expected ')' here"))
10947 return true;
10948
10949 return false;
10950}
10951
10952/// VFuncId
10953/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10954/// 'offset' ':' UInt64 ')'
10955bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10956 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10957 assert(Lex.getKind() == lltok::kw_vFuncId);
10958 Lex.Lex();
10959
10960 if (parseToken(lltok::colon, "expected ':' here") ||
10961 parseToken(lltok::lparen, "expected '(' here"))
10962 return true;
10963
10964 if (Lex.getKind() == lltok::SummaryID) {
10965 VFuncId.GUID = 0;
10966 unsigned ID = Lex.getUIntVal();
10967 LocTy Loc = Lex.getLoc();
10968 // Keep track of the array index needing a forward reference.
10969 // We will save the location of the GUID needing an update, but
10970 // can only do so once the caller's std::vector is finalized.
10971 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10972 Lex.Lex();
10973 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10974 parseToken(lltok::colon, "expected ':' here") ||
10975 parseUInt64(VFuncId.GUID))
10976 return true;
10977
10978 if (parseToken(lltok::comma, "expected ',' here") ||
10979 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10980 parseToken(lltok::colon, "expected ':' here") ||
10981 parseUInt64(VFuncId.Offset) ||
10982 parseToken(lltok::rparen, "expected ')' here"))
10983 return true;
10984
10985 return false;
10986}
10987
10988/// GVFlags
10989/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10990/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10991/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10992/// 'canAutoHide' ':' Flag ',' ')'
10993bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10994 assert(Lex.getKind() == lltok::kw_flags);
10995 Lex.Lex();
10996
10997 if (parseToken(lltok::colon, "expected ':' here") ||
10998 parseToken(lltok::lparen, "expected '(' here"))
10999 return true;
11000
11001 do {
11002 unsigned Flag = 0;
11003 switch (Lex.getKind()) {
11004 case lltok::kw_linkage:
11005 Lex.Lex();
11006 if (parseToken(lltok::colon, "expected ':'"))
11007 return true;
11008 bool HasLinkage;
11009 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11010 assert(HasLinkage && "Linkage not optional in summary entry");
11011 Lex.Lex();
11012 break;
11014 Lex.Lex();
11015 if (parseToken(lltok::colon, "expected ':'"))
11016 return true;
11017 parseOptionalVisibility(Flag);
11018 GVFlags.Visibility = Flag;
11019 break;
11021 Lex.Lex();
11022 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11023 return true;
11024 GVFlags.NotEligibleToImport = Flag;
11025 break;
11026 case lltok::kw_live:
11027 Lex.Lex();
11028 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11029 return true;
11030 GVFlags.Live = Flag;
11031 break;
11032 case lltok::kw_dsoLocal:
11033 Lex.Lex();
11034 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11035 return true;
11036 GVFlags.DSOLocal = Flag;
11037 break;
11039 Lex.Lex();
11040 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11041 return true;
11042 GVFlags.CanAutoHide = Flag;
11043 break;
11045 Lex.Lex();
11046 if (parseToken(lltok::colon, "expected ':'"))
11047 return true;
11049 if (parseOptionalImportType(Lex.getKind(), IK))
11050 return true;
11051 GVFlags.ImportType = static_cast<unsigned>(IK);
11052 Lex.Lex();
11053 break;
11055 Lex.Lex();
11056 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11057 return true;
11058 GVFlags.NoRenameOnPromotion = Flag;
11059 break;
11060 default:
11061 return error(Lex.getLoc(), "expected gv flag type");
11062 }
11063 } while (EatIfPresent(lltok::comma));
11064
11065 if (parseToken(lltok::rparen, "expected ')' here"))
11066 return true;
11067
11068 return false;
11069}
11070
11071/// GVarFlags
11072/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11073/// ',' 'writeonly' ':' Flag
11074/// ',' 'constant' ':' Flag ')'
11075bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11076 assert(Lex.getKind() == lltok::kw_varFlags);
11077 Lex.Lex();
11078
11079 if (parseToken(lltok::colon, "expected ':' here") ||
11080 parseToken(lltok::lparen, "expected '(' here"))
11081 return true;
11082
11083 auto ParseRest = [this](unsigned int &Val) {
11084 Lex.Lex();
11085 if (parseToken(lltok::colon, "expected ':'"))
11086 return true;
11087 return parseFlag(Val);
11088 };
11089
11090 do {
11091 unsigned Flag = 0;
11092 switch (Lex.getKind()) {
11093 case lltok::kw_readonly:
11094 if (ParseRest(Flag))
11095 return true;
11096 GVarFlags.MaybeReadOnly = Flag;
11097 break;
11098 case lltok::kw_writeonly:
11099 if (ParseRest(Flag))
11100 return true;
11101 GVarFlags.MaybeWriteOnly = Flag;
11102 break;
11103 case lltok::kw_constant:
11104 if (ParseRest(Flag))
11105 return true;
11106 GVarFlags.Constant = Flag;
11107 break;
11109 if (ParseRest(Flag))
11110 return true;
11111 GVarFlags.VCallVisibility = Flag;
11112 break;
11113 default:
11114 return error(Lex.getLoc(), "expected gvar flag type");
11115 }
11116 } while (EatIfPresent(lltok::comma));
11117 return parseToken(lltok::rparen, "expected ')' here");
11118}
11119
11120/// ModuleReference
11121/// ::= 'module' ':' UInt
11122bool LLParser::parseModuleReference(StringRef &ModulePath) {
11123 // parse module id.
11124 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11125 parseToken(lltok::colon, "expected ':' here") ||
11126 parseToken(lltok::SummaryID, "expected module ID"))
11127 return true;
11128
11129 unsigned ModuleID = Lex.getUIntVal();
11130 auto I = ModuleIdMap.find(ModuleID);
11131 // We should have already parsed all module IDs
11132 assert(I != ModuleIdMap.end());
11133 ModulePath = I->second;
11134 return false;
11135}
11136
11137/// GVReference
11138/// ::= SummaryID
11139bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11140 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11141 if (!ReadOnly)
11142 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11143 if (parseToken(lltok::SummaryID, "expected GV ID"))
11144 return true;
11145
11146 GVId = Lex.getUIntVal();
11147 // Check if we already have a VI for this GV
11148 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11149 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11150 VI = NumberedValueInfos[GVId];
11151 } else
11152 // We will create a forward reference to the stored location.
11153 VI = ValueInfo(false, FwdVIRef);
11154
11155 if (ReadOnly)
11156 VI.setReadOnly();
11157 if (WriteOnly)
11158 VI.setWriteOnly();
11159 return false;
11160}
11161
11162/// OptionalAllocs
11163/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11164/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11165/// ',' MemProfs ')'
11166/// Version ::= UInt32
11167bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11168 assert(Lex.getKind() == lltok::kw_allocs);
11169 Lex.Lex();
11170
11171 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11172 parseToken(lltok::lparen, "expected '(' in allocs"))
11173 return true;
11174
11175 // parse each alloc
11176 do {
11177 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11178 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11179 parseToken(lltok::colon, "expected ':'") ||
11180 parseToken(lltok::lparen, "expected '(' in versions"))
11181 return true;
11182
11183 SmallVector<uint8_t> Versions;
11184 do {
11185 uint8_t V = 0;
11186 if (parseAllocType(V))
11187 return true;
11188 Versions.push_back(V);
11189 } while (EatIfPresent(lltok::comma));
11190
11191 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11192 parseToken(lltok::comma, "expected ',' in alloc"))
11193 return true;
11194
11195 std::vector<MIBInfo> MIBs;
11196 if (parseMemProfs(MIBs))
11197 return true;
11198
11199 Allocs.push_back({Versions, MIBs});
11200
11201 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11202 return true;
11203 } while (EatIfPresent(lltok::comma));
11204
11205 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11206 return true;
11207
11208 return false;
11209}
11210
11211/// MemProfs
11212/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11213/// MemProf ::= '(' 'type' ':' AllocType
11214/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11215/// StackId ::= UInt64
11216bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11217 assert(Lex.getKind() == lltok::kw_memProf);
11218 Lex.Lex();
11219
11220 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11221 parseToken(lltok::lparen, "expected '(' in memprof"))
11222 return true;
11223
11224 // parse each MIB
11225 do {
11226 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11227 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11228 parseToken(lltok::colon, "expected ':'"))
11229 return true;
11230
11231 uint8_t AllocType;
11232 if (parseAllocType(AllocType))
11233 return true;
11234
11235 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11236 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11237 parseToken(lltok::colon, "expected ':'") ||
11238 parseToken(lltok::lparen, "expected '(' in stackIds"))
11239 return true;
11240
11241 SmallVector<unsigned> StackIdIndices;
11242 // Combined index alloc records may not have a stack id list.
11243 if (Lex.getKind() != lltok::rparen) {
11244 do {
11245 uint64_t StackId = 0;
11246 if (parseUInt64(StackId))
11247 return true;
11248 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11249 } while (EatIfPresent(lltok::comma));
11250 }
11251
11252 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11253 return true;
11254
11255 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11256
11257 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11258 return true;
11259 } while (EatIfPresent(lltok::comma));
11260
11261 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11262 return true;
11263
11264 return false;
11265}
11266
11267/// AllocType
11268/// := ('none'|'notcold'|'cold'|'hot')
11269bool LLParser::parseAllocType(uint8_t &AllocType) {
11270 switch (Lex.getKind()) {
11271 case lltok::kw_none:
11273 break;
11274 case lltok::kw_notcold:
11276 break;
11277 case lltok::kw_cold:
11279 break;
11280 case lltok::kw_hot:
11281 AllocType = (uint8_t)AllocationType::Hot;
11282 break;
11283 default:
11284 return error(Lex.getLoc(), "invalid alloc type");
11285 }
11286 Lex.Lex();
11287 return false;
11288}
11289
11290/// OptionalCallsites
11291/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11292/// Callsite ::= '(' 'callee' ':' GVReference
11293/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11294/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11295/// Version ::= UInt32
11296/// StackId ::= UInt64
11297bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11298 assert(Lex.getKind() == lltok::kw_callsites);
11299 Lex.Lex();
11300
11301 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11302 parseToken(lltok::lparen, "expected '(' in callsites"))
11303 return true;
11304
11305 IdToIndexMapType IdToIndexMap;
11306 // parse each callsite
11307 do {
11308 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11309 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11310 parseToken(lltok::colon, "expected ':'"))
11311 return true;
11312
11313 ValueInfo VI;
11314 unsigned GVId = 0;
11315 LocTy Loc = Lex.getLoc();
11316 if (!EatIfPresent(lltok::kw_null)) {
11317 if (parseGVReference(VI, GVId))
11318 return true;
11319 }
11320
11321 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11322 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11323 parseToken(lltok::colon, "expected ':'") ||
11324 parseToken(lltok::lparen, "expected '(' in clones"))
11325 return true;
11326
11327 SmallVector<unsigned> Clones;
11328 do {
11329 unsigned V = 0;
11330 if (parseUInt32(V))
11331 return true;
11332 Clones.push_back(V);
11333 } while (EatIfPresent(lltok::comma));
11334
11335 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11336 parseToken(lltok::comma, "expected ',' in callsite") ||
11337 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11338 parseToken(lltok::colon, "expected ':'") ||
11339 parseToken(lltok::lparen, "expected '(' in stackIds"))
11340 return true;
11341
11342 SmallVector<unsigned> StackIdIndices;
11343 // Synthesized callsite records will not have a stack id list.
11344 if (Lex.getKind() != lltok::rparen) {
11345 do {
11346 uint64_t StackId = 0;
11347 if (parseUInt64(StackId))
11348 return true;
11349 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11350 } while (EatIfPresent(lltok::comma));
11351 }
11352
11353 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11354 return true;
11355
11356 // Keep track of the Callsites array index needing a forward reference.
11357 // We will save the location of the ValueInfo needing an update, but
11358 // can only do so once the SmallVector is finalized.
11359 if (VI.getRef() == FwdVIRef)
11360 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11361 Callsites.push_back({VI, Clones, StackIdIndices});
11362
11363 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11364 return true;
11365 } while (EatIfPresent(lltok::comma));
11366
11367 // Now that the Callsites vector is finalized, it is safe to save the
11368 // locations of any forward GV references that need updating later.
11369 for (auto I : IdToIndexMap) {
11370 auto &Infos = ForwardRefValueInfos[I.first];
11371 for (auto P : I.second) {
11372 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11373 "Forward referenced ValueInfo expected to be empty");
11374 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11375 }
11376 }
11377
11378 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11379 return true;
11380
11381 return false;
11382}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:253
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 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:152
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:68
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
if(PassOpts->AAPipeline)
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
dot regions Print regions of function to dot file(with no function bodies)"
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 make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
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:278
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:360
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1244
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:835
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:143
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ None
No attributes have been set.
Definition Attributes.h:126
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static 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:537
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_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:1579
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1451
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
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, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:205
unsigned size() const
Definition DenseMap.h:110
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool any() const
Definition FMF.h:59
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:473
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:468
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:168
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:823
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:449
arg_iterator arg_begin()
Definition Function.h:868
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1040
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1052
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
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:621
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:678
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:223
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:284
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:254
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:96
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:170
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:260
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:237
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:542
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:589
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:68
lltok::Kind getKind() const
Definition LLLexer.h:72
LocTy getLoc() const
Definition LLLexer.h:71
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:124
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:231
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:108
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:95
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:76
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1080
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1580
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1540
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
static MemoryEffectsBase readOnly()
Definition ModRef.h: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:110
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:946
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:221
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:483
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:689
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:773
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:608
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:510
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:984
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:314
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:290
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:281
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:293
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:65
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:284
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:287
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:255
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:201
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:328
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:321
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:310
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:287
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:275
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:110
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:233
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:509
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
static constexpr uint64_t MaximumAlignment
Definition Value.h:808
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:107
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
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:599
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:632
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:704
#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
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > 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.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:765
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:220
MacinfoRecordType
Definition Dwarf.h:815
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:821
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:155
@ kw_riscv_vls_cc
Definition LLToken.h:191
@ kw_cxx_fast_tlscc
Definition LLToken.h:174
@ kw_extractvalue
Definition LLToken.h:377
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:513
@ 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:225
@ kw_mustBeUnreachable
Definition LLToken.h:424
@ kw_internal
Definition LLToken.h:54
@ kw_target_mem
Definition LLToken.h:211
@ kw_no_sanitize_hwaddress
Definition LLToken.h:492
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:463
@ kw_canAutoHide
Definition LLToken.h:407
@ kw_alwaysInline
Definition LLToken.h:420
@ kw_insertelement
Definition LLToken.h:374
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:194
@ kw_fmaximumnum
Definition LLToken.h:296
@ kw_inaccessiblememonly
Definition LLToken.h:218
@ kw_amdgpu_gfx
Definition LLToken.h:185
@ kw_getelementptr
Definition LLToken.h:371
@ FloatHexLiteral
Definition LLToken.h:532
@ 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:403
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:193
@ kw_positivezero
Definition LLToken.h:231
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:466
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:443
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:151
@ kw_amdgpu_kernel
Definition LLToken.h:184
@ kw_uselistorder
Definition LLToken.h:390
@ kw_blockcount
Definition LLToken.h:401
@ kw_notEligibleToImport
Definition LLToken.h:404
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:145
@ kw_ptx_device
Definition LLToken.h:159
@ kw_personality
Definition LLToken.h:346
@ DwarfEnumKind
Definition LLToken.h:526
@ kw_declaration
Definition LLToken.h:410
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:512
@ 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:423
@ kw_x86_intrcc
Definition LLToken.h:171
@ kw_addrspacecast
Definition LLToken.h:341
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:510
@ kw_x86_thiscallcc
Definition LLToken.h:144
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:192
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:391
@ NameTableKind
Definition LLToken.h:518
@ kw_inlineBits
Definition LLToken.h:461
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:217
@ kw_blockaddress
Definition LLToken.h:379
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:186
@ kw_landingpad
Definition LLToken.h:345
@ kw_aarch64_vector_pcs
Definition LLToken.h:150
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:442
@ FixedPointKind
Definition LLToken.h:519
@ kw_target_mem1
Definition LLToken.h:213
@ kw_ptx_kernel
Definition LLToken.h:158
@ kw_extractelement
Definition LLToken.h:373
@ kw_branchFunnel
Definition LLToken.h:467
@ kw_typeidCompatibleVTable
Definition LLToken.h:448
@ kw_vTableFuncs
Definition LLToken.h:434
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:441
@ kw_no_sanitize_address
Definition LLToken.h:489
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:219
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:495
@ DwarfSourceLangName
Definition LLToken.h:515
@ kw_noRenameOnPromotion
Definition LLToken.h:411
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:183
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:359
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:148
@ kw_read_provenance
Definition LLToken.h:226
@ kw_cleanuppad
Definition LLToken.h:362
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:468
@ kw_target_mem0
Definition LLToken.h:212
@ kw_swifttailcc
Definition LLToken.h:166
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:440
@ kw_preservesign
Definition LLToken.h:230
@ kw_attributes
Definition LLToken.h:197
@ kw_code_model
Definition LLToken.h:123
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:471
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:457
@ kw_nodeduplicate
Definition LLToken.h:261
@ kw_avr_signalcc
Definition LLToken.h:157
@ kw_exactmatch
Definition LLToken.h:259
@ kw_fminimumnum
Definition LLToken.h:297
@ kw_unreachable
Definition LLToken.h:357
@ kw_intel_ocl_bicc
Definition LLToken.h:140
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:418
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:168
@ kw_importType
Definition LLToken.h:408
@ kw_cleanupret
Definition LLToken.h:358
@ kw_shufflevector
Definition LLToken.h:375
@ kw_riscv_vector_cc
Definition LLToken.h:190
@ kw_avr_intrcc
Definition LLToken.h:156
@ kw_definition
Definition LLToken.h:409
@ kw_virtualConstProp
Definition LLToken.h:473
@ kw_vcall_visibility
Definition LLToken.h:462
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:210
@ kw_preserve_mostcc
Definition LLToken.h:167
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:149
@ kw_typeTestRes
Definition LLToken.h:450
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:438
@ kw_amdgpu_cs_chain
Definition LLToken.h:182
@ kw_dso_local_equivalent
Definition LLToken.h:380
@ kw_x86_64_sysvcc
Definition LLToken.h:162
@ DbgRecordType
Definition LLToken.h:525
@ kw_address_is_null
Definition LLToken.h:224
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:154
@ kw_uniqueRetVal
Definition LLToken.h:472
@ kw_insertvalue
Definition LLToken.h:378
@ kw_indirectbr
Definition LLToken.h:354
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:584
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:557
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1668
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:53
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:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:154
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:156
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:370
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h: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:36
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2011
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:1916
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
@ 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:106
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.