LLVM 19.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
49#include "llvm/Support/ModRef.h"
52#include <algorithm>
53#include <cassert>
54#include <cstring>
55#include <optional>
56#include <vector>
57
58using namespace llvm;
59
61 "allow-incomplete-ir", cl::init(false), cl::Hidden,
63 "Allow incomplete IR on a best effort basis (references to unknown "
64 "metadata will be dropped)"));
65
70
71static std::string getTypeString(Type *T) {
72 std::string Result;
73 raw_string_ostream Tmp(Result);
74 Tmp << *T;
75 return Tmp.str();
76}
77
78/// Run: module ::= toplevelentity*
80 DataLayoutCallbackTy DataLayoutCallback) {
81 // Prime the lexer.
82 Lex.Lex();
83
84 if (Context.shouldDiscardValueNames())
85 return error(
86 Lex.getLoc(),
87 "Can't read textual IR with a Context that discards named Values");
88
89 if (M) {
90 if (parseTargetDefinitions(DataLayoutCallback))
91 return true;
92 }
93
94 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
95 validateEndOfIndex();
96}
97
99 const SlotMapping *Slots) {
100 restoreParsingState(Slots);
101 Lex.Lex();
102
103 Type *Ty = nullptr;
104 if (parseType(Ty) || parseConstantValue(Ty, C))
105 return true;
106 if (Lex.getKind() != lltok::Eof)
107 return error(Lex.getLoc(), "expected end of string");
108 return false;
109}
110
111bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
112 const SlotMapping *Slots) {
113 restoreParsingState(Slots);
114 Lex.Lex();
115
116 Read = 0;
117 SMLoc Start = Lex.getLoc();
118 Ty = nullptr;
119 if (parseType(Ty))
120 return true;
121 SMLoc End = Lex.getLoc();
122 Read = End.getPointer() - Start.getPointer();
123
124 return false;
125}
126
127void LLParser::restoreParsingState(const SlotMapping *Slots) {
128 if (!Slots)
129 return;
130 NumberedVals = Slots->GlobalValues;
131 NumberedMetadata = Slots->MetadataNodes;
132 for (const auto &I : Slots->NamedTypes)
133 NamedTypes.insert(
134 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
135 for (const auto &I : Slots->Types)
136 NumberedTypes.insert(
137 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
138}
139
141 // White-list intrinsics that are safe to drop.
142 if (!isa<DbgInfoIntrinsic>(II) &&
143 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
144 return;
145
147 for (Value *V : II->args())
148 if (auto *MV = dyn_cast<MetadataAsValue>(V))
149 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
150 if (MD->isTemporary())
151 MVs.push_back(MV);
152
153 if (!MVs.empty()) {
154 assert(II->use_empty() && "Cannot have uses");
155 II->eraseFromParent();
156
157 // Also remove no longer used MetadataAsValue wrappers.
158 for (MetadataAsValue *MV : MVs)
159 if (MV->use_empty())
160 delete MV;
161 }
162}
163
164void LLParser::dropUnknownMetadataReferences() {
165 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
166 for (Function &F : *M) {
167 F.eraseMetadataIf(Pred);
169 I.eraseMetadataIf(Pred);
170
171 if (auto *II = dyn_cast<IntrinsicInst>(&I))
173 }
174 }
175
176 for (GlobalVariable &GV : M->globals())
177 GV.eraseMetadataIf(Pred);
178
179 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
180 // Check whether there is only a single use left, which would be in our
181 // own NumberedMetadata.
182 if (Info.first->getNumTemporaryUses() == 1) {
183 NumberedMetadata.erase(ID);
184 ForwardRefMDNodes.erase(ID);
185 }
186 }
187}
188
189/// validateEndOfModule - Do final validity and basic correctness checks at the
190/// end of the module.
191bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
192 if (!M)
193 return false;
194
195 // We should have already returned an error if we observed both intrinsics and
196 // records in this IR.
197 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
198 "Mixed debug intrinsics/records seen without a parsing error?");
200 UseNewDbgInfoFormat = SeenNewDbgInfoFormat;
201 WriteNewDbgInfoFormatToBitcode = SeenNewDbgInfoFormat;
202 WriteNewDbgInfoFormat = SeenNewDbgInfoFormat;
203 M->setNewDbgInfoFormatFlag(SeenNewDbgInfoFormat);
204 }
205
206 // Handle any function attribute group forward references.
207 for (const auto &RAG : ForwardRefAttrGroups) {
208 Value *V = RAG.first;
209 const std::vector<unsigned> &Attrs = RAG.second;
210 AttrBuilder B(Context);
211
212 for (const auto &Attr : Attrs) {
213 auto R = NumberedAttrBuilders.find(Attr);
214 if (R != NumberedAttrBuilders.end())
215 B.merge(R->second);
216 }
217
218 if (Function *Fn = dyn_cast<Function>(V)) {
219 AttributeList AS = Fn->getAttributes();
220 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
221 AS = AS.removeFnAttributes(Context);
222
223 FnAttrs.merge(B);
224
225 // If the alignment was parsed as an attribute, move to the alignment
226 // field.
227 if (MaybeAlign A = FnAttrs.getAlignment()) {
228 Fn->setAlignment(*A);
229 FnAttrs.removeAttribute(Attribute::Alignment);
230 }
231
232 AS = AS.addFnAttributes(Context, FnAttrs);
233 Fn->setAttributes(AS);
234 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
235 AttributeList AS = CI->getAttributes();
236 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
237 AS = AS.removeFnAttributes(Context);
238 FnAttrs.merge(B);
239 AS = AS.addFnAttributes(Context, FnAttrs);
240 CI->setAttributes(AS);
241 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
242 AttributeList AS = II->getAttributes();
243 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
244 AS = AS.removeFnAttributes(Context);
245 FnAttrs.merge(B);
246 AS = AS.addFnAttributes(Context, FnAttrs);
247 II->setAttributes(AS);
248 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
249 AttributeList AS = CBI->getAttributes();
250 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
251 AS = AS.removeFnAttributes(Context);
252 FnAttrs.merge(B);
253 AS = AS.addFnAttributes(Context, FnAttrs);
254 CBI->setAttributes(AS);
255 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
256 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
257 Attrs.merge(B);
258 GV->setAttributes(AttributeSet::get(Context,Attrs));
259 } else {
260 llvm_unreachable("invalid object with forward attribute group reference");
261 }
262 }
263
264 // If there are entries in ForwardRefBlockAddresses at this point, the
265 // function was never defined.
266 if (!ForwardRefBlockAddresses.empty())
267 return error(ForwardRefBlockAddresses.begin()->first.Loc,
268 "expected function name in blockaddress");
269
270 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
271 GlobalValue *FwdRef) {
272 GlobalValue *GV = nullptr;
273 if (GVRef.Kind == ValID::t_GlobalName) {
274 GV = M->getNamedValue(GVRef.StrVal);
275 } else {
276 GV = NumberedVals.get(GVRef.UIntVal);
277 }
278
279 if (!GV)
280 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
281 "' referenced by dso_local_equivalent");
282
283 if (!GV->getValueType()->isFunctionTy())
284 return error(GVRef.Loc,
285 "expected a function, alias to function, or ifunc "
286 "in dso_local_equivalent");
287
288 auto *Equiv = DSOLocalEquivalent::get(GV);
289 FwdRef->replaceAllUsesWith(Equiv);
290 FwdRef->eraseFromParent();
291 return false;
292 };
293
294 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
295 // point, they are references after the function was defined. Resolve those
296 // now.
297 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
298 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
299 return true;
300 }
301 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
302 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
303 return true;
304 }
305 ForwardRefDSOLocalEquivalentIDs.clear();
306 ForwardRefDSOLocalEquivalentNames.clear();
307
308 for (const auto &NT : NumberedTypes)
309 if (NT.second.second.isValid())
310 return error(NT.second.second,
311 "use of undefined type '%" + Twine(NT.first) + "'");
312
313 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
314 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
315 if (I->second.second.isValid())
316 return error(I->second.second,
317 "use of undefined type named '" + I->getKey() + "'");
318
319 if (!ForwardRefComdats.empty())
320 return error(ForwardRefComdats.begin()->second,
321 "use of undefined comdat '$" +
322 ForwardRefComdats.begin()->first + "'");
323
324 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
325 if (StringRef(Name).starts_with("llvm.")) {
327 if (IID == Intrinsic::not_intrinsic)
328 // Don't do anything for unknown intrinsics.
329 continue;
330
331 // Automatically create declarations for intrinsics. Intrinsics can only
332 // be called directly, so the call function type directly determines the
333 // declaration function type.
334 //
335 // Additionally, automatically add the required mangling suffix to the
336 // intrinsic name. This means that we may replace a single forward
337 // declaration with multiple functions here.
338 for (Use &U : make_early_inc_range(Info.first->uses())) {
339 auto *CB = dyn_cast<CallBase>(U.getUser());
340 if (!CB || !CB->isCallee(&U))
341 return error(Info.second, "intrinsic can only be used as callee");
342
343 SmallVector<Type *> OverloadTys;
344 if (!Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
345 OverloadTys))
346 return error(Info.second, "invalid intrinsic signature");
347
348 U.set(Intrinsic::getDeclaration(M, IID, OverloadTys));
349 }
350
351 Info.first->eraseFromParent();
352 ForwardRefVals.erase(Name);
353 continue;
354 }
355
356 // If incomplete IR is allowed, also add declarations for
357 // non-intrinsics.
359 continue;
360
361 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
362 FunctionType *FTy = nullptr;
363 for (Use &U : V->uses()) {
364 auto *CB = dyn_cast<CallBase>(U.getUser());
365 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
366 return nullptr;
367 FTy = CB->getFunctionType();
368 }
369 return FTy;
370 };
371
372 // First check whether this global is only used in calls with the same
373 // type, in which case we'll insert a function. Otherwise, fall back to
374 // using a dummy i8 type.
375 Type *Ty = GetCommonFunctionType(Info.first);
376 if (!Ty)
377 Ty = Type::getInt8Ty(Context);
378
379 GlobalValue *GV;
380 if (auto *FTy = dyn_cast<FunctionType>(Ty))
382 else
383 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
385 /*Initializer*/ nullptr, Name);
386 Info.first->replaceAllUsesWith(GV);
387 Info.first->eraseFromParent();
388 ForwardRefVals.erase(Name);
389 }
390
391 if (!ForwardRefVals.empty())
392 return error(ForwardRefVals.begin()->second.second,
393 "use of undefined value '@" + ForwardRefVals.begin()->first +
394 "'");
395
396 if (!ForwardRefValIDs.empty())
397 return error(ForwardRefValIDs.begin()->second.second,
398 "use of undefined value '@" +
399 Twine(ForwardRefValIDs.begin()->first) + "'");
400
401 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
402 dropUnknownMetadataReferences();
403
404 if (!ForwardRefMDNodes.empty())
405 return error(ForwardRefMDNodes.begin()->second.second,
406 "use of undefined metadata '!" +
407 Twine(ForwardRefMDNodes.begin()->first) + "'");
408
409 // Resolve metadata cycles.
410 for (auto &N : NumberedMetadata) {
411 if (N.second && !N.second->isResolved())
412 N.second->resolveCycles();
413 }
414
415 for (auto *Inst : InstsWithTBAATag) {
416 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
417 // With incomplete IR, the tbaa metadata may have been dropped.
419 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
420 if (MD) {
421 auto *UpgradedMD = UpgradeTBAANode(*MD);
422 if (MD != UpgradedMD)
423 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
424 }
425 }
426
427 // Look for intrinsic functions and CallInst that need to be upgraded. We use
428 // make_early_inc_range here because we may remove some functions.
431
432 if (UpgradeDebugInfo)
434
437
439 M->setIsNewDbgInfoFormat(UseNewDbgInfoFormat);
440
441 if (!Slots)
442 return false;
443 // Initialize the slot mapping.
444 // Because by this point we've parsed and validated everything, we can "steal"
445 // the mapping from LLParser as it doesn't need it anymore.
446 Slots->GlobalValues = std::move(NumberedVals);
447 Slots->MetadataNodes = std::move(NumberedMetadata);
448 for (const auto &I : NamedTypes)
449 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
450 for (const auto &I : NumberedTypes)
451 Slots->Types.insert(std::make_pair(I.first, I.second.first));
452
453 return false;
454}
455
456/// Do final validity and basic correctness checks at the end of the index.
457bool LLParser::validateEndOfIndex() {
458 if (!Index)
459 return false;
460
461 if (!ForwardRefValueInfos.empty())
462 return error(ForwardRefValueInfos.begin()->second.front().second,
463 "use of undefined summary '^" +
464 Twine(ForwardRefValueInfos.begin()->first) + "'");
465
466 if (!ForwardRefAliasees.empty())
467 return error(ForwardRefAliasees.begin()->second.front().second,
468 "use of undefined summary '^" +
469 Twine(ForwardRefAliasees.begin()->first) + "'");
470
471 if (!ForwardRefTypeIds.empty())
472 return error(ForwardRefTypeIds.begin()->second.front().second,
473 "use of undefined type id summary '^" +
474 Twine(ForwardRefTypeIds.begin()->first) + "'");
475
476 return false;
477}
478
479//===----------------------------------------------------------------------===//
480// Top-Level Entities
481//===----------------------------------------------------------------------===//
482
483bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
484 // Delay parsing of the data layout string until the target triple is known.
485 // Then, pass both the the target triple and the tentative data layout string
486 // to DataLayoutCallback, allowing to override the DL string.
487 // This enables importing modules with invalid DL strings.
488 std::string TentativeDLStr = M->getDataLayoutStr();
489 LocTy DLStrLoc;
490
491 bool Done = false;
492 while (!Done) {
493 switch (Lex.getKind()) {
494 case lltok::kw_target:
495 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
496 return true;
497 break;
499 if (parseSourceFileName())
500 return true;
501 break;
502 default:
503 Done = true;
504 }
505 }
506 // Run the override callback to potentially change the data layout string, and
507 // parse the data layout string.
508 if (auto LayoutOverride =
509 DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
510 TentativeDLStr = *LayoutOverride;
511 DLStrLoc = {};
512 }
513 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
514 if (!MaybeDL)
515 return error(DLStrLoc, toString(MaybeDL.takeError()));
516 M->setDataLayout(MaybeDL.get());
517 return false;
518}
519
520bool LLParser::parseTopLevelEntities() {
521 // If there is no Module, then parse just the summary index entries.
522 if (!M) {
523 while (true) {
524 switch (Lex.getKind()) {
525 case lltok::Eof:
526 return false;
527 case lltok::SummaryID:
528 if (parseSummaryEntry())
529 return true;
530 break;
532 if (parseSourceFileName())
533 return true;
534 break;
535 default:
536 // Skip everything else
537 Lex.Lex();
538 }
539 }
540 }
541 while (true) {
542 switch (Lex.getKind()) {
543 default:
544 return tokError("expected top-level entity");
545 case lltok::Eof: return false;
547 if (parseDeclare())
548 return true;
549 break;
550 case lltok::kw_define:
551 if (parseDefine())
552 return true;
553 break;
554 case lltok::kw_module:
555 if (parseModuleAsm())
556 return true;
557 break;
559 if (parseUnnamedType())
560 return true;
561 break;
562 case lltok::LocalVar:
563 if (parseNamedType())
564 return true;
565 break;
566 case lltok::GlobalID:
567 if (parseUnnamedGlobal())
568 return true;
569 break;
570 case lltok::GlobalVar:
571 if (parseNamedGlobal())
572 return true;
573 break;
574 case lltok::ComdatVar: if (parseComdat()) return true; break;
575 case lltok::exclaim:
576 if (parseStandaloneMetadata())
577 return true;
578 break;
579 case lltok::SummaryID:
580 if (parseSummaryEntry())
581 return true;
582 break;
584 if (parseNamedMetadata())
585 return true;
586 break;
588 if (parseUnnamedAttrGrp())
589 return true;
590 break;
592 if (parseUseListOrder())
593 return true;
594 break;
596 if (parseUseListOrderBB())
597 return true;
598 break;
599 }
600 }
601}
602
603/// toplevelentity
604/// ::= 'module' 'asm' STRINGCONSTANT
605bool LLParser::parseModuleAsm() {
607 Lex.Lex();
608
609 std::string AsmStr;
610 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
611 parseStringConstant(AsmStr))
612 return true;
613
614 M->appendModuleInlineAsm(AsmStr);
615 return false;
616}
617
618/// toplevelentity
619/// ::= 'target' 'triple' '=' STRINGCONSTANT
620/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
621bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
622 LocTy &DLStrLoc) {
624 std::string Str;
625 switch (Lex.Lex()) {
626 default:
627 return tokError("unknown target property");
628 case lltok::kw_triple:
629 Lex.Lex();
630 if (parseToken(lltok::equal, "expected '=' after target triple") ||
631 parseStringConstant(Str))
632 return true;
633 M->setTargetTriple(Str);
634 return false;
636 Lex.Lex();
637 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
638 return true;
639 DLStrLoc = Lex.getLoc();
640 if (parseStringConstant(TentativeDLStr))
641 return true;
642 return false;
643 }
644}
645
646/// toplevelentity
647/// ::= 'source_filename' '=' STRINGCONSTANT
648bool LLParser::parseSourceFileName() {
650 Lex.Lex();
651 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
652 parseStringConstant(SourceFileName))
653 return true;
654 if (M)
655 M->setSourceFileName(SourceFileName);
656 return false;
657}
658
659/// parseUnnamedType:
660/// ::= LocalVarID '=' 'type' type
661bool LLParser::parseUnnamedType() {
662 LocTy TypeLoc = Lex.getLoc();
663 unsigned TypeID = Lex.getUIntVal();
664 Lex.Lex(); // eat LocalVarID;
665
666 if (parseToken(lltok::equal, "expected '=' after name") ||
667 parseToken(lltok::kw_type, "expected 'type' after '='"))
668 return true;
669
670 Type *Result = nullptr;
671 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
672 return true;
673
674 if (!isa<StructType>(Result)) {
675 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
676 if (Entry.first)
677 return error(TypeLoc, "non-struct types may not be recursive");
678 Entry.first = Result;
679 Entry.second = SMLoc();
680 }
681
682 return false;
683}
684
685/// toplevelentity
686/// ::= LocalVar '=' 'type' type
687bool LLParser::parseNamedType() {
688 std::string Name = Lex.getStrVal();
689 LocTy NameLoc = Lex.getLoc();
690 Lex.Lex(); // eat LocalVar.
691
692 if (parseToken(lltok::equal, "expected '=' after name") ||
693 parseToken(lltok::kw_type, "expected 'type' after name"))
694 return true;
695
696 Type *Result = nullptr;
697 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
698 return true;
699
700 if (!isa<StructType>(Result)) {
701 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
702 if (Entry.first)
703 return error(NameLoc, "non-struct types may not be recursive");
704 Entry.first = Result;
705 Entry.second = SMLoc();
706 }
707
708 return false;
709}
710
711/// toplevelentity
712/// ::= 'declare' FunctionHeader
713bool LLParser::parseDeclare() {
715 Lex.Lex();
716
717 std::vector<std::pair<unsigned, MDNode *>> MDs;
718 while (Lex.getKind() == lltok::MetadataVar) {
719 unsigned MDK;
720 MDNode *N;
721 if (parseMetadataAttachment(MDK, N))
722 return true;
723 MDs.push_back({MDK, N});
724 }
725
726 Function *F;
727 unsigned FunctionNumber = -1;
728 SmallVector<unsigned> UnnamedArgNums;
729 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
730 return true;
731 for (auto &MD : MDs)
732 F->addMetadata(MD.first, *MD.second);
733 return false;
734}
735
736/// toplevelentity
737/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
738bool LLParser::parseDefine() {
740 Lex.Lex();
741
742 Function *F;
743 unsigned FunctionNumber = -1;
744 SmallVector<unsigned> UnnamedArgNums;
745 return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
746 parseOptionalFunctionMetadata(*F) ||
747 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
748}
749
750/// parseGlobalType
751/// ::= 'constant'
752/// ::= 'global'
753bool LLParser::parseGlobalType(bool &IsConstant) {
754 if (Lex.getKind() == lltok::kw_constant)
755 IsConstant = true;
756 else if (Lex.getKind() == lltok::kw_global)
757 IsConstant = false;
758 else {
759 IsConstant = false;
760 return tokError("expected 'global' or 'constant'");
761 }
762 Lex.Lex();
763 return false;
764}
765
766bool LLParser::parseOptionalUnnamedAddr(
767 GlobalVariable::UnnamedAddr &UnnamedAddr) {
768 if (EatIfPresent(lltok::kw_unnamed_addr))
770 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
772 else
773 UnnamedAddr = GlobalValue::UnnamedAddr::None;
774 return false;
775}
776
777/// parseUnnamedGlobal:
778/// OptionalVisibility (ALIAS | IFUNC) ...
779/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
780/// OptionalDLLStorageClass
781/// ... -> global variable
782/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
783/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
784/// OptionalVisibility
785/// OptionalDLLStorageClass
786/// ... -> global variable
787bool LLParser::parseUnnamedGlobal() {
788 unsigned VarID;
789 std::string Name;
790 LocTy NameLoc = Lex.getLoc();
791
792 // Handle the GlobalID form.
793 if (Lex.getKind() == lltok::GlobalID) {
794 VarID = Lex.getUIntVal();
795 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
796 return true;
797
798 Lex.Lex(); // eat GlobalID;
799 if (parseToken(lltok::equal, "expected '=' after name"))
800 return true;
801 } else {
802 VarID = NumberedVals.getNext();
803 }
804
805 bool HasLinkage;
806 unsigned Linkage, Visibility, DLLStorageClass;
807 bool DSOLocal;
809 GlobalVariable::UnnamedAddr UnnamedAddr;
810 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
811 DSOLocal) ||
812 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
813 return true;
814
815 switch (Lex.getKind()) {
816 default:
817 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
818 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
819 case lltok::kw_alias:
820 case lltok::kw_ifunc:
821 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
822 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
823 }
824}
825
826/// parseNamedGlobal:
827/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
828/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
829/// OptionalVisibility OptionalDLLStorageClass
830/// ... -> global variable
831bool LLParser::parseNamedGlobal() {
833 LocTy NameLoc = Lex.getLoc();
834 std::string Name = Lex.getStrVal();
835 Lex.Lex();
836
837 bool HasLinkage;
838 unsigned Linkage, Visibility, DLLStorageClass;
839 bool DSOLocal;
841 GlobalVariable::UnnamedAddr UnnamedAddr;
842 if (parseToken(lltok::equal, "expected '=' in global variable") ||
843 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
844 DSOLocal) ||
845 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
846 return true;
847
848 switch (Lex.getKind()) {
849 default:
850 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
851 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
852 case lltok::kw_alias:
853 case lltok::kw_ifunc:
854 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
855 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
856 }
857}
858
859bool LLParser::parseComdat() {
861 std::string Name = Lex.getStrVal();
862 LocTy NameLoc = Lex.getLoc();
863 Lex.Lex();
864
865 if (parseToken(lltok::equal, "expected '=' here"))
866 return true;
867
868 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
869 return tokError("expected comdat type");
870
872 switch (Lex.getKind()) {
873 default:
874 return tokError("unknown selection kind");
875 case lltok::kw_any:
876 SK = Comdat::Any;
877 break;
880 break;
882 SK = Comdat::Largest;
883 break;
886 break;
888 SK = Comdat::SameSize;
889 break;
890 }
891 Lex.Lex();
892
893 // See if the comdat was forward referenced, if so, use the comdat.
894 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
896 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
897 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
898
899 Comdat *C;
900 if (I != ComdatSymTab.end())
901 C = &I->second;
902 else
903 C = M->getOrInsertComdat(Name);
904 C->setSelectionKind(SK);
905
906 return false;
907}
908
909// MDString:
910// ::= '!' STRINGCONSTANT
911bool LLParser::parseMDString(MDString *&Result) {
912 std::string Str;
913 if (parseStringConstant(Str))
914 return true;
915 Result = MDString::get(Context, Str);
916 return false;
917}
918
919// MDNode:
920// ::= '!' MDNodeNumber
921bool LLParser::parseMDNodeID(MDNode *&Result) {
922 // !{ ..., !42, ... }
923 LocTy IDLoc = Lex.getLoc();
924 unsigned MID = 0;
925 if (parseUInt32(MID))
926 return true;
927
928 // If not a forward reference, just return it now.
929 if (NumberedMetadata.count(MID)) {
930 Result = NumberedMetadata[MID];
931 return false;
932 }
933
934 // Otherwise, create MDNode forward reference.
935 auto &FwdRef = ForwardRefMDNodes[MID];
936 FwdRef = std::make_pair(MDTuple::getTemporary(Context, std::nullopt), IDLoc);
937
938 Result = FwdRef.first.get();
939 NumberedMetadata[MID].reset(Result);
940 return false;
941}
942
943/// parseNamedMetadata:
944/// !foo = !{ !1, !2 }
945bool LLParser::parseNamedMetadata() {
947 std::string Name = Lex.getStrVal();
948 Lex.Lex();
949
950 if (parseToken(lltok::equal, "expected '=' here") ||
951 parseToken(lltok::exclaim, "Expected '!' here") ||
952 parseToken(lltok::lbrace, "Expected '{' here"))
953 return true;
954
955 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
956 if (Lex.getKind() != lltok::rbrace)
957 do {
958 MDNode *N = nullptr;
959 // parse DIExpressions inline as a special case. They are still MDNodes,
960 // so they can still appear in named metadata. Remove this logic if they
961 // become plain Metadata.
962 if (Lex.getKind() == lltok::MetadataVar &&
963 Lex.getStrVal() == "DIExpression") {
964 if (parseDIExpression(N, /*IsDistinct=*/false))
965 return true;
966 // DIArgLists should only appear inline in a function, as they may
967 // contain LocalAsMetadata arguments which require a function context.
968 } else if (Lex.getKind() == lltok::MetadataVar &&
969 Lex.getStrVal() == "DIArgList") {
970 return tokError("found DIArgList outside of function");
971 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
972 parseMDNodeID(N)) {
973 return true;
974 }
975 NMD->addOperand(N);
976 } while (EatIfPresent(lltok::comma));
977
978 return parseToken(lltok::rbrace, "expected end of metadata node");
979}
980
981/// parseStandaloneMetadata:
982/// !42 = !{...}
983bool LLParser::parseStandaloneMetadata() {
984 assert(Lex.getKind() == lltok::exclaim);
985 Lex.Lex();
986 unsigned MetadataID = 0;
987
988 MDNode *Init;
989 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
990 return true;
991
992 // Detect common error, from old metadata syntax.
993 if (Lex.getKind() == lltok::Type)
994 return tokError("unexpected type in metadata definition");
995
996 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
997 if (Lex.getKind() == lltok::MetadataVar) {
998 if (parseSpecializedMDNode(Init, IsDistinct))
999 return true;
1000 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1001 parseMDTuple(Init, IsDistinct))
1002 return true;
1003
1004 // See if this was forward referenced, if so, handle it.
1005 auto FI = ForwardRefMDNodes.find(MetadataID);
1006 if (FI != ForwardRefMDNodes.end()) {
1007 auto *ToReplace = FI->second.first.get();
1008 // DIAssignID has its own special forward-reference "replacement" for
1009 // attachments (the temporary attachments are never actually attached).
1010 if (isa<DIAssignID>(Init)) {
1011 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1012 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1013 "Inst unexpectedly already has DIAssignID attachment");
1014 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1015 }
1016 }
1017
1018 ToReplace->replaceAllUsesWith(Init);
1019 ForwardRefMDNodes.erase(FI);
1020
1021 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1022 } else {
1023 if (NumberedMetadata.count(MetadataID))
1024 return tokError("Metadata id is already used");
1025 NumberedMetadata[MetadataID].reset(Init);
1026 }
1027
1028 return false;
1029}
1030
1031// Skips a single module summary entry.
1032bool LLParser::skipModuleSummaryEntry() {
1033 // Each module summary entry consists of a tag for the entry
1034 // type, followed by a colon, then the fields which may be surrounded by
1035 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1036 // support is in place we will look for the tokens corresponding to the
1037 // expected tags.
1038 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1039 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1041 return tokError(
1042 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1043 "start of summary entry");
1044 if (Lex.getKind() == lltok::kw_flags)
1045 return parseSummaryIndexFlags();
1046 if (Lex.getKind() == lltok::kw_blockcount)
1047 return parseBlockCount();
1048 Lex.Lex();
1049 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1050 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1051 return true;
1052 // Now walk through the parenthesized entry, until the number of open
1053 // parentheses goes back down to 0 (the first '(' was parsed above).
1054 unsigned NumOpenParen = 1;
1055 do {
1056 switch (Lex.getKind()) {
1057 case lltok::lparen:
1058 NumOpenParen++;
1059 break;
1060 case lltok::rparen:
1061 NumOpenParen--;
1062 break;
1063 case lltok::Eof:
1064 return tokError("found end of file while parsing summary entry");
1065 default:
1066 // Skip everything in between parentheses.
1067 break;
1068 }
1069 Lex.Lex();
1070 } while (NumOpenParen > 0);
1071 return false;
1072}
1073
1074/// SummaryEntry
1075/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1076bool LLParser::parseSummaryEntry() {
1078 unsigned SummaryID = Lex.getUIntVal();
1079
1080 // For summary entries, colons should be treated as distinct tokens,
1081 // not an indication of the end of a label token.
1083
1084 Lex.Lex();
1085 if (parseToken(lltok::equal, "expected '=' here"))
1086 return true;
1087
1088 // If we don't have an index object, skip the summary entry.
1089 if (!Index)
1090 return skipModuleSummaryEntry();
1091
1092 bool result = false;
1093 switch (Lex.getKind()) {
1094 case lltok::kw_gv:
1095 result = parseGVEntry(SummaryID);
1096 break;
1097 case lltok::kw_module:
1098 result = parseModuleEntry(SummaryID);
1099 break;
1100 case lltok::kw_typeid:
1101 result = parseTypeIdEntry(SummaryID);
1102 break;
1104 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1105 break;
1106 case lltok::kw_flags:
1107 result = parseSummaryIndexFlags();
1108 break;
1110 result = parseBlockCount();
1111 break;
1112 default:
1113 result = error(Lex.getLoc(), "unexpected summary kind");
1114 break;
1115 }
1116 Lex.setIgnoreColonInIdentifiers(false);
1117 return result;
1118}
1119
1120static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
1123}
1124static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
1127}
1128
1129// If there was an explicit dso_local, update GV. In the absence of an explicit
1130// dso_local we keep the default value.
1131static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1132 if (DSOLocal)
1133 GV.setDSOLocal(true);
1134}
1135
1136/// parseAliasOrIFunc:
1137/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1138/// OptionalVisibility OptionalDLLStorageClass
1139/// OptionalThreadLocal OptionalUnnamedAddr
1140/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1141///
1142/// AliaseeOrResolver
1143/// ::= TypeAndValue
1144///
1145/// SymbolAttrs
1146/// ::= ',' 'partition' StringConstant
1147///
1148/// Everything through OptionalUnnamedAddr has already been parsed.
1149///
1150bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1151 LocTy NameLoc, unsigned L, unsigned Visibility,
1152 unsigned DLLStorageClass, bool DSOLocal,
1154 GlobalVariable::UnnamedAddr UnnamedAddr) {
1155 bool IsAlias;
1156 if (Lex.getKind() == lltok::kw_alias)
1157 IsAlias = true;
1158 else if (Lex.getKind() == lltok::kw_ifunc)
1159 IsAlias = false;
1160 else
1161 llvm_unreachable("Not an alias or ifunc!");
1162 Lex.Lex();
1163
1165
1166 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1167 return error(NameLoc, "invalid linkage type for alias");
1168
1169 if (!isValidVisibilityForLinkage(Visibility, L))
1170 return error(NameLoc,
1171 "symbol with local linkage must have default visibility");
1172
1173 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1174 return error(NameLoc,
1175 "symbol with local linkage cannot have a DLL storage class");
1176
1177 Type *Ty;
1178 LocTy ExplicitTypeLoc = Lex.getLoc();
1179 if (parseType(Ty) ||
1180 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1181 return true;
1182
1183 Constant *Aliasee;
1184 LocTy AliaseeLoc = Lex.getLoc();
1185 if (Lex.getKind() != lltok::kw_bitcast &&
1188 Lex.getKind() != lltok::kw_inttoptr) {
1189 if (parseGlobalTypeAndValue(Aliasee))
1190 return true;
1191 } else {
1192 // The bitcast dest type is not present, it is implied by the dest type.
1193 ValID ID;
1194 if (parseValID(ID, /*PFS=*/nullptr))
1195 return true;
1196 if (ID.Kind != ValID::t_Constant)
1197 return error(AliaseeLoc, "invalid aliasee");
1198 Aliasee = ID.ConstantVal;
1199 }
1200
1201 Type *AliaseeType = Aliasee->getType();
1202 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1203 if (!PTy)
1204 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1205 unsigned AddrSpace = PTy->getAddressSpace();
1206
1207 GlobalValue *GVal = nullptr;
1208
1209 // See if the alias was forward referenced, if so, prepare to replace the
1210 // forward reference.
1211 if (!Name.empty()) {
1212 auto I = ForwardRefVals.find(Name);
1213 if (I != ForwardRefVals.end()) {
1214 GVal = I->second.first;
1215 ForwardRefVals.erase(Name);
1216 } else if (M->getNamedValue(Name)) {
1217 return error(NameLoc, "redefinition of global '@" + Name + "'");
1218 }
1219 } else {
1220 auto I = ForwardRefValIDs.find(NameID);
1221 if (I != ForwardRefValIDs.end()) {
1222 GVal = I->second.first;
1223 ForwardRefValIDs.erase(I);
1224 }
1225 }
1226
1227 // Okay, create the alias/ifunc but do not insert it into the module yet.
1228 std::unique_ptr<GlobalAlias> GA;
1229 std::unique_ptr<GlobalIFunc> GI;
1230 GlobalValue *GV;
1231 if (IsAlias) {
1232 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1234 Aliasee, /*Parent*/ nullptr));
1235 GV = GA.get();
1236 } else {
1237 GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1239 Aliasee, /*Parent*/ nullptr));
1240 GV = GI.get();
1241 }
1242 GV->setThreadLocalMode(TLM);
1245 GV->setUnnamedAddr(UnnamedAddr);
1246 maybeSetDSOLocal(DSOLocal, *GV);
1247
1248 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1249 // Now parse them if there are any.
1250 while (Lex.getKind() == lltok::comma) {
1251 Lex.Lex();
1252
1253 if (Lex.getKind() == lltok::kw_partition) {
1254 Lex.Lex();
1255 GV->setPartition(Lex.getStrVal());
1256 if (parseToken(lltok::StringConstant, "expected partition string"))
1257 return true;
1258 } else {
1259 return tokError("unknown alias or ifunc property!");
1260 }
1261 }
1262
1263 if (Name.empty())
1264 NumberedVals.add(NameID, GV);
1265
1266 if (GVal) {
1267 // Verify that types agree.
1268 if (GVal->getType() != GV->getType())
1269 return error(
1270 ExplicitTypeLoc,
1271 "forward reference and definition of alias have different types");
1272
1273 // If they agree, just RAUW the old value with the alias and remove the
1274 // forward ref info.
1275 GVal->replaceAllUsesWith(GV);
1276 GVal->eraseFromParent();
1277 }
1278
1279 // Insert into the module, we know its name won't collide now.
1280 if (IsAlias)
1281 M->insertAlias(GA.release());
1282 else
1283 M->insertIFunc(GI.release());
1284 assert(GV->getName() == Name && "Should not be a name conflict!");
1285
1286 return false;
1287}
1288
1289static bool isSanitizer(lltok::Kind Kind) {
1290 switch (Kind) {
1293 case lltok::kw_sanitize_memtag:
1295 return true;
1296 default:
1297 return false;
1298 }
1299}
1300
1301bool LLParser::parseSanitizer(GlobalVariable *GV) {
1304 if (GV->hasSanitizerMetadata())
1305 Meta = GV->getSanitizerMetadata();
1306
1307 switch (Lex.getKind()) {
1309 Meta.NoAddress = true;
1310 break;
1312 Meta.NoHWAddress = true;
1313 break;
1314 case lltok::kw_sanitize_memtag:
1315 Meta.Memtag = true;
1316 break;
1318 Meta.IsDynInit = true;
1319 break;
1320 default:
1321 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1322 }
1323 GV->setSanitizerMetadata(Meta);
1324 Lex.Lex();
1325 return false;
1326}
1327
1328/// parseGlobal
1329/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1330/// OptionalVisibility OptionalDLLStorageClass
1331/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1332/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1333/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1334/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1335/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1336/// Const OptionalAttrs
1337///
1338/// Everything up to and including OptionalUnnamedAddr has been parsed
1339/// already.
1340///
1341bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1342 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1343 unsigned Visibility, unsigned DLLStorageClass,
1344 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1345 GlobalVariable::UnnamedAddr UnnamedAddr) {
1346 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1347 return error(NameLoc,
1348 "symbol with local linkage must have default visibility");
1349
1350 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1351 return error(NameLoc,
1352 "symbol with local linkage cannot have a DLL storage class");
1353
1354 unsigned AddrSpace;
1355 bool IsConstant, IsExternallyInitialized;
1356 LocTy IsExternallyInitializedLoc;
1357 LocTy TyLoc;
1358
1359 Type *Ty = nullptr;
1360 if (parseOptionalAddrSpace(AddrSpace) ||
1361 parseOptionalToken(lltok::kw_externally_initialized,
1362 IsExternallyInitialized,
1363 &IsExternallyInitializedLoc) ||
1364 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1365 return true;
1366
1367 // If the linkage is specified and is external, then no initializer is
1368 // present.
1369 Constant *Init = nullptr;
1370 if (!HasLinkage ||
1372 (GlobalValue::LinkageTypes)Linkage)) {
1373 if (parseGlobalValue(Ty, Init))
1374 return true;
1375 }
1376
1378 return error(TyLoc, "invalid type for global variable");
1379
1380 GlobalValue *GVal = nullptr;
1381
1382 // See if the global was forward referenced, if so, use the global.
1383 if (!Name.empty()) {
1384 auto I = ForwardRefVals.find(Name);
1385 if (I != ForwardRefVals.end()) {
1386 GVal = I->second.first;
1387 ForwardRefVals.erase(I);
1388 } else if (M->getNamedValue(Name)) {
1389 return error(NameLoc, "redefinition of global '@" + Name + "'");
1390 }
1391 } else {
1392 // Handle @"", where a name is syntactically specified, but semantically
1393 // missing.
1394 if (NameID == (unsigned)-1)
1395 NameID = NumberedVals.getNext();
1396
1397 auto I = ForwardRefValIDs.find(NameID);
1398 if (I != ForwardRefValIDs.end()) {
1399 GVal = I->second.first;
1400 ForwardRefValIDs.erase(I);
1401 }
1402 }
1403
1405 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1407
1408 if (Name.empty())
1409 NumberedVals.add(NameID, GV);
1410
1411 // Set the parsed properties on the global.
1412 if (Init)
1413 GV->setInitializer(Init);
1414 GV->setConstant(IsConstant);
1416 maybeSetDSOLocal(DSOLocal, *GV);
1419 GV->setExternallyInitialized(IsExternallyInitialized);
1420 GV->setThreadLocalMode(TLM);
1421 GV->setUnnamedAddr(UnnamedAddr);
1422
1423 if (GVal) {
1424 if (GVal->getAddressSpace() != AddrSpace)
1425 return error(
1426 TyLoc,
1427 "forward reference and definition of global have different types");
1428
1429 GVal->replaceAllUsesWith(GV);
1430 GVal->eraseFromParent();
1431 }
1432
1433 // parse attributes on the global.
1434 while (Lex.getKind() == lltok::comma) {
1435 Lex.Lex();
1436
1437 if (Lex.getKind() == lltok::kw_section) {
1438 Lex.Lex();
1439 GV->setSection(Lex.getStrVal());
1440 if (parseToken(lltok::StringConstant, "expected global section string"))
1441 return true;
1442 } else if (Lex.getKind() == lltok::kw_partition) {
1443 Lex.Lex();
1444 GV->setPartition(Lex.getStrVal());
1445 if (parseToken(lltok::StringConstant, "expected partition string"))
1446 return true;
1447 } else if (Lex.getKind() == lltok::kw_align) {
1448 MaybeAlign Alignment;
1449 if (parseOptionalAlignment(Alignment))
1450 return true;
1451 if (Alignment)
1452 GV->setAlignment(*Alignment);
1453 } else if (Lex.getKind() == lltok::kw_code_model) {
1455 if (parseOptionalCodeModel(CodeModel))
1456 return true;
1457 GV->setCodeModel(CodeModel);
1458 } else if (Lex.getKind() == lltok::MetadataVar) {
1459 if (parseGlobalObjectMetadataAttachment(*GV))
1460 return true;
1461 } else if (isSanitizer(Lex.getKind())) {
1462 if (parseSanitizer(GV))
1463 return true;
1464 } else {
1465 Comdat *C;
1466 if (parseOptionalComdat(Name, C))
1467 return true;
1468 if (C)
1469 GV->setComdat(C);
1470 else
1471 return tokError("unknown global variable property!");
1472 }
1473 }
1474
1475 AttrBuilder Attrs(M->getContext());
1476 LocTy BuiltinLoc;
1477 std::vector<unsigned> FwdRefAttrGrps;
1478 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1479 return true;
1480 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1481 GV->setAttributes(AttributeSet::get(Context, Attrs));
1482 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1483 }
1484
1485 return false;
1486}
1487
1488/// parseUnnamedAttrGrp
1489/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1490bool LLParser::parseUnnamedAttrGrp() {
1492 LocTy AttrGrpLoc = Lex.getLoc();
1493 Lex.Lex();
1494
1495 if (Lex.getKind() != lltok::AttrGrpID)
1496 return tokError("expected attribute group id");
1497
1498 unsigned VarID = Lex.getUIntVal();
1499 std::vector<unsigned> unused;
1500 LocTy BuiltinLoc;
1501 Lex.Lex();
1502
1503 if (parseToken(lltok::equal, "expected '=' here") ||
1504 parseToken(lltok::lbrace, "expected '{' here"))
1505 return true;
1506
1507 auto R = NumberedAttrBuilders.find(VarID);
1508 if (R == NumberedAttrBuilders.end())
1509 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1510
1511 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1512 parseToken(lltok::rbrace, "expected end of attribute group"))
1513 return true;
1514
1515 if (!R->second.hasAttributes())
1516 return error(AttrGrpLoc, "attribute group has no attributes");
1517
1518 return false;
1519}
1520
1522 switch (Kind) {
1523#define GET_ATTR_NAMES
1524#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1525 case lltok::kw_##DISPLAY_NAME: \
1526 return Attribute::ENUM_NAME;
1527#include "llvm/IR/Attributes.inc"
1528 default:
1529 return Attribute::None;
1530 }
1531}
1532
1533bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1534 bool InAttrGroup) {
1535 if (Attribute::isTypeAttrKind(Attr))
1536 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1537
1538 switch (Attr) {
1539 case Attribute::Alignment: {
1540 MaybeAlign Alignment;
1541 if (InAttrGroup) {
1542 uint32_t Value = 0;
1543 Lex.Lex();
1544 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1545 return true;
1546 Alignment = Align(Value);
1547 } else {
1548 if (parseOptionalAlignment(Alignment, true))
1549 return true;
1550 }
1551 B.addAlignmentAttr(Alignment);
1552 return false;
1553 }
1554 case Attribute::StackAlignment: {
1555 unsigned Alignment;
1556 if (InAttrGroup) {
1557 Lex.Lex();
1558 if (parseToken(lltok::equal, "expected '=' here") ||
1559 parseUInt32(Alignment))
1560 return true;
1561 } else {
1562 if (parseOptionalStackAlignment(Alignment))
1563 return true;
1564 }
1565 B.addStackAlignmentAttr(Alignment);
1566 return false;
1567 }
1568 case Attribute::AllocSize: {
1569 unsigned ElemSizeArg;
1570 std::optional<unsigned> NumElemsArg;
1571 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1572 return true;
1573 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1574 return false;
1575 }
1576 case Attribute::VScaleRange: {
1577 unsigned MinValue, MaxValue;
1578 if (parseVScaleRangeArguments(MinValue, MaxValue))
1579 return true;
1580 B.addVScaleRangeAttr(MinValue,
1581 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1582 return false;
1583 }
1584 case Attribute::Dereferenceable: {
1585 uint64_t Bytes;
1586 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1587 return true;
1588 B.addDereferenceableAttr(Bytes);
1589 return false;
1590 }
1591 case Attribute::DereferenceableOrNull: {
1592 uint64_t Bytes;
1593 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1594 return true;
1595 B.addDereferenceableOrNullAttr(Bytes);
1596 return false;
1597 }
1598 case Attribute::UWTable: {
1600 if (parseOptionalUWTableKind(Kind))
1601 return true;
1602 B.addUWTableAttr(Kind);
1603 return false;
1604 }
1605 case Attribute::AllocKind: {
1607 if (parseAllocKind(Kind))
1608 return true;
1609 B.addAllocKindAttr(Kind);
1610 return false;
1611 }
1612 case Attribute::Memory: {
1613 std::optional<MemoryEffects> ME = parseMemoryAttr();
1614 if (!ME)
1615 return true;
1616 B.addMemoryAttr(*ME);
1617 return false;
1618 }
1619 case Attribute::NoFPClass: {
1620 if (FPClassTest NoFPClass =
1621 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1622 B.addNoFPClassAttr(NoFPClass);
1623 return false;
1624 }
1625
1626 return true;
1627 }
1628 case Attribute::Range:
1629 return parseRangeAttr(B);
1630 case Attribute::Initializes:
1631 return parseInitializesAttr(B);
1632 default:
1633 B.addAttribute(Attr);
1634 Lex.Lex();
1635 return false;
1636 }
1637}
1638
1640 switch (Kind) {
1641 case lltok::kw_readnone:
1642 ME &= MemoryEffects::none();
1643 return true;
1644 case lltok::kw_readonly:
1646 return true;
1647 case lltok::kw_writeonly:
1649 return true;
1652 return true;
1655 return true;
1658 return true;
1659 default:
1660 return false;
1661 }
1662}
1663
1664/// parseFnAttributeValuePairs
1665/// ::= <attr> | <attr> '=' <value>
1666bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1667 std::vector<unsigned> &FwdRefAttrGrps,
1668 bool InAttrGrp, LocTy &BuiltinLoc) {
1669 bool HaveError = false;
1670
1671 B.clear();
1672
1674 while (true) {
1675 lltok::Kind Token = Lex.getKind();
1676 if (Token == lltok::rbrace)
1677 break; // Finished.
1678
1679 if (Token == lltok::StringConstant) {
1680 if (parseStringAttribute(B))
1681 return true;
1682 continue;
1683 }
1684
1685 if (Token == lltok::AttrGrpID) {
1686 // Allow a function to reference an attribute group:
1687 //
1688 // define void @foo() #1 { ... }
1689 if (InAttrGrp) {
1690 HaveError |= error(
1691 Lex.getLoc(),
1692 "cannot have an attribute group reference in an attribute group");
1693 } else {
1694 // Save the reference to the attribute group. We'll fill it in later.
1695 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1696 }
1697 Lex.Lex();
1698 continue;
1699 }
1700
1701 SMLoc Loc = Lex.getLoc();
1702 if (Token == lltok::kw_builtin)
1703 BuiltinLoc = Loc;
1704
1705 if (upgradeMemoryAttr(ME, Token)) {
1706 Lex.Lex();
1707 continue;
1708 }
1709
1711 if (Attr == Attribute::None) {
1712 if (!InAttrGrp)
1713 break;
1714 return error(Lex.getLoc(), "unterminated attribute group");
1715 }
1716
1717 if (parseEnumAttribute(Attr, B, InAttrGrp))
1718 return true;
1719
1720 // As a hack, we allow function alignment to be initially parsed as an
1721 // attribute on a function declaration/definition or added to an attribute
1722 // group and later moved to the alignment field.
1723 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1724 HaveError |= error(Loc, "this attribute does not apply to functions");
1725 }
1726
1727 if (ME != MemoryEffects::unknown())
1728 B.addMemoryAttr(ME);
1729 return HaveError;
1730}
1731
1732//===----------------------------------------------------------------------===//
1733// GlobalValue Reference/Resolution Routines.
1734//===----------------------------------------------------------------------===//
1735
1737 // The used global type does not matter. We will later RAUW it with a
1738 // global/function of the correct type.
1739 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1742 PTy->getAddressSpace());
1743}
1744
1745Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1746 Value *Val) {
1747 Type *ValTy = Val->getType();
1748 if (ValTy == Ty)
1749 return Val;
1750 if (Ty->isLabelTy())
1751 error(Loc, "'" + Name + "' is not a basic block");
1752 else
1753 error(Loc, "'" + Name + "' defined with type '" +
1754 getTypeString(Val->getType()) + "' but expected '" +
1755 getTypeString(Ty) + "'");
1756 return nullptr;
1757}
1758
1759/// getGlobalVal - Get a value with the specified name or ID, creating a
1760/// forward reference record if needed. This can return null if the value
1761/// exists but does not have the right type.
1762GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1763 LocTy Loc) {
1764 PointerType *PTy = dyn_cast<PointerType>(Ty);
1765 if (!PTy) {
1766 error(Loc, "global variable reference must have pointer type");
1767 return nullptr;
1768 }
1769
1770 // Look this name up in the normal function symbol table.
1771 GlobalValue *Val =
1772 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1773
1774 // If this is a forward reference for the value, see if we already created a
1775 // forward ref record.
1776 if (!Val) {
1777 auto I = ForwardRefVals.find(Name);
1778 if (I != ForwardRefVals.end())
1779 Val = I->second.first;
1780 }
1781
1782 // If we have the value in the symbol table or fwd-ref table, return it.
1783 if (Val)
1784 return cast_or_null<GlobalValue>(
1785 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1786
1787 // Otherwise, create a new forward reference for this value and remember it.
1788 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1789 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1790 return FwdVal;
1791}
1792
1793GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1794 PointerType *PTy = dyn_cast<PointerType>(Ty);
1795 if (!PTy) {
1796 error(Loc, "global variable reference must have pointer type");
1797 return nullptr;
1798 }
1799
1800 GlobalValue *Val = NumberedVals.get(ID);
1801
1802 // If this is a forward reference for the value, see if we already created a
1803 // forward ref record.
1804 if (!Val) {
1805 auto I = ForwardRefValIDs.find(ID);
1806 if (I != ForwardRefValIDs.end())
1807 Val = I->second.first;
1808 }
1809
1810 // If we have the value in the symbol table or fwd-ref table, return it.
1811 if (Val)
1812 return cast_or_null<GlobalValue>(
1813 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1814
1815 // Otherwise, create a new forward reference for this value and remember it.
1816 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1817 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1818 return FwdVal;
1819}
1820
1821//===----------------------------------------------------------------------===//
1822// Comdat Reference/Resolution Routines.
1823//===----------------------------------------------------------------------===//
1824
1825Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1826 // Look this name up in the comdat symbol table.
1827 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1829 if (I != ComdatSymTab.end())
1830 return &I->second;
1831
1832 // Otherwise, create a new forward reference for this value and remember it.
1833 Comdat *C = M->getOrInsertComdat(Name);
1834 ForwardRefComdats[Name] = Loc;
1835 return C;
1836}
1837
1838//===----------------------------------------------------------------------===//
1839// Helper Routines.
1840//===----------------------------------------------------------------------===//
1841
1842/// parseToken - If the current token has the specified kind, eat it and return
1843/// success. Otherwise, emit the specified error and return failure.
1844bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1845 if (Lex.getKind() != T)
1846 return tokError(ErrMsg);
1847 Lex.Lex();
1848 return false;
1849}
1850
1851/// parseStringConstant
1852/// ::= StringConstant
1853bool LLParser::parseStringConstant(std::string &Result) {
1854 if (Lex.getKind() != lltok::StringConstant)
1855 return tokError("expected string constant");
1856 Result = Lex.getStrVal();
1857 Lex.Lex();
1858 return false;
1859}
1860
1861/// parseUInt32
1862/// ::= uint32
1863bool LLParser::parseUInt32(uint32_t &Val) {
1864 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1865 return tokError("expected integer");
1866 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1867 if (Val64 != unsigned(Val64))
1868 return tokError("expected 32-bit integer (too large)");
1869 Val = Val64;
1870 Lex.Lex();
1871 return false;
1872}
1873
1874/// parseUInt64
1875/// ::= uint64
1876bool LLParser::parseUInt64(uint64_t &Val) {
1877 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1878 return tokError("expected integer");
1879 Val = Lex.getAPSIntVal().getLimitedValue();
1880 Lex.Lex();
1881 return false;
1882}
1883
1884/// parseTLSModel
1885/// := 'localdynamic'
1886/// := 'initialexec'
1887/// := 'localexec'
1888bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1889 switch (Lex.getKind()) {
1890 default:
1891 return tokError("expected localdynamic, initialexec or localexec");
1894 break;
1897 break;
1900 break;
1901 }
1902
1903 Lex.Lex();
1904 return false;
1905}
1906
1907/// parseOptionalThreadLocal
1908/// := /*empty*/
1909/// := 'thread_local'
1910/// := 'thread_local' '(' tlsmodel ')'
1911bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1913 if (!EatIfPresent(lltok::kw_thread_local))
1914 return false;
1915
1917 if (Lex.getKind() == lltok::lparen) {
1918 Lex.Lex();
1919 return parseTLSModel(TLM) ||
1920 parseToken(lltok::rparen, "expected ')' after thread local model");
1921 }
1922 return false;
1923}
1924
1925/// parseOptionalAddrSpace
1926/// := /*empty*/
1927/// := 'addrspace' '(' uint32 ')'
1928bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1929 AddrSpace = DefaultAS;
1930 if (!EatIfPresent(lltok::kw_addrspace))
1931 return false;
1932
1933 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1934 if (Lex.getKind() == lltok::StringConstant) {
1935 auto AddrSpaceStr = Lex.getStrVal();
1936 if (AddrSpaceStr == "A") {
1937 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1938 } else if (AddrSpaceStr == "G") {
1939 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1940 } else if (AddrSpaceStr == "P") {
1941 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1942 } else {
1943 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1944 }
1945 Lex.Lex();
1946 return false;
1947 }
1948 if (Lex.getKind() != lltok::APSInt)
1949 return tokError("expected integer or string constant");
1950 SMLoc Loc = Lex.getLoc();
1951 if (parseUInt32(AddrSpace))
1952 return true;
1953 if (!isUInt<24>(AddrSpace))
1954 return error(Loc, "invalid address space, must be a 24-bit integer");
1955 return false;
1956 };
1957
1958 return parseToken(lltok::lparen, "expected '(' in address space") ||
1959 ParseAddrspaceValue(AddrSpace) ||
1960 parseToken(lltok::rparen, "expected ')' in address space");
1961}
1962
1963/// parseStringAttribute
1964/// := StringConstant
1965/// := StringConstant '=' StringConstant
1966bool LLParser::parseStringAttribute(AttrBuilder &B) {
1967 std::string Attr = Lex.getStrVal();
1968 Lex.Lex();
1969 std::string Val;
1970 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1971 return true;
1972 B.addAttribute(Attr, Val);
1973 return false;
1974}
1975
1976/// Parse a potentially empty list of parameter or return attributes.
1977bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1978 bool HaveError = false;
1979
1980 B.clear();
1981
1982 while (true) {
1983 lltok::Kind Token = Lex.getKind();
1984 if (Token == lltok::StringConstant) {
1985 if (parseStringAttribute(B))
1986 return true;
1987 continue;
1988 }
1989
1990 SMLoc Loc = Lex.getLoc();
1992 if (Attr == Attribute::None)
1993 return HaveError;
1994
1995 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1996 return true;
1997
1998 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1999 HaveError |= error(Loc, "this attribute does not apply to parameters");
2000 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2001 HaveError |= error(Loc, "this attribute does not apply to return values");
2002 }
2003}
2004
2005static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2006 HasLinkage = true;
2007 switch (Kind) {
2008 default:
2009 HasLinkage = false;
2011 case lltok::kw_private:
2013 case lltok::kw_internal:
2015 case lltok::kw_weak:
2017 case lltok::kw_weak_odr:
2019 case lltok::kw_linkonce:
2027 case lltok::kw_common:
2031 case lltok::kw_external:
2033 }
2034}
2035
2036/// parseOptionalLinkage
2037/// ::= /*empty*/
2038/// ::= 'private'
2039/// ::= 'internal'
2040/// ::= 'weak'
2041/// ::= 'weak_odr'
2042/// ::= 'linkonce'
2043/// ::= 'linkonce_odr'
2044/// ::= 'available_externally'
2045/// ::= 'appending'
2046/// ::= 'common'
2047/// ::= 'extern_weak'
2048/// ::= 'external'
2049bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2050 unsigned &Visibility,
2051 unsigned &DLLStorageClass, bool &DSOLocal) {
2052 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2053 if (HasLinkage)
2054 Lex.Lex();
2055 parseOptionalDSOLocal(DSOLocal);
2056 parseOptionalVisibility(Visibility);
2057 parseOptionalDLLStorageClass(DLLStorageClass);
2058
2059 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2060 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2061 }
2062
2063 return false;
2064}
2065
2066void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2067 switch (Lex.getKind()) {
2068 default:
2069 DSOLocal = false;
2070 break;
2072 DSOLocal = true;
2073 Lex.Lex();
2074 break;
2076 DSOLocal = false;
2077 Lex.Lex();
2078 break;
2079 }
2080}
2081
2082/// parseOptionalVisibility
2083/// ::= /*empty*/
2084/// ::= 'default'
2085/// ::= 'hidden'
2086/// ::= 'protected'
2087///
2088void LLParser::parseOptionalVisibility(unsigned &Res) {
2089 switch (Lex.getKind()) {
2090 default:
2092 return;
2093 case lltok::kw_default:
2095 break;
2096 case lltok::kw_hidden:
2098 break;
2101 break;
2102 }
2103 Lex.Lex();
2104}
2105
2106bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2108 switch (Kind) {
2109 default:
2110 return tokError("unknown import kind. Expect definition or declaration.");
2113 return false;
2116 return false;
2117 }
2118}
2119
2120/// parseOptionalDLLStorageClass
2121/// ::= /*empty*/
2122/// ::= 'dllimport'
2123/// ::= 'dllexport'
2124///
2125void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2126 switch (Lex.getKind()) {
2127 default:
2129 return;
2132 break;
2135 break;
2136 }
2137 Lex.Lex();
2138}
2139
2140/// parseOptionalCallingConv
2141/// ::= /*empty*/
2142/// ::= 'ccc'
2143/// ::= 'fastcc'
2144/// ::= 'intel_ocl_bicc'
2145/// ::= 'coldcc'
2146/// ::= 'cfguard_checkcc'
2147/// ::= 'x86_stdcallcc'
2148/// ::= 'x86_fastcallcc'
2149/// ::= 'x86_thiscallcc'
2150/// ::= 'x86_vectorcallcc'
2151/// ::= 'arm_apcscc'
2152/// ::= 'arm_aapcscc'
2153/// ::= 'arm_aapcs_vfpcc'
2154/// ::= 'aarch64_vector_pcs'
2155/// ::= 'aarch64_sve_vector_pcs'
2156/// ::= 'aarch64_sme_preservemost_from_x0'
2157/// ::= 'aarch64_sme_preservemost_from_x1'
2158/// ::= 'aarch64_sme_preservemost_from_x2'
2159/// ::= 'msp430_intrcc'
2160/// ::= 'avr_intrcc'
2161/// ::= 'avr_signalcc'
2162/// ::= 'ptx_kernel'
2163/// ::= 'ptx_device'
2164/// ::= 'spir_func'
2165/// ::= 'spir_kernel'
2166/// ::= 'x86_64_sysvcc'
2167/// ::= 'win64cc'
2168/// ::= 'anyregcc'
2169/// ::= 'preserve_mostcc'
2170/// ::= 'preserve_allcc'
2171/// ::= 'preserve_nonecc'
2172/// ::= 'ghccc'
2173/// ::= 'swiftcc'
2174/// ::= 'swifttailcc'
2175/// ::= 'x86_intrcc'
2176/// ::= 'hhvmcc'
2177/// ::= 'hhvm_ccc'
2178/// ::= 'cxx_fast_tlscc'
2179/// ::= 'amdgpu_vs'
2180/// ::= 'amdgpu_ls'
2181/// ::= 'amdgpu_hs'
2182/// ::= 'amdgpu_es'
2183/// ::= 'amdgpu_gs'
2184/// ::= 'amdgpu_ps'
2185/// ::= 'amdgpu_cs'
2186/// ::= 'amdgpu_cs_chain'
2187/// ::= 'amdgpu_cs_chain_preserve'
2188/// ::= 'amdgpu_kernel'
2189/// ::= 'tailcc'
2190/// ::= 'm68k_rtdcc'
2191/// ::= 'graalcc'
2192/// ::= 'riscv_vector_cc'
2193/// ::= 'cc' UINT
2194///
2195bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2196 switch (Lex.getKind()) {
2197 default: CC = CallingConv::C; return false;
2198 case lltok::kw_ccc: CC = CallingConv::C; break;
2199 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2200 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2213 break;
2216 break;
2219 break;
2222 break;
2237 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2241 case lltok::kw_hhvmcc:
2243 break;
2244 case lltok::kw_hhvm_ccc:
2246 break;
2258 break;
2261 break;
2263 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2268 break;
2269 case lltok::kw_cc: {
2270 Lex.Lex();
2271 return parseUInt32(CC);
2272 }
2273 }
2274
2275 Lex.Lex();
2276 return false;
2277}
2278
2279/// parseMetadataAttachment
2280/// ::= !dbg !42
2281bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2282 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2283
2284 std::string Name = Lex.getStrVal();
2285 Kind = M->getMDKindID(Name);
2286 Lex.Lex();
2287
2288 return parseMDNode(MD);
2289}
2290
2291/// parseInstructionMetadata
2292/// ::= !dbg !42 (',' !dbg !57)*
2293bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2294 do {
2295 if (Lex.getKind() != lltok::MetadataVar)
2296 return tokError("expected metadata after comma");
2297
2298 unsigned MDK;
2299 MDNode *N;
2300 if (parseMetadataAttachment(MDK, N))
2301 return true;
2302
2303 if (MDK == LLVMContext::MD_DIAssignID)
2304 TempDIAssignIDAttachments[N].push_back(&Inst);
2305 else
2306 Inst.setMetadata(MDK, N);
2307
2308 if (MDK == LLVMContext::MD_tbaa)
2309 InstsWithTBAATag.push_back(&Inst);
2310
2311 // If this is the end of the list, we're done.
2312 } while (EatIfPresent(lltok::comma));
2313 return false;
2314}
2315
2316/// parseGlobalObjectMetadataAttachment
2317/// ::= !dbg !57
2318bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2319 unsigned MDK;
2320 MDNode *N;
2321 if (parseMetadataAttachment(MDK, N))
2322 return true;
2323
2324 GO.addMetadata(MDK, *N);
2325 return false;
2326}
2327
2328/// parseOptionalFunctionMetadata
2329/// ::= (!dbg !57)*
2330bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2331 while (Lex.getKind() == lltok::MetadataVar)
2332 if (parseGlobalObjectMetadataAttachment(F))
2333 return true;
2334 return false;
2335}
2336
2337/// parseOptionalAlignment
2338/// ::= /* empty */
2339/// ::= 'align' 4
2340bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2341 Alignment = std::nullopt;
2342 if (!EatIfPresent(lltok::kw_align))
2343 return false;
2344 LocTy AlignLoc = Lex.getLoc();
2345 uint64_t Value = 0;
2346
2347 LocTy ParenLoc = Lex.getLoc();
2348 bool HaveParens = false;
2349 if (AllowParens) {
2350 if (EatIfPresent(lltok::lparen))
2351 HaveParens = true;
2352 }
2353
2354 if (parseUInt64(Value))
2355 return true;
2356
2357 if (HaveParens && !EatIfPresent(lltok::rparen))
2358 return error(ParenLoc, "expected ')'");
2359
2360 if (!isPowerOf2_64(Value))
2361 return error(AlignLoc, "alignment is not a power of two");
2363 return error(AlignLoc, "huge alignments are not supported yet");
2364 Alignment = Align(Value);
2365 return false;
2366}
2367
2368/// parseOptionalCodeModel
2369/// ::= /* empty */
2370/// ::= 'code_model' "large"
2371bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2372 Lex.Lex();
2373 auto StrVal = Lex.getStrVal();
2374 auto ErrMsg = "expected global code model string";
2375 if (StrVal == "tiny")
2376 model = CodeModel::Tiny;
2377 else if (StrVal == "small")
2378 model = CodeModel::Small;
2379 else if (StrVal == "kernel")
2380 model = CodeModel::Kernel;
2381 else if (StrVal == "medium")
2382 model = CodeModel::Medium;
2383 else if (StrVal == "large")
2384 model = CodeModel::Large;
2385 else
2386 return tokError(ErrMsg);
2387 if (parseToken(lltok::StringConstant, ErrMsg))
2388 return true;
2389 return false;
2390}
2391
2392/// parseOptionalDerefAttrBytes
2393/// ::= /* empty */
2394/// ::= AttrKind '(' 4 ')'
2395///
2396/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2397bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2398 uint64_t &Bytes) {
2399 assert((AttrKind == lltok::kw_dereferenceable ||
2400 AttrKind == lltok::kw_dereferenceable_or_null) &&
2401 "contract!");
2402
2403 Bytes = 0;
2404 if (!EatIfPresent(AttrKind))
2405 return false;
2406 LocTy ParenLoc = Lex.getLoc();
2407 if (!EatIfPresent(lltok::lparen))
2408 return error(ParenLoc, "expected '('");
2409 LocTy DerefLoc = Lex.getLoc();
2410 if (parseUInt64(Bytes))
2411 return true;
2412 ParenLoc = Lex.getLoc();
2413 if (!EatIfPresent(lltok::rparen))
2414 return error(ParenLoc, "expected ')'");
2415 if (!Bytes)
2416 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2417 return false;
2418}
2419
2420bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2421 Lex.Lex();
2423 if (!EatIfPresent(lltok::lparen))
2424 return false;
2425 LocTy KindLoc = Lex.getLoc();
2426 if (Lex.getKind() == lltok::kw_sync)
2428 else if (Lex.getKind() == lltok::kw_async)
2430 else
2431 return error(KindLoc, "expected unwind table kind");
2432 Lex.Lex();
2433 return parseToken(lltok::rparen, "expected ')'");
2434}
2435
2436bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2437 Lex.Lex();
2438 LocTy ParenLoc = Lex.getLoc();
2439 if (!EatIfPresent(lltok::lparen))
2440 return error(ParenLoc, "expected '('");
2441 LocTy KindLoc = Lex.getLoc();
2442 std::string Arg;
2443 if (parseStringConstant(Arg))
2444 return error(KindLoc, "expected allockind value");
2445 for (StringRef A : llvm::split(Arg, ",")) {
2446 if (A == "alloc") {
2448 } else if (A == "realloc") {
2450 } else if (A == "free") {
2452 } else if (A == "uninitialized") {
2454 } else if (A == "zeroed") {
2456 } else if (A == "aligned") {
2458 } else {
2459 return error(KindLoc, Twine("unknown allockind ") + A);
2460 }
2461 }
2462 ParenLoc = Lex.getLoc();
2463 if (!EatIfPresent(lltok::rparen))
2464 return error(ParenLoc, "expected ')'");
2465 if (Kind == AllocFnKind::Unknown)
2466 return error(KindLoc, "expected allockind value");
2467 return false;
2468}
2469
2470static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2471 switch (Tok) {
2472 case lltok::kw_argmem:
2473 return IRMemLocation::ArgMem;
2476 default:
2477 return std::nullopt;
2478 }
2479}
2480
2481static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2482 switch (Tok) {
2483 case lltok::kw_none:
2484 return ModRefInfo::NoModRef;
2485 case lltok::kw_read:
2486 return ModRefInfo::Ref;
2487 case lltok::kw_write:
2488 return ModRefInfo::Mod;
2490 return ModRefInfo::ModRef;
2491 default:
2492 return std::nullopt;
2493 }
2494}
2495
2496std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2498
2499 // We use syntax like memory(argmem: read), so the colon should not be
2500 // interpreted as a label terminator.
2502 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2503
2504 Lex.Lex();
2505 if (!EatIfPresent(lltok::lparen)) {
2506 tokError("expected '('");
2507 return std::nullopt;
2508 }
2509
2510 bool SeenLoc = false;
2511 do {
2512 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2513 if (Loc) {
2514 Lex.Lex();
2515 if (!EatIfPresent(lltok::colon)) {
2516 tokError("expected ':' after location");
2517 return std::nullopt;
2518 }
2519 }
2520
2521 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2522 if (!MR) {
2523 if (!Loc)
2524 tokError("expected memory location (argmem, inaccessiblemem) "
2525 "or access kind (none, read, write, readwrite)");
2526 else
2527 tokError("expected access kind (none, read, write, readwrite)");
2528 return std::nullopt;
2529 }
2530
2531 Lex.Lex();
2532 if (Loc) {
2533 SeenLoc = true;
2534 ME = ME.getWithModRef(*Loc, *MR);
2535 } else {
2536 if (SeenLoc) {
2537 tokError("default access kind must be specified first");
2538 return std::nullopt;
2539 }
2540 ME = MemoryEffects(*MR);
2541 }
2542
2543 if (EatIfPresent(lltok::rparen))
2544 return ME;
2545 } while (EatIfPresent(lltok::comma));
2546
2547 tokError("unterminated memory attribute");
2548 return std::nullopt;
2549}
2550
2551static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2552 switch (Tok) {
2553 case lltok::kw_all:
2554 return fcAllFlags;
2555 case lltok::kw_nan:
2556 return fcNan;
2557 case lltok::kw_snan:
2558 return fcSNan;
2559 case lltok::kw_qnan:
2560 return fcQNan;
2561 case lltok::kw_inf:
2562 return fcInf;
2563 case lltok::kw_ninf:
2564 return fcNegInf;
2565 case lltok::kw_pinf:
2566 return fcPosInf;
2567 case lltok::kw_norm:
2568 return fcNormal;
2569 case lltok::kw_nnorm:
2570 return fcNegNormal;
2571 case lltok::kw_pnorm:
2572 return fcPosNormal;
2573 case lltok::kw_sub:
2574 return fcSubnormal;
2575 case lltok::kw_nsub:
2576 return fcNegSubnormal;
2577 case lltok::kw_psub:
2578 return fcPosSubnormal;
2579 case lltok::kw_zero:
2580 return fcZero;
2581 case lltok::kw_nzero:
2582 return fcNegZero;
2583 case lltok::kw_pzero:
2584 return fcPosZero;
2585 default:
2586 return 0;
2587 }
2588}
2589
2590unsigned LLParser::parseNoFPClassAttr() {
2591 unsigned Mask = fcNone;
2592
2593 Lex.Lex();
2594 if (!EatIfPresent(lltok::lparen)) {
2595 tokError("expected '('");
2596 return 0;
2597 }
2598
2599 do {
2600 uint64_t Value = 0;
2601 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2602 if (TestMask != 0) {
2603 Mask |= TestMask;
2604 // TODO: Disallow overlapping masks to avoid copy paste errors
2605 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2606 !parseUInt64(Value)) {
2607 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2608 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2609 return 0;
2610 }
2611
2612 if (!EatIfPresent(lltok::rparen)) {
2613 error(Lex.getLoc(), "expected ')'");
2614 return 0;
2615 }
2616
2617 return Value;
2618 } else {
2619 error(Lex.getLoc(), "expected nofpclass test mask");
2620 return 0;
2621 }
2622
2623 Lex.Lex();
2624 if (EatIfPresent(lltok::rparen))
2625 return Mask;
2626 } while (1);
2627
2628 llvm_unreachable("unterminated nofpclass attribute");
2629}
2630
2631/// parseOptionalCommaAlign
2632/// ::=
2633/// ::= ',' align 4
2634///
2635/// This returns with AteExtraComma set to true if it ate an excess comma at the
2636/// end.
2637bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2638 bool &AteExtraComma) {
2639 AteExtraComma = false;
2640 while (EatIfPresent(lltok::comma)) {
2641 // Metadata at the end is an early exit.
2642 if (Lex.getKind() == lltok::MetadataVar) {
2643 AteExtraComma = true;
2644 return false;
2645 }
2646
2647 if (Lex.getKind() != lltok::kw_align)
2648 return error(Lex.getLoc(), "expected metadata or 'align'");
2649
2650 if (parseOptionalAlignment(Alignment))
2651 return true;
2652 }
2653
2654 return false;
2655}
2656
2657/// parseOptionalCommaAddrSpace
2658/// ::=
2659/// ::= ',' addrspace(1)
2660///
2661/// This returns with AteExtraComma set to true if it ate an excess comma at the
2662/// end.
2663bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2664 bool &AteExtraComma) {
2665 AteExtraComma = false;
2666 while (EatIfPresent(lltok::comma)) {
2667 // Metadata at the end is an early exit.
2668 if (Lex.getKind() == lltok::MetadataVar) {
2669 AteExtraComma = true;
2670 return false;
2671 }
2672
2673 Loc = Lex.getLoc();
2674 if (Lex.getKind() != lltok::kw_addrspace)
2675 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2676
2677 if (parseOptionalAddrSpace(AddrSpace))
2678 return true;
2679 }
2680
2681 return false;
2682}
2683
2684bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2685 std::optional<unsigned> &HowManyArg) {
2686 Lex.Lex();
2687
2688 auto StartParen = Lex.getLoc();
2689 if (!EatIfPresent(lltok::lparen))
2690 return error(StartParen, "expected '('");
2691
2692 if (parseUInt32(BaseSizeArg))
2693 return true;
2694
2695 if (EatIfPresent(lltok::comma)) {
2696 auto HowManyAt = Lex.getLoc();
2697 unsigned HowMany;
2698 if (parseUInt32(HowMany))
2699 return true;
2700 if (HowMany == BaseSizeArg)
2701 return error(HowManyAt,
2702 "'allocsize' indices can't refer to the same parameter");
2703 HowManyArg = HowMany;
2704 } else
2705 HowManyArg = std::nullopt;
2706
2707 auto EndParen = Lex.getLoc();
2708 if (!EatIfPresent(lltok::rparen))
2709 return error(EndParen, "expected ')'");
2710 return false;
2711}
2712
2713bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2714 unsigned &MaxValue) {
2715 Lex.Lex();
2716
2717 auto StartParen = Lex.getLoc();
2718 if (!EatIfPresent(lltok::lparen))
2719 return error(StartParen, "expected '('");
2720
2721 if (parseUInt32(MinValue))
2722 return true;
2723
2724 if (EatIfPresent(lltok::comma)) {
2725 if (parseUInt32(MaxValue))
2726 return true;
2727 } else
2728 MaxValue = MinValue;
2729
2730 auto EndParen = Lex.getLoc();
2731 if (!EatIfPresent(lltok::rparen))
2732 return error(EndParen, "expected ')'");
2733 return false;
2734}
2735
2736/// parseScopeAndOrdering
2737/// if isAtomic: ::= SyncScope? AtomicOrdering
2738/// else: ::=
2739///
2740/// This sets Scope and Ordering to the parsed values.
2741bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2742 AtomicOrdering &Ordering) {
2743 if (!IsAtomic)
2744 return false;
2745
2746 return parseScope(SSID) || parseOrdering(Ordering);
2747}
2748
2749/// parseScope
2750/// ::= syncscope("singlethread" | "<target scope>")?
2751///
2752/// This sets synchronization scope ID to the ID of the parsed value.
2753bool LLParser::parseScope(SyncScope::ID &SSID) {
2754 SSID = SyncScope::System;
2755 if (EatIfPresent(lltok::kw_syncscope)) {
2756 auto StartParenAt = Lex.getLoc();
2757 if (!EatIfPresent(lltok::lparen))
2758 return error(StartParenAt, "Expected '(' in syncscope");
2759
2760 std::string SSN;
2761 auto SSNAt = Lex.getLoc();
2762 if (parseStringConstant(SSN))
2763 return error(SSNAt, "Expected synchronization scope name");
2764
2765 auto EndParenAt = Lex.getLoc();
2766 if (!EatIfPresent(lltok::rparen))
2767 return error(EndParenAt, "Expected ')' in syncscope");
2768
2769 SSID = Context.getOrInsertSyncScopeID(SSN);
2770 }
2771
2772 return false;
2773}
2774
2775/// parseOrdering
2776/// ::= AtomicOrdering
2777///
2778/// This sets Ordering to the parsed value.
2779bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2780 switch (Lex.getKind()) {
2781 default:
2782 return tokError("Expected ordering on atomic instruction");
2783 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2784 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2785 // Not specified yet:
2786 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2787 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2788 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2789 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2790 case lltok::kw_seq_cst:
2792 break;
2793 }
2794 Lex.Lex();
2795 return false;
2796}
2797
2798/// parseOptionalStackAlignment
2799/// ::= /* empty */
2800/// ::= 'alignstack' '(' 4 ')'
2801bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2802 Alignment = 0;
2803 if (!EatIfPresent(lltok::kw_alignstack))
2804 return false;
2805 LocTy ParenLoc = Lex.getLoc();
2806 if (!EatIfPresent(lltok::lparen))
2807 return error(ParenLoc, "expected '('");
2808 LocTy AlignLoc = Lex.getLoc();
2809 if (parseUInt32(Alignment))
2810 return true;
2811 ParenLoc = Lex.getLoc();
2812 if (!EatIfPresent(lltok::rparen))
2813 return error(ParenLoc, "expected ')'");
2814 if (!isPowerOf2_32(Alignment))
2815 return error(AlignLoc, "stack alignment is not a power of two");
2816 return false;
2817}
2818
2819/// parseIndexList - This parses the index list for an insert/extractvalue
2820/// instruction. This sets AteExtraComma in the case where we eat an extra
2821/// comma at the end of the line and find that it is followed by metadata.
2822/// Clients that don't allow metadata can call the version of this function that
2823/// only takes one argument.
2824///
2825/// parseIndexList
2826/// ::= (',' uint32)+
2827///
2828bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2829 bool &AteExtraComma) {
2830 AteExtraComma = false;
2831
2832 if (Lex.getKind() != lltok::comma)
2833 return tokError("expected ',' as start of index list");
2834
2835 while (EatIfPresent(lltok::comma)) {
2836 if (Lex.getKind() == lltok::MetadataVar) {
2837 if (Indices.empty())
2838 return tokError("expected index");
2839 AteExtraComma = true;
2840 return false;
2841 }
2842 unsigned Idx = 0;
2843 if (parseUInt32(Idx))
2844 return true;
2845 Indices.push_back(Idx);
2846 }
2847
2848 return false;
2849}
2850
2851//===----------------------------------------------------------------------===//
2852// Type Parsing.
2853//===----------------------------------------------------------------------===//
2854
2855/// parseType - parse a type.
2856bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2857 SMLoc TypeLoc = Lex.getLoc();
2858 switch (Lex.getKind()) {
2859 default:
2860 return tokError(Msg);
2861 case lltok::Type:
2862 // Type ::= 'float' | 'void' (etc)
2863 Result = Lex.getTyVal();
2864 Lex.Lex();
2865
2866 // Handle "ptr" opaque pointer type.
2867 //
2868 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2869 if (Result->isPointerTy()) {
2870 unsigned AddrSpace;
2871 if (parseOptionalAddrSpace(AddrSpace))
2872 return true;
2873 Result = PointerType::get(getContext(), AddrSpace);
2874
2875 // Give a nice error for 'ptr*'.
2876 if (Lex.getKind() == lltok::star)
2877 return tokError("ptr* is invalid - use ptr instead");
2878
2879 // Fall through to parsing the type suffixes only if this 'ptr' is a
2880 // function return. Otherwise, return success, implicitly rejecting other
2881 // suffixes.
2882 if (Lex.getKind() != lltok::lparen)
2883 return false;
2884 }
2885 break;
2886 case lltok::kw_target: {
2887 // Type ::= TargetExtType
2888 if (parseTargetExtType(Result))
2889 return true;
2890 break;
2891 }
2892 case lltok::lbrace:
2893 // Type ::= StructType
2894 if (parseAnonStructType(Result, false))
2895 return true;
2896 break;
2897 case lltok::lsquare:
2898 // Type ::= '[' ... ']'
2899 Lex.Lex(); // eat the lsquare.
2900 if (parseArrayVectorType(Result, false))
2901 return true;
2902 break;
2903 case lltok::less: // Either vector or packed struct.
2904 // Type ::= '<' ... '>'
2905 Lex.Lex();
2906 if (Lex.getKind() == lltok::lbrace) {
2907 if (parseAnonStructType(Result, true) ||
2908 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2909 return true;
2910 } else if (parseArrayVectorType(Result, true))
2911 return true;
2912 break;
2913 case lltok::LocalVar: {
2914 // Type ::= %foo
2915 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2916
2917 // If the type hasn't been defined yet, create a forward definition and
2918 // remember where that forward def'n was seen (in case it never is defined).
2919 if (!Entry.first) {
2920 Entry.first = StructType::create(Context, Lex.getStrVal());
2921 Entry.second = Lex.getLoc();
2922 }
2923 Result = Entry.first;
2924 Lex.Lex();
2925 break;
2926 }
2927
2928 case lltok::LocalVarID: {
2929 // Type ::= %4
2930 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2931
2932 // If the type hasn't been defined yet, create a forward definition and
2933 // remember where that forward def'n was seen (in case it never is defined).
2934 if (!Entry.first) {
2935 Entry.first = StructType::create(Context);
2936 Entry.second = Lex.getLoc();
2937 }
2938 Result = Entry.first;
2939 Lex.Lex();
2940 break;
2941 }
2942 }
2943
2944 // parse the type suffixes.
2945 while (true) {
2946 switch (Lex.getKind()) {
2947 // End of type.
2948 default:
2949 if (!AllowVoid && Result->isVoidTy())
2950 return error(TypeLoc, "void type only allowed for function results");
2951 return false;
2952
2953 // Type ::= Type '*'
2954 case lltok::star:
2955 if (Result->isLabelTy())
2956 return tokError("basic block pointers are invalid");
2957 if (Result->isVoidTy())
2958 return tokError("pointers to void are invalid - use i8* instead");
2960 return tokError("pointer to this type is invalid");
2962 Lex.Lex();
2963 break;
2964
2965 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2966 case lltok::kw_addrspace: {
2967 if (Result->isLabelTy())
2968 return tokError("basic block pointers are invalid");
2969 if (Result->isVoidTy())
2970 return tokError("pointers to void are invalid; use i8* instead");
2972 return tokError("pointer to this type is invalid");
2973 unsigned AddrSpace;
2974 if (parseOptionalAddrSpace(AddrSpace) ||
2975 parseToken(lltok::star, "expected '*' in address space"))
2976 return true;
2977
2978 Result = PointerType::get(Result, AddrSpace);
2979 break;
2980 }
2981
2982 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2983 case lltok::lparen:
2984 if (parseFunctionType(Result))
2985 return true;
2986 break;
2987 }
2988 }
2989}
2990
2991/// parseParameterList
2992/// ::= '(' ')'
2993/// ::= '(' Arg (',' Arg)* ')'
2994/// Arg
2995/// ::= Type OptionalAttributes Value OptionalAttributes
2996bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2997 PerFunctionState &PFS, bool IsMustTailCall,
2998 bool InVarArgsFunc) {
2999 if (parseToken(lltok::lparen, "expected '(' in call"))
3000 return true;
3001
3002 while (Lex.getKind() != lltok::rparen) {
3003 // If this isn't the first argument, we need a comma.
3004 if (!ArgList.empty() &&
3005 parseToken(lltok::comma, "expected ',' in argument list"))
3006 return true;
3007
3008 // parse an ellipsis if this is a musttail call in a variadic function.
3009 if (Lex.getKind() == lltok::dotdotdot) {
3010 const char *Msg = "unexpected ellipsis in argument list for ";
3011 if (!IsMustTailCall)
3012 return tokError(Twine(Msg) + "non-musttail call");
3013 if (!InVarArgsFunc)
3014 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3015 Lex.Lex(); // Lex the '...', it is purely for readability.
3016 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3017 }
3018
3019 // parse the argument.
3020 LocTy ArgLoc;
3021 Type *ArgTy = nullptr;
3022 Value *V;
3023 if (parseType(ArgTy, ArgLoc))
3024 return true;
3025
3026 AttrBuilder ArgAttrs(M->getContext());
3027
3028 if (ArgTy->isMetadataTy()) {
3029 if (parseMetadataAsValue(V, PFS))
3030 return true;
3031 } else {
3032 // Otherwise, handle normal operands.
3033 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3034 return true;
3035 }
3036 ArgList.push_back(ParamInfo(
3037 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3038 }
3039
3040 if (IsMustTailCall && InVarArgsFunc)
3041 return tokError("expected '...' at end of argument list for musttail call "
3042 "in varargs function");
3043
3044 Lex.Lex(); // Lex the ')'.
3045 return false;
3046}
3047
3048/// parseRequiredTypeAttr
3049/// ::= attrname(<ty>)
3050bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3051 Attribute::AttrKind AttrKind) {
3052 Type *Ty = nullptr;
3053 if (!EatIfPresent(AttrToken))
3054 return true;
3055 if (!EatIfPresent(lltok::lparen))
3056 return error(Lex.getLoc(), "expected '('");
3057 if (parseType(Ty))
3058 return true;
3059 if (!EatIfPresent(lltok::rparen))
3060 return error(Lex.getLoc(), "expected ')'");
3061
3062 B.addTypeAttr(AttrKind, Ty);
3063 return false;
3064}
3065
3066/// parseRangeAttr
3067/// ::= range(<ty> <n>,<n>)
3068bool LLParser::parseRangeAttr(AttrBuilder &B) {
3069 Lex.Lex();
3070
3071 APInt Lower;
3072 APInt Upper;
3073 Type *Ty = nullptr;
3074 LocTy TyLoc;
3075
3076 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3077 if (Lex.getKind() != lltok::APSInt)
3078 return tokError("expected integer");
3079 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3080 return tokError(
3081 "integer is too large for the bit width of specified type");
3082 Val = Lex.getAPSIntVal().extend(BitWidth);
3083 Lex.Lex();
3084 return false;
3085 };
3086
3087 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3088 return true;
3089 if (!Ty->isIntegerTy())
3090 return error(TyLoc, "the range must have integer type!");
3091
3092 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3093
3094 if (ParseAPSInt(BitWidth, Lower) ||
3095 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3096 return true;
3097 if (Lower == Upper)
3098 return tokError("the range should not represent the full or empty set!");
3099
3100 if (parseToken(lltok::rparen, "expected ')'"))
3101 return true;
3102
3103 B.addRangeAttr(ConstantRange(Lower, Upper));
3104 return false;
3105}
3106
3107/// parseInitializesAttr
3108/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3109bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3110 Lex.Lex();
3111
3112 auto ParseAPSInt = [&](APInt &Val) {
3113 if (Lex.getKind() != lltok::APSInt)
3114 return tokError("expected integer");
3115 Val = Lex.getAPSIntVal().extend(64);
3116 Lex.Lex();
3117 return false;
3118 };
3119
3120 if (parseToken(lltok::lparen, "expected '('"))
3121 return true;
3122
3124 // Parse each constant range.
3125 do {
3126 APInt Lower, Upper;
3127 if (parseToken(lltok::lparen, "expected '('"))
3128 return true;
3129
3130 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3131 ParseAPSInt(Upper))
3132 return true;
3133
3134 if (Lower == Upper)
3135 return tokError("the range should not represent the full or empty set!");
3136
3137 if (parseToken(lltok::rparen, "expected ')'"))
3138 return true;
3139
3140 RangeList.push_back(ConstantRange(Lower, Upper));
3141 } while (EatIfPresent(lltok::comma));
3142
3143 if (parseToken(lltok::rparen, "expected ')'"))
3144 return true;
3145
3146 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3147 if (!CRLOrNull.has_value())
3148 return tokError("Invalid (unordered or overlapping) range list");
3149 B.addInitializesAttr(*CRLOrNull);
3150 return false;
3151}
3152
3153/// parseOptionalOperandBundles
3154/// ::= /*empty*/
3155/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3156///
3157/// OperandBundle
3158/// ::= bundle-tag '(' ')'
3159/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3160///
3161/// bundle-tag ::= String Constant
3162bool LLParser::parseOptionalOperandBundles(
3163 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3164 LocTy BeginLoc = Lex.getLoc();
3165 if (!EatIfPresent(lltok::lsquare))
3166 return false;
3167
3168 while (Lex.getKind() != lltok::rsquare) {
3169 // If this isn't the first operand bundle, we need a comma.
3170 if (!BundleList.empty() &&
3171 parseToken(lltok::comma, "expected ',' in input list"))
3172 return true;
3173
3174 std::string Tag;
3175 if (parseStringConstant(Tag))
3176 return true;
3177
3178 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3179 return true;
3180
3181 std::vector<Value *> Inputs;
3182 while (Lex.getKind() != lltok::rparen) {
3183 // If this isn't the first input, we need a comma.
3184 if (!Inputs.empty() &&
3185 parseToken(lltok::comma, "expected ',' in input list"))
3186 return true;
3187
3188 Type *Ty = nullptr;
3189 Value *Input = nullptr;
3190 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3191 return true;
3192 Inputs.push_back(Input);
3193 }
3194
3195 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3196
3197 Lex.Lex(); // Lex the ')'.
3198 }
3199
3200 if (BundleList.empty())
3201 return error(BeginLoc, "operand bundle set must not be empty");
3202
3203 Lex.Lex(); // Lex the ']'.
3204 return false;
3205}
3206
3207bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3208 unsigned NextID, unsigned ID) const {
3209 if (ID < NextID)
3210 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3211 Twine(NextID) + "' or greater");
3212
3213 return false;
3214}
3215
3216/// parseArgumentList - parse the argument list for a function type or function
3217/// prototype.
3218/// ::= '(' ArgTypeListI ')'
3219/// ArgTypeListI
3220/// ::= /*empty*/
3221/// ::= '...'
3222/// ::= ArgTypeList ',' '...'
3223/// ::= ArgType (',' ArgType)*
3224///
3225bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3226 SmallVectorImpl<unsigned> &UnnamedArgNums,
3227 bool &IsVarArg) {
3228 unsigned CurValID = 0;
3229 IsVarArg = false;
3230 assert(Lex.getKind() == lltok::lparen);
3231 Lex.Lex(); // eat the (.
3232
3233 if (Lex.getKind() != lltok::rparen) {
3234 do {
3235 // Handle ... at end of arg list.
3236 if (EatIfPresent(lltok::dotdotdot)) {
3237 IsVarArg = true;
3238 break;
3239 }
3240
3241 // Otherwise must be an argument type.
3242 LocTy TypeLoc = Lex.getLoc();
3243 Type *ArgTy = nullptr;
3244 AttrBuilder Attrs(M->getContext());
3245 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3246 return true;
3247
3248 if (ArgTy->isVoidTy())
3249 return error(TypeLoc, "argument can not have void type");
3250
3251 std::string Name;
3252 if (Lex.getKind() == lltok::LocalVar) {
3253 Name = Lex.getStrVal();
3254 Lex.Lex();
3255 } else {
3256 unsigned ArgID;
3257 if (Lex.getKind() == lltok::LocalVarID) {
3258 ArgID = Lex.getUIntVal();
3259 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3260 return true;
3261 Lex.Lex();
3262 } else {
3263 ArgID = CurValID;
3264 }
3265 UnnamedArgNums.push_back(ArgID);
3266 CurValID = ArgID + 1;
3267 }
3268
3269 if (!ArgTy->isFirstClassType())
3270 return error(TypeLoc, "invalid type for function argument");
3271
3272 ArgList.emplace_back(TypeLoc, ArgTy,
3273 AttributeSet::get(ArgTy->getContext(), Attrs),
3274 std::move(Name));
3275 } while (EatIfPresent(lltok::comma));
3276 }
3277
3278 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3279}
3280
3281/// parseFunctionType
3282/// ::= Type ArgumentList OptionalAttrs
3283bool LLParser::parseFunctionType(Type *&Result) {
3284 assert(Lex.getKind() == lltok::lparen);
3285
3287 return tokError("invalid function return type");
3288
3290 bool IsVarArg;
3291 SmallVector<unsigned> UnnamedArgNums;
3292 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3293 return true;
3294
3295 // Reject names on the arguments lists.
3296 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3297 if (!ArgList[i].Name.empty())
3298 return error(ArgList[i].Loc, "argument name invalid in function type");
3299 if (ArgList[i].Attrs.hasAttributes())
3300 return error(ArgList[i].Loc,
3301 "argument attributes invalid in function type");
3302 }
3303
3304 SmallVector<Type*, 16> ArgListTy;
3305 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3306 ArgListTy.push_back(ArgList[i].Ty);
3307
3308 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3309 return false;
3310}
3311
3312/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3313/// other structs.
3314bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3316 if (parseStructBody(Elts))
3317 return true;
3318
3319 Result = StructType::get(Context, Elts, Packed);
3320 return false;
3321}
3322
3323/// parseStructDefinition - parse a struct in a 'type' definition.
3324bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3325 std::pair<Type *, LocTy> &Entry,
3326 Type *&ResultTy) {
3327 // If the type was already defined, diagnose the redefinition.
3328 if (Entry.first && !Entry.second.isValid())
3329 return error(TypeLoc, "redefinition of type");
3330
3331 // If we have opaque, just return without filling in the definition for the
3332 // struct. This counts as a definition as far as the .ll file goes.
3333 if (EatIfPresent(lltok::kw_opaque)) {
3334 // This type is being defined, so clear the location to indicate this.
3335 Entry.second = SMLoc();
3336
3337 // If this type number has never been uttered, create it.
3338 if (!Entry.first)
3339 Entry.first = StructType::create(Context, Name);
3340 ResultTy = Entry.first;
3341 return false;
3342 }
3343
3344 // If the type starts with '<', then it is either a packed struct or a vector.
3345 bool isPacked = EatIfPresent(lltok::less);
3346
3347 // If we don't have a struct, then we have a random type alias, which we
3348 // accept for compatibility with old files. These types are not allowed to be
3349 // forward referenced and not allowed to be recursive.
3350 if (Lex.getKind() != lltok::lbrace) {
3351 if (Entry.first)
3352 return error(TypeLoc, "forward references to non-struct type");
3353
3354 ResultTy = nullptr;
3355 if (isPacked)
3356 return parseArrayVectorType(ResultTy, true);
3357 return parseType(ResultTy);
3358 }
3359
3360 // This type is being defined, so clear the location to indicate this.
3361 Entry.second = SMLoc();
3362
3363 // If this type number has never been uttered, create it.
3364 if (!Entry.first)
3365 Entry.first = StructType::create(Context, Name);
3366
3367 StructType *STy = cast<StructType>(Entry.first);
3368
3370 if (parseStructBody(Body) ||
3371 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3372 return true;
3373
3374 STy->setBody(Body, isPacked);
3375 ResultTy = STy;
3376 return false;
3377}
3378
3379/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3380/// StructType
3381/// ::= '{' '}'
3382/// ::= '{' Type (',' Type)* '}'
3383/// ::= '<' '{' '}' '>'
3384/// ::= '<' '{' Type (',' Type)* '}' '>'
3385bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3386 assert(Lex.getKind() == lltok::lbrace);
3387 Lex.Lex(); // Consume the '{'
3388
3389 // Handle the empty struct.
3390 if (EatIfPresent(lltok::rbrace))
3391 return false;
3392
3393 LocTy EltTyLoc = Lex.getLoc();
3394 Type *Ty = nullptr;
3395 if (parseType(Ty))
3396 return true;
3397 Body.push_back(Ty);
3398
3400 return error(EltTyLoc, "invalid element type for struct");
3401
3402 while (EatIfPresent(lltok::comma)) {
3403 EltTyLoc = Lex.getLoc();
3404 if (parseType(Ty))
3405 return true;
3406
3408 return error(EltTyLoc, "invalid element type for struct");
3409
3410 Body.push_back(Ty);
3411 }
3412
3413 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3414}
3415
3416/// parseArrayVectorType - parse an array or vector type, assuming the first
3417/// token has already been consumed.
3418/// Type
3419/// ::= '[' APSINTVAL 'x' Types ']'
3420/// ::= '<' APSINTVAL 'x' Types '>'
3421/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3422bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3423 bool Scalable = false;
3424
3425 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3426 Lex.Lex(); // consume the 'vscale'
3427 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3428 return true;
3429
3430 Scalable = true;
3431 }
3432
3433 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3434 Lex.getAPSIntVal().getBitWidth() > 64)
3435 return tokError("expected number in address space");
3436
3437 LocTy SizeLoc = Lex.getLoc();
3439 Lex.Lex();
3440
3441 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3442 return true;
3443
3444 LocTy TypeLoc = Lex.getLoc();
3445 Type *EltTy = nullptr;
3446 if (parseType(EltTy))
3447 return true;
3448
3449 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3450 "expected end of sequential type"))
3451 return true;
3452
3453 if (IsVector) {
3454 if (Size == 0)
3455 return error(SizeLoc, "zero element vector is illegal");
3456 if ((unsigned)Size != Size)
3457 return error(SizeLoc, "size too large for vector");
3459 return error(TypeLoc, "invalid vector element type");
3460 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3461 } else {
3463 return error(TypeLoc, "invalid array element type");
3464 Result = ArrayType::get(EltTy, Size);
3465 }
3466 return false;
3467}
3468
3469/// parseTargetExtType - handle target extension type syntax
3470/// TargetExtType
3471/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3472///
3473/// TargetExtTypeParams
3474/// ::= /*empty*/
3475/// ::= ',' Type TargetExtTypeParams
3476///
3477/// TargetExtIntParams
3478/// ::= /*empty*/
3479/// ::= ',' uint32 TargetExtIntParams
3480bool LLParser::parseTargetExtType(Type *&Result) {
3481 Lex.Lex(); // Eat the 'target' keyword.
3482
3483 // Get the mandatory type name.
3484 std::string TypeName;
3485 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3486 parseStringConstant(TypeName))
3487 return true;
3488
3489 // Parse all of the integer and type parameters at the same time; the use of
3490 // SeenInt will allow us to catch cases where type parameters follow integer
3491 // parameters.
3492 SmallVector<Type *> TypeParams;
3493 SmallVector<unsigned> IntParams;
3494 bool SeenInt = false;
3495 while (Lex.getKind() == lltok::comma) {
3496 Lex.Lex(); // Eat the comma.
3497
3498 if (Lex.getKind() == lltok::APSInt) {
3499 SeenInt = true;
3500 unsigned IntVal;
3501 if (parseUInt32(IntVal))
3502 return true;
3503 IntParams.push_back(IntVal);
3504 } else if (SeenInt) {
3505 // The only other kind of parameter we support is type parameters, which
3506 // must precede the integer parameters. This is therefore an error.
3507 return tokError("expected uint32 param");
3508 } else {
3509 Type *TypeParam;
3510 if (parseType(TypeParam, /*AllowVoid=*/true))
3511 return true;
3512 TypeParams.push_back(TypeParam);
3513 }
3514 }
3515
3516 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3517 return true;
3518
3519 Result = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
3520 return false;
3521}
3522
3523//===----------------------------------------------------------------------===//
3524// Function Semantic Analysis.
3525//===----------------------------------------------------------------------===//
3526
3527LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3528 int functionNumber,
3529 ArrayRef<unsigned> UnnamedArgNums)
3530 : P(p), F(f), FunctionNumber(functionNumber) {
3531
3532 // Insert unnamed arguments into the NumberedVals list.
3533 auto It = UnnamedArgNums.begin();
3534 for (Argument &A : F.args()) {
3535 if (!A.hasName()) {
3536 unsigned ArgNum = *It++;
3537 NumberedVals.add(ArgNum, &A);
3538 }
3539 }
3540}
3541
3542LLParser::PerFunctionState::~PerFunctionState() {
3543 // If there were any forward referenced non-basicblock values, delete them.
3544
3545 for (const auto &P : ForwardRefVals) {
3546 if (isa<BasicBlock>(P.second.first))
3547 continue;
3548 P.second.first->replaceAllUsesWith(
3549 PoisonValue::get(P.second.first->getType()));
3550 P.second.first->deleteValue();
3551 }
3552
3553 for (const auto &P : ForwardRefValIDs) {
3554 if (isa<BasicBlock>(P.second.first))
3555 continue;
3556 P.second.first->replaceAllUsesWith(
3557 PoisonValue::get(P.second.first->getType()));
3558 P.second.first->deleteValue();
3559 }
3560}
3561
3562bool LLParser::PerFunctionState::finishFunction() {
3563 if (!ForwardRefVals.empty())
3564 return P.error(ForwardRefVals.begin()->second.second,
3565 "use of undefined value '%" + ForwardRefVals.begin()->first +
3566 "'");
3567 if (!ForwardRefValIDs.empty())
3568 return P.error(ForwardRefValIDs.begin()->second.second,
3569 "use of undefined value '%" +
3570 Twine(ForwardRefValIDs.begin()->first) + "'");
3571 return false;
3572}
3573
3574/// getVal - Get a value with the specified name or ID, creating a
3575/// forward reference record if needed. This can return null if the value
3576/// exists but does not have the right type.
3577Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3578 LocTy Loc) {
3579 // Look this name up in the normal function symbol table.
3580 Value *Val = F.getValueSymbolTable()->lookup(Name);
3581
3582 // If this is a forward reference for the value, see if we already created a
3583 // forward ref record.
3584 if (!Val) {
3585 auto I = ForwardRefVals.find(Name);
3586 if (I != ForwardRefVals.end())
3587 Val = I->second.first;
3588 }
3589
3590 // If we have the value in the symbol table or fwd-ref table, return it.
3591 if (Val)
3592 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3593
3594 // Don't make placeholders with invalid type.
3595 if (!Ty->isFirstClassType()) {
3596 P.error(Loc, "invalid use of a non-first-class type");
3597 return nullptr;
3598 }
3599
3600 // Otherwise, create a new forward reference for this value and remember it.
3601 Value *FwdVal;
3602 if (Ty->isLabelTy()) {
3603 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3604 } else {
3605 FwdVal = new Argument(Ty, Name);
3606 }
3607 if (FwdVal->getName() != Name) {
3608 P.error(Loc, "name is too long which can result in name collisions, "
3609 "consider making the name shorter or "
3610 "increasing -non-global-value-max-name-size");
3611 return nullptr;
3612 }
3613
3614 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3615 return FwdVal;
3616}
3617
3618Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3619 // Look this name up in the normal function symbol table.
3620 Value *Val = NumberedVals.get(ID);
3621
3622 // If this is a forward reference for the value, see if we already created a
3623 // forward ref record.
3624 if (!Val) {
3625 auto I = ForwardRefValIDs.find(ID);
3626 if (I != ForwardRefValIDs.end())
3627 Val = I->second.first;
3628 }
3629
3630 // If we have the value in the symbol table or fwd-ref table, return it.
3631 if (Val)
3632 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3633
3634 if (!Ty->isFirstClassType()) {
3635 P.error(Loc, "invalid use of a non-first-class type");
3636 return nullptr;
3637 }
3638
3639 // Otherwise, create a new forward reference for this value and remember it.
3640 Value *FwdVal;
3641 if (Ty->isLabelTy()) {
3642 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3643 } else {
3644 FwdVal = new Argument(Ty);
3645 }
3646
3647 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3648 return FwdVal;
3649}
3650
3651/// setInstName - After an instruction is parsed and inserted into its
3652/// basic block, this installs its name.
3653bool LLParser::PerFunctionState::setInstName(int NameID,
3654 const std::string &NameStr,
3655 LocTy NameLoc, Instruction *Inst) {
3656 // If this instruction has void type, it cannot have a name or ID specified.
3657 if (Inst->getType()->isVoidTy()) {
3658 if (NameID != -1 || !NameStr.empty())
3659 return P.error(NameLoc, "instructions returning void cannot have a name");
3660 return false;
3661 }
3662
3663 // If this was a numbered instruction, verify that the instruction is the
3664 // expected value and resolve any forward references.
3665 if (NameStr.empty()) {
3666 // If neither a name nor an ID was specified, just use the next ID.
3667 if (NameID == -1)
3668 NameID = NumberedVals.getNext();
3669
3670 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3671 NameID))
3672 return true;
3673
3674 auto FI = ForwardRefValIDs.find(NameID);
3675 if (FI != ForwardRefValIDs.end()) {
3676 Value *Sentinel = FI->second.first;
3677 if (Sentinel->getType() != Inst->getType())
3678 return P.error(NameLoc, "instruction forward referenced with type '" +
3679 getTypeString(FI->second.first->getType()) +
3680 "'");
3681
3682 Sentinel->replaceAllUsesWith(Inst);
3683 Sentinel->deleteValue();
3684 ForwardRefValIDs.erase(FI);
3685 }
3686
3687 NumberedVals.add(NameID, Inst);
3688 return false;
3689 }
3690
3691 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3692 auto FI = ForwardRefVals.find(NameStr);
3693 if (FI != ForwardRefVals.end()) {
3694 Value *Sentinel = FI->second.first;
3695 if (Sentinel->getType() != Inst->getType())
3696 return P.error(NameLoc, "instruction forward referenced with type '" +
3697 getTypeString(FI->second.first->getType()) +
3698 "'");
3699
3700 Sentinel->replaceAllUsesWith(Inst);
3701 Sentinel->deleteValue();
3702 ForwardRefVals.erase(FI);
3703 }
3704
3705 // Set the name on the instruction.
3706 Inst->setName(NameStr);
3707
3708 if (Inst->getName() != NameStr)
3709 return P.error(NameLoc, "multiple definition of local value named '" +
3710 NameStr + "'");
3711 return false;
3712}
3713
3714/// getBB - Get a basic block with the specified name or ID, creating a
3715/// forward reference record if needed.
3716BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3717 LocTy Loc) {
3718 return dyn_cast_or_null<BasicBlock>(
3719 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3720}
3721
3722BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3723 return dyn_cast_or_null<BasicBlock>(
3724 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3725}
3726
3727/// defineBB - Define the specified basic block, which is either named or
3728/// unnamed. If there is an error, this returns null otherwise it returns
3729/// the block being defined.
3730BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3731 int NameID, LocTy Loc) {
3732 BasicBlock *BB;
3733 if (Name.empty()) {
3734 if (NameID != -1) {
3735 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3736 return nullptr;
3737 } else {
3738 NameID = NumberedVals.getNext();
3739 }
3740 BB = getBB(NameID, Loc);
3741 if (!BB) {
3742 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3743 return nullptr;
3744 }
3745 } else {
3746 BB = getBB(Name, Loc);
3747 if (!BB) {
3748 P.error(Loc, "unable to create block named '" + Name + "'");
3749 return nullptr;
3750 }
3751 }
3752
3753 // Move the block to the end of the function. Forward ref'd blocks are
3754 // inserted wherever they happen to be referenced.
3755 F.splice(F.end(), &F, BB->getIterator());
3756
3757 // Remove the block from forward ref sets.
3758 if (Name.empty()) {
3759 ForwardRefValIDs.erase(NameID);
3760 NumberedVals.add(NameID, BB);
3761 } else {
3762 // BB forward references are already in the function symbol table.
3763 ForwardRefVals.erase(Name);
3764 }
3765
3766 return BB;
3767}
3768
3769//===----------------------------------------------------------------------===//
3770// Constants.
3771//===----------------------------------------------------------------------===//
3772
3773/// parseValID - parse an abstract value that doesn't necessarily have a
3774/// type implied. For example, if we parse "4" we don't know what integer type
3775/// it has. The value will later be combined with its type and checked for
3776/// basic correctness. PFS is used to convert function-local operands of
3777/// metadata (since metadata operands are not just parsed here but also
3778/// converted to values). PFS can be null when we are not parsing metadata
3779/// values inside a function.
3780bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3781 ID.Loc = Lex.getLoc();
3782 switch (Lex.getKind()) {
3783 default:
3784 return tokError("expected value token");
3785 case lltok::GlobalID: // @42
3786 ID.UIntVal = Lex.getUIntVal();
3787 ID.Kind = ValID::t_GlobalID;
3788 break;
3789 case lltok::GlobalVar: // @foo
3790 ID.StrVal = Lex.getStrVal();
3791 ID.Kind = ValID::t_GlobalName;
3792 break;
3793 case lltok::LocalVarID: // %42
3794 ID.UIntVal = Lex.getUIntVal();
3795 ID.Kind = ValID::t_LocalID;
3796 break;
3797 case lltok::LocalVar: // %foo
3798 ID.StrVal = Lex.getStrVal();
3799 ID.Kind = ValID::t_LocalName;
3800 break;
3801 case lltok::APSInt:
3802 ID.APSIntVal = Lex.getAPSIntVal();
3803 ID.Kind = ValID::t_APSInt;
3804 break;
3805 case lltok::APFloat:
3806 ID.APFloatVal = Lex.getAPFloatVal();
3807 ID.Kind = ValID::t_APFloat;
3808 break;
3809 case lltok::kw_true:
3810 ID.ConstantVal = ConstantInt::getTrue(Context);
3811 ID.Kind = ValID::t_Constant;
3812 break;
3813 case lltok::kw_false:
3814 ID.ConstantVal = ConstantInt::getFalse(Context);
3815 ID.Kind = ValID::t_Constant;
3816 break;
3817 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3818 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3819 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3820 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3821 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3822
3823 case lltok::lbrace: {
3824 // ValID ::= '{' ConstVector '}'
3825 Lex.Lex();
3827 if (parseGlobalValueVector(Elts) ||
3828 parseToken(lltok::rbrace, "expected end of struct constant"))
3829 return true;
3830
3831 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3832 ID.UIntVal = Elts.size();
3833 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3834 Elts.size() * sizeof(Elts[0]));
3836 return false;
3837 }
3838 case lltok::less: {
3839 // ValID ::= '<' ConstVector '>' --> Vector.
3840 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3841 Lex.Lex();
3842 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3843
3845 LocTy FirstEltLoc = Lex.getLoc();
3846 if (parseGlobalValueVector(Elts) ||
3847 (isPackedStruct &&
3848 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3849 parseToken(lltok::greater, "expected end of constant"))
3850 return true;
3851
3852 if (isPackedStruct) {
3853 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3854 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3855 Elts.size() * sizeof(Elts[0]));
3856 ID.UIntVal = Elts.size();
3858 return false;
3859 }
3860
3861 if (Elts.empty())
3862 return error(ID.Loc, "constant vector must not be empty");
3863
3864 if (!Elts[0]->getType()->isIntegerTy() &&
3865 !Elts[0]->getType()->isFloatingPointTy() &&
3866 !Elts[0]->getType()->isPointerTy())
3867 return error(
3868 FirstEltLoc,
3869 "vector elements must have integer, pointer or floating point type");
3870
3871 // Verify that all the vector elements have the same type.
3872 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3873 if (Elts[i]->getType() != Elts[0]->getType())
3874 return error(FirstEltLoc, "vector element #" + Twine(i) +
3875 " is not of type '" +
3876 getTypeString(Elts[0]->getType()));
3877
3878 ID.ConstantVal = ConstantVector::get(Elts);
3879 ID.Kind = ValID::t_Constant;
3880 return false;
3881 }
3882 case lltok::lsquare: { // Array Constant
3883 Lex.Lex();
3885 LocTy FirstEltLoc = Lex.getLoc();
3886 if (parseGlobalValueVector(Elts) ||
3887 parseToken(lltok::rsquare, "expected end of array constant"))
3888 return true;
3889
3890 // Handle empty element.
3891 if (Elts.empty()) {
3892 // Use undef instead of an array because it's inconvenient to determine
3893 // the element type at this point, there being no elements to examine.
3894 ID.Kind = ValID::t_EmptyArray;
3895 return false;
3896 }
3897
3898 if (!Elts[0]->getType()->isFirstClassType())
3899 return error(FirstEltLoc, "invalid array element type: " +
3900 getTypeString(Elts[0]->getType()));
3901
3902 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3903
3904 // Verify all elements are correct type!
3905 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3906 if (Elts[i]->getType() != Elts[0]->getType())
3907 return error(FirstEltLoc, "array element #" + Twine(i) +
3908 " is not of type '" +
3909 getTypeString(Elts[0]->getType()));
3910 }
3911
3912 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3913 ID.Kind = ValID::t_Constant;
3914 return false;
3915 }
3916 case lltok::kw_c: // c "foo"
3917 Lex.Lex();
3918 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3919 false);
3920 if (parseToken(lltok::StringConstant, "expected string"))
3921 return true;
3922 ID.Kind = ValID::t_Constant;
3923 return false;
3924
3925 case lltok::kw_asm: {
3926 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3927 // STRINGCONSTANT
3928 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3929 Lex.Lex();
3930 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3931 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3932 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3933 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3934 parseStringConstant(ID.StrVal) ||
3935 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3936 parseToken(lltok::StringConstant, "expected constraint string"))
3937 return true;
3938 ID.StrVal2 = Lex.getStrVal();
3939 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3940 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3941 ID.Kind = ValID::t_InlineAsm;
3942 return false;
3943 }
3944
3946 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3947 Lex.Lex();
3948
3949 ValID Fn, Label;
3950
3951 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3952 parseValID(Fn, PFS) ||
3953 parseToken(lltok::comma,
3954 "expected comma in block address expression") ||
3955 parseValID(Label, PFS) ||
3956 parseToken(lltok::rparen, "expected ')' in block address expression"))
3957 return true;
3958
3960 return error(Fn.Loc, "expected function name in blockaddress");
3961 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3962 return error(Label.Loc, "expected basic block name in blockaddress");
3963
3964 // Try to find the function (but skip it if it's forward-referenced).
3965 GlobalValue *GV = nullptr;
3966 if (Fn.Kind == ValID::t_GlobalID) {
3967 GV = NumberedVals.get(Fn.UIntVal);
3968 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3969 GV = M->getNamedValue(Fn.StrVal);
3970 }
3971 Function *F = nullptr;
3972 if (GV) {
3973 // Confirm that it's actually a function with a definition.
3974 if (!isa<Function>(GV))
3975 return error(Fn.Loc, "expected function name in blockaddress");
3976 F = cast<Function>(GV);
3977 if (F->isDeclaration())
3978 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3979 }
3980
3981 if (!F) {
3982 // Make a global variable as a placeholder for this reference.
3983 GlobalValue *&FwdRef =
3984 ForwardRefBlockAddresses.insert(std::make_pair(
3985 std::move(Fn),
3986 std::map<ValID, GlobalValue *>()))
3987 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3988 .first->second;
3989 if (!FwdRef) {
3990 unsigned FwdDeclAS;
3991 if (ExpectedTy) {
3992 // If we know the type that the blockaddress is being assigned to,
3993 // we can use the address space of that type.
3994 if (!ExpectedTy->isPointerTy())
3995 return error(ID.Loc,
3996 "type of blockaddress must be a pointer and not '" +
3997 getTypeString(ExpectedTy) + "'");
3998 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3999 } else if (PFS) {
4000 // Otherwise, we default the address space of the current function.
4001 FwdDeclAS = PFS->getFunction().getAddressSpace();
4002 } else {
4003 llvm_unreachable("Unknown address space for blockaddress");
4004 }
4005 FwdRef = new GlobalVariable(
4006 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4007 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4008 }
4009
4010 ID.ConstantVal = FwdRef;
4011 ID.Kind = ValID::t_Constant;
4012 return false;
4013 }
4014
4015 // We found the function; now find the basic block. Don't use PFS, since we
4016 // might be inside a constant expression.
4017 BasicBlock *BB;
4018 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4019 if (Label.Kind == ValID::t_LocalID)
4020 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4021 else
4022 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4023 if (!BB)
4024 return error(Label.Loc, "referenced value is not a basic block");
4025 } else {
4026 if (Label.Kind == ValID::t_LocalID)
4027 return error(Label.Loc, "cannot take address of numeric label after "
4028 "the function is defined");
4029 BB = dyn_cast_or_null<BasicBlock>(
4030 F->getValueSymbolTable()->lookup(Label.StrVal));
4031 if (!BB)
4032 return error(Label.Loc, "referenced value is not a basic block");
4033 }
4034
4035 ID.ConstantVal = BlockAddress::get(F, BB);
4036 ID.Kind = ValID::t_Constant;
4037 return false;
4038 }
4039
4041 // ValID ::= 'dso_local_equivalent' @foo
4042 Lex.Lex();
4043
4044 ValID Fn;
4045
4046 if (parseValID(Fn, PFS))
4047 return true;
4048
4050 return error(Fn.Loc,
4051 "expected global value name in dso_local_equivalent");
4052
4053 // Try to find the function (but skip it if it's forward-referenced).
4054 GlobalValue *GV = nullptr;
4055 if (Fn.Kind == ValID::t_GlobalID) {
4056 GV = NumberedVals.get(Fn.UIntVal);
4057 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4058 GV = M->getNamedValue(Fn.StrVal);
4059 }
4060
4061 if (!GV) {
4062 // Make a placeholder global variable as a placeholder for this reference.
4063 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4064 ? ForwardRefDSOLocalEquivalentIDs
4065 : ForwardRefDSOLocalEquivalentNames;
4066 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;
4067 if (!FwdRef) {
4068 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4069 GlobalValue::InternalLinkage, nullptr, "",
4071 }
4072
4073 ID.ConstantVal = FwdRef;
4074 ID.Kind = ValID::t_Constant;
4075 return false;
4076 }
4077
4078 if (!GV->getValueType()->isFunctionTy())
4079 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4080 "in dso_local_equivalent");
4081
4082 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4083 ID.Kind = ValID::t_Constant;
4084 return false;
4085 }
4086
4087 case lltok::kw_no_cfi: {
4088 // ValID ::= 'no_cfi' @foo
4089 Lex.Lex();
4090
4091 if (parseValID(ID, PFS))
4092 return true;
4093
4094 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4095 return error(ID.Loc, "expected global value name in no_cfi");
4096
4097 ID.NoCFI = true;
4098 return false;
4099 }
4100 case lltok::kw_ptrauth: {
4101 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4102 // (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4103 Lex.Lex();
4104
4105 Constant *Ptr, *Key;
4106 Constant *Disc = nullptr, *AddrDisc = nullptr;
4107
4108 if (parseToken(lltok::lparen,
4109 "expected '(' in constant ptrauth expression") ||
4110 parseGlobalTypeAndValue(Ptr) ||
4111 parseToken(lltok::comma,
4112 "expected comma in constant ptrauth expression") ||
4113 parseGlobalTypeAndValue(Key))
4114 return true;
4115 // If present, parse the optional disc/addrdisc.
4116 if (EatIfPresent(lltok::comma))
4117 if (parseGlobalTypeAndValue(Disc) ||
4118 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4119 return true;
4120 if (parseToken(lltok::rparen,
4121 "expected ')' in constant ptrauth expression"))
4122 return true;
4123
4124 if (!Ptr->getType()->isPointerTy())
4125 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4126
4127 auto *KeyC = dyn_cast<ConstantInt>(Key);
4128 if (!KeyC || KeyC->getBitWidth() != 32)
4129 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4130
4131 ConstantInt *DiscC = nullptr;
4132 if (Disc) {
4133 DiscC = dyn_cast<ConstantInt>(Disc);
4134 if (!DiscC || DiscC->getBitWidth() != 64)
4135 return error(
4136 ID.Loc,
4137 "constant ptrauth integer discriminator must be i64 constant");
4138 } else {
4139 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4140 }
4141
4142 if (AddrDisc) {
4143 if (!AddrDisc->getType()->isPointerTy())
4144 return error(
4145 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4146 } else {
4147 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4148 }
4149
4150 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4151 ID.Kind = ValID::t_Constant;
4152 return false;
4153 }
4154
4155 case lltok::kw_trunc:
4156 case lltok::kw_bitcast:
4158 case lltok::kw_inttoptr:
4159 case lltok::kw_ptrtoint: {
4160 unsigned Opc = Lex.getUIntVal();
4161 Type *DestTy = nullptr;
4162 Constant *SrcVal;
4163 Lex.Lex();
4164 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4165 parseGlobalTypeAndValue(SrcVal) ||
4166 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4167 parseType(DestTy) ||
4168 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4169 return true;
4170 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4171 return error(ID.Loc, "invalid cast opcode for cast from '" +
4172 getTypeString(SrcVal->getType()) + "' to '" +
4173 getTypeString(DestTy) + "'");
4175 SrcVal, DestTy);
4176 ID.Kind = ValID::t_Constant;
4177 return false;
4178 }
4180 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4182 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4183 case lltok::kw_udiv:
4184 return error(ID.Loc, "udiv constexprs are no longer supported");
4185 case lltok::kw_sdiv:
4186 return error(ID.Loc, "sdiv constexprs are no longer supported");
4187 case lltok::kw_urem:
4188 return error(ID.Loc, "urem constexprs are no longer supported");
4189 case lltok::kw_srem:
4190 return error(ID.Loc, "srem constexprs are no longer supported");
4191 case lltok::kw_fadd:
4192 return error(ID.Loc, "fadd constexprs are no longer supported");
4193 case lltok::kw_fsub:
4194 return error(ID.Loc, "fsub constexprs are no longer supported");
4195 case lltok::kw_fmul:
4196 return error(ID.Loc, "fmul constexprs are no longer supported");
4197 case lltok::kw_fdiv:
4198 return error(ID.Loc, "fdiv constexprs are no longer supported");
4199 case lltok::kw_frem:
4200 return error(ID.Loc, "frem constexprs are no longer supported");
4201 case lltok::kw_and:
4202 return error(ID.Loc, "and constexprs are no longer supported");
4203 case lltok::kw_or:
4204 return error(ID.Loc, "or constexprs are no longer supported");
4205 case lltok::kw_lshr:
4206 return error(ID.Loc, "lshr constexprs are no longer supported");
4207 case lltok::kw_ashr:
4208 return error(ID.Loc, "ashr constexprs are no longer supported");
4209 case lltok::kw_shl:
4210 return error(ID.Loc, "shl constexprs are no longer supported");
4211 case lltok::kw_fneg:
4212 return error(ID.Loc, "fneg constexprs are no longer supported");
4213 case lltok::kw_select:
4214 return error(ID.Loc, "select constexprs are no longer supported");
4215 case lltok::kw_zext:
4216 return error(ID.Loc, "zext constexprs are no longer supported");
4217 case lltok::kw_sext:
4218 return error(ID.Loc, "sext constexprs are no longer supported");
4219 case lltok::kw_fptrunc:
4220 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4221 case lltok::kw_fpext:
4222 return error(ID.Loc, "fpext constexprs are no longer supported");
4223 case lltok::kw_uitofp:
4224 return error(ID.Loc, "uitofp constexprs are no longer supported");
4225 case lltok::kw_sitofp:
4226 return error(ID.Loc, "sitofp constexprs are no longer supported");
4227 case lltok::kw_fptoui:
4228 return error(ID.Loc, "fptoui constexprs are no longer supported");
4229 case lltok::kw_fptosi:
4230 return error(ID.Loc, "fptosi constexprs are no longer supported");
4231 case lltok::kw_icmp:
4232 return error(ID.Loc, "icmp constexprs are no longer supported");
4233 case lltok::kw_fcmp:
4234 return error(ID.Loc, "fcmp constexprs are no longer supported");
4235
4236 // Binary Operators.
4237 case lltok::kw_add:
4238 case lltok::kw_sub:
4239 case lltok::kw_mul:
4240 case lltok::kw_xor: {
4241 bool NUW = false;
4242 bool NSW = false;
4243 unsigned Opc = Lex.getUIntVal();
4244 Constant *Val0, *Val1;
4245 Lex.Lex();
4246 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4247 Opc == Instruction::Mul) {
4248 if (EatIfPresent(lltok::kw_nuw))
4249 NUW = true;
4250 if (EatIfPresent(lltok::kw_nsw)) {
4251 NSW = true;
4252 if (EatIfPresent(lltok::kw_nuw))
4253 NUW = true;
4254 }
4255 }
4256 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4257 parseGlobalTypeAndValue(Val0) ||
4258 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4259 parseGlobalTypeAndValue(Val1) ||
4260 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4261 return true;
4262 if (Val0->getType() != Val1->getType())
4263 return error(ID.Loc, "operands of constexpr must have same type");
4264 // Check that the type is valid for the operator.
4265 if (!Val0->getType()->isIntOrIntVectorTy())
4266 return error(ID.Loc,
4267 "constexpr requires integer or integer vector operands");
4268 unsigned Flags = 0;
4271 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4272 ID.Kind = ValID::t_Constant;
4273 return false;
4274 }
4275
4276 case lltok::kw_splat: {
4277 Lex.Lex();
4278 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4279 return true;
4280 Constant *C;
4281 if (parseGlobalTypeAndValue(C))
4282 return true;
4283 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4284 return true;
4285
4286 ID.ConstantVal = C;
4288 return false;
4289 }
4290
4295 unsigned Opc = Lex.getUIntVal();
4297 GEPNoWrapFlags NW;
4298 bool HasInRange = false;
4299 APSInt InRangeStart;
4300 APSInt InRangeEnd;
4301 Type *Ty;
4302 Lex.Lex();
4303
4304 if (Opc == Instruction::GetElementPtr) {
4305 while (true) {
4306 if (EatIfPresent(lltok::kw_inbounds))
4308 else if (EatIfPresent(lltok::kw_nusw))
4310 else if (EatIfPresent(lltok::kw_nuw))
4312 else
4313 break;
4314 }
4315
4316 if (EatIfPresent(lltok::kw_inrange)) {
4317 if (parseToken(lltok::lparen, "expected '('"))
4318 return true;
4319 if (Lex.getKind() != lltok::APSInt)
4320 return tokError("expected integer");
4321 InRangeStart = Lex.getAPSIntVal();
4322 Lex.Lex();
4323 if (parseToken(lltok::comma, "expected ','"))
4324 return true;
4325 if (Lex.getKind() != lltok::APSInt)
4326 return tokError("expected integer");
4327 InRangeEnd = Lex.getAPSIntVal();
4328 Lex.Lex();
4329 if (parseToken(lltok::rparen, "expected ')'"))
4330 return true;
4331 HasInRange = true;
4332 }
4333 }
4334
4335 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4336 return true;
4337
4338 if (Opc == Instruction::GetElementPtr) {
4339 if (parseType(Ty) ||
4340 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4341 return true;
4342 }
4343
4344 if (parseGlobalValueVector(Elts) ||
4345 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4346 return true;
4347
4348 if (Opc == Instruction::GetElementPtr) {
4349 if (Elts.size() == 0 ||
4350 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4351 return error(ID.Loc, "base of getelementptr must be a pointer");
4352
4353 Type *BaseType = Elts[0]->getType();
4354 std::optional<ConstantRange> InRange;
4355 if (HasInRange) {
4356 unsigned IndexWidth =
4357 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4358 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4359 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4360 if (InRangeStart.sge(InRangeEnd))
4361 return error(ID.Loc, "expected end to be larger than start");
4362 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4363 }
4364
4365 unsigned GEPWidth =
4366 BaseType->isVectorTy()
4367 ? cast<FixedVectorType>(BaseType)->getNumElements()
4368 : 0;
4369
4370 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4371 for (Constant *Val : Indices) {
4372 Type *ValTy = Val->getType();
4373 if (!ValTy->isIntOrIntVectorTy())
4374 return error(ID.Loc, "getelementptr index must be an integer");
4375 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4376 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4377 if (GEPWidth && (ValNumEl != GEPWidth))
4378 return error(
4379 ID.Loc,
4380 "getelementptr vector index has a wrong number of elements");
4381 // GEPWidth may have been unknown because the base is a scalar,
4382 // but it is known now.
4383 GEPWidth = ValNumEl;
4384 }
4385 }
4386
4387 SmallPtrSet<Type*, 4> Visited;
4388 if (!Indices.empty() && !Ty->isSized(&Visited))
4389 return error(ID.Loc, "base element of getelementptr must be sized");
4390
4391 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4392 return error(ID.Loc, "invalid getelementptr indices");
4393
4394 ID.ConstantVal =
4395 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4396 } else if (Opc == Instruction::ShuffleVector) {
4397 if (Elts.size() != 3)
4398 return error(ID.Loc, "expected three operands to shufflevector");
4399 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4400 return error(ID.Loc, "invalid operands to shufflevector");
4402 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
4403 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4404 } else if (Opc == Instruction::ExtractElement) {
4405 if (Elts.size() != 2)
4406 return error(ID.Loc, "expected two operands to extractelement");
4407 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4408 return error(ID.Loc, "invalid extractelement operands");
4409 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4410 } else {
4411 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4412 if (Elts.size() != 3)
4413 return error(ID.Loc, "expected three operands to insertelement");
4414 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4415 return error(ID.Loc, "invalid insertelement operands");
4416 ID.ConstantVal =
4417 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4418 }
4419
4420 ID.Kind = ValID::t_Constant;
4421 return false;
4422 }
4423 }
4424
4425 Lex.Lex();
4426 return false;
4427}
4428
4429/// parseGlobalValue - parse a global value with the specified type.
4430bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4431 C = nullptr;
4432 ValID ID;
4433 Value *V = nullptr;
4434 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4435 convertValIDToValue(Ty, ID, V, nullptr);
4436 if (V && !(C = dyn_cast<Constant>(V)))
4437 return error(ID.Loc, "global values must be constants");
4438 return Parsed;
4439}
4440
4441bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4442 Type *Ty = nullptr;
4443 return parseType(Ty) || parseGlobalValue(Ty, V);
4444}
4445
4446bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4447 C = nullptr;
4448
4449 LocTy KwLoc = Lex.getLoc();
4450 if (!EatIfPresent(lltok::kw_comdat))
4451 return false;
4452
4453 if (EatIfPresent(lltok::lparen)) {
4454 if (Lex.getKind() != lltok::ComdatVar)
4455 return tokError("expected comdat variable");
4456 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4457 Lex.Lex();
4458 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4459 return true;
4460 } else {
4461 if (GlobalName.empty())
4462 return tokError("comdat cannot be unnamed");
4463 C = getComdat(std::string(GlobalName), KwLoc);
4464 }
4465
4466 return false;
4467}
4468
4469/// parseGlobalValueVector
4470/// ::= /*empty*/
4471/// ::= TypeAndValue (',' TypeAndValue)*
4472bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4473 // Empty list.
4474 if (Lex.getKind() == lltok::rbrace ||
4475 Lex.getKind() == lltok::rsquare ||
4476 Lex.getKind() == lltok::greater ||
4477 Lex.getKind() == lltok::rparen)
4478 return false;
4479
4480 do {
4481 // Let the caller deal with inrange.
4482 if (Lex.getKind() == lltok::kw_inrange)
4483 return false;
4484
4485 Constant *C;
4486 if (parseGlobalTypeAndValue(C))
4487 return true;
4488 Elts.push_back(C);
4489 } while (EatIfPresent(lltok::comma));
4490
4491 return false;
4492}
4493
4494bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4496 if (parseMDNodeVector(Elts))
4497 return true;
4498
4499 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4500 return false;
4501}
4502
4503/// MDNode:
4504/// ::= !{ ... }
4505/// ::= !7
4506/// ::= !DILocation(...)
4507bool LLParser::parseMDNode(MDNode *&N) {
4508 if (Lex.getKind() == lltok::MetadataVar)
4509 return parseSpecializedMDNode(N);
4510
4511 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4512}
4513
4514bool LLParser::parseMDNodeTail(MDNode *&N) {
4515 // !{ ... }
4516 if (Lex.getKind() == lltok::lbrace)
4517 return parseMDTuple(N);
4518
4519 // !42
4520 return parseMDNodeID(N);
4521}
4522
4523namespace {
4524
4525/// Structure to represent an optional metadata field.
4526template <class FieldTy> struct MDFieldImpl {
4527 typedef MDFieldImpl ImplTy;
4528 FieldTy Val;
4529 bool Seen;
4530
4531 void assign(FieldTy Val) {
4532 Seen = true;
4533 this->Val = std::move(Val);
4534 }
4535
4536 explicit MDFieldImpl(FieldTy Default)
4537 : Val(std::move(Default)), Seen(false) {}
4538};
4539
4540/// Structure to represent an optional metadata field that
4541/// can be of either type (A or B) and encapsulates the
4542/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4543/// to reimplement the specifics for representing each Field.
4544template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4545 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4546 FieldTypeA A;
4547 FieldTypeB B;
4548 bool Seen;
4549
4550 enum {
4551 IsInvalid = 0,
4552 IsTypeA = 1,
4553 IsTypeB = 2
4554 } WhatIs;
4555
4556 void assign(FieldTypeA A) {
4557 Seen = true;
4558 this->A = std::move(A);
4559 WhatIs = IsTypeA;
4560 }
4561
4562 void assign(FieldTypeB B) {
4563 Seen = true;
4564 this->B = std::move(B);
4565 WhatIs = IsTypeB;
4566 }
4567
4568 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4569 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4570 WhatIs(IsInvalid) {}
4571};
4572
4573struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4574 uint64_t Max;
4575
4576 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4577 : ImplTy(Default), Max(Max) {}
4578};
4579
4580struct LineField : public MDUnsignedField {
4581 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4582};
4583
4584struct ColumnField : public MDUnsignedField {
4585 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4586};
4587
4588struct DwarfTagField : public MDUnsignedField {
4589 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4590 DwarfTagField(dwarf::Tag DefaultTag)
4591 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4592};
4593
4594struct DwarfMacinfoTypeField : public MDUnsignedField {
4595 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4596 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4597 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4598};
4599
4600struct DwarfAttEncodingField : public MDUnsignedField {
4601 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4602};
4603
4604struct DwarfVirtualityField : public MDUnsignedField {
4605 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4606};
4607
4608struct DwarfLangField : public MDUnsignedField {
4609 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4610};
4611
4612struct DwarfCCField : public MDUnsignedField {
4613 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4614};
4615
4616struct EmissionKindField : public MDUnsignedField {
4617 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4618};
4619
4620struct NameTableKindField : public MDUnsignedField {
4621 NameTableKindField()
4622 : MDUnsignedField(
4623 0, (unsigned)
4624 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4625};
4626
4627struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4628 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4629};
4630
4631struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4632 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4633};
4634
4635struct MDAPSIntField : public MDFieldImpl<APSInt> {
4636 MDAPSIntField() : ImplTy(APSInt()) {}
4637};
4638
4639struct MDSignedField : public MDFieldImpl<int64_t> {
4640 int64_t Min = INT64_MIN;
4641 int64_t Max = INT64_MAX;
4642
4643 MDSignedField(int64_t Default = 0)
4644 : ImplTy(Default) {}
4645 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4646 : ImplTy(Default), Min(Min), Max(Max) {}
4647};
4648
4649struct MDBoolField : public MDFieldImpl<bool> {
4650 MDBoolField(bool Default = false) : ImplTy(Default) {}
4651};
4652
4653struct MDField : public MDFieldImpl<Metadata *> {
4654 bool AllowNull;
4655
4656 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4657};
4658
4659struct MDStringField : public MDFieldImpl<MDString *> {
4660 bool AllowEmpty;
4661 MDStringField(bool AllowEmpty = true)
4662 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4663};
4664
4665struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4666 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4667};
4668
4669struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4670 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4671};
4672
4673struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4674 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4675 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4676
4677 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4678 bool AllowNull = true)
4679 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4680
4681 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4682 bool isMDField() const { return WhatIs == IsTypeB; }
4683 int64_t getMDSignedValue() const {
4684 assert(isMDSignedField() && "Wrong field type");
4685 return A.Val;
4686 }
4687 Metadata *getMDFieldValue() const {
4688 assert(isMDField() && "Wrong field type");
4689 return B.Val;
4690 }
4691};
4692
4693} // end anonymous namespace
4694
4695namespace llvm {
4696
4697template <>
4698bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4699 if (Lex.getKind() != lltok::APSInt)
4700 return tokError("expected integer");
4701
4702 Result.assign(Lex.getAPSIntVal());
4703 Lex.Lex();
4704 return false;
4705}
4706
4707template <>
4708bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4709 MDUnsignedField &Result) {
4710 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4711 return tokError("expected unsigned integer");
4712
4713 auto &U = Lex.getAPSIntVal();
4714 if (U.ugt(Result.Max))
4715 return tokError("value for '" + Name + "' too large, limit is " +
4716 Twine(Result.Max));
4717 Result.assign(U.getZExtValue());
4718 assert(Result.Val <= Result.Max && "Expected value in range");
4719 Lex.Lex();
4720 return false;
4721}
4722
4723template <>
4724bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4725 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4726}
4727template <>
4728bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4729 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4730}
4731
4732template <>
4733bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4734 if (Lex.getKind() == lltok::APSInt)
4735 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4736
4737 if (Lex.getKind() != lltok::DwarfTag)
4738 return tokError("expected DWARF tag");
4739
4740 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4742 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4743 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4744
4745 Result.assign(Tag);
4746 Lex.Lex();
4747 return false;
4748}
4749
4750template <>
4751bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4752 DwarfMacinfoTypeField &Result) {
4753 if (Lex.getKind() == lltok::APSInt)
4754 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4755
4756 if (Lex.getKind() != lltok::DwarfMacinfo)
4757 return tokError("expected DWARF macinfo type");
4758
4759 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4760 if (Macinfo == dwarf::DW_MACINFO_invalid)
4761 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4762 Lex.getStrVal() + "'");
4763 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4764
4765 Result.assign(Macinfo);
4766 Lex.Lex();
4767 return false;
4768}
4769
4770template <>
4771bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4772 DwarfVirtualityField &Result) {
4773 if (Lex.getKind() == lltok::APSInt)
4774 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4775
4776 if (Lex.getKind() != lltok::DwarfVirtuality)
4777 return tokError("expected DWARF virtuality code");
4778
4779 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4780 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4781 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4782 Lex.getStrVal() + "'");
4783 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4784 Result.assign(Virtuality);
4785 Lex.Lex();
4786 return false;
4787}
4788
4789template <>
4790bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4791 if (Lex.getKind() == lltok::APSInt)
4792 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4793
4794 if (Lex.getKind() != lltok::DwarfLang)
4795 return tokError("expected DWARF language");
4796
4797 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4798 if (!Lang)
4799 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4800 "'");
4801 assert(Lang <= Result.Max && "Expected valid DWARF language");
4802 Result.assign(Lang);
4803 Lex.Lex();
4804 return false;
4805}
4806
4807template <>
4808bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4809 if (Lex.getKind() == lltok::APSInt)
4810 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4811
4812 if (Lex.getKind() != lltok::DwarfCC)
4813 return tokError("expected DWARF calling convention");
4814
4815 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4816 if (!CC)
4817 return tokError("invalid DWARF calling convention" + Twine(" '") +
4818 Lex.getStrVal() + "'");
4819 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4820 Result.assign(CC);
4821 Lex.Lex();
4822 return false;
4823}
4824
4825template <>
4826bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4827 EmissionKindField &Result) {
4828 if (Lex.getKind() == lltok::APSInt)
4829 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4830
4831 if (Lex.getKind() != lltok::EmissionKind)
4832 return tokError("expected emission kind");
4833
4834 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4835 if (!Kind)
4836 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4837 "'");
4838 assert(*Kind <= Result.Max && "Expected valid emission kind");
4839 Result.assign(*Kind);
4840 Lex.Lex();
4841 return false;
4842}
4843
4844template <>
4845bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4846 NameTableKindField &Result) {
4847 if (Lex.getKind() == lltok::APSInt)
4848 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4849
4850 if (Lex.getKind() != lltok::NameTableKind)
4851 return tokError("expected nameTable kind");
4852
4853 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4854 if (!Kind)
4855 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4856 "'");
4857 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4858 Result.assign((unsigned)*Kind);
4859 Lex.Lex();
4860 return false;
4861}
4862
4863template <>
4864bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4865 DwarfAttEncodingField &Result) {
4866 if (Lex.getKind() == lltok::APSInt)
4867 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4868
4869 if (Lex.getKind() != lltok::DwarfAttEncoding)
4870 return tokError("expected DWARF type attribute encoding");
4871
4872 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4873 if (!Encoding)
4874 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4875 Lex.getStrVal() + "'");
4876 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4877 Result.assign(Encoding);
4878 Lex.Lex();
4879 return false;
4880}
4881
4882/// DIFlagField
4883/// ::= uint32
4884/// ::= DIFlagVector
4885/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4886template <>
4887bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4888
4889 // parser for a single flag.
4890 auto parseFlag = [&](DINode::DIFlags &Val) {
4891 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4892 uint32_t TempVal = static_cast<uint32_t>(Val);
4893 bool Res = parseUInt32(TempVal);
4894 Val = static_cast<DINode::DIFlags>(TempVal);
4895 return Res;
4896 }
4897
4898 if (Lex.getKind() != lltok::DIFlag)
4899 return tokError("expected debug info flag");
4900
4901 Val = DINode::getFlag(Lex.getStrVal());
4902 if (!Val)
4903 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4904 "'");
4905 Lex.Lex();
4906 return false;
4907 };
4908
4909 // parse the flags and combine them together.
4910 DINode::DIFlags Combined = DINode::FlagZero;
4911 do {
4912 DINode::DIFlags Val;
4913 if (parseFlag(Val))
4914 return true;
4915 Combined |= Val;
4916 } while (EatIfPresent(lltok::bar));
4917
4918 Result.assign(Combined);
4919 return false;
4920}
4921
4922/// DISPFlagField
4923/// ::= uint32
4924/// ::= DISPFlagVector
4925/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4926template <>
4927bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4928
4929 // parser for a single flag.
4930 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4931 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4932 uint32_t TempVal = static_cast<uint32_t>(Val);
4933 bool Res = parseUInt32(TempVal);
4934 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4935 return Res;
4936 }
4937
4938 if (Lex.getKind() != lltok::DISPFlag)
4939 return tokError("expected debug info flag");
4940
4941 Val = DISubprogram::getFlag(Lex.getStrVal());
4942 if (!Val)
4943 return tokError(Twine("invalid subprogram debug info flag '") +
4944 Lex.getStrVal() + "'");
4945 Lex.Lex();
4946 return false;
4947 };
4948
4949 // parse the flags and combine them together.
4950 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4951 do {
4953 if (parseFlag(Val))
4954 return true;
4955 Combined |= Val;
4956 } while (EatIfPresent(lltok::bar));
4957
4958 Result.assign(Combined);
4959 return false;
4960}
4961
4962template <>
4963bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4964 if (Lex.getKind() != lltok::APSInt)
4965 return tokError("expected signed integer");
4966
4967 auto &S = Lex.getAPSIntVal();
4968 if (S < Result.Min)
4969 return tokError("value for '" + Name + "' too small, limit is " +
4970 Twine(Result.Min));
4971 if (S > Result.Max)
4972 return tokError("value for '" + Name + "' too large, limit is " +
4973 Twine(Result.Max));
4974 Result.assign(S.getExtValue());
4975 assert(Result.Val >= Result.Min && "Expected value in range");
4976 assert(Result.Val <= Result.Max && "Expected value in range");
4977 Lex.Lex();
4978 return false;
4979}
4980
4981template <>
4982bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4983 switch (Lex.getKind()) {
4984 default:
4985 return tokError("expected 'true' or 'false'");
4986 case lltok::kw_true:
4987 Result.assign(true);
4988 break;
4989 case lltok::kw_false:
4990 Result.assign(false);
4991 break;
4992 }
4993 Lex.Lex();
4994 return false;
4995}
4996
4997template <>
4998bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4999 if (Lex.getKind() == lltok::kw_null) {
5000 if (!Result.AllowNull)
5001 return tokError("'" + Name + "' cannot be null");
5002 Lex.Lex();
5003 Result.assign(nullptr);
5004 return false;
5005 }
5006
5007 Metadata *MD;
5008 if (parseMetadata(MD, nullptr))
5009 return true;
5010
5011 Result.assign(MD);
5012 return false;
5013}
5014
5015template <>
5016bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5017 MDSignedOrMDField &Result) {
5018 // Try to parse a signed int.
5019 if (Lex.getKind() == lltok::APSInt) {
5020 MDSignedField Res = Result.A;
5021 if (!parseMDField(Loc, Name, Res)) {
5022 Result.assign(Res);
5023 return false;
5024 }
5025 return true;
5026 }
5027
5028 // Otherwise, try to parse as an MDField.
5029 MDField Res = Result.B;
5030 if (!parseMDField(Loc, Name, Res)) {
5031 Result.assign(Res);
5032 return false;
5033 }
5034
5035 return true;
5036}
5037
5038template <>
5039bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5040 LocTy ValueLoc = Lex.getLoc();
5041 std::string S;
5042 if (parseStringConstant(S))
5043 return true;
5044
5045 if (!Result.AllowEmpty && S.empty())
5046 return error(ValueLoc, "'" + Name + "' cannot be empty");
5047
5048 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
5049 return false;
5050}
5051
5052template <>
5053bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5055 if (parseMDNodeVector(MDs))
5056 return true;
5057
5058 Result.assign(std::move(MDs));
5059 return false;
5060}
5061
5062template <>
5063bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5064 ChecksumKindField &Result) {
5065 std::optional<DIFile::ChecksumKind> CSKind =
5067
5068 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5069 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5070 "'");
5071
5072 Result.assign(*CSKind);
5073 Lex.Lex();
5074 return false;
5075}
5076
5077} // end namespace llvm
5078
5079template <class ParserTy>
5080bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5081 do {
5082 if (Lex.getKind() != lltok::LabelStr)
5083 return tokError("expected field label here");
5084
5085 if (ParseField())
5086 return true;
5087 } while (EatIfPresent(lltok::comma));
5088
5089 return false;
5090}
5091
5092template <class ParserTy>
5093bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5094 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5095 Lex.Lex();
5096
5097 if (parseToken(lltok::lparen, "expected '(' here"))
5098 return true;
5099 if (Lex.getKind() != lltok::rparen)
5100 if (parseMDFieldsImplBody(ParseField))
5101 return true;
5102
5103 ClosingLoc = Lex.getLoc();
5104 return parseToken(lltok::rparen, "expected ')' here");
5105}
5106
5107template <class FieldTy>
5108bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5109 if (Result.Seen)
5110 return tokError("field '" + Name + "' cannot be specified more than once");
5111
5112 LocTy Loc = Lex.getLoc();
5113 Lex.Lex();
5114 return parseMDField(Loc, Name, Result);
5115}
5116
5117bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5118 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5119
5120#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5121 if (Lex.getStrVal() == #CLASS) \
5122 return parse##CLASS(N, IsDistinct);
5123#include "llvm/IR/Metadata.def"
5124
5125 return tokError("expected metadata type");
5126}
5127
5128#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5129#define NOP_FIELD(NAME, TYPE, INIT)
5130#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5131 if (!NAME.Seen) \
5132 return error(ClosingLoc, "missing required field '" #NAME "'");
5133#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5134 if (Lex.getStrVal() == #NAME) \
5135 return parseMDField(#NAME, NAME);
5136#define PARSE_MD_FIELDS() \
5137 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5138 do { \
5139 LocTy ClosingLoc; \
5140 if (parseMDFieldsImpl( \
5141 [&]() -> bool { \
5142 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5143 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5144 "'"); \
5145 }, \
5146 ClosingLoc)) \
5147 return true; \
5148 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5149 } while (false)
5150#define GET_OR_DISTINCT(CLASS, ARGS) \
5151 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5152
5153/// parseDILocationFields:
5154/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5155/// isImplicitCode: true)
5156bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5157#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5158 OPTIONAL(line, LineField, ); \
5159 OPTIONAL(column, ColumnField, ); \
5160 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5161 OPTIONAL(inlinedAt, MDField, ); \
5162 OPTIONAL(isImplicitCode, MDBoolField, (false));
5164#undef VISIT_MD_FIELDS
5165
5166 Result =
5167 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5168 inlinedAt.Val, isImplicitCode.Val));
5169 return false;
5170}
5171
5172/// parseDIAssignID:
5173/// ::= distinct !DIAssignID()
5174bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5175 if (!IsDistinct)
5176 return Lex.Error("missing 'distinct', required for !DIAssignID()");
5177
5178 Lex.Lex();
5179
5180 // Now eat the parens.
5181 if (parseToken(lltok::lparen, "expected '(' here"))
5182 return true;
5183 if (parseToken(lltok::rparen, "expected ')' here"))
5184 return true;
5185
5187 return false;
5188}
5189
5190/// parseGenericDINode:
5191/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5192bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5193#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5194 REQUIRED(tag, DwarfTagField, ); \
5195 OPTIONAL(header, MDStringField, ); \
5196 OPTIONAL(operands, MDFieldList, );
5198#undef VISIT_MD_FIELDS
5199
5201 (Context, tag.Val, header.Val, operands.Val));
5202 return false;
5203}
5204
5205/// parseDISubrange:
5206/// ::= !DISubrange(count: 30, lowerBound: 2)
5207/// ::= !DISubrange(count: !node, lowerBound: 2)
5208/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5209bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5210#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5211 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5212 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5213 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5214 OPTIONAL(stride, MDSignedOrMDField, );
5216#undef VISIT_MD_FIELDS
5217
5218 Metadata *Count = nullptr;
5219 Metadata *LowerBound = nullptr;
5220 Metadata *UpperBound = nullptr;
5221 Metadata *Stride = nullptr;
5222
5223 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5224 if (Bound.isMDSignedField())
5226 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5227 if (Bound.isMDField())
5228 return Bound.getMDFieldValue();
5229 return nullptr;
5230 };
5231
5232 Count = convToMetadata(count);
5233 LowerBound = convToMetadata(lowerBound);
5234 UpperBound = convToMetadata(upperBound);
5235 Stride = convToMetadata(stride);
5236
5238 (Context, Count, LowerBound, UpperBound, Stride));
5239
5240 return false;
5241}
5242
5243/// parseDIGenericSubrange:
5244/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5245/// !node3)
5246bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5247#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5248 OPTIONAL(count, MDSignedOrMDField, ); \
5249 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5250 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5251 OPTIONAL(stride, MDSignedOrMDField, );
5253#undef VISIT_MD_FIELDS
5254
5255 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5256 if (Bound.isMDSignedField())
5257 return DIExpression::get(
5258 Context, {dwarf::DW_OP_consts,
5259 static_cast<uint64_t>(Bound.getMDSignedValue())});
5260 if (Bound.isMDField())
5261 return Bound.getMDFieldValue();
5262 return nullptr;
5263 };
5264
5265 Metadata *Count = ConvToMetadata(count);
5266 Metadata *LowerBound = ConvToMetadata(lowerBound);
5267 Metadata *UpperBound = ConvToMetadata(upperBound);
5268 Metadata *Stride = ConvToMetadata(stride);
5269
5271 (Context, Count, LowerBound, UpperBound, Stride));
5272
5273 return false;
5274}
5275
5276/// parseDIEnumerator:
5277/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5278bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5279#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5280 REQUIRED(name, MDStringField, ); \
5281 REQUIRED(value, MDAPSIntField, ); \
5282 OPTIONAL(isUnsigned, MDBoolField, (false));
5284#undef VISIT_MD_FIELDS
5285
5286 if (isUnsigned.Val && value.Val.isNegative())
5287 return tokError("unsigned enumerator with negative value");
5288
5289 APSInt Value(value.Val);
5290 // Add a leading zero so that unsigned values with the msb set are not
5291 // mistaken for negative values when used for signed enumerators.
5292 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5293 Value = Value.zext(Value.getBitWidth() + 1);
5294
5295 Result =
5296 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5297
5298 return false;
5299}
5300
5301/// parseDIBasicType:
5302/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5303/// encoding: DW_ATE_encoding, flags: 0)
5304bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5305#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5306 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5307 OPTIONAL(name, MDStringField, ); \
5308 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5309 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5310 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5311 OPTIONAL(flags, DIFlagField, );
5313#undef VISIT_MD_FIELDS
5314
5315 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
5316 align.Val, encoding.Val, flags.Val));
5317 return false;
5318}
5319
5320/// parseDIStringType:
5321/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5322bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5323#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5324 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5325 OPTIONAL(name, MDStringField, ); \
5326 OPTIONAL(stringLength, MDField, ); \
5327 OPTIONAL(stringLengthExpression, MDField, ); \
5328 OPTIONAL(stringLocationExpression, MDField, ); \
5329 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5330 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5331 OPTIONAL(encoding, DwarfAttEncodingField, );
5333#undef VISIT_MD_FIELDS
5334
5337 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5338 stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
5339 return false;
5340}
5341
5342/// parseDIDerivedType:
5343/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5344/// line: 7, scope: !1, baseType: !2, size: 32,
5345/// align: 32, offset: 0, flags: 0, extraData: !3,
5346/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5347/// ptrAuthIsAddressDiscriminated: true,
5348/// ptrAuthExtraDiscriminator: 0x1234,
5349/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5350/// )
5351bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5352#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5353 REQUIRED(tag, DwarfTagField, ); \
5354 OPTIONAL(name, MDStringField, ); \
5355 OPTIONAL(file, MDField, ); \
5356 OPTIONAL(line, LineField, ); \
5357 OPTIONAL(scope, MDField, ); \
5358 REQUIRED(baseType, MDField, ); \
5359 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5360 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5361 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5362 OPTIONAL(flags, DIFlagField, ); \
5363 OPTIONAL(extraData, MDField, ); \
5364 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5365 OPTIONAL(annotations, MDField, ); \
5366 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5367 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5368 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5369 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5370 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5372#undef VISIT_MD_FIELDS
5373
5374 std::optional<unsigned> DWARFAddressSpace;
5375 if (dwarfAddressSpace.Val != UINT32_MAX)
5376 DWARFAddressSpace = dwarfAddressSpace.Val;
5377 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5378 if (ptrAuthKey.Val)
5379 PtrAuthData.emplace(
5380 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5381 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5382 ptrAuthAuthenticatesNullValues.Val);
5383
5385 (Context, tag.Val, name.Val, file.Val, line.Val,
5386 scope.Val, baseType.Val, size.Val, align.Val,
5387 offset.Val, DWARFAddressSpace, PtrAuthData,
5388 flags.Val, extraData.Val, annotations.Val));
5389 return false;
5390}
5391
5392bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5393#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5394 REQUIRED(tag, DwarfTagField, ); \
5395 OPTIONAL(name, MDStringField, ); \
5396 OPTIONAL(file, MDField, ); \
5397 OPTIONAL(line, LineField, ); \
5398 OPTIONAL(scope, MDField, ); \
5399 OPTIONAL(baseType, MDField, ); \
5400 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5401 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5402 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5403 OPTIONAL(flags, DIFlagField, ); \
5404 OPTIONAL(elements, MDField, ); \
5405 OPTIONAL(runtimeLang, DwarfLangField, ); \
5406 OPTIONAL(vtableHolder, MDField, ); \
5407 OPTIONAL(templateParams, MDField, ); \
5408 OPTIONAL(identifier, MDStringField, ); \
5409 OPTIONAL(discriminator, MDField, ); \
5410 OPTIONAL(dataLocation, MDField, ); \
5411 OPTIONAL(associated, MDField, ); \
5412 OPTIONAL(allocated, MDField, ); \
5413 OPTIONAL(rank, MDSignedOrMDField, ); \
5414 OPTIONAL(annotations, MDField, );
5416#undef VISIT_MD_FIELDS
5417
5418 Metadata *Rank = nullptr;
5419 if (rank.isMDSignedField())
5421 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5422 else if (rank.isMDField())
5423 Rank = rank.getMDFieldValue();
5424
5425 // If this has an identifier try to build an ODR type.
5426 if (identifier.Val)
5427 if (auto *CT = DICompositeType::buildODRType(
5428 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5429 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
5430 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5431 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5432 Rank, annotations.Val)) {
5433 Result = CT;
5434 return false;
5435 }
5436
5437 // Create a new node, and save it in the context if it belongs in the type
5438 // map.
5441 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5442 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5443 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5444 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5445 annotations.Val));
5446 return false;
5447}
5448
5449bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5450#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5451 OPTIONAL(flags, DIFlagField, ); \
5452 OPTIONAL(cc, DwarfCCField, ); \
5453 REQUIRED(types, MDField, );
5455#undef VISIT_MD_FIELDS
5456
5458 (Context, flags.Val, cc.Val, types.Val));
5459 return false;
5460}
5461
5462/// parseDIFileType:
5463/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5464/// checksumkind: CSK_MD5,
5465/// checksum: "000102030405060708090a0b0c0d0e0f",
5466/// source: "source file contents")
5467bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5468 // The default constructed value for checksumkind is required, but will never
5469 // be used, as the parser checks if the field was actually Seen before using
5470 // the Val.
5471#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5472 REQUIRED(filename, MDStringField, ); \
5473 REQUIRED(directory, MDStringField, ); \
5474 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5475 OPTIONAL(checksum, MDStringField, ); \
5476 OPTIONAL(source, MDStringField, );
5478#undef VISIT_MD_FIELDS
5479
5480 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5481 if (checksumkind.Seen && checksum.Seen)
5482 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5483 else if (checksumkind.Seen || checksum.Seen)
5484 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
5485
5486 MDString *Source = nullptr;
5487 if (source.Seen)
5488 Source = source.Val;
5490 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5491 return false;
5492}
5493
5494/// parseDICompileUnit:
5495/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5496/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5497/// splitDebugFilename: "abc.debug",
5498/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5499/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5500/// sysroot: "/", sdk: "MacOSX.sdk")
5501bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5502 if (!IsDistinct)
5503 return Lex.Error("missing 'distinct', required for !DICompileUnit");
5504
5505#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5506 REQUIRED(language, DwarfLangField, ); \
5507 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5508 OPTIONAL(producer, MDStringField, ); \
5509 OPTIONAL(isOptimized, MDBoolField, ); \
5510 OPTIONAL(flags, MDStringField, ); \
5511 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5512 OPTIONAL(splitDebugFilename, MDStringField, ); \
5513 OPTIONAL(emissionKind, EmissionKindField, ); \
5514 OPTIONAL(enums, MDField, ); \
5515 OPTIONAL(retainedTypes, MDField, ); \
5516 OPTIONAL(globals, MDField, ); \
5517 OPTIONAL(imports, MDField, ); \
5518 OPTIONAL(macros, MDField, ); \
5519 OPTIONAL(dwoId, MDUnsignedField, ); \
5520 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5521 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5522 OPTIONAL(nameTableKind, NameTableKindField, ); \
5523 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5524 OPTIONAL(sysroot, MDStringField, ); \
5525 OPTIONAL(sdk, MDStringField, );
5527#undef VISIT_MD_FIELDS
5528
5530 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5531 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5532 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5533 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5534 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5535 return false;
5536}
5537
5538/// parseDISubprogram:
5539/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5540/// file: !1, line: 7, type: !2, isLocal: false,
5541/// isDefinition: true, scopeLine: 8, containingType: !3,
5542/// virtuality: DW_VIRTUALTIY_pure_virtual,
5543/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5544/// spFlags: 10, isOptimized: false, templateParams: !4,
5545/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5546/// annotations: !8)
5547bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5548 auto Loc = Lex.getLoc();
5549#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5550 OPTIONAL(scope, MDField, ); \
5551 OPTIONAL(name, MDStringField, ); \
5552 OPTIONAL(linkageName, MDStringField, ); \
5553 OPTIONAL(file, MDField, ); \
5554 OPTIONAL(line, LineField, ); \
5555 OPTIONAL(type, MDField, ); \
5556 OPTIONAL(isLocal, MDBoolField, ); \
5557 OPTIONAL(isDefinition, MDBoolField, (true)); \
5558 OPTIONAL(scopeLine, LineField, ); \
5559 OPTIONAL(containingType, MDField, ); \
5560 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5561 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5562 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5563 OPTIONAL(flags, DIFlagField, ); \
5564 OPTIONAL(spFlags, DISPFlagField, ); \
5565 OPTIONAL(isOptimized, MDBoolField, ); \
5566 OPTIONAL(unit, MDField, ); \
5567 OPTIONAL(templateParams, MDField, ); \
5568 OPTIONAL(declaration, MDField, ); \
5569 OPTIONAL(retainedNodes, MDField, ); \
5570 OPTIONAL(thrownTypes, MDField, ); \
5571 OPTIONAL(annotations, MDField, ); \
5572 OPTIONAL(targetFuncName, MDStringField, );
5574#undef VISIT_MD_FIELDS
5575
5576 // An explicit spFlags field takes precedence over individual fields in
5577 // older IR versions.
5578 DISubprogram::DISPFlags SPFlags =
5579 spFlags.Seen ? spFlags.Val
5580 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5581 isOptimized.Val, virtuality.Val);
5582 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5583 return Lex.Error(
5584 Loc,
5585 "missing 'distinct', required for !DISubprogram that is a Definition");
5588 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5589 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5590 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5591 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5592 targetFuncName.Val));
5593 return false;
5594}
5595
5596/// parseDILexicalBlock:
5597/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5598bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5599#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5600 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5601 OPTIONAL(file, MDField, ); \
5602 OPTIONAL(line, LineField, ); \
5603 OPTIONAL(column, ColumnField, );
5605#undef VISIT_MD_FIELDS
5606
5608 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5609 return false;
5610}
5611
5612/// parseDILexicalBlockFile:
5613/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5614bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5615#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5616 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5617 OPTIONAL(file, MDField, ); \
5618 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5620#undef VISIT_MD_FIELDS
5621
5623 (Context, scope.Val, file.Val, discriminator.Val));
5624 return false;
5625}
5626
5627/// parseDICommonBlock:
5628/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5629bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5630#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5631 REQUIRED(scope, MDField, ); \
5632 OPTIONAL(declaration, MDField, ); \
5633 OPTIONAL(name, MDStringField, ); \
5634 OPTIONAL(file, MDField, ); \
5635 OPTIONAL(line, LineField, );
5637#undef VISIT_MD_FIELDS
5638
5640 (Context, scope.Val, declaration.Val, name.Val,
5641 file.Val, line.Val));
5642 return false;
5643}
5644
5645/// parseDINamespace:
5646/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5647bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5648#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5649 REQUIRED(scope, MDField, ); \
5650 OPTIONAL(name, MDStringField, ); \
5651 OPTIONAL(exportSymbols, MDBoolField, );
5653#undef VISIT_MD_FIELDS
5654
5656 (Context, scope.Val, name.Val, exportSymbols.Val));
5657 return false;
5658}
5659
5660/// parseDIMacro:
5661/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5662/// "SomeValue")
5663bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5664#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5665 REQUIRED(type, DwarfMacinfoTypeField, ); \
5666 OPTIONAL(line, LineField, ); \
5667 REQUIRED(name, MDStringField, ); \
5668 OPTIONAL(value, MDStringField, );
5670#undef VISIT_MD_FIELDS
5671
5673 (Context, type.Val, line.Val, name.Val, value.Val));
5674 return false;
5675}
5676
5677/// parseDIMacroFile:
5678/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5679bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5680#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5681 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5682 OPTIONAL(line, LineField, ); \
5683 REQUIRED(file, MDField, ); \
5684 OPTIONAL(nodes, MDField, );
5686#undef VISIT_MD_FIELDS
5687
5689 (Context, type.Val, line.Val, file.Val, nodes.Val));
5690 return false;
5691}
5692
5693/// parseDIModule:
5694/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5695/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5696/// file: !1, line: 4, isDecl: false)
5697bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5698#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5699 REQUIRED(scope, MDField, ); \
5700 REQUIRED(name, MDStringField, ); \
5701 OPTIONAL(configMacros, MDStringField, ); \
5702 OPTIONAL(includePath, MDStringField, ); \
5703 OPTIONAL(apinotes, MDStringField, ); \
5704 OPTIONAL(file, MDField, ); \
5705 OPTIONAL(line, LineField, ); \
5706 OPTIONAL(isDecl, MDBoolField, );
5708#undef VISIT_MD_FIELDS
5709
5710 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5711 configMacros.Val, includePath.Val,
5712 apinotes.Val, line.Val, isDecl.Val));
5713 return false;
5714}
5715
5716/// parseDITemplateTypeParameter:
5717/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5718bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5719#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5720 OPTIONAL(name, MDStringField, ); \
5721 REQUIRED(type, MDField, ); \
5722 OPTIONAL(defaulted, MDBoolField, );
5724#undef VISIT_MD_FIELDS
5725
5727 (Context, name.Val, type.Val, defaulted.Val));
5728 return false;
5729}
5730
5731/// parseDITemplateValueParameter:
5732/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5733/// name: "V", type: !1, defaulted: false,
5734/// value: i32 7)
5735bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5736#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5737 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5738 OPTIONAL(name, MDStringField, ); \
5739 OPTIONAL(type, MDField, ); \
5740 OPTIONAL(defaulted, MDBoolField, ); \
5741 REQUIRED(value, MDField, );
5742
5744#undef VISIT_MD_FIELDS
5745
5748 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5749 return false;
5750}
5751
5752/// parseDIGlobalVariable:
5753/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5754/// file: !1, line: 7, type: !2, isLocal: false,
5755/// isDefinition: true, templateParams: !3,
5756/// declaration: !4, align: 8)
5757bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5758#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5759 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5760 OPTIONAL(scope, MDField, ); \
5761 OPTIONAL(linkageName, MDStringField, ); \
5762 OPTIONAL(file, MDField, ); \
5763 OPTIONAL(line, LineField, ); \
5764 OPTIONAL(type, MDField, ); \
5765 OPTIONAL(isLocal, MDBoolField, ); \
5766 OPTIONAL(isDefinition, MDBoolField, (true)); \
5767 OPTIONAL(templateParams, MDField, ); \
5768 OPTIONAL(declaration, MDField, ); \
5769 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5770 OPTIONAL(annotations, MDField, );
5772#undef VISIT_MD_FIELDS
5773
5774 Result =
5776 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5777 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5778 declaration.Val, templateParams.Val, align.Val,
5779 annotations.Val));
5780 return false;
5781}
5782
5783/// parseDILocalVariable:
5784/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5785/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5786/// align: 8)
5787/// ::= !DILocalVariable(scope: !0, name: "foo",
5788/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5789/// align: 8)
5790bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5791#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5792 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5793 OPTIONAL(name, MDStringField, ); \
5794 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5795 OPTIONAL(file, MDField, ); \
5796 OPTIONAL(line, LineField, ); \
5797 OPTIONAL(type, MDField, ); \
5798 OPTIONAL(flags, DIFlagField, ); \
5799 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5800 OPTIONAL(annotations, MDField, );
5802#undef VISIT_MD_FIELDS
5803
5805 (Context, scope.Val, name.Val, file.Val, line.Val,
5806 type.Val, arg.Val, flags.Val, align.Val,
5807 annotations.Val));
5808 return false;
5809}
5810
5811/// parseDILabel:
5812/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5813bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5814#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5815 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5816 REQUIRED(name, MDStringField, ); \
5817 REQUIRED(file, MDField, ); \
5818 REQUIRED(line, LineField, );
5820#undef VISIT_MD_FIELDS
5821
5823 (Context, scope.Val, name.Val, file.Val, line.Val));
5824 return false;
5825}
5826
5827/// parseDIExpression:
5828/// ::= !DIExpression(0, 7, -1)
5829bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5830 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5831 Lex.Lex();
5832
5833 if (parseToken(lltok::lparen, "expected '(' here"))
5834 return true;
5835
5837 if (Lex.getKind() != lltok::rparen)
5838 do {
5839 if (Lex.getKind() == lltok::DwarfOp) {
5840 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5841 Lex.Lex();
5842 Elements.push_back(Op);
5843 continue;
5844 }
5845 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5846 }
5847
5848 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5849 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5850 Lex.Lex();
5851 Elements.push_back(Op);
5852 continue;
5853 }
5854 return tokError(Twine("invalid DWARF attribute encoding '") +
5855 Lex.getStrVal() + "'");
5856 }
5857
5858 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5859 return tokError("expected unsigned integer");
5860
5861 auto &U = Lex.getAPSIntVal();
5862 if (U.ugt(UINT64_MAX))
5863 return tokError("element too large, limit is " + Twine(UINT64_MAX));
5864 Elements.push_back(U.getZExtValue());
5865 Lex.Lex();
5866 } while (EatIfPresent(lltok::comma));
5867
5868 if (parseToken(lltok::rparen, "expected ')' here"))
5869 return true;
5870
5871 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5872 return false;
5873}
5874
5875/// ParseDIArgList:
5876/// ::= !DIArgList(i32 7, i64 %0)
5877bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
5878 assert(PFS && "Expected valid function state");
5879 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5880 Lex.Lex();
5881
5882 if (parseToken(lltok::lparen, "expected '(' here"))
5883 return true;
5884
5886 if (Lex.getKind() != lltok::rparen)
5887 do {
5888 Metadata *MD;
5889 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5890 return true;
5891 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5892 } while (EatIfPresent(lltok::comma));
5893
5894 if (parseToken(lltok::rparen, "expected ')' here"))
5895 return true;
5896
5897 MD = DIArgList::get(Context, Args);
5898 return false;
5899}
5900
5901/// parseDIGlobalVariableExpression:
5902/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5903bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5904 bool IsDistinct) {
5905#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5906 REQUIRED(var, MDField, ); \
5907 REQUIRED(expr, MDField, );
5909#undef VISIT_MD_FIELDS
5910
5911 Result =
5912 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5913 return false;
5914}
5915
5916/// parseDIObjCProperty:
5917/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5918/// getter: "getFoo", attributes: 7, type: !2)
5919bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5921 OPTIONAL(name, MDStringField, ); \
5922 OPTIONAL(file, MDField, ); \
5923 OPTIONAL(line, LineField, ); \
5924 OPTIONAL(setter, MDStringField, ); \
5925 OPTIONAL(getter, MDStringField, ); \
5926 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5927 OPTIONAL(type, MDField, );
5929#undef VISIT_MD_FIELDS
5930
5932 (Context, name.Val, file.Val, line.Val, setter.Val,
5933 getter.Val, attributes.Val, type.Val));
5934 return false;
5935}
5936
5937/// parseDIImportedEntity:
5938/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5939/// line: 7, name: "foo", elements: !2)
5940bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 REQUIRED(tag, DwarfTagField, ); \
5943 REQUIRED(scope, MDField, ); \
5944 OPTIONAL(entity, MDField, ); \
5945 OPTIONAL(file, MDField, ); \
5946 OPTIONAL(line, LineField, ); \
5947 OPTIONAL(name, MDStringField, ); \
5948 OPTIONAL(elements, MDField, );
5950#undef VISIT_MD_FIELDS
5951
5953 (Context, tag.Val, scope.Val, entity.Val, file.Val,
5954 line.Val, name.Val, elements.Val));
5955 return false;
5956}
5957
5958#undef PARSE_MD_FIELD
5959#undef NOP_FIELD
5960#undef REQUIRE_FIELD
5961#undef DECLARE_FIELD
5962
5963/// parseMetadataAsValue
5964/// ::= metadata i32 %local
5965/// ::= metadata i32 @global
5966/// ::= metadata i32 7
5967/// ::= metadata !0
5968/// ::= metadata !{...}
5969/// ::= metadata !"string"
5970bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5971 // Note: the type 'metadata' has already been parsed.
5972 Metadata *MD;
5973 if (parseMetadata(MD, &PFS))
5974 return true;
5975
5976 V = MetadataAsValue::get(Context, MD);
5977 return false;
5978}
5979
5980/// parseValueAsMetadata
5981/// ::= i32 %local
5982/// ::= i32 @global
5983/// ::= i32 7
5984bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5985 PerFunctionState *PFS) {
5986 Type *Ty;
5987 LocTy Loc;
5988 if (parseType(Ty, TypeMsg, Loc))
5989 return true;
5990 if (Ty->isMetadataTy())
5991 return error(Loc, "invalid metadata-value-metadata roundtrip");
5992
5993 Value *V;
5994 if (parseValue(Ty, V, PFS))
5995 return true;
5996
5997 MD = ValueAsMetadata::get(V);
5998 return false;
5999}
6000
6001/// parseMetadata
6002/// ::= i32 %local
6003/// ::= i32 @global
6004/// ::= i32 7
6005/// ::= !42
6006/// ::= !{...}
6007/// ::= !"string"
6008/// ::= !DILocation(...)
6009bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6010 if (Lex.getKind() == lltok::MetadataVar) {
6011 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6012 // so parsing this requires a Function State.
6013 if (Lex.getStrVal() == "DIArgList") {
6014 Metadata *AL;
6015 if (parseDIArgList(AL, PFS))
6016 return true;
6017 MD = AL;
6018 return false;
6019 }
6020 MDNode *N;
6021 if (parseSpecializedMDNode(N)) {
6022 return true;
6023 }
6024 MD = N;
6025 return false;
6026 }
6027
6028 // ValueAsMetadata:
6029 // <type> <value>
6030 if (Lex.getKind() != lltok::exclaim)
6031 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6032
6033 // '!'.
6034 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6035 Lex.Lex();
6036
6037 // MDString:
6038 // ::= '!' STRINGCONSTANT
6039 if (Lex.getKind() == lltok::StringConstant) {
6040 MDString *S;
6041 if (parseMDString(S))
6042 return true;
6043 MD = S;
6044 return false;
6045 }
6046
6047 // MDNode:
6048 // !{ ... }
6049 // !7
6050 MDNode *N;
6051 if (parseMDNodeTail(N))
6052 return true;
6053 MD = N;
6054 return false;
6055}
6056
6057//===----------------------------------------------------------------------===//
6058// Function Parsing.
6059//===----------------------------------------------------------------------===//
6060
6061bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6062 PerFunctionState *PFS) {
6063 if (Ty->isFunctionTy())
6064 return error(ID.Loc, "functions are not values, refer to them as pointers");
6065
6066 switch (ID.Kind) {
6067 case ValID::t_LocalID:
6068 if (!PFS)
6069 return error(ID.Loc, "invalid use of function-local name");
6070 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6071 return V == nullptr;
6072 case ValID::t_LocalName:
6073 if (!PFS)
6074 return error(ID.Loc, "invalid use of function-local name");
6075 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6076 return V == nullptr;
6077 case ValID::t_InlineAsm: {
6078 if (!ID.FTy)
6079 return error(ID.Loc, "invalid type for inline asm constraint string");
6080 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6081 return error(ID.Loc, toString(std::move(Err)));
6082 V = InlineAsm::get(
6083 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6084 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6085 return false;
6086 }
6088 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6089 if (V && ID.NoCFI)
6090 V = NoCFIValue::get(cast<GlobalValue>(V));
6091 return V == nullptr;
6092 case ValID::t_GlobalID:
6093 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6094 if (V && ID.NoCFI)
6095 V = NoCFIValue::get(cast<GlobalValue>(V));
6096 return V == nullptr;
6097 case ValID::t_APSInt:
6098 if (!Ty->isIntegerTy())
6099 return error(ID.Loc, "integer constant must have integer type");
6100 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6101 V = ConstantInt::get(Context, ID.APSIntVal);
6102 return false;
6103 case ValID::t_APFloat:
6104 if (!Ty->isFloatingPointTy() ||
6105 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6106 return error(ID.Loc, "floating point constant invalid for type");
6107
6108 // The lexer has no type info, so builds all half, bfloat, float, and double
6109 // FP constants as double. Fix this here. Long double does not need this.
6110 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6111 // Check for signaling before potentially converting and losing that info.
6112 bool IsSNAN = ID.APFloatVal.isSignaling();
6113 bool Ignored;
6114 if (Ty->isHalfTy())
6116 &Ignored);
6117 else if (Ty->isBFloatTy())
6118 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6119 &Ignored);
6120 else if (Ty->isFloatTy())
6122 &Ignored);
6123 if (IsSNAN) {
6124 // The convert call above may quiet an SNaN, so manufacture another
6125 // SNaN. The bitcast works because the payload (significand) parameter
6126 // is truncated to fit.
6127 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6128 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6129 ID.APFloatVal.isNegative(), &Payload);
6130 }
6131 }
6132 V = ConstantFP::get(Context, ID.APFloatVal);
6133
6134 if (V->getType() != Ty)
6135 return error(ID.Loc, "floating point constant does not have type '" +
6136 getTypeString(Ty) + "'");
6137
6138 return false;
6139 case ValID::t_Null:
6140 if (!Ty->isPointerTy())
6141 return error(ID.Loc, "null must be a pointer type");
6142 V = ConstantPointerNull::get(cast<PointerType>(Ty));
6143 return false;
6144 case ValID::t_Undef:
6145 // FIXME: LabelTy should not be a first-class type.
6146 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6147 return error(ID.Loc, "invalid type for undef constant");
6148 V = UndefValue::get(Ty);
6149 return false;
6151 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6152 return error(ID.Loc, "invalid empty array initializer");
6153 V = UndefValue::get(Ty);
6154 return false;
6155 case ValID::t_Zero:
6156 // FIXME: LabelTy should not be a first-class type.
6157 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6158 return error(ID.Loc, "invalid type for null constant");
6159 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6160 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6161 return error(ID.Loc, "invalid type for null constant");
6163 return false;
6164 case ValID::t_None:
6165 if (!Ty->isTokenTy())
6166 return error(ID.Loc, "invalid type for none constant");
6168 return false;
6169 case ValID::t_Poison:
6170 // FIXME: LabelTy should not be a first-class type.
6171 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6172 return error(ID.Loc, "invalid type for poison constant");
6173 V = PoisonValue::get(Ty);
6174 return false;
6175 case ValID::t_Constant:
6176 if (ID.ConstantVal->getType() != Ty)
6177 return error(ID.Loc, "constant expression type mismatch: got type '" +
6178 getTypeString(ID.ConstantVal->getType()) +
6179 "' but expected '" + getTypeString(Ty) + "'");
6180 V = ID.ConstantVal;
6181 return false;
6183 if (!Ty->isVectorTy())
6184 return error(ID.Loc, "vector constant must have vector type");
6185 if (ID.ConstantVal->getType() != Ty->getScalarType())
6186 return error(ID.Loc, "constant expression type mismatch: got type '" +
6187 getTypeString(ID.ConstantVal->getType()) +
6188 "' but expected '" +
6189 getTypeString(Ty->getScalarType()) + "'");
6190 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6191 ID.ConstantVal);
6192 return false;
6195 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6196 if (ST->getNumElements() != ID.UIntVal)
6197 return error(ID.Loc,
6198 "initializer with struct type has wrong # elements");
6199 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6200 return error(ID.Loc, "packed'ness of initializer and type don't match");
6201
6202 // Verify that the elements are compatible with the structtype.
6203 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6204 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6205 return error(
6206 ID.Loc,
6207 "element " + Twine(i) +
6208 " of struct initializer doesn't match struct element type");
6209
6211 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6212 } else
6213 return error(ID.Loc, "constant expression type mismatch");
6214 return false;
6215 }
6216 llvm_unreachable("Invalid ValID");
6217}
6218
6219bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6220 C = nullptr;
6221 ValID ID;
6222 auto Loc = Lex.getLoc();
6223 if (parseValID(ID, /*PFS=*/nullptr))
6224 return true;
6225 switch (ID.Kind) {
6226 case ValID::t_APSInt:
6227 case ValID::t_APFloat:
6228 case ValID::t_Undef:
6229 case ValID::t_Constant:
6233 Value *V;
6234 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6235 return true;
6236 assert(isa<Constant>(V) && "Expected a constant value");
6237 C = cast<Constant>(V);
6238 return false;
6239 }
6240 case ValID::t_Null:
6242 return false;
6243 default:
6244 return error(Loc, "expected a constant value");
6245 }
6246}
6247
6248bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6249 V = nullptr;
6250 ValID ID;
6251 return parseValID(ID, PFS, Ty) ||
6252 convertValIDToValue(Ty, ID, V, PFS);
6253}
6254
6255bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6256 Type *Ty = nullptr;
6257 return parseType(Ty) || parseValue(Ty, V, PFS);
6258}
6259
6260bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6261 PerFunctionState &PFS) {
6262 Value *V;
6263 Loc = Lex.getLoc();
6264 if (parseTypeAndValue(V, PFS))
6265 return true;
6266 if (!isa<BasicBlock>(V))
6267 return error(Loc, "expected a basic block");
6268 BB = cast<BasicBlock>(V);
6269 return false;
6270}
6271
6273 // Exit early for the common (non-debug-intrinsic) case.
6274 // We can make this the only check when we begin supporting all "llvm.dbg"
6275 // intrinsics in the new debug info format.
6276 if (!Name.starts_with("llvm.dbg."))
6277 return false;
6279 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6280 FnID == Intrinsic::dbg_assign;
6281}
6282
6283/// FunctionHeader
6284/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6285/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6286/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6287/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6288bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6289 unsigned &FunctionNumber,
6290 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6291 // parse the linkage.
6292 LocTy LinkageLoc = Lex.getLoc();
6293 unsigned Linkage;
6294 unsigned Visibility;
6295 unsigned DLLStorageClass;
6296 bool DSOLocal;
6297 AttrBuilder RetAttrs(M->getContext());
6298 unsigned CC;
6299 bool HasLinkage;
6300 Type *RetType = nullptr;
6301 LocTy RetTypeLoc = Lex.getLoc();
6302 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6303 DSOLocal) ||
6304 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6305 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6306 return true;
6307
6308 // Verify that the linkage is ok.
6309 switch ((GlobalValue::LinkageTypes)Linkage) {
6311 break; // always ok.
6313 if (IsDefine)
6314 return error(LinkageLoc, "invalid linkage for function definition");
6315 break;
6323 if (!IsDefine)
6324 return error(LinkageLoc, "invalid linkage for function declaration");
6325 break;
6328 return error(LinkageLoc, "invalid function linkage type");
6329 }
6330
6331 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6332 return error(LinkageLoc,
6333 "symbol with local linkage must have default visibility");
6334
6335 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6336 return error(LinkageLoc,
6337 "symbol with local linkage cannot have a DLL storage class");
6338
6339 if (!FunctionType::isValidReturnType(RetType))
6340 return error(RetTypeLoc, "invalid function return type");
6341
6342 LocTy NameLoc = Lex.getLoc();
6343
6344 std::string FunctionName;
6345 if (Lex.getKind() == lltok::GlobalVar) {
6346 FunctionName = Lex.getStrVal();
6347 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6348 FunctionNumber = Lex.getUIntVal();
6349 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6350 FunctionNumber))
6351 return true;
6352 } else {
6353 return tokError("expected function name");
6354 }
6355
6356 Lex.Lex();
6357
6358 if (Lex.getKind() != lltok::lparen)
6359 return tokError("expected '(' in function argument list");
6360
6362 bool IsVarArg;
6363 AttrBuilder FuncAttrs(M->getContext());
6364 std::vector<unsigned> FwdRefAttrGrps;
6365 LocTy BuiltinLoc;
6366 std::string Section;
6367 std::string Partition;
6368 MaybeAlign Alignment;
6369 std::string GC;
6371 unsigned AddrSpace = 0;
6372 Constant *Prefix = nullptr;
6373 Constant *Prologue = nullptr;
6374 Constant *PersonalityFn = nullptr;
6375 Comdat *C;
6376
6377 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6378 parseOptionalUnnamedAddr(UnnamedAddr) ||
6379 parseOptionalProgramAddrSpace(AddrSpace) ||
6380 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6381 BuiltinLoc) ||
6382 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6383 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6384 parseOptionalComdat(FunctionName, C) ||
6385 parseOptionalAlignment(Alignment) ||
6386 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6387 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6388 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6389 (EatIfPresent(lltok::kw_personality) &&
6390 parseGlobalTypeAndValue(PersonalityFn)))
6391 return true;
6392
6393 if (FuncAttrs.contains(Attribute::Builtin))
6394 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6395
6396 // If the alignment was parsed as an attribute, move to the alignment field.
6397 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6398 Alignment = A;
6399 FuncAttrs.removeAttribute(Attribute::Alignment);
6400 }
6401
6402 // Okay, if we got here, the function is syntactically valid. Convert types
6403 // and do semantic checks.
6404 std::vector<Type*> ParamTypeList;
6406
6407 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6408 ParamTypeList.push_back(ArgList[i].Ty);
6409 Attrs.push_back(ArgList[i].Attrs);
6410 }
6411
6412 AttributeList PAL =
6413 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6414 AttributeSet::get(Context, RetAttrs), Attrs);
6415
6416 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6417 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6418
6419 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6420 PointerType *PFT = PointerType::get(FT, AddrSpace);
6421
6422 Fn = nullptr;
6423 GlobalValue *FwdFn = nullptr;
6424 if (!FunctionName.empty()) {
6425 // If this was a definition of a forward reference, remove the definition
6426 // from the forward reference table and fill in the forward ref.
6427 auto FRVI = ForwardRefVals.find(FunctionName);
6428 if (FRVI != ForwardRefVals.end()) {
6429 FwdFn = FRVI->second.first;
6430 if (FwdFn->getType() != PFT)
6431 return error(FRVI->second.second,
6432 "invalid forward reference to "
6433 "function '" +
6434 FunctionName +
6435 "' with wrong type: "
6436 "expected '" +
6437 getTypeString(PFT) + "' but was '" +
6438 getTypeString(FwdFn->getType()) + "'");
6439 ForwardRefVals.erase(FRVI);
6440 } else if ((Fn = M->getFunction(FunctionName))) {
6441 // Reject redefinitions.
6442 return error(NameLoc,
6443 "invalid redefinition of function '" + FunctionName + "'");
6444 } else if (M->getNamedValue(FunctionName)) {
6445 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6446 }
6447
6448 } else {
6449 // Handle @"", where a name is syntactically specified, but semantically
6450 // missing.
6451 if (FunctionNumber == (unsigned)-1)
6452 FunctionNumber = NumberedVals.getNext();
6453
6454 // If this is a definition of a forward referenced function, make sure the
6455 // types agree.
6456 auto I = ForwardRefValIDs.find(FunctionNumber);
6457 if (I != ForwardRefValIDs.end()) {
6458 FwdFn = I->second.first;
6459 if (FwdFn->getType() != PFT)
6460 return error(NameLoc, "type of definition and forward reference of '@" +
6461 Twine(FunctionNumber) +
6462 "' disagree: "
6463 "expected '" +
6464 getTypeString(PFT) + "' but was '" +
6465 getTypeString(FwdFn->getType()) + "'");
6466 ForwardRefValIDs.erase(I);
6467 }
6468 }
6469
6471 FunctionName, M);
6472
6473 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6474
6475 if (FunctionName.empty())
6476 NumberedVals.add(FunctionNumber, Fn);
6477
6479 maybeSetDSOLocal(DSOLocal, *Fn);
6482 Fn->setCallingConv(CC);
6483 Fn->setAttributes(PAL);
6484 Fn->setUnnamedAddr(UnnamedAddr);
6485 if (Alignment)
6486 Fn->setAlignment(*Alignment);
6487 Fn->setSection(Section);
6488 Fn->setPartition(Partition);
6489 Fn->setComdat(C);
6490 Fn->setPersonalityFn(PersonalityFn);
6491 if (!GC.empty()) Fn->setGC(GC);
6492 Fn->setPrefixData(Prefix);
6493 Fn->setPrologueData(Prologue);
6494 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6495
6496 // Add all of the arguments we parsed to the function.
6497 Function::arg_iterator ArgIt = Fn->arg_begin();
6498 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6499 // If the argument has a name, insert it into the argument symbol table.
6500 if (ArgList[i].Name.empty()) continue;
6501
6502 // Set the name, if it conflicted, it will be auto-renamed.
6503 ArgIt->setName(ArgList[i].Name);
6504
6505 if (ArgIt->getName() != ArgList[i].Name)
6506 return error(ArgList[i].Loc,
6507 "redefinition of argument '%" + ArgList[i].Name + "'");
6508 }
6509
6510 if (FwdFn) {
6511 FwdFn->replaceAllUsesWith(Fn);
6512 FwdFn->eraseFromParent();
6513 }
6514
6515 if (IsDefine)
6516 return false;
6517
6518 // Check the declaration has no block address forward references.
6519 ValID ID;
6520 if (FunctionName.empty()) {
6521 ID.Kind = ValID::t_GlobalID;
6522 ID.UIntVal = FunctionNumber;
6523 } else {
6524 ID.Kind = ValID::t_GlobalName;
6525 ID.StrVal = FunctionName;
6526 }
6527 auto Blocks = ForwardRefBlockAddresses.find(ID);
6528 if (Blocks != ForwardRefBlockAddresses.end())
6529 return error(Blocks->first.Loc,
6530 "cannot take blockaddress inside a declaration");
6531 return false;
6532}
6533
6534bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6535 ValID ID;
6536 if (FunctionNumber == -1) {
6537 ID.Kind = ValID::t_GlobalName;
6538 ID.StrVal = std::string(F.getName());
6539 } else {
6540 ID.Kind = ValID::t_GlobalID;
6541 ID.UIntVal = FunctionNumber;
6542 }
6543
6544 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6545 if (Blocks == P.ForwardRefBlockAddresses.end())
6546 return false;
6547
6548 for (const auto &I : Blocks->second) {
6549 const ValID &BBID = I.first;
6550 GlobalValue *GV = I.second;
6551
6552 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6553 "Expected local id or name");
6554 BasicBlock *BB;
6555 if (BBID.Kind == ValID::t_LocalName)
6556 BB = getBB(BBID.StrVal, BBID.Loc);
6557 else
6558 BB = getBB(BBID.UIntVal, BBID.Loc);
6559 if (!BB)
6560 return P.error(BBID.Loc, "referenced value is not a basic block");
6561
6562 Value *ResolvedVal = BlockAddress::get(&F, BB);
6563 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6564 ResolvedVal);
6565 if (!ResolvedVal)
6566 return true;
6567 GV->replaceAllUsesWith(ResolvedVal);
6568 GV->eraseFromParent();
6569 }
6570
6571 P.ForwardRefBlockAddresses.erase(Blocks);
6572 return false;
6573}
6574
6575/// parseFunctionBody
6576/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6577bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6578 ArrayRef<unsigned> UnnamedArgNums) {
6579 if (Lex.getKind() != lltok::lbrace)
6580 return tokError("expected '{' in function body");
6581 Lex.Lex(); // eat the {.
6582
6583 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
6584
6585 // Resolve block addresses and allow basic blocks to be forward-declared
6586 // within this function.
6587 if (PFS.resolveForwardRefBlockAddresses())
6588 return true;
6589 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6590
6591 // We need at least one basic block.
6592 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6593 return tokError("function body requires at least one basic block");
6594
6595 while (Lex.getKind() != lltok::rbrace &&
6597 if (parseBasicBlock(PFS))
6598 return true;
6599
6600 while (Lex.getKind() != lltok::rbrace)
6601 if (parseUseListOrder(&PFS))
6602 return true;
6603
6604 // Eat the }.
6605 Lex.Lex();
6606
6607 // Verify function is ok.
6608 return PFS.finishFunction();
6609}
6610
6611/// parseBasicBlock
6612/// ::= (LabelStr|LabelID)? Instruction*
6613bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6614 // If this basic block starts out with a name, remember it.
6615 std::string Name;
6616 int NameID = -1;
6617 LocTy NameLoc = Lex.getLoc();
6618 if (Lex.getKind() == lltok::LabelStr) {
6619 Name = Lex.getStrVal();
6620 Lex.Lex();
6621 } else if (Lex.getKind() == lltok::LabelID) {
6622 NameID = Lex.getUIntVal();
6623 Lex.Lex();
6624 }
6625
6626 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6627 if (!BB)
6628 return true;
6629
6630 std::string NameStr;
6631
6632 // Parse the instructions and debug values in this block until we get a
6633 // terminator.
6634 Instruction *Inst;
6635 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
6636 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
6637 SmallVector<DbgRecordPtr> TrailingDbgRecord;
6638 do {
6639 // Handle debug records first - there should always be an instruction
6640 // following the debug records, i.e. they cannot appear after the block
6641 // terminator.
6642 while (Lex.getKind() == lltok::hash) {
6643 if (SeenOldDbgInfoFormat)
6644 return error(Lex.getLoc(), "debug record should not appear in a module "
6645 "containing debug info intrinsics");
6646 if (!SeenNewDbgInfoFormat)
6647 M->setNewDbgInfoFormatFlag(true);
6648 SeenNewDbgInfoFormat = true;
6649 Lex.Lex();
6650
6651 DbgRecord *DR;
6652 if (parseDebugRecord(DR, PFS))
6653 return true;
6654 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6655 }
6656
6657 // This instruction may have three possibilities for a name: a) none
6658 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6659 LocTy NameLoc = Lex.getLoc();
6660 int NameID = -1;
6661 NameStr = "";
6662
6663 if (Lex.getKind() == lltok::LocalVarID) {
6664 NameID = Lex.getUIntVal();
6665 Lex.Lex();
6666 if (parseToken(lltok::equal, "expected '=' after instruction id"))
6667 return true;
6668 } else if (Lex.getKind() == lltok::LocalVar) {
6669 NameStr = Lex.getStrVal();
6670 Lex.Lex();
6671 if (parseToken(lltok::equal, "expected '=' after instruction name"))
6672 return true;
6673 }
6674
6675 switch (parseInstruction(Inst, BB, PFS)) {
6676 default:
6677 llvm_unreachable("Unknown parseInstruction result!");
6678 case InstError: return true;
6679 case InstNormal:
6680 Inst->insertInto(BB, BB->end());
6681
6682 // With a normal result, we check to see if the instruction is followed by
6683 // a comma and metadata.
6684 if (EatIfPresent(lltok::comma))
6685 if (parseInstructionMetadata(*Inst))
6686 return true;
6687 break;
6688 case InstExtraComma:
6689 Inst->insertInto(BB, BB->end());
6690
6691 // If the instruction parser ate an extra comma at the end of it, it
6692 // *must* be followed by metadata.
6693 if (parseInstructionMetadata(*Inst))
6694 return true;
6695 break;
6696 }
6697
6698 // Set the name on the instruction.
6699 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6700 return true;
6701
6702 // Attach any preceding debug values to this instruction.
6703 for (DbgRecordPtr &DR : TrailingDbgRecord)
6704 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
6705 TrailingDbgRecord.clear();
6706 } while (!Inst->isTerminator());
6707
6708 assert(TrailingDbgRecord.empty() &&
6709 "All debug values should have been attached to an instruction.");
6710
6711 return false;
6712}
6713
6714/// parseDebugRecord
6715/// ::= #dbg_label '(' MDNode ')'
6716/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
6717/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
6718bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
6719 using RecordKind = DbgRecord::Kind;
6720 using LocType = DbgVariableRecord::LocationType;
6721 LocTy DVRLoc = Lex.getLoc();
6722 if (Lex.getKind() != lltok::DbgRecordType)
6723 return error(DVRLoc, "expected debug record type here");
6725 .Case("declare", RecordKind::ValueKind)
6726 .Case("value", RecordKind::ValueKind)
6727 .Case("assign", RecordKind::ValueKind)
6728 .Case("label", RecordKind::LabelKind);
6729
6730 // Parsing labels is trivial; parse here and early exit, otherwise go into the
6731 // full DbgVariableRecord processing stage.
6732 if (RecordType == RecordKind::LabelKind) {
6733 Lex.Lex();
6734 if (parseToken(lltok::lparen, "Expected '(' here"))
6735 return true;
6736 MDNode *Label;
6737 if (parseMDNode(Label))
6738 return true;
6739 if (parseToken(lltok::comma, "Expected ',' here"))
6740 return true;
6741 MDNode *DbgLoc;
6742 if (parseMDNode(DbgLoc))
6743 return true;
6744 if (parseToken(lltok::rparen, "Expected ')' here"))
6745 return true;
6747 return false;
6748 }
6749
6751 .Case("declare", LocType::Declare)
6752 .Case("value", LocType::Value)
6753 .Case("assign", LocType::Assign);
6754
6755 Lex.Lex();
6756 if (parseToken(lltok::lparen, "Expected '(' here"))
6757 return true;
6758
6759 // Parse Value field.
6760 Metadata *ValLocMD;
6761 if (parseMetadata(ValLocMD, &PFS))
6762 return true;
6763 if (parseToken(lltok::comma, "Expected ',' here"))
6764 return true;
6765
6766 // Parse Variable field.
6767 MDNode *Variable;
6768 if (parseMDNode(Variable))
6769 return true;
6770 if (parseToken(lltok::comma, "Expected ',' here"))
6771 return true;
6772
6773 // Parse Expression field.
6775 if (parseMDNode(Expression))
6776 return true;
6777 if (parseToken(lltok::comma, "Expected ',' here"))
6778 return true;
6779
6780 // Parse additional fields for #dbg_assign.
6781 MDNode *AssignID = nullptr;
6782 Metadata *AddressLocation = nullptr;
6783 MDNode *AddressExpression = nullptr;
6784 if (ValueType == LocType::Assign) {
6785 // Parse DIAssignID.
6786 if (parseMDNode(AssignID))
6787 return true;
6788 if (parseToken(lltok::comma, "Expected ',' here"))
6789 return true;
6790
6791 // Parse address ValueAsMetadata.
6792 if (parseMetadata(AddressLocation, &PFS))
6793 return true;
6794 if (parseToken(lltok::comma, "Expected ',' here"))
6795 return true;
6796
6797 // Parse address DIExpression.
6798 if (parseMDNode(AddressExpression))
6799 return true;
6800 if (parseToken(lltok::comma, "Expected ',' here"))
6801 return true;
6802 }
6803
6804 /// Parse DILocation.
6806 if (parseMDNode(DebugLoc))
6807 return true;
6808
6809 if (parseToken(lltok::rparen, "Expected ')' here"))
6810 return true;
6812 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
6813 AddressExpression, DebugLoc);
6814 return false;
6815}
6816//===----------------------------------------------------------------------===//
6817// Instruction Parsing.
6818//===----------------------------------------------------------------------===//
6819
6820/// parseInstruction - parse one of the many different instructions.
6821///
6822int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6823 PerFunctionState &PFS) {
6824 lltok::Kind Token = Lex.getKind();
6825 if (Token == lltok::Eof)
6826 return tokError("found end of file when expecting more instructions");
6827 LocTy Loc = Lex.getLoc();
6828 unsigned KeywordVal = Lex.getUIntVal();
6829 Lex.Lex(); // Eat the keyword.
6830
6831 switch (Token) {
6832 default:
6833 return error(Loc, "expected instruction opcode");
6834 // Terminator Instructions.
6835 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6836 case lltok::kw_ret:
6837 return parseRet(Inst, BB, PFS);
6838 case lltok::kw_br:
6839 return parseBr(Inst, PFS);
6840 case lltok::kw_switch:
6841 return parseSwitch(Inst, PFS);
6843 return parseIndirectBr(Inst, PFS);
6844 case lltok::kw_invoke:
6845 return parseInvoke(Inst, PFS);
6846 case lltok::kw_resume:
6847 return parseResume(Inst, PFS);
6849 return parseCleanupRet(Inst, PFS);
6850 case lltok::kw_catchret:
6851 return parseCatchRet(Inst, PFS);
6853 return parseCatchSwitch(Inst, PFS);
6854 case lltok::kw_catchpad:
6855 return parseCatchPad(Inst, PFS);
6857 return parseCleanupPad(Inst, PFS);
6858 case lltok::kw_callbr:
6859 return parseCallBr(Inst, PFS);
6860 // Unary Operators.
6861 case lltok::kw_fneg: {
6862 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6863 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6864 if (Res != 0)
6865 return Res;
6866 if (FMF.any())
6867 Inst->setFastMathFlags(FMF);
6868 return false;
6869 }
6870 // Binary Operators.
6871 case lltok::kw_add:
6872 case lltok::kw_sub:
6873 case lltok::kw_mul:
6874 case lltok::kw_shl: {
6875 bool NUW = EatIfPresent(lltok::kw_nuw);
6876 bool NSW = EatIfPresent(lltok::kw_nsw);
6877 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6878
6879 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6880 return true;
6881
6882 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6883 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6884 return false;
6885 }
6886 case lltok::kw_fadd:
6887 case lltok::kw_fsub:
6888 case lltok::kw_fmul:
6889 case lltok::kw_fdiv:
6890 case lltok::kw_frem: {
6891 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6892 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6893 if (Res != 0)
6894 return Res;
6895 if (FMF.any())
6896 Inst->setFastMathFlags(FMF);
6897 return 0;
6898 }
6899
6900 case lltok::kw_sdiv:
6901 case lltok::kw_udiv:
6902 case lltok::kw_lshr:
6903 case lltok::kw_ashr: {
6904 bool Exact = EatIfPresent(lltok::kw_exact);
6905
6906 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6907 return true;
6908 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6909 return false;
6910 }
6911
6912 case lltok::kw_urem:
6913 case lltok::kw_srem:
6914 return parseArithmetic(Inst, PFS, KeywordVal,
6915 /*IsFP*/ false);
6916 case lltok::kw_or: {
6917 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
6918 if (parseLogical(Inst, PFS, KeywordVal))
6919 return true;
6920 if (Disjoint)
6921 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
6922 return false;
6923 }
6924 case lltok::kw_and:
6925 case lltok::kw_xor:
6926 return parseLogical(Inst, PFS, KeywordVal);
6927 case lltok::kw_icmp:
6928 return parseCompare(Inst, PFS, KeywordVal);
6929 case lltok::kw_fcmp: {
6930 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6931 int Res = parseCompare(Inst, PFS, KeywordVal);
6932 if (Res != 0)
6933 return Res;
6934 if (FMF.any())
6935 Inst->setFastMathFlags(FMF);
6936 return 0;
6937 }
6938
6939 // Casts.
6940 case lltok::kw_uitofp:
6941 case lltok::kw_zext: {
6942 bool NonNeg = EatIfPresent(lltok::kw_nneg);
6943 bool Res = parseCast(Inst, PFS, KeywordVal);
6944 if (Res != 0)
6945 return Res;
6946 if (NonNeg)
6947 Inst->setNonNeg();
6948 return 0;
6949 }
6950 case lltok::kw_trunc: {
6951 bool NUW = EatIfPresent(lltok::kw_nuw);
6952 bool NSW = EatIfPresent(lltok::kw_nsw);
6953 if (!NUW)
6954 NUW = EatIfPresent(lltok::kw_nuw);
6955 if (parseCast(Inst, PFS, KeywordVal))
6956 return true;
6957 if (NUW)
6958 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
6959 if (NSW)
6960 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
6961 return false;
6962 }
6963 case lltok::kw_sext:
6964 case lltok::kw_fptrunc:
6965 case lltok::kw_fpext:
6966 case lltok::kw_bitcast:
6968 case lltok::kw_sitofp:
6969 case lltok::kw_fptoui:
6970 case lltok::kw_fptosi:
6971 case lltok::kw_inttoptr:
6972 case lltok::kw_ptrtoint:
6973 return parseCast(Inst, PFS, KeywordVal);
6974 // Other.
6975 case lltok::kw_select: {
6976 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6977 int Res = parseSelect(Inst, PFS);
6978 if (Res != 0)
6979 return Res;
6980 if (FMF.any()) {
6981 if (!isa<FPMathOperator>(Inst))
6982 return error(Loc, "fast-math-flags specified for select without "
6983 "floating-point scalar or vector return type");
6984 Inst->setFastMathFlags(FMF);
6985 }
6986 return 0;
6987 }
6988 case lltok::kw_va_arg:
6989 return parseVAArg(Inst, PFS);
6991 return parseExtractElement(Inst, PFS);
6993 return parseInsertElement(Inst, PFS);
6995 return parseShuffleVector(Inst, PFS);
6996 case lltok::kw_phi: {
6997 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6998 int Res = parsePHI(Inst, PFS);
6999 if (Res != 0)
7000 return Res;
7001 if (FMF.any()) {
7002 if (!isa<FPMathOperator>(Inst))
7003 return error(Loc, "fast-math-flags specified for phi without "
7004 "floating-point scalar or vector return type");
7005 Inst->setFastMathFlags(FMF);
7006 }
7007 return 0;
7008 }
7010 return parseLandingPad(Inst, PFS);
7011 case lltok::kw_freeze:
7012 return parseFreeze(Inst, PFS);
7013 // Call.
7014 case lltok::kw_call:
7015 return parseCall(Inst, PFS, CallInst::TCK_None);
7016 case lltok::kw_tail:
7017 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7018 case lltok::kw_musttail:
7019 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7020 case lltok::kw_notail:
7021 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7022 // Memory.
7023 case lltok::kw_alloca:
7024 return parseAlloc(Inst, PFS);
7025 case lltok::kw_load:
7026 return parseLoad(Inst, PFS);
7027 case lltok::kw_store:
7028 return parseStore(Inst, PFS);
7029 case lltok::kw_cmpxchg:
7030 return parseCmpXchg(Inst, PFS);
7032 return parseAtomicRMW(Inst, PFS);
7033 case lltok::kw_fence:
7034 return parseFence(Inst, PFS);
7036 return parseGetElementPtr(Inst, PFS);
7038 return parseExtractValue(Inst, PFS);
7040 return parseInsertValue(Inst, PFS);
7041 }
7042}
7043
7044/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7045bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7046 if (Opc == Instruction::FCmp) {
7047 switch (Lex.getKind()) {
7048 default:
7049 return tokError("expected fcmp predicate (e.g. 'oeq')");
7050 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7051 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7052 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7053 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7054 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7055 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7056 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7057 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7058 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7059 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7060 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7061 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7062 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7063 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7064 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7065 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7066 }
7067 } else {
7068 switch (Lex.getKind()) {
7069 default:
7070 return tokError("expected icmp predicate (e.g. 'eq')");
7071 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7072 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7073 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7074 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7075 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7076 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7077 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7078 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7079 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7080 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7081 }
7082 }
7083 Lex.Lex();
7084 return false;
7085}
7086
7087//===----------------------------------------------------------------------===//
7088// Terminator Instructions.
7089//===----------------------------------------------------------------------===//
7090
7091/// parseRet - parse a return instruction.
7092/// ::= 'ret' void (',' !dbg, !1)*
7093/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7094bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7095 PerFunctionState &PFS) {
7096 SMLoc TypeLoc = Lex.getLoc();
7097 Type *Ty = nullptr;
7098 if (parseType(Ty, true /*void allowed*/))
7099 return true;
7100
7101 Type *ResType = PFS.getFunction().getReturnType();
7102
7103 if (Ty->isVoidTy()) {
7104 if (!ResType->isVoidTy())
7105 return error(TypeLoc, "value doesn't match function result type '" +
7106 getTypeString(ResType) + "'");
7107
7108 Inst = ReturnInst::Create(Context);
7109 return false;
7110 }
7111
7112 Value *RV;
7113 if (parseValue(Ty, RV, PFS))
7114 return true;
7115
7116 if (ResType != RV->getType())
7117 return error(TypeLoc, "value doesn't match function result type '" +
7118 getTypeString(ResType) + "'");
7119
7120 Inst = ReturnInst::Create(Context, RV);
7121 return false;
7122}
7123
7124/// parseBr
7125/// ::= 'br' TypeAndValue
7126/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7127bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7128 LocTy Loc, Loc2;
7129 Value *Op0;
7130 BasicBlock *Op1, *Op2;
7131 if (parseTypeAndValue(Op0, Loc, PFS))
7132 return true;
7133
7134 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7135 Inst = BranchInst::Create(BB);
7136 return false;
7137 }
7138
7139 if (Op0->getType() != Type::getInt1Ty(Context))
7140 return error(Loc, "branch condition must have 'i1' type");
7141
7142 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7143 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7144 parseToken(lltok::comma, "expected ',' after true destination") ||
7145 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7146 return true;
7147
7148 Inst = BranchInst::Create(Op1, Op2, Op0);
7149 return false;
7150}
7151
7152/// parseSwitch
7153/// Instruction
7154/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7155/// JumpTable
7156/// ::= (TypeAndValue ',' TypeAndValue)*
7157bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7158 LocTy CondLoc, BBLoc;
7159 Value *Cond;
7160 BasicBlock *DefaultBB;
7161 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7162 parseToken(lltok::comma, "expected ',' after switch condition") ||
7163 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7164 parseToken(lltok::lsquare, "expected '[' with switch table"))
7165 return true;
7166
7167 if (!Cond->getType()->isIntegerTy())
7168 return error(CondLoc, "switch condition must have integer type");
7169
7170 // parse the jump table pairs.
7171 SmallPtrSet<Value*, 32> SeenCases;
7173 while (Lex.getKind() != lltok::rsquare) {
7174 Value *Constant;
7175 BasicBlock *DestBB;
7176
7177 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7178 parseToken(lltok::comma, "expected ',' after case value") ||
7179 parseTypeAndBasicBlock(DestBB, PFS))
7180 return true;
7181
7182 if (!SeenCases.insert(Constant).second)
7183 return error(CondLoc, "duplicate case value in switch");
7184 if (!isa<ConstantInt>(Constant))
7185 return error(CondLoc, "case value is not a constant integer");
7186
7187 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7188 }
7189
7190 Lex.Lex(); // Eat the ']'.
7191
7192 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7193 for (unsigned i = 0, e = Table.size(); i != e; ++i)
7194 SI->addCase(Table[i].first, Table[i].second);
7195 Inst = SI;
7196 return false;
7197}
7198
7199/// parseIndirectBr
7200/// Instruction
7201/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7202bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7203 LocTy AddrLoc;
7204 Value *Address;
7205 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7206 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7207 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7208 return true;
7209
7210 if (!Address->getType()->isPointerTy())
7211 return error(AddrLoc, "indirectbr address must have pointer type");
7212
7213 // parse the destination list.
7215
7216 if (Lex.getKind() != lltok::rsquare) {
7217 BasicBlock *DestBB;
7218 if (parseTypeAndBasicBlock(DestBB, PFS))
7219 return true;
7220 DestList.push_back(DestBB);
7221
7222 while (EatIfPresent(lltok::comma)) {
7223 if (parseTypeAndBasicBlock(DestBB, PFS))
7224 return true;
7225 DestList.push_back(DestBB);
7226 }
7227 }
7228
7229 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7230 return true;
7231
7233 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
7234 IBI->addDestination(DestList[i]);
7235 Inst = IBI;
7236 return false;
7237}
7238
7239// If RetType is a non-function pointer type, then this is the short syntax
7240// for the call, which means that RetType is just the return type. Infer the
7241// rest of the function argument types from the arguments that are present.
7242bool LLParser::resolveFunctionType(Type *RetType,
7243 const SmallVector<ParamInfo, 16> &ArgList,
7244 FunctionType *&FuncTy) {
7245 FuncTy = dyn_cast<FunctionType>(RetType);
7246 if (!FuncTy) {
7247 // Pull out the types of all of the arguments...
7248 std::vector<Type*> ParamTypes;
7249 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7250 ParamTypes.push_back(ArgList[i].V->getType());
7251
7252 if (!FunctionType::isValidReturnType(RetType))
7253 return true;
7254
7255 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7256 }
7257 return false;
7258}
7259
7260/// parseInvoke
7261/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7262/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7263bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7264 LocTy CallLoc = Lex.getLoc();
7265 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7266 std::vector<unsigned> FwdRefAttrGrps;
7267 LocTy NoBuiltinLoc;
7268 unsigned CC;
7269 unsigned InvokeAddrSpace;
7270 Type *RetType = nullptr;
7271 LocTy RetTypeLoc;
7272 ValID CalleeID;
7275
7276 BasicBlock *NormalBB, *UnwindBB;
7277 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7278 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7279 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7280 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7281 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7282 NoBuiltinLoc) ||
7283 parseOptionalOperandBundles(BundleList, PFS) ||
7284 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7285 parseTypeAndBasicBlock(NormalBB, PFS) ||
7286 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7287 parseTypeAndBasicBlock(UnwindBB, PFS))
7288 return true;
7289
7290 // If RetType is a non-function pointer type, then this is the short syntax
7291 // for the call, which means that RetType is just the return type. Infer the
7292 // rest of the function argument types from the arguments that are present.
7293 FunctionType *Ty;
7294 if (resolveFunctionType(RetType, ArgList, Ty))
7295 return error(RetTypeLoc, "Invalid result type for LLVM function");
7296
7297 CalleeID.FTy = Ty;
7298
7299 // Look up the callee.
7300 Value *Callee;
7301 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
7302 Callee, &PFS))
7303 return true;
7304
7305 // Set up the Attribute for the function.
7308
7309 // Loop through FunctionType's arguments and ensure they are specified
7310 // correctly. Also, gather any parameter attributes.
7311 FunctionType::param_iterator I = Ty->param_begin();
7312 FunctionType::param_iterator E = Ty->param_end();
7313 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7314 Type *ExpectedTy = nullptr;
7315 if (I != E) {
7316 ExpectedTy = *I++;
7317 } else if (!Ty->isVarArg()) {
7318 return error(ArgList[i].Loc, "too many arguments specified");
7319 }
7320
7321 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7322 return error(ArgList[i].Loc, "argument is not of expected type '" +
7323 getTypeString(ExpectedTy) + "'");
7324 Args.push_back(ArgList[i].V);
7325 ArgAttrs.push_back(ArgList[i].Attrs);
7326 }
7327
7328 if (I != E)
7329 return error(CallLoc, "not enough parameters specified for call");
7330
7331 // Finish off the Attribute and check them
7332 AttributeList PAL =
7333 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7334 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7335
7336 InvokeInst *II =
7337 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7338 II->setCallingConv(CC);
7339 II->setAttributes(PAL);
7340 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7341 Inst = II;
7342 return false;
7343}
7344
7345/// parseResume
7346/// ::= 'resume' TypeAndValue
7347bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7348 Value *Exn; LocTy ExnLoc;
7349 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7350 return true;
7351
7352 ResumeInst *RI = ResumeInst::Create(Exn);
7353 Inst = RI;
7354 return false;
7355}
7356
7357bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7358 PerFunctionState &PFS) {
7359 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7360 return true;
7361
7362 while (Lex.getKind() != lltok::rsquare) {
7363 // If this isn't the first argument, we need a comma.
7364 if (!Args.empty() &&
7365 parseToken(lltok::comma, "expected ',' in argument list"))
7366 return true;
7367
7368 // parse the argument.
7369 LocTy ArgLoc;
7370 Type *ArgTy = nullptr;
7371 if (parseType(ArgTy, ArgLoc))
7372 return true;
7373
7374 Value *V;
7375 if (ArgTy->isMetadataTy()) {
7376 if (parseMetadataAsValue(V, PFS))
7377 return true;
7378 } else {
7379 if (parseValue(ArgTy, V, PFS))
7380 return true;
7381 }
7382 Args.push_back(V);
7383 }
7384
7385 Lex.Lex(); // Lex the ']'.
7386 return false;
7387}
7388
7389/// parseCleanupRet
7390/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7391bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7392 Value *CleanupPad = nullptr;
7393
7394 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7395 return true;
7396
7397 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7398 return true;
7399
7400 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7401 return true;
7402
7403 BasicBlock *UnwindBB = nullptr;
7404 if (Lex.getKind() == lltok::kw_to) {
7405 Lex.Lex();
7406 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7407 return true;
7408 } else {
7409 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7410 return true;
7411 }
7412 }
7413
7414 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7415 return false;
7416}
7417
7418/// parseCatchRet
7419/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7420bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7421 Value *CatchPad = nullptr;
7422
7423 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7424 return true;
7425
7426 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7427 return true;
7428
7429 BasicBlock *BB;
7430 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7431 parseTypeAndBasicBlock(BB, PFS))
7432 return true;
7433
7434 Inst = CatchReturnInst::Create(CatchPad, BB);
7435 return false;
7436}
7437
7438/// parseCatchSwitch
7439/// ::= 'catchswitch' within Parent
7440bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7441 Value *ParentPad;
7442
7443 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7444 return true;
7445
7446 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7447 Lex.getKind() != lltok::LocalVarID)
7448 return tokError("expected scope value for catchswitch");
7449
7450 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7451 return true;
7452
7453 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7454 return true;
7455
7457 do {
7458 BasicBlock *DestBB;
7459 if (parseTypeAndBasicBlock(DestBB, PFS))
7460 return true;
7461 Table.push_back(DestBB);
7462 } while (EatIfPresent(lltok::comma));
7463
7464 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7465 return true;
7466
7467 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7468 return true;
7469
7470 BasicBlock *UnwindBB = nullptr;
7471 if (EatIfPresent(lltok::kw_to)) {
7472 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7473 return true;
7474 } else {
7475 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7476 return true;
7477 }
7478
7479 auto *CatchSwitch =
7480 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7481 for (BasicBlock *DestBB : Table)
7482 CatchSwitch->addHandler(DestBB);
7483 Inst = CatchSwitch;
7484 return false;
7485}
7486
7487/// parseCatchPad
7488/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7489bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7490 Value *CatchSwitch = nullptr;
7491
7492 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7493 return true;
7494
7495 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7496 return tokError("expected scope value for catchpad");
7497
7498 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7499 return true;
7500
7502 if (parseExceptionArgs(Args, PFS))
7503 return true;
7504
7505 Inst = CatchPadInst::Create(CatchSwitch, Args);
7506 return false;
7507}
7508
7509/// parseCleanupPad
7510/// ::= 'cleanuppad' within Parent ParamList
7511bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7512 Value *ParentPad = nullptr;
7513
7514 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7515 return true;
7516
7517 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7518 Lex.getKind() != lltok::LocalVarID)
7519 return tokError("expected scope value for cleanuppad");
7520
7521 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7522 return true;
7523
7525 if (parseExceptionArgs(Args, PFS))
7526 return true;
7527
7528 Inst = CleanupPadInst::Create(ParentPad, Args);
7529 return false;
7530}
7531
7532//===----------------------------------------------------------------------===//
7533// Unary Operators.
7534//===----------------------------------------------------------------------===//
7535
7536/// parseUnaryOp
7537/// ::= UnaryOp TypeAndValue ',' Value
7538///
7539/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7540/// operand is allowed.
7541bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7542 unsigned Opc, bool IsFP) {
7543 LocTy Loc; Value *LHS;
7544 if (parseTypeAndValue(LHS, Loc, PFS))
7545 return true;
7546
7547 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7549
7550 if (!Valid)
7551 return error(Loc, "invalid operand type for instruction");
7552
7554 return false;
7555}
7556
7557/// parseCallBr
7558/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7559/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7560/// '[' LabelList ']'
7561bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7562 LocTy CallLoc = Lex.getLoc();
7563 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7564 std::vector<unsigned> FwdRefAttrGrps;
7565 LocTy NoBuiltinLoc;
7566 unsigned CC;
7567 Type *RetType = nullptr;
7568 LocTy RetTypeLoc;
7569 ValID CalleeID;
7572
7573 BasicBlock *DefaultDest;
7574 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7575 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7576 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7577 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7578 NoBuiltinLoc) ||
7579 parseOptionalOperandBundles(BundleList, PFS) ||
7580 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7581 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7582 parseToken(lltok::lsquare, "expected '[' in callbr"))
7583 return true;
7584
7585 // parse the destination list.
7586 SmallVector<BasicBlock *, 16> IndirectDests;
7587
7588 if (Lex.getKind() != lltok::rsquare) {
7589 BasicBlock *DestBB;
7590 if (parseTypeAndBasicBlock(DestBB, PFS))
7591 return true;
7592 IndirectDests.push_back(DestBB);
7593
7594 while (EatIfPresent(lltok::comma)) {
7595 if (parseTypeAndBasicBlock(DestBB, PFS))
7596 return true;
7597 IndirectDests.push_back(DestBB);
7598 }
7599 }
7600
7601 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7602 return true;
7603
7604 // If RetType is a non-function pointer type, then this is the short syntax
7605 // for the call, which means that RetType is just the return type. Infer the
7606 // rest of the function argument types from the arguments that are present.
7607 FunctionType *Ty;
7608 if (resolveFunctionType(RetType, ArgList, Ty))
7609 return error(RetTypeLoc, "Invalid result type for LLVM function");
7610
7611 CalleeID.FTy = Ty;
7612
7613 // Look up the callee.
7614 Value *Callee;
7615 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
7616 return true;
7617
7618 // Set up the Attribute for the function.
7621
7622 // Loop through FunctionType's arguments and ensure they are specified
7623 // correctly. Also, gather any parameter attributes.
7624 FunctionType::param_iterator I = Ty->param_begin();
7625 FunctionType::param_iterator E = Ty->param_end();
7626 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7627 Type *ExpectedTy = nullptr;
7628 if (I != E) {
7629 ExpectedTy = *I++;
7630 } else if (!Ty->isVarArg()) {
7631 return error(ArgList[i].Loc, "too many arguments specified");
7632 }
7633
7634 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7635 return error(ArgList[i].Loc, "argument is not of expected type '" +
7636 getTypeString(ExpectedTy) + "'");
7637 Args.push_back(ArgList[i].V);
7638 ArgAttrs.push_back(ArgList[i].Attrs);
7639 }
7640
7641 if (I != E)
7642 return error(CallLoc, "not enough parameters specified for call");
7643
7644 // Finish off the Attribute and check them
7645 AttributeList PAL =
7646 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7647 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7648
7649 CallBrInst *CBI =
7650 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
7651 BundleList);
7652 CBI->setCallingConv(CC);
7653 CBI->setAttributes(PAL);
7654 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7655 Inst = CBI;
7656 return false;
7657}
7658
7659//===----------------------------------------------------------------------===//
7660// Binary Operators.
7661//===----------------------------------------------------------------------===//
7662
7663/// parseArithmetic
7664/// ::= ArithmeticOps TypeAndValue ',' Value
7665///
7666/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7667/// operand is allowed.
7668bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
7669 unsigned Opc, bool IsFP) {
7670 LocTy Loc; Value *LHS, *RHS;
7671 if (parseTypeAndValue(LHS, Loc, PFS) ||
7672 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
7673 parseValue(LHS->getType(), RHS, PFS))
7674 return true;
7675
7676 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7678
7679 if (!Valid)
7680 return error(Loc, "invalid operand type for instruction");
7681
7682 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7683 return false;
7684}
7685
7686/// parseLogical
7687/// ::= ArithmeticOps TypeAndValue ',' Value {
7688bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
7689 unsigned Opc) {
7690 LocTy Loc; Value *LHS, *RHS;
7691 if (parseTypeAndValue(LHS, Loc, PFS) ||
7692 parseToken(lltok::comma, "expected ',' in logical operation") ||
7693 parseValue(LHS->getType(), RHS, PFS))
7694 return true;
7695
7696 if (!LHS->getType()->isIntOrIntVectorTy())
7697 return error(Loc,
7698 "instruction requires integer or integer vector operands");
7699
7700 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7701 return false;
7702}
7703
7704/// parseCompare
7705/// ::= 'icmp' IPredicates TypeAndValue ',' Value
7706/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
7707bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7708 unsigned Opc) {
7709 // parse the integer/fp comparison predicate.
7710 LocTy Loc;
7711 unsigned Pred;
7712 Value *LHS, *RHS;
7713 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7714 parseToken(lltok::comma, "expected ',' after compare value") ||
7715 parseValue(LHS->getType(), RHS, PFS))
7716 return true;
7717
7718 if (Opc == Instruction::FCmp) {
7719 if (!LHS->getType()->isFPOrFPVectorTy())
7720 return error(Loc, "fcmp requires floating point operands");
7721 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7722 } else {
7723 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7724 if (!LHS->getType()->isIntOrIntVectorTy() &&
7726 return error(Loc, "icmp requires integer operands");
7727 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7728 }
7729 return false;
7730}
7731
7732//===----------------------------------------------------------------------===//
7733// Other Instructions.
7734//===----------------------------------------------------------------------===//
7735
7736/// parseCast
7737/// ::= CastOpc TypeAndValue 'to' Type
7738bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7739 unsigned Opc) {
7740 LocTy Loc;
7741 Value *Op;
7742 Type *DestTy = nullptr;
7743 if (parseTypeAndValue(Op, Loc, PFS) ||
7744 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7745 parseType(DestTy))
7746 return true;
7747
7748 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
7750 return error(Loc, "invalid cast opcode for cast from '" +
7751 getTypeString(Op->getType()) + "' to '" +
7752 getTypeString(DestTy) + "'");
7753 }
7754 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7755 return false;
7756}
7757
7758/// parseSelect
7759/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7760bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7761 LocTy Loc;
7762 Value *Op0, *Op1, *Op2;
7763 if (parseTypeAndValue(Op0, Loc, PFS) ||
7764 parseToken(lltok::comma, "expected ',' after select condition") ||
7765 parseTypeAndValue(Op1, PFS) ||
7766 parseToken(lltok::comma, "expected ',' after select value") ||
7767 parseTypeAndValue(Op2, PFS))
7768 return true;
7769
7770 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7771 return error(Loc, Reason);
7772
7773 Inst = SelectInst::Create(Op0, Op1, Op2);
7774 return false;
7775}
7776
7777/// parseVAArg
7778/// ::= 'va_arg' TypeAndValue ',' Type
7779bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7780 Value *Op;
7781 Type *EltTy = nullptr;
7782 LocTy TypeLoc;
7783 if (parseTypeAndValue(Op, PFS) ||
7784 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7785 parseType(EltTy, TypeLoc))
7786 return true;
7787
7788 if (!EltTy->isFirstClassType())
7789 return error(TypeLoc, "va_arg requires operand with first class type");
7790
7791 Inst = new VAArgInst(Op, EltTy);
7792 return false;
7793}
7794
7795/// parseExtractElement
7796/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
7797bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7798 LocTy Loc;
7799 Value *Op0, *Op1;
7800 if (parseTypeAndValue(Op0, Loc, PFS) ||
7801 parseToken(lltok::comma, "expected ',' after extract value") ||
7802 parseTypeAndValue(Op1, PFS))
7803 return true;
7804
7806 return error(Loc, "invalid extractelement operands");
7807
7808 Inst = ExtractElementInst::Create(Op0, Op1);
7809 return false;
7810}
7811
7812/// parseInsertElement
7813/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7814bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7815 LocTy Loc;
7816 Value *Op0, *Op1, *Op2;
7817 if (parseTypeAndValue(Op0, Loc, PFS) ||
7818 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7819 parseTypeAndValue(Op1, PFS) ||
7820 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7821 parseTypeAndValue(Op2, PFS))
7822 return true;
7823
7824 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7825 return error(Loc, "invalid insertelement operands");
7826
7827 Inst = InsertElementInst::Create(Op0, Op1, Op2);
7828 return false;
7829}
7830
7831/// parseShuffleVector
7832/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7833bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7834 LocTy Loc;
7835 Value *Op0, *Op1, *Op2;
7836 if (parseTypeAndValue(Op0, Loc, PFS) ||
7837 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7838 parseTypeAndValue(Op1, PFS) ||
7839 parseToken(lltok::comma, "expected ',' after shuffle value") ||
7840 parseTypeAndValue(Op2, PFS))
7841 return true;
7842
7843 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7844 return error(Loc, "invalid shufflevector operands");
7845
7846 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7847 return false;
7848}
7849
7850/// parsePHI
7851/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7852int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7853 Type *Ty = nullptr; LocTy TypeLoc;
7854 Value *Op0, *Op1;
7855
7856 if (parseType(Ty, TypeLoc))
7857 return true;
7858
7859 if (!Ty->isFirstClassType())
7860 return error(TypeLoc, "phi node must have first class type");
7861
7862 bool First = true;
7863 bool AteExtraComma = false;
7865
7866 while (true) {
7867 if (First) {
7868 if (Lex.getKind() != lltok::lsquare)
7869 break;
7870 First = false;
7871 } else if (!EatIfPresent(lltok::comma))
7872 break;
7873
7874 if (Lex.getKind() == lltok::MetadataVar) {
7875 AteExtraComma = true;
7876 break;
7877 }
7878
7879 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7880 parseValue(Ty, Op0, PFS) ||
7881 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7882 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7883 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7884 return true;
7885
7886 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7887 }
7888
7889 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7890 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7891 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7892 Inst = PN;
7893 return AteExtraComma ? InstExtraComma : InstNormal;
7894}
7895
7896/// parseLandingPad
7897/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7898/// Clause
7899/// ::= 'catch' TypeAndValue
7900/// ::= 'filter'
7901/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7902bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7903 Type *Ty = nullptr; LocTy TyLoc;
7904
7905 if (parseType(Ty, TyLoc))
7906 return true;
7907
7908 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7909 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7910
7911 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7913 if (EatIfPresent(lltok::kw_catch))
7915 else if (EatIfPresent(lltok::kw_filter))
7917 else
7918 return tokError("expected 'catch' or 'filter' clause type");
7919
7920 Value *V;
7921 LocTy VLoc;
7922 if (parseTypeAndValue(V, VLoc, PFS))
7923 return true;
7924
7925 // A 'catch' type expects a non-array constant. A filter clause expects an
7926 // array constant.
7927 if (CT == LandingPadInst::Catch) {
7928 if (isa<ArrayType>(V->getType()))
7929 error(VLoc, "'catch' clause has an invalid type");
7930 } else {
7931 if (!isa<ArrayType>(V->getType()))
7932 error(VLoc, "'filter' clause has an invalid type");
7933 }
7934
7935 Constant *CV = dyn_cast<Constant>(V);
7936 if (!CV)
7937 return error(VLoc, "clause argument must be a constant");
7938 LP->addClause(CV);
7939 }
7940
7941 Inst = LP.release();
7942 return false;
7943}
7944
7945/// parseFreeze
7946/// ::= 'freeze' Type Value
7947bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7948 LocTy Loc;
7949 Value *Op;
7950 if (parseTypeAndValue(Op, Loc, PFS))
7951 return true;
7952
7953 Inst = new FreezeInst(Op);
7954 return false;
7955}
7956
7957/// parseCall
7958/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7959/// OptionalAttrs Type Value ParameterList OptionalAttrs
7960/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7961/// OptionalAttrs Type Value ParameterList OptionalAttrs
7962/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7963/// OptionalAttrs Type Value ParameterList OptionalAttrs
7964/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7965/// OptionalAttrs Type Value ParameterList OptionalAttrs
7966bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7968 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7969 std::vector<unsigned> FwdRefAttrGrps;
7970 LocTy BuiltinLoc;
7971 unsigned CallAddrSpace;
7972 unsigned CC;
7973 Type *RetType = nullptr;
7974 LocTy RetTypeLoc;
7975 ValID CalleeID;
7978 LocTy CallLoc = Lex.getLoc();
7979
7980 if (TCK != CallInst::TCK_None &&
7981 parseToken(lltok::kw_call,
7982 "expected 'tail call', 'musttail call', or 'notail call'"))
7983 return true;
7984
7985 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7986
7987 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7988 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7989 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7990 parseValID(CalleeID, &PFS) ||
7991 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7992 PFS.getFunction().isVarArg()) ||
7993 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7994 parseOptionalOperandBundles(BundleList, PFS))
7995 return true;
7996
7997 // If RetType is a non-function pointer type, then this is the short syntax
7998 // for the call, which means that RetType is just the return type. Infer the
7999 // rest of the function argument types from the arguments that are present.
8000 FunctionType *Ty;
8001 if (resolveFunctionType(RetType, ArgList, Ty))
8002 return error(RetTypeLoc, "Invalid result type for LLVM function");
8003
8004 CalleeID.FTy = Ty;
8005
8006 // Look up the callee.
8007 Value *Callee;
8008 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
8009 &PFS))
8010 return true;
8011
8012 // Set up the Attribute for the function.
8014
8016
8017 // Loop through FunctionType's arguments and ensure they are specified
8018 // correctly. Also, gather any parameter attributes.
8019 FunctionType::param_iterator I = Ty->param_begin();
8020 FunctionType::param_iterator E = Ty->param_end();
8021 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
8022 Type *ExpectedTy = nullptr;
8023 if (I != E) {
8024 ExpectedTy = *I++;
8025 } else if (!Ty->isVarArg()) {
8026 return error(ArgList[i].Loc, "too many arguments specified");
8027 }
8028
8029 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
8030 return error(ArgList[i].Loc, "argument is not of expected type '" +
8031 getTypeString(ExpectedTy) + "'");
8032 Args.push_back(ArgList[i].V);
8033 Attrs.push_back(ArgList[i].Attrs);
8034 }
8035
8036 if (I != E)
8037 return error(CallLoc, "not enough parameters specified for call");
8038
8039 // Finish off the Attribute and check them
8040 AttributeList PAL =
8041 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8042 AttributeSet::get(Context, RetAttrs), Attrs);
8043
8044 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8045 CI->setTailCallKind(TCK);
8046 CI->setCallingConv(CC);
8047 if (FMF.any()) {
8048 if (!isa<FPMathOperator>(CI)) {
8049 CI->deleteValue();
8050 return error(CallLoc, "fast-math-flags specified for call without "
8051 "floating-point scalar or vector return type");
8052 }
8053 CI->setFastMathFlags(FMF);
8054 }
8055
8056 if (CalleeID.Kind == ValID::t_GlobalName &&
8057 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8058 if (SeenNewDbgInfoFormat) {
8059 CI->deleteValue();
8060 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8061 "using non-intrinsic debug info");
8062 }
8063 if (!SeenOldDbgInfoFormat)
8064 M->setNewDbgInfoFormatFlag(false);
8065 SeenOldDbgInfoFormat = true;
8066 }
8067 CI->setAttributes(PAL);
8068 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8069 Inst = CI;
8070 return false;
8071}
8072
8073//===----------------------------------------------------------------------===//
8074// Memory Instructions.
8075//===----------------------------------------------------------------------===//
8076
8077/// parseAlloc
8078/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8079/// (',' 'align' i32)? (',', 'addrspace(n))?
8080int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8081 Value *Size = nullptr;
8082 LocTy SizeLoc, TyLoc, ASLoc;
8083 MaybeAlign Alignment;
8084 unsigned AddrSpace = 0;
8085 Type *Ty = nullptr;
8086
8087 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8088 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8089
8090 if (parseType(Ty, TyLoc))
8091 return true;
8092
8094 return error(TyLoc, "invalid type for alloca");
8095
8096 bool AteExtraComma = false;
8097 if (EatIfPresent(lltok::comma)) {
8098 if (Lex.getKind() == lltok::kw_align) {
8099 if (parseOptionalAlignment(Alignment))
8100 return true;
8101 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8102 return true;
8103 } else if (Lex.getKind() == lltok::kw_addrspace) {
8104 ASLoc = Lex.getLoc();
8105 if (parseOptionalAddrSpace(AddrSpace))
8106 return true;
8107 } else if (Lex.getKind() == lltok::MetadataVar) {
8108 AteExtraComma = true;
8109 } else {
8110 if (parseTypeAndValue(Size, SizeLoc, PFS))
8111 return true;
8112 if (EatIfPresent(lltok::comma)) {
8113 if (Lex.getKind() == lltok::kw_align) {
8114 if (parseOptionalAlignment(Alignment))
8115 return true;
8116 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8117 return true;
8118 } else if (Lex.getKind() == lltok::kw_addrspace) {
8119 ASLoc = Lex.getLoc();
8120 if (parseOptionalAddrSpace(AddrSpace))
8121 return true;
8122 } else if (Lex.getKind() == lltok::MetadataVar) {
8123 AteExtraComma = true;
8124 }
8125 }
8126 }
8127 }
8128
8129 if (Size && !Size->getType()->isIntegerTy())
8130 return error(SizeLoc, "element count must have integer type");
8131
8132 SmallPtrSet<Type *, 4> Visited;
8133 if (!Alignment && !Ty->isSized(&Visited))
8134 return error(TyLoc, "Cannot allocate unsized type");
8135 if (!Alignment)
8136 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8137 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8138 AI->setUsedWithInAlloca(IsInAlloca);
8139 AI->setSwiftError(IsSwiftError);
8140 Inst = AI;
8141 return AteExtraComma ? InstExtraComma : InstNormal;
8142}
8143
8144/// parseLoad
8145/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8146/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8147/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8148int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8149 Value *Val; LocTy Loc;
8150 MaybeAlign Alignment;
8151 bool AteExtraComma = false;
8152 bool isAtomic = false;
8155
8156 if (Lex.getKind() == lltok::kw_atomic) {
8157 isAtomic = true;
8158 Lex.Lex();
8159 }
8160
8161 bool isVolatile = false;
8162 if (Lex.getKind() == lltok::kw_volatile) {
8163 isVolatile = true;
8164 Lex.Lex();
8165 }
8166
8167 Type *Ty;
8168 LocTy ExplicitTypeLoc = Lex.getLoc();
8169 if (parseType(Ty) ||
8170 parseToken(lltok::comma, "expected comma after load's type") ||
8171 parseTypeAndValue(Val, Loc, PFS) ||
8172 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8173 parseOptionalCommaAlign(Alignment, AteExtraComma))
8174 return true;
8175
8176 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8177 return error(Loc, "load operand must be a pointer to a first class type");
8178 if (isAtomic && !Alignment)
8179 return error(Loc, "atomic load must have explicit non-zero alignment");
8180 if (Ordering == AtomicOrdering::Release ||
8182 return error(Loc, "atomic load cannot use Release ordering");
8183
8184 SmallPtrSet<Type *, 4> Visited;
8185 if (!Alignment && !Ty->isSized(&Visited))
8186 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8187 if (!Alignment)
8188 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8189 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8190 return AteExtraComma ? InstExtraComma : InstNormal;
8191}
8192
8193/// parseStore
8194
8195/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8196/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8197/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8198int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8199 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8200 MaybeAlign Alignment;
8201 bool AteExtraComma = false;
8202 bool isAtomic = false;
8205
8206 if (Lex.getKind() == lltok::kw_atomic) {
8207 isAtomic = true;
8208 Lex.Lex();
8209 }
8210
8211 bool isVolatile = false;
8212 if (Lex.getKind() == lltok::kw_volatile) {
8213 isVolatile = true;
8214 Lex.Lex();
8215 }
8216
8217 if (parseTypeAndValue(Val, Loc, PFS) ||
8218 parseToken(lltok::comma, "expected ',' after store operand") ||
8219 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8220 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8221 parseOptionalCommaAlign(Alignment, AteExtraComma))
8222 return true;
8223
8224 if (!Ptr->getType()->isPointerTy())
8225 return error(PtrLoc, "store operand must be a pointer");
8226 if (!Val->getType()->isFirstClassType())
8227 return error(Loc, "store operand must be a first class value");
8228 if (isAtomic && !Alignment)
8229 return error(Loc, "atomic store must have explicit non-zero alignment");
8230 if (Ordering == AtomicOrdering::Acquire ||
8232 return error(Loc, "atomic store cannot use Acquire ordering");
8233 SmallPtrSet<Type *, 4> Visited;
8234 if (!Alignment && !Val->getType()->isSized(&Visited))
8235 return error(Loc, "storing unsized types is not allowed");
8236 if (!Alignment)
8237 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8238
8239 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8240 return AteExtraComma ? InstExtraComma : InstNormal;
8241}
8242
8243/// parseCmpXchg
8244/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8245/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8246/// 'Align'?
8247int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8248 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8249 bool AteExtraComma = false;
8250 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8251 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8253 bool isVolatile = false;
8254 bool isWeak = false;
8255 MaybeAlign Alignment;
8256
8257 if (EatIfPresent(lltok::kw_weak))
8258 isWeak = true;
8259
8260 if (EatIfPresent(lltok::kw_volatile))
8261 isVolatile = true;
8262
8263 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8264 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8265 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8266 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8267 parseTypeAndValue(New, NewLoc, PFS) ||
8268 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8269 parseOrdering(FailureOrdering) ||
8270 parseOptionalCommaAlign(Alignment, AteExtraComma))
8271 return true;
8272
8273 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8274 return tokError("invalid cmpxchg success ordering");
8275 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8276 return tokError("invalid cmpxchg failure ordering");
8277 if (!Ptr->getType()->isPointerTy())
8278 return error(PtrLoc, "cmpxchg operand must be a pointer");
8279 if (Cmp->getType() != New->getType())
8280 return error(NewLoc, "compare value and new value type do not match");
8281 if (!New->getType()->isFirstClassType())
8282 return error(NewLoc, "cmpxchg operand must be a first class value");
8283
8284 const Align DefaultAlignment(
8285 PFS.getFunction().getDataLayout().getTypeStoreSize(
8286 Cmp->getType()));
8287
8288 AtomicCmpXchgInst *CXI =
8289 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8290 SuccessOrdering, FailureOrdering, SSID);
8291 CXI->setVolatile(isVolatile);
8292 CXI->setWeak(isWeak);
8293
8294 Inst = CXI;
8295 return AteExtraComma ? InstExtraComma : InstNormal;
8296}
8297
8298/// parseAtomicRMW
8299/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8300/// 'singlethread'? AtomicOrdering
8301int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8302 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8303 bool AteExtraComma = false;
8306 bool isVolatile = false;
8307 bool IsFP = false;
8309 MaybeAlign Alignment;
8310
8311 if (EatIfPresent(lltok::kw_volatile))
8312 isVolatile = true;
8313
8314 switch (Lex.getKind()) {
8315 default:
8316 return tokError("expected binary operation in atomicrmw");
8330 break;
8333 break;
8334 case lltok::kw_fadd:
8336 IsFP = true;
8337 break;
8338 case lltok::kw_fsub:
8340 IsFP = true;
8341 break;
8342 case lltok::kw_fmax:
8344 IsFP = true;
8345 break;
8346 case lltok::kw_fmin:
8348 IsFP = true;
8349 break;
8350 }
8351 Lex.Lex(); // Eat the operation.
8352
8353 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8354 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8355 parseTypeAndValue(Val, ValLoc, PFS) ||
8356 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8357 parseOptionalCommaAlign(Alignment, AteExtraComma))
8358 return true;
8359
8360 if (Ordering == AtomicOrdering::Unordered)
8361 return tokError("atomicrmw cannot be unordered");
8362 if (!Ptr->getType()->isPointerTy())
8363 return error(PtrLoc, "atomicrmw operand must be a pointer");
8364 if (Val->getType()->isScalableTy())
8365 return error(ValLoc, "atomicrmw operand may not be scalable");
8366
8368 if (!Val->getType()->isIntegerTy() &&
8369 !Val->getType()->isFloatingPointTy() &&
8370 !Val->getType()->isPointerTy()) {
8371 return error(
8372 ValLoc,
8374 " operand must be an integer, floating point, or pointer type");
8375 }
8376 } else if (IsFP) {
8377 if (!Val->getType()->isFPOrFPVectorTy()) {
8378 return error(ValLoc, "atomicrmw " +
8380 " operand must be a floating point type");
8381 }
8382 } else {
8383 if (!Val->getType()->isIntegerTy()) {
8384 return error(ValLoc, "atomicrmw " +
8386 " operand must be an integer");
8387 }
8388 }
8389
8390 unsigned Size =
8391 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8392 Val->getType());
8393 if (Size < 8 || (Size & (Size - 1)))
8394 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8395 " integer");
8396 const Align DefaultAlignment(
8397 PFS.getFunction().getDataLayout().getTypeStoreSize(
8398 Val->getType()));
8399 AtomicRMWInst *RMWI =
8400 new AtomicRMWInst(Operation, Ptr, Val,
8401 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8402 RMWI->setVolatile(isVolatile);
8403 Inst = RMWI;
8404 return AteExtraComma ? InstExtraComma : InstNormal;
8405}
8406
8407/// parseFence
8408/// ::= 'fence' 'singlethread'? AtomicOrdering
8409int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8412 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8413 return true;
8414
8415 if (Ordering == AtomicOrdering::Unordered)
8416 return tokError("fence cannot be unordered");
8417 if (Ordering == AtomicOrdering::Monotonic)
8418 return tokError("fence cannot be monotonic");
8419
8420 Inst = new FenceInst(Context, Ordering, SSID);
8421 return InstNormal;
8422}
8423
8424/// parseGetElementPtr
8425/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8426int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8427 Value *Ptr = nullptr;
8428 Value *Val = nullptr;
8429 LocTy Loc, EltLoc;
8430 GEPNoWrapFlags NW;
8431
8432 while (true) {
8433 if (EatIfPresent(lltok::kw_inbounds))
8435 else if (EatIfPresent(lltok::kw_nusw))
8437 else if (EatIfPresent(lltok::kw_nuw))
8439 else
8440 break;
8441 }
8442
8443 Type *Ty = nullptr;
8444 if (parseType(Ty) ||
8445 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8446 parseTypeAndValue(Ptr, Loc, PFS))
8447 return true;
8448
8449 Type *BaseType = Ptr->getType();
8450 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8451 if (!BasePointerType)
8452 return error(Loc, "base of getelementptr must be a pointer");
8453
8455 bool AteExtraComma = false;
8456 // GEP returns a vector of pointers if at least one of parameters is a vector.
8457 // All vector parameters should have the same vector width.
8458 ElementCount GEPWidth = BaseType->isVectorTy()
8459 ? cast<VectorType>(BaseType)->getElementCount()
8461
8462 while (EatIfPresent(lltok::comma)) {
8463 if (Lex.getKind() == lltok::MetadataVar) {
8464 AteExtraComma = true;
8465 break;
8466 }
8467 if (parseTypeAndValue(Val, EltLoc, PFS))
8468 return true;
8469 if (!Val->getType()->isIntOrIntVectorTy())
8470 return error(EltLoc, "getelementptr index must be an integer");
8471
8472 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8473 ElementCount ValNumEl = ValVTy->getElementCount();
8474 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8475 return error(
8476 EltLoc,
8477 "getelementptr vector index has a wrong number of elements");
8478 GEPWidth = ValNumEl;
8479 }
8480 Indices.push_back(Val);
8481 }
8482
8483 SmallPtrSet<Type*, 4> Visited;
8484 if (!Indices.empty() && !Ty->isSized(&Visited))
8485 return error(Loc, "base element of getelementptr must be sized");
8486
8487 auto *STy = dyn_cast<StructType>(Ty);
8488 if (STy && STy->containsScalableVectorType())
8489 return error(Loc, "getelementptr cannot target structure that contains "
8490 "scalable vector type");
8491
8492 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8493 return error(Loc, "invalid getelementptr indices");
8495 Inst = GEP;
8496 GEP->setNoWrapFlags(NW);
8497 return AteExtraComma ? InstExtraComma : InstNormal;
8498}
8499
8500/// parseExtractValue
8501/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8502int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8503 Value *Val; LocTy Loc;
8505 bool AteExtraComma;
8506 if (parseTypeAndValue(Val, Loc, PFS) ||
8507 parseIndexList(Indices, AteExtraComma))
8508 return true;
8509
8510 if (!Val->getType()->isAggregateType())
8511 return error(Loc, "extractvalue operand must be aggregate type");
8512
8513 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8514 return error(Loc, "invalid indices for extractvalue");
8515 Inst = ExtractValueInst::Create(Val, Indices);
8516 return AteExtraComma ? InstExtraComma : InstNormal;
8517}
8518
8519/// parseInsertValue
8520/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8521int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8522 Value *Val0, *Val1; LocTy Loc0, Loc1;
8524 bool AteExtraComma;
8525 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8526 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8527 parseTypeAndValue(Val1, Loc1, PFS) ||
8528 parseIndexList(Indices, AteExtraComma))
8529 return true;
8530
8531 if (!Val0->getType()->isAggregateType())
8532 return error(Loc0, "insertvalue operand must be aggregate type");
8533
8534 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8535 if (!IndexedType)
8536 return error(Loc0, "invalid indices for insertvalue");
8537 if (IndexedType != Val1->getType())
8538 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8539 getTypeString(Val1->getType()) + "' instead of '" +
8540 getTypeString(IndexedType) + "'");
8541 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8542 return AteExtraComma ? InstExtraComma : InstNormal;
8543}
8544
8545//===----------------------------------------------------------------------===//
8546// Embedded metadata.
8547//===----------------------------------------------------------------------===//
8548
8549/// parseMDNodeVector
8550/// ::= { Element (',' Element)* }
8551/// Element
8552/// ::= 'null' | Metadata
8553bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8554 if (parseToken(lltok::lbrace, "expected '{' here"))
8555 return true;
8556
8557 // Check for an empty list.
8558 if (EatIfPresent(lltok::rbrace))
8559 return false;
8560
8561 do {
8562 if (EatIfPresent(lltok::kw_null)) {
8563 Elts.push_back(nullptr);
8564 continue;
8565 }
8566
8567 Metadata *MD;
8568 if (parseMetadata(MD, nullptr))
8569 return true;
8570 Elts.push_back(MD);
8571 } while (EatIfPresent(lltok::comma));
8572
8573 return parseToken(lltok::rbrace, "expected end of metadata node");
8574}
8575
8576//===----------------------------------------------------------------------===//
8577// Use-list order directives.
8578//===----------------------------------------------------------------------===//
8579bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
8580 SMLoc Loc) {
8581 if (V->use_empty())
8582 return error(Loc, "value has no uses");
8583
8584 unsigned NumUses = 0;
8586 for (const Use &U : V->uses()) {
8587 if (++NumUses > Indexes.size())
8588 break;
8589 Order[&U] = Indexes[NumUses - 1];
8590 }
8591 if (NumUses < 2)
8592 return error(Loc, "value only has one use");
8593 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
8594 return error(Loc,
8595 "wrong number of indexes, expected " + Twine(V->getNumUses()));
8596
8597 V->sortUseList([&](const Use &L, const Use &R) {
8598 return Order.lookup(&L) < Order.lookup(&R);
8599 });
8600 return false;
8601}
8602
8603/// parseUseListOrderIndexes
8604/// ::= '{' uint32 (',' uint32)+ '}'
8605bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8606 SMLoc Loc = Lex.getLoc();
8607 if (parseToken(lltok::lbrace, "expected '{' here"))
8608 return true;
8609 if (Lex.getKind() == lltok::rbrace)
8610 return Lex.Error("expected non-empty list of uselistorder indexes");
8611
8612 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8613 // indexes should be distinct numbers in the range [0, size-1], and should
8614 // not be in order.
8615 unsigned Offset = 0;
8616 unsigned Max = 0;
8617 bool IsOrdered = true;
8618 assert(Indexes.empty() && "Expected empty order vector");
8619 do {
8620 unsigned Index;
8621 if (parseUInt32(Index))
8622 return true;
8623
8624 // Update consistency checks.
8625 Offset += Index - Indexes.size();
8626 Max = std::max(Max, Index);
8627 IsOrdered &= Index == Indexes.size();
8628
8629 Indexes.push_back(Index);
8630 } while (EatIfPresent(lltok::comma));
8631
8632 if (parseToken(lltok::rbrace, "expected '}' here"))
8633 return true;
8634
8635 if (Indexes.size() < 2)
8636 return error(Loc, "expected >= 2 uselistorder indexes");
8637 if (Offset != 0 || Max >= Indexes.size())
8638 return error(Loc,
8639 "expected distinct uselistorder indexes in range [0, size)");
8640 if (IsOrdered)
8641 return error(Loc, "expected uselistorder indexes to change the order");
8642
8643 return false;
8644}
8645
8646/// parseUseListOrder
8647/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8648bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8649 SMLoc Loc = Lex.getLoc();
8650 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
8651 return true;
8652
8653 Value *V;
8655 if (parseTypeAndValue(V, PFS) ||
8656 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
8657 parseUseListOrderIndexes(Indexes))
8658 return true;
8659
8660 return sortUseListOrder(V, Indexes, Loc);
8661}
8662
8663/// parseUseListOrderBB
8664/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8665bool LLParser::parseUseListOrderBB() {
8667 SMLoc Loc = Lex.getLoc();
8668 Lex.Lex();
8669
8670 ValID Fn, Label;
8672 if (parseValID(Fn, /*PFS=*/nullptr) ||
8673 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8674 parseValID(Label, /*PFS=*/nullptr) ||
8675 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8676 parseUseListOrderIndexes(Indexes))
8677 return true;
8678
8679 // Check the function.
8680 GlobalValue *GV;
8681 if (Fn.Kind == ValID::t_GlobalName)
8682 GV = M->getNamedValue(Fn.StrVal);
8683 else if (Fn.Kind == ValID::t_GlobalID)
8684 GV = NumberedVals.get(Fn.UIntVal);
8685 else
8686 return error(Fn.Loc, "expected function name in uselistorder_bb");
8687 if (!GV)
8688 return error(Fn.Loc,
8689 "invalid function forward reference in uselistorder_bb");
8690 auto *F = dyn_cast<Function>(GV);
8691 if (!F)
8692 return error(Fn.Loc, "expected function name in uselistorder_bb");
8693 if (F->isDeclaration())
8694 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
8695
8696 // Check the basic block.
8697 if (Label.Kind == ValID::t_LocalID)
8698 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
8699 if (Label.Kind != ValID::t_LocalName)
8700 return error(Label.Loc, "expected basic block name in uselistorder_bb");
8701 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
8702 if (!V)
8703 return error(Label.Loc, "invalid basic block in uselistorder_bb");
8704 if (!isa<BasicBlock>(V))
8705 return error(Label.Loc, "expected basic block in uselistorder_bb");
8706
8707 return sortUseListOrder(V, Indexes, Loc);
8708}
8709
8710/// ModuleEntry
8711/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8712/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8713bool LLParser::parseModuleEntry(unsigned ID) {
8715 Lex.Lex();
8716
8717 std::string Path;
8718 if (parseToken(lltok::colon, "expected ':' here") ||
8719 parseToken(lltok::lparen, "expected '(' here") ||
8720 parseToken(lltok::kw_path, "expected 'path' here") ||
8721 parseToken(lltok::colon, "expected ':' here") ||
8722 parseStringConstant(Path) ||
8723 parseToken(lltok::comma, "expected ',' here") ||
8724 parseToken(lltok::kw_hash, "expected 'hash' here") ||
8725 parseToken(lltok::colon, "expected ':' here") ||
8726 parseToken(lltok::lparen, "expected '(' here"))
8727 return true;
8728
8729 ModuleHash Hash;
8730 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8731 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8732 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8733 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8734 parseUInt32(Hash[4]))
8735 return true;
8736
8737 if (parseToken(lltok::rparen, "expected ')' here") ||
8738 parseToken(lltok::rparen, "expected ')' here"))
8739 return true;
8740
8741 auto ModuleEntry = Index->addModule(Path, Hash);
8742 ModuleIdMap[ID] = ModuleEntry->first();
8743
8744 return false;
8745}
8746
8747/// TypeIdEntry
8748/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8749bool LLParser::parseTypeIdEntry(unsigned ID) {
8751 Lex.Lex();
8752
8753 std::string Name;
8754 if (parseToken(lltok::colon, "expected ':' here") ||
8755 parseToken(lltok::lparen, "expected '(' here") ||
8756 parseToken(lltok::kw_name, "expected 'name' here") ||
8757 parseToken(lltok::colon, "expected ':' here") ||
8758 parseStringConstant(Name))
8759 return true;
8760
8761 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8762 if (parseToken(lltok::comma, "expected ',' here") ||
8763 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8764 return true;
8765
8766 // Check if this ID was forward referenced, and if so, update the
8767 // corresponding GUIDs.
8768 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8769 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8770 for (auto TIDRef : FwdRefTIDs->second) {
8771 assert(!*TIDRef.first &&
8772 "Forward referenced type id GUID expected to be 0");
8773 *TIDRef.first = GlobalValue::getGUID(Name);
8774 }
8775 ForwardRefTypeIds.erase(FwdRefTIDs);
8776 }
8777
8778 return false;
8779}
8780
8781/// TypeIdSummary
8782/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8783bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8784 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8785 parseToken(lltok::colon, "expected ':' here") ||
8786 parseToken(lltok::lparen, "expected '(' here") ||
8787 parseTypeTestResolution(TIS.TTRes))
8788 return true;
8789
8790 if (EatIfPresent(lltok::comma)) {
8791 // Expect optional wpdResolutions field
8792 if (parseOptionalWpdResolutions(TIS.WPDRes))
8793 return true;
8794 }
8795
8796 if (parseToken(lltok::rparen, "expected ')' here"))
8797 return true;
8798
8799 return false;
8800}
8801
8803 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8804
8805/// TypeIdCompatibleVtableEntry
8806/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8807/// TypeIdCompatibleVtableInfo
8808/// ')'
8809bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8811 Lex.Lex();
8812
8813 std::string Name;
8814 if (parseToken(lltok::colon, "expected ':' here") ||
8815 parseToken(lltok::lparen, "expected '(' here") ||
8816 parseToken(lltok::kw_name, "expected 'name' here") ||
8817 parseToken(lltok::colon, "expected ':' here") ||
8818 parseStringConstant(Name))
8819 return true;
8820
8822 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8823 if (parseToken(lltok::comma, "expected ',' here") ||
8824 parseToken(lltok::kw_summary, "expected 'summary' here") ||
8825 parseToken(lltok::colon, "expected ':' here") ||
8826 parseToken(lltok::lparen, "expected '(' here"))
8827 return true;
8828
8829 IdToIndexMapType IdToIndexMap;
8830 // parse each call edge
8831 do {
8833 if (parseToken(lltok::lparen, "expected '(' here") ||
8834 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8835 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8836 parseToken(lltok::comma, "expected ',' here"))
8837 return true;
8838
8839 LocTy Loc = Lex.getLoc();
8840 unsigned GVId;
8841 ValueInfo VI;
8842 if (parseGVReference(VI, GVId))
8843 return true;
8844
8845 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8846 // forward reference. We will save the location of the ValueInfo needing an
8847 // update, but can only do so once the std::vector is finalized.
8848 if (VI == EmptyVI)
8849 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8850 TI.push_back({Offset, VI});
8851
8852 if (parseToken(lltok::rparen, "expected ')' in call"))
8853 return true;
8854 } while (EatIfPresent(lltok::comma));
8855
8856 // Now that the TI vector is finalized, it is safe to save the locations
8857 // of any forward GV references that need updating later.
8858 for (auto I : IdToIndexMap) {
8859 auto &Infos = ForwardRefValueInfos[I.first];
8860 for (auto P : I.second) {
8861 assert(TI[P.first].VTableVI == EmptyVI &&
8862 "Forward referenced ValueInfo expected to be empty");
8863 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8864 }
8865 }
8866
8867 if (parseToken(lltok::rparen, "expected ')' here") ||
8868 parseToken(lltok::rparen, "expected ')' here"))
8869 return true;
8870
8871 // Check if this ID was forward referenced, and if so, update the
8872 // corresponding GUIDs.
8873 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8874 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8875 for (auto TIDRef : FwdRefTIDs->second) {
8876 assert(!*TIDRef.first &&
8877 "Forward referenced type id GUID expected to be 0");
8878 *TIDRef.first = GlobalValue::getGUID(Name);
8879 }
8880 ForwardRefTypeIds.erase(FwdRefTIDs);
8881 }
8882
8883 return false;
8884}
8885
8886/// TypeTestResolution
8887/// ::= 'typeTestRes' ':' '(' 'kind' ':'
8888/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8889/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8890/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8891/// [',' 'inlinesBits' ':' UInt64]? ')'
8892bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8893 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8894 parseToken(lltok::colon, "expected ':' here") ||
8895 parseToken(lltok::lparen, "expected '(' here") ||
8896 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8897 parseToken(lltok::colon, "expected ':' here"))
8898 return true;
8899
8900 switch (Lex.getKind()) {
8901 case lltok::kw_unknown:
8903 break;
8904 case lltok::kw_unsat:
8906 break;
8909 break;
8910 case lltok::kw_inline:
8912 break;
8913 case lltok::kw_single:
8915 break;
8916 case lltok::kw_allOnes:
8918 break;
8919 default:
8920 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8921 }
8922 Lex.Lex();
8923
8924 if (parseToken(lltok::comma, "expected ',' here") ||
8925 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8926 parseToken(lltok::colon, "expected ':' here") ||
8927 parseUInt32(TTRes.SizeM1BitWidth))
8928 return true;
8929
8930 // parse optional fields
8931 while (EatIfPresent(lltok::comma)) {
8932 switch (Lex.getKind()) {
8934 Lex.Lex();
8935 if (parseToken(lltok::colon, "expected ':'") ||
8936 parseUInt64(TTRes.AlignLog2))
8937 return true;
8938 break;
8939 case lltok::kw_sizeM1:
8940 Lex.Lex();
8941 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8942 return true;
8943 break;
8944 case lltok::kw_bitMask: {
8945 unsigned Val;
8946 Lex.Lex();
8947 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8948 return true;
8949 assert(Val <= 0xff);
8950 TTRes.BitMask = (uint8_t)Val;
8951 break;
8952 }
8954 Lex.Lex();
8955 if (parseToken(lltok::colon, "expected ':'") ||
8956 parseUInt64(TTRes.InlineBits))
8957 return true;
8958 break;
8959 default:
8960 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8961 }
8962 }
8963
8964 if (parseToken(lltok::rparen, "expected ')' here"))
8965 return true;
8966
8967 return false;
8968}
8969
8970/// OptionalWpdResolutions
8971/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8972/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8973bool LLParser::parseOptionalWpdResolutions(
8974 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8975 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8976 parseToken(lltok::colon, "expected ':' here") ||
8977 parseToken(lltok::lparen, "expected '(' here"))
8978 return true;
8979
8980 do {
8983 if (parseToken(lltok::lparen, "expected '(' here") ||
8984 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8985 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8986 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8987 parseToken(lltok::rparen, "expected ')' here"))
8988 return true;
8989 WPDResMap[Offset] = WPDRes;
8990 } while (EatIfPresent(lltok::comma));
8991
8992 if (parseToken(lltok::rparen, "expected ')' here"))
8993 return true;
8994
8995 return false;
8996}
8997
8998/// WpdRes
8999/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9000/// [',' OptionalResByArg]? ')'
9001/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9002/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9003/// [',' OptionalResByArg]? ')'
9004/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9005/// [',' OptionalResByArg]? ')'
9006bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9007 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9008 parseToken(lltok::colon, "expected ':' here") ||
9009 parseToken(lltok::lparen, "expected '(' here") ||
9010 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9011 parseToken(lltok::colon, "expected ':' here"))
9012 return true;
9013
9014 switch (Lex.getKind()) {
9015 case lltok::kw_indir:
9017 break;
9020 break;
9023 break;
9024 default:
9025 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9026 }
9027 Lex.Lex();
9028
9029 // parse optional fields
9030 while (EatIfPresent(lltok::comma)) {
9031 switch (Lex.getKind()) {
9033 Lex.Lex();
9034 if (parseToken(lltok::colon, "expected ':' here") ||
9035 parseStringConstant(WPDRes.SingleImplName))
9036 return true;
9037 break;
9038 case lltok::kw_resByArg:
9039 if (parseOptionalResByArg(WPDRes.ResByArg))
9040 return true;
9041 break;
9042 default:
9043 return error(Lex.getLoc(),
9044 "expected optional WholeProgramDevirtResolution field");
9045 }
9046 }
9047
9048 if (parseToken(lltok::rparen, "expected ')' here"))
9049 return true;
9050
9051 return false;
9052}
9053
9054/// OptionalResByArg
9055/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9056/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9057/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9058/// 'virtualConstProp' )
9059/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9060/// [',' 'bit' ':' UInt32]? ')'
9061bool LLParser::parseOptionalResByArg(
9062 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9063 &ResByArg) {
9064 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9065 parseToken(lltok::colon, "expected ':' here") ||
9066 parseToken(lltok::lparen, "expected '(' here"))
9067 return true;
9068
9069 do {
9070 std::vector<uint64_t> Args;
9071 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9072 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9073 parseToken(lltok::colon, "expected ':' here") ||
9074 parseToken(lltok::lparen, "expected '(' here") ||
9075 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9076 parseToken(lltok::colon, "expected ':' here"))
9077 return true;
9078
9080 switch (Lex.getKind()) {
9081 case lltok::kw_indir:
9083 break;
9086 break;
9089 break;
9092 break;
9093 default:
9094 return error(Lex.getLoc(),
9095 "unexpected WholeProgramDevirtResolution::ByArg kind");
9096 }
9097 Lex.Lex();
9098
9099 // parse optional fields
9100 while (EatIfPresent(lltok::comma)) {
9101 switch (Lex.getKind()) {
9102 case lltok::kw_info:
9103 Lex.Lex();
9104 if (parseToken(lltok::colon, "expected ':' here") ||
9105 parseUInt64(ByArg.Info))
9106 return true;
9107 break;
9108 case lltok::kw_byte:
9109 Lex.Lex();
9110 if (parseToken(lltok::colon, "expected ':' here") ||
9111 parseUInt32(ByArg.Byte))
9112 return true;
9113 break;
9114 case lltok::kw_bit:
9115 Lex.Lex();
9116 if (parseToken(lltok::colon, "expected ':' here") ||
9117 parseUInt32(ByArg.Bit))
9118 return true;
9119 break;
9120 default:
9121 return error(Lex.getLoc(),
9122 "expected optional whole program devirt field");
9123 }
9124 }
9125
9126 if (parseToken(lltok::rparen, "expected ')' here"))
9127 return true;
9128
9129 ResByArg[Args] = ByArg;
9130 } while (EatIfPresent(lltok::comma));
9131
9132 if (parseToken(lltok::rparen, "expected ')' here"))
9133 return true;
9134
9135 return false;
9136}
9137
9138/// OptionalResByArg
9139/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9140bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9141 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9142 parseToken(lltok::colon, "expected ':' here") ||
9143 parseToken(lltok::lparen, "expected '(' here"))
9144 return true;
9145
9146 do {
9147 uint64_t Val;
9148 if (parseUInt64(Val))
9149 return true;
9150 Args.push_back(Val);
9151 } while (EatIfPresent(lltok::comma));
9152
9153 if (parseToken(lltok::rparen, "expected ')' here"))
9154 return true;
9155
9156 return false;
9157}
9158
9159static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9160
9161static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9162 bool ReadOnly = Fwd->isReadOnly();
9163 bool WriteOnly = Fwd->isWriteOnly();
9164 assert(!(ReadOnly && WriteOnly));
9165 *Fwd = Resolved;
9166 if (ReadOnly)
9167 Fwd->setReadOnly();
9168 if (WriteOnly)
9169 Fwd->setWriteOnly();
9170}
9171
9172/// Stores the given Name/GUID and associated summary into the Index.
9173/// Also updates any forward references to the associated entry ID.
9174bool LLParser::addGlobalValueToIndex(
9175 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9176 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9177 // First create the ValueInfo utilizing the Name or GUID.
9178 ValueInfo VI;
9179 if (GUID != 0) {
9180 assert(Name.empty());
9181 VI = Index->getOrInsertValueInfo(GUID);
9182 } else {
9183 assert(!Name.empty());
9184 if (M) {
9185 auto *GV = M->getNamedValue(Name);
9186 if (!GV)
9187 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9188
9189 VI = Index->getOrInsertValueInfo(GV);
9190 } else {
9191 assert(
9192 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9193 "Need a source_filename to compute GUID for local");
9195 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9196 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9197 }
9198 }
9199
9200 // Resolve forward references from calls/refs
9201 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9202 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9203 for (auto VIRef : FwdRefVIs->second) {
9204 assert(VIRef.first->getRef() == FwdVIRef &&
9205 "Forward referenced ValueInfo expected to be empty");
9206 resolveFwdRef(VIRef.first, VI);
9207 }
9208 ForwardRefValueInfos.erase(FwdRefVIs);
9209 }
9210
9211 // Resolve forward references from aliases
9212 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9213 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9214 for (auto AliaseeRef : FwdRefAliasees->second) {
9215 assert(!AliaseeRef.first->hasAliasee() &&
9216 "Forward referencing alias already has aliasee");
9217 assert(Summary && "Aliasee must be a definition");
9218 AliaseeRef.first->setAliasee(VI, Summary.get());
9219 }
9220 ForwardRefAliasees.erase(FwdRefAliasees);
9221 }
9222
9223 // Add the summary if one was provided.
9224 if (Summary)
9225 Index->addGlobalValueSummary(VI, std::move(Summary));
9226
9227 // Save the associated ValueInfo for use in later references by ID.
9228 if (ID == NumberedValueInfos.size())
9229 NumberedValueInfos.push_back(VI);
9230 else {
9231 // Handle non-continuous numbers (to make test simplification easier).
9232 if (ID > NumberedValueInfos.size())
9233 NumberedValueInfos.resize(ID + 1);
9234 NumberedValueInfos[ID] = VI;
9235 }
9236
9237 return false;
9238}
9239
9240/// parseSummaryIndexFlags
9241/// ::= 'flags' ':' UInt64
9242bool LLParser::parseSummaryIndexFlags() {
9243 assert(Lex.getKind() == lltok::kw_flags);
9244 Lex.Lex();
9245
9246 if (parseToken(lltok::colon, "expected ':' here"))
9247 return true;
9249 if (parseUInt64(Flags))
9250 return true;
9251 if (Index)
9252 Index->setFlags(Flags);
9253 return false;
9254}
9255
9256/// parseBlockCount
9257/// ::= 'blockcount' ':' UInt64
9258bool LLParser::parseBlockCount() {
9260 Lex.Lex();
9261
9262 if (parseToken(lltok::colon, "expected ':' here"))
9263 return true;
9264 uint64_t BlockCount;
9265 if (parseUInt64(BlockCount))
9266 return true;
9267 if (Index)
9268 Index->setBlockCount(BlockCount);
9269 return false;
9270}
9271
9272/// parseGVEntry
9273/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9274/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9275/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9276bool LLParser::parseGVEntry(unsigned ID) {
9277 assert(Lex.getKind() == lltok::kw_gv);
9278 Lex.Lex();
9279
9280 if (parseToken(lltok::colon, "expected ':' here") ||
9281 parseToken(lltok::lparen, "expected '(' here"))
9282 return true;
9283
9284 LocTy Loc = Lex.getLoc();
9285 std::string Name;
9287 switch (Lex.getKind()) {
9288 case lltok::kw_name:
9289 Lex.Lex();
9290 if (parseToken(lltok::colon, "expected ':' here") ||
9291 parseStringConstant(Name))
9292 return true;
9293 // Can't create GUID/ValueInfo until we have the linkage.
9294 break;
9295 case lltok::kw_guid:
9296 Lex.Lex();
9297 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9298 return true;
9299 break;
9300 default:
9301 return error(Lex.getLoc(), "expected name or guid tag");
9302 }
9303
9304 if (!EatIfPresent(lltok::comma)) {
9305 // No summaries. Wrap up.
9306 if (parseToken(lltok::rparen, "expected ')' here"))
9307 return true;
9308 // This was created for a call to an external or indirect target.
9309 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9310 // created for indirect calls with VP. A Name with no GUID came from
9311 // an external definition. We pass ExternalLinkage since that is only
9312 // used when the GUID must be computed from Name, and in that case
9313 // the symbol must have external linkage.
9314 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9315 nullptr, Loc);
9316 }
9317
9318 // Have a list of summaries
9319 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9320 parseToken(lltok::colon, "expected ':' here") ||
9321 parseToken(lltok::lparen, "expected '(' here"))
9322 return true;
9323 do {
9324 switch (Lex.getKind()) {
9325 case lltok::kw_function:
9326 if (parseFunctionSummary(Name, GUID, ID))
9327 return true;
9328 break;
9329 case lltok::kw_variable:
9330 if (parseVariableSummary(Name, GUID, ID))
9331 return true;
9332 break;
9333 case lltok::kw_alias:
9334 if (parseAliasSummary(Name, GUID, ID))
9335 return true;
9336 break;
9337 default:
9338 return error(Lex.getLoc(), "expected summary type");
9339 }
9340 } while (EatIfPresent(lltok::comma));
9341
9342 if (parseToken(lltok::rparen, "expected ')' here") ||
9343 parseToken(lltok::rparen, "expected ')' here"))
9344 return true;
9345
9346 return false;
9347}
9348
9349/// FunctionSummary
9350/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9351/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9352/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9353/// [',' OptionalRefs]? ')'
9354bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9355 unsigned ID) {
9356 LocTy Loc = Lex.getLoc();
9358 Lex.Lex();
9359
9360 StringRef ModulePath;
9363 /*NotEligibleToImport=*/false,
9364 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9366 unsigned InstCount;
9367 std::vector<FunctionSummary::EdgeTy> Calls;
9368 FunctionSummary::TypeIdInfo TypeIdInfo;
9369 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9370 std::vector<ValueInfo> Refs;
9371 std::vector<CallsiteInfo> Callsites;
9372 std::vector<AllocInfo> Allocs;
9373 // Default is all-zeros (conservative values).
9374 FunctionSummary::FFlags FFlags = {};
9375 if (parseToken(lltok::colon, "expected ':' here") ||
9376 parseToken(lltok::lparen, "expected '(' here") ||
9377 parseModuleReference(ModulePath) ||
9378 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9379 parseToken(lltok::comma, "expected ',' here") ||
9380 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9381 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9382 return true;
9383
9384 // parse optional fields
9385 while (EatIfPresent(lltok::comma)) {
9386 switch (Lex.getKind()) {
9388 if (parseOptionalFFlags(FFlags))
9389 return true;
9390 break;
9391 case lltok::kw_calls:
9392 if (parseOptionalCalls(Calls))
9393 return true;
9394 break;
9396 if (parseOptionalTypeIdInfo(TypeIdInfo))
9397 return true;
9398 break;
9399 case lltok::kw_refs:
9400 if (parseOptionalRefs(Refs))
9401 return true;
9402 break;
9403 case lltok::kw_params:
9404 if (parseOptionalParamAccesses(ParamAccesses))
9405 return true;
9406 break;
9407 case lltok::kw_allocs:
9408 if (parseOptionalAllocs(Allocs))
9409 return true;
9410 break;
9412 if (parseOptionalCallsites(Callsites))
9413 return true;
9414 break;
9415 default:
9416 return error(Lex.getLoc(), "expected optional function summary field");
9417 }
9418 }
9419
9420 if (parseToken(lltok::rparen, "expected ')' here"))
9421 return true;
9422
9423 auto FS = std::make_unique<FunctionSummary>(
9424 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
9425 std::move(Calls), std::move(TypeIdInfo.TypeTests),
9426 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9427 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9428 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9429 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9430 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9431
9432 FS->setModulePath(ModulePath);
9433
9434 return addGlobalValueToIndex(Name, GUID,
9436 std::move(FS), Loc);
9437}
9438
9439/// VariableSummary
9440/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9441/// [',' OptionalRefs]? ')'
9442bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9443 unsigned ID) {
9444 LocTy Loc = Lex.getLoc();
9446 Lex.Lex();
9447
9448 StringRef ModulePath;
9451 /*NotEligibleToImport=*/false,
9452 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9454 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9455 /* WriteOnly */ false,
9456 /* Constant */ false,
9458 std::vector<ValueInfo> Refs;
9459 VTableFuncList VTableFuncs;
9460 if (parseToken(lltok::colon, "expected ':' here") ||
9461 parseToken(lltok::lparen, "expected '(' here") ||
9462 parseModuleReference(ModulePath) ||
9463 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9464 parseToken(lltok::comma, "expected ',' here") ||
9465 parseGVarFlags(GVarFlags))
9466 return true;
9467
9468 // parse optional fields
9469 while (EatIfPresent(lltok::comma)) {
9470 switch (Lex.getKind()) {
9472 if (parseOptionalVTableFuncs(VTableFuncs))
9473 return true;
9474 break;
9475 case lltok::kw_refs:
9476 if (parseOptionalRefs(Refs))
9477 return true;
9478 break;
9479 default:
9480 return error(Lex.getLoc(), "expected optional variable summary field");
9481 }
9482 }
9483
9484 if (parseToken(lltok::rparen, "expected ')' here"))
9485 return true;
9486
9487 auto GS =
9488 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9489
9490 GS->setModulePath(ModulePath);
9491 GS->setVTableFuncs(std::move(VTableFuncs));
9492
9493 return addGlobalValueToIndex(Name, GUID,
9495 std::move(GS), Loc);
9496}
9497
9498/// AliasSummary
9499/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9500/// 'aliasee' ':' GVReference ')'
9501bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9502 unsigned ID) {
9503 assert(Lex.getKind() == lltok::kw_alias);
9504 LocTy Loc = Lex.getLoc();
9505 Lex.Lex();
9506
9507 StringRef ModulePath;
9510 /*NotEligibleToImport=*/false,
9511 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9513 if (parseToken(lltok::colon, "expected ':' here") ||
9514 parseToken(lltok::lparen, "expected '(' here") ||
9515 parseModuleReference(ModulePath) ||
9516 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9517 parseToken(lltok::comma, "expected ',' here") ||
9518 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9519 parseToken(lltok::colon, "expected ':' here"))
9520 return true;
9521
9522 ValueInfo AliaseeVI;
9523 unsigned GVId;
9524 if (parseGVReference(AliaseeVI, GVId))
9525 return true;
9526
9527 if (parseToken(lltok::rparen, "expected ')' here"))
9528 return true;
9529
9530 auto AS = std::make_unique<AliasSummary>(GVFlags);
9531
9532 AS->setModulePath(ModulePath);
9533
9534 // Record forward reference if the aliasee is not parsed yet.
9535 if (AliaseeVI.getRef() == FwdVIRef) {
9536 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9537 } else {
9538 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9539 assert(Summary && "Aliasee must be a definition");
9540 AS->setAliasee(AliaseeVI, Summary);
9541 }
9542
9543 return addGlobalValueToIndex(Name, GUID,
9545 std::move(AS), Loc);
9546}
9547
9548/// Flag
9549/// ::= [0|1]
9550bool LLParser::parseFlag(unsigned &Val) {
9551 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9552 return tokError("expected integer");
9553 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9554 Lex.Lex();
9555 return false;
9556}
9557
9558/// OptionalFFlags
9559/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9560/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9561/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9562/// [',' 'noInline' ':' Flag]? ')'
9563/// [',' 'alwaysInline' ':' Flag]? ')'
9564/// [',' 'noUnwind' ':' Flag]? ')'
9565/// [',' 'mayThrow' ':' Flag]? ')'
9566/// [',' 'hasUnknownCall' ':' Flag]? ')'
9567/// [',' 'mustBeUnreachable' ':' Flag]? ')'
9568
9569bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9571 Lex.Lex();
9572
9573 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
9574 parseToken(lltok::lparen, "expected '(' in funcFlags"))
9575 return true;
9576
9577 do {
9578 unsigned Val = 0;
9579 switch (Lex.getKind()) {
9580 case lltok::kw_readNone:
9581 Lex.Lex();
9582 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9583 return true;
9584 FFlags.ReadNone = Val;
9585 break;
9586 case lltok::kw_readOnly:
9587 Lex.Lex();
9588 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9589 return true;
9590 FFlags.ReadOnly = Val;
9591 break;
9593 Lex.Lex();
9594 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9595 return true;
9596 FFlags.NoRecurse = Val;
9597 break;
9599 Lex.Lex();
9600 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9601 return true;
9602 FFlags.ReturnDoesNotAlias = Val;
9603 break;
9604 case lltok::kw_noInline:
9605 Lex.Lex();
9606 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9607 return true;
9608 FFlags.NoInline = Val;
9609 break;
9611 Lex.Lex();
9612 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9613 return true;
9614 FFlags.AlwaysInline = Val;
9615 break;
9616 case lltok::kw_noUnwind:
9617 Lex.Lex();
9618 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9619 return true;
9620 FFlags.NoUnwind = Val;
9621 break;
9622 case lltok::kw_mayThrow:
9623 Lex.Lex();
9624 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9625 return true;
9626 FFlags.MayThrow = Val;
9627 break;
9629 Lex.Lex();
9630 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9631 return true;
9632 FFlags.HasUnknownCall = Val;
9633 break;
9635 Lex.Lex();
9636 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9637 return true;
9638 FFlags.MustBeUnreachable = Val;
9639 break;
9640 default:
9641 return error(Lex.getLoc(), "expected function flag type");
9642 }
9643 } while (EatIfPresent(lltok::comma));
9644
9645 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
9646 return true;
9647
9648 return false;
9649}
9650
9651/// OptionalCalls
9652/// := 'calls' ':' '(' Call [',' Call]* ')'
9653/// Call ::= '(' 'callee' ':' GVReference
9654/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
9655/// [ ',' 'tail' ]? ')'
9656bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9657 assert(Lex.getKind() == lltok::kw_calls);
9658 Lex.Lex();
9659
9660 if (parseToken(lltok::colon, "expected ':' in calls") ||
9661 parseToken(lltok::lparen, "expected '(' in calls"))
9662 return true;
9663
9664 IdToIndexMapType IdToIndexMap;
9665 // parse each call edge
9666 do {
9667 ValueInfo VI;
9668 if (parseToken(lltok::lparen, "expected '(' in call") ||
9669 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
9670 parseToken(lltok::colon, "expected ':'"))
9671 return true;
9672
9673 LocTy Loc = Lex.getLoc();
9674 unsigned GVId;
9675 if (parseGVReference(VI, GVId))
9676 return true;
9677
9679 unsigned RelBF = 0;
9680 unsigned HasTailCall = false;
9681
9682 // parse optional fields
9683 while (EatIfPresent(lltok::comma)) {
9684 switch (Lex.getKind()) {
9685 case lltok::kw_hotness:
9686 Lex.Lex();
9687 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
9688 return true;
9689 break;
9690 case lltok::kw_relbf:
9691 Lex.Lex();
9692 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
9693 return true;
9694 break;
9695 case lltok::kw_tail:
9696 Lex.Lex();
9697 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
9698 return true;
9699 break;
9700 default:
9701 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
9702 }
9703 }
9704 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
9705 return tokError("Expected only one of hotness or relbf");
9706 // Keep track of the Call array index needing a forward reference.
9707 // We will save the location of the ValueInfo needing an update, but
9708 // can only do so once the std::vector is finalized.
9709 if (VI.getRef() == FwdVIRef)
9710 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9711 Calls.push_back(
9712 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
9713
9714 if (parseToken(lltok::rparen, "expected ')' in call"))
9715 return true;
9716 } while (EatIfPresent(lltok::comma));
9717
9718 // Now that the Calls vector is finalized, it is safe to save the locations
9719 // of any forward GV references that need updating later.
9720 for (auto I : IdToIndexMap) {
9721 auto &Infos = ForwardRefValueInfos[I.first];
9722 for (auto P : I.second) {
9723 assert(Calls[P.first].first.getRef() == FwdVIRef &&
9724 "Forward referenced ValueInfo expected to be empty");
9725 Infos.emplace_back(&Calls[P.first].first, P.second);
9726 }
9727 }
9728
9729 if (parseToken(lltok::rparen, "expected ')' in calls"))
9730 return true;
9731
9732 return false;
9733}
9734
9735/// Hotness
9736/// := ('unknown'|'cold'|'none'|'hot'|'critical')
9737bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
9738 switch (Lex.getKind()) {
9739 case lltok::kw_unknown:
9741 break;
9742 case lltok::kw_cold:
9744 break;
9745 case lltok::kw_none:
9747 break;
9748 case lltok::kw_hot:
9750 break;
9751 case lltok::kw_critical:
9753 break;
9754 default:
9755 return error(Lex.getLoc(), "invalid call edge hotness");
9756 }
9757 Lex.Lex();
9758 return false;
9759}
9760
9761/// OptionalVTableFuncs
9762/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9763/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9764bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
9766 Lex.Lex();
9767
9768 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
9769 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9770 return true;
9771
9772 IdToIndexMapType IdToIndexMap;
9773 // parse each virtual function pair
9774 do {
9775 ValueInfo VI;
9776 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9777 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9778 parseToken(lltok::colon, "expected ':'"))
9779 return true;
9780
9781 LocTy Loc = Lex.getLoc();
9782 unsigned GVId;
9783 if (parseGVReference(VI, GVId))
9784 return true;
9785
9787 if (parseToken(lltok::comma, "expected comma") ||
9788 parseToken(lltok::kw_offset, "expected offset") ||
9789 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9790 return true;
9791
9792 // Keep track of the VTableFuncs array index needing a forward reference.
9793 // We will save the location of the ValueInfo needing an update, but
9794 // can only do so once the std::vector is finalized.
9795 if (VI == EmptyVI)
9796 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9797 VTableFuncs.push_back({VI, Offset});
9798
9799 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9800 return true;
9801 } while (EatIfPresent(lltok::comma));
9802
9803 // Now that the VTableFuncs vector is finalized, it is safe to save the
9804 // locations of any forward GV references that need updating later.
9805 for (auto I : IdToIndexMap) {
9806 auto &Infos = ForwardRefValueInfos[I.first];
9807 for (auto P : I.second) {
9808 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9809 "Forward referenced ValueInfo expected to be empty");
9810 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9811 }
9812 }
9813
9814 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9815 return true;
9816
9817 return false;
9818}
9819
9820/// ParamNo := 'param' ':' UInt64
9821bool LLParser::parseParamNo(uint64_t &ParamNo) {
9822 if (parseToken(lltok::kw_param, "expected 'param' here") ||
9823 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9824 return true;
9825 return false;
9826}
9827
9828/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9829bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9830 APSInt Lower;
9831 APSInt Upper;
9832 auto ParseAPSInt = [&](APSInt &Val) {
9833 if (Lex.getKind() != lltok::APSInt)
9834 return tokError("expected integer");
9835 Val = Lex.getAPSIntVal();
9836 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9837 Val.setIsSigned(true);
9838 Lex.Lex();
9839 return false;
9840 };
9841 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9842 parseToken(lltok::colon, "expected ':' here") ||
9843 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9844 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9845 parseToken(lltok::rsquare, "expected ']' here"))
9846 return true;
9847
9848 ++Upper;
9849 Range =
9850 (Lower == Upper && !Lower.isMaxValue())
9851 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9853
9854 return false;
9855}
9856
9857/// ParamAccessCall
9858/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9859bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9860 IdLocListType &IdLocList) {
9861 if (parseToken(lltok::lparen, "expected '(' here") ||
9862 parseToken(lltok::kw_callee, "expected 'callee' here") ||
9863 parseToken(lltok::colon, "expected ':' here"))
9864 return true;
9865
9866 unsigned GVId;
9867 ValueInfo VI;
9868 LocTy Loc = Lex.getLoc();
9869 if (parseGVReference(VI, GVId))
9870 return true;
9871
9872 Call.Callee = VI;
9873 IdLocList.emplace_back(GVId, Loc);
9874
9875 if (parseToken(lltok::comma, "expected ',' here") ||
9876 parseParamNo(Call.ParamNo) ||
9877 parseToken(lltok::comma, "expected ',' here") ||
9878 parseParamAccessOffset(Call.Offsets))
9879 return true;
9880
9881 if (parseToken(lltok::rparen, "expected ')' here"))
9882 return true;
9883
9884 return false;
9885}
9886
9887/// ParamAccess
9888/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9889/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9890bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
9891 IdLocListType &IdLocList) {
9892 if (parseToken(lltok::lparen, "expected '(' here") ||
9893 parseParamNo(Param.ParamNo) ||
9894 parseToken(lltok::comma, "expected ',' here") ||
9895 parseParamAccessOffset(Param.Use))
9896 return true;
9897
9898 if (EatIfPresent(lltok::comma)) {
9899 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
9900 parseToken(lltok::colon, "expected ':' here") ||
9901 parseToken(lltok::lparen, "expected '(' here"))
9902 return true;
9903 do {
9905 if (parseParamAccessCall(Call, IdLocList))
9906 return true;
9907 Param.Calls.push_back(Call);
9908 } while (EatIfPresent(lltok::comma));
9909
9910 if (parseToken(lltok::rparen, "expected ')' here"))
9911 return true;
9912 }
9913
9914 if (parseToken(lltok::rparen, "expected ')' here"))
9915 return true;
9916
9917 return false;
9918}
9919
9920/// OptionalParamAccesses
9921/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9922bool LLParser::parseOptionalParamAccesses(
9923 std::vector<FunctionSummary::ParamAccess> &Params) {
9925 Lex.Lex();
9926
9927 if (parseToken(lltok::colon, "expected ':' here") ||
9928 parseToken(lltok::lparen, "expected '(' here"))
9929 return true;
9930
9931 IdLocListType VContexts;
9932 size_t CallsNum = 0;
9933 do {
9934 FunctionSummary::ParamAccess ParamAccess;
9935 if (parseParamAccess(ParamAccess, VContexts))
9936 return true;
9937 CallsNum += ParamAccess.Calls.size();
9938 assert(VContexts.size() == CallsNum);
9939 (void)CallsNum;
9940 Params.emplace_back(std::move(ParamAccess));
9941 } while (EatIfPresent(lltok::comma));
9942
9943 if (parseToken(lltok::rparen, "expected ')' here"))
9944 return true;
9945
9946 // Now that the Params is finalized, it is safe to save the locations
9947 // of any forward GV references that need updating later.
9948 IdLocListType::const_iterator ItContext = VContexts.begin();
9949 for (auto &PA : Params) {
9950 for (auto &C : PA.Calls) {
9951 if (C.Callee.getRef() == FwdVIRef)
9952 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9953 ItContext->second);
9954 ++ItContext;
9955 }
9956 }
9957 assert(ItContext == VContexts.end());
9958
9959 return false;
9960}
9961
9962/// OptionalRefs
9963/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9964bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9965 assert(Lex.getKind() == lltok::kw_refs);
9966 Lex.Lex();
9967
9968 if (parseToken(lltok::colon, "expected ':' in refs") ||
9969 parseToken(lltok::lparen, "expected '(' in refs"))
9970 return true;
9971
9972 struct ValueContext {
9973 ValueInfo VI;
9974 unsigned GVId;
9975 LocTy Loc;
9976 };
9977 std::vector<ValueContext> VContexts;
9978 // parse each ref edge
9979 do {
9980 ValueContext VC;
9981 VC.Loc = Lex.getLoc();
9982 if (parseGVReference(VC.VI, VC.GVId))
9983 return true;
9984 VContexts.push_back(VC);
9985 } while (EatIfPresent(lltok::comma));
9986
9987 // Sort value contexts so that ones with writeonly
9988 // and readonly ValueInfo are at the end of VContexts vector.
9989 // See FunctionSummary::specialRefCounts()
9990 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9991 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9992 });
9993
9994 IdToIndexMapType IdToIndexMap;
9995 for (auto &VC : VContexts) {
9996 // Keep track of the Refs array index needing a forward reference.
9997 // We will save the location of the ValueInfo needing an update, but
9998 // can only do so once the std::vector is finalized.
9999 if (VC.VI.getRef() == FwdVIRef)
10000 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10001 Refs.push_back(VC.VI);
10002 }
10003
10004 // Now that the Refs vector is finalized, it is safe to save the locations
10005 // of any forward GV references that need updating later.
10006 for (auto I : IdToIndexMap) {
10007 auto &Infos = ForwardRefValueInfos[I.first];
10008 for (auto P : I.second) {
10009 assert(Refs[P.first].getRef() == FwdVIRef &&
10010 "Forward referenced ValueInfo expected to be empty");
10011 Infos.emplace_back(&Refs[P.first], P.second);
10012 }
10013 }
10014
10015 if (parseToken(lltok::rparen, "expected ')' in refs"))
10016 return true;
10017
10018 return false;
10019}
10020
10021/// OptionalTypeIdInfo
10022/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10023/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10024/// [',' TypeCheckedLoadConstVCalls]? ')'
10025bool LLParser::parseOptionalTypeIdInfo(
10026 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10028 Lex.Lex();
10029
10030 if (parseToken(lltok::colon, "expected ':' here") ||
10031 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10032 return true;
10033
10034 do {
10035 switch (Lex.getKind()) {
10037 if (parseTypeTests(TypeIdInfo.TypeTests))
10038 return true;
10039 break;
10041 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10042 TypeIdInfo.TypeTestAssumeVCalls))
10043 return true;
10044 break;
10046 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10047 TypeIdInfo.TypeCheckedLoadVCalls))
10048 return true;
10049 break;
10051 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10052 TypeIdInfo.TypeTestAssumeConstVCalls))
10053 return true;
10054 break;
10056 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10057 TypeIdInfo.TypeCheckedLoadConstVCalls))
10058 return true;
10059 break;
10060 default:
10061 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10062 }
10063 } while (EatIfPresent(lltok::comma));
10064
10065 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10066 return true;
10067
10068 return false;
10069}
10070
10071/// TypeTests
10072/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10073/// [',' (SummaryID | UInt64)]* ')'
10074bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10076 Lex.Lex();
10077
10078 if (parseToken(lltok::colon, "expected ':' here") ||
10079 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10080 return true;
10081
10082 IdToIndexMapType IdToIndexMap;
10083 do {
10085 if (Lex.getKind() == lltok::SummaryID) {
10086 unsigned ID = Lex.getUIntVal();
10087 LocTy Loc = Lex.getLoc();
10088 // Keep track of the TypeTests array index needing a forward reference.
10089 // We will save the location of the GUID needing an update, but
10090 // can only do so once the std::vector is finalized.
10091 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10092 Lex.Lex();
10093 } else if (parseUInt64(GUID))
10094 return true;
10095 TypeTests.push_back(GUID);
10096 } while (EatIfPresent(lltok::comma));
10097
10098 // Now that the TypeTests vector is finalized, it is safe to save the
10099 // locations of any forward GV references that need updating later.
10100 for (auto I : IdToIndexMap) {
10101 auto &Ids = ForwardRefTypeIds[I.first];
10102 for (auto P : I.second) {
10103 assert(TypeTests[P.first] == 0 &&
10104 "Forward referenced type id GUID expected to be 0");
10105 Ids.emplace_back(&TypeTests[P.first], P.second);
10106 }
10107 }
10108
10109 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10110 return true;
10111
10112 return false;
10113}
10114
10115/// VFuncIdList
10116/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10117bool LLParser::parseVFuncIdList(
10118 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10119 assert(Lex.getKind() == Kind);
10120 Lex.Lex();
10121
10122 if (parseToken(lltok::colon, "expected ':' here") ||
10123 parseToken(lltok::lparen, "expected '(' here"))
10124 return true;
10125
10126 IdToIndexMapType IdToIndexMap;
10127 do {
10129 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10130 return true;
10131 VFuncIdList.push_back(VFuncId);
10132 } while (EatIfPresent(lltok::comma));
10133
10134 if (parseToken(lltok::rparen, "expected ')' here"))
10135 return true;
10136
10137 // Now that the VFuncIdList vector is finalized, it is safe to save the
10138 // locations of any forward GV references that need updating later.
10139 for (auto I : IdToIndexMap) {
10140 auto &Ids = ForwardRefTypeIds[I.first];
10141 for (auto P : I.second) {
10142 assert(VFuncIdList[P.first].GUID == 0 &&
10143 "Forward referenced type id GUID expected to be 0");
10144 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10145 }
10146 }
10147
10148 return false;
10149}
10150
10151/// ConstVCallList
10152/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10153bool LLParser::parseConstVCallList(
10154 lltok::Kind Kind,
10155 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10156 assert(Lex.getKind() == Kind);
10157 Lex.Lex();
10158
10159 if (parseToken(lltok::colon, "expected ':' here") ||
10160 parseToken(lltok::lparen, "expected '(' here"))
10161 return true;
10162
10163 IdToIndexMapType IdToIndexMap;
10164 do {
10165 FunctionSummary::ConstVCall ConstVCall;
10166 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10167 return true;
10168 ConstVCallList.push_back(ConstVCall);
10169 } while (EatIfPresent(lltok::comma));
10170
10171 if (parseToken(lltok::rparen, "expected ')' here"))
10172 return true;
10173
10174 // Now that the ConstVCallList vector is finalized, it is safe to save the
10175 // locations of any forward GV references that need updating later.
10176 for (auto I : IdToIndexMap) {
10177 auto &Ids = ForwardRefTypeIds[I.first];
10178 for (auto P : I.second) {
10179 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10180 "Forward referenced type id GUID expected to be 0");
10181 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10182 }
10183 }
10184
10185 return false;
10186}
10187
10188/// ConstVCall
10189/// ::= '(' VFuncId ',' Args ')'
10190bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10191 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10192 if (parseToken(lltok::lparen, "expected '(' here") ||
10193 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10194 return true;
10195
10196 if (EatIfPresent(lltok::comma))
10197 if (parseArgs(ConstVCall.Args))
10198 return true;
10199
10200 if (parseToken(lltok::rparen, "expected ')' here"))
10201 return true;
10202
10203 return false;
10204}
10205
10206/// VFuncId
10207/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10208/// 'offset' ':' UInt64 ')'
10209bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10210 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10212 Lex.Lex();
10213
10214 if (parseToken(lltok::colon, "expected ':' here") ||
10215 parseToken(lltok::lparen, "expected '(' here"))
10216 return true;
10217
10218 if (Lex.getKind() == lltok::SummaryID) {
10219 VFuncId.GUID = 0;
10220 unsigned ID = Lex.getUIntVal();
10221 LocTy Loc = Lex.getLoc();
10222 // Keep track of the array index needing a forward reference.
10223 // We will save the location of the GUID needing an update, but
10224 // can only do so once the caller's std::vector is finalized.
10225 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10226 Lex.Lex();
10227 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10228 parseToken(lltok::colon, "expected ':' here") ||
10229 parseUInt64(VFuncId.GUID))
10230 return true;
10231
10232 if (parseToken(lltok::comma, "expected ',' here") ||
10233 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10234 parseToken(lltok::colon, "expected ':' here") ||
10235 parseUInt64(VFuncId.Offset) ||
10236 parseToken(lltok::rparen, "expected ')' here"))
10237 return true;
10238
10239 return false;
10240}
10241
10242/// GVFlags
10243/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10244/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10245/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10246/// 'canAutoHide' ':' Flag ',' ')'
10247bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10248 assert(Lex.getKind() == lltok::kw_flags);
10249 Lex.Lex();
10250
10251 if (parseToken(lltok::colon, "expected ':' here") ||
10252 parseToken(lltok::lparen, "expected '(' here"))
10253 return true;
10254
10255 do {
10256 unsigned Flag = 0;
10257 switch (Lex.getKind()) {
10258 case lltok::kw_linkage:
10259 Lex.Lex();
10260 if (parseToken(lltok::colon, "expected ':'"))
10261 return true;
10262 bool HasLinkage;
10263 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10264 assert(HasLinkage && "Linkage not optional in summary entry");
10265 Lex.Lex();
10266 break;
10268 Lex.Lex();
10269 if (parseToken(lltok::colon, "expected ':'"))
10270 return true;
10271 parseOptionalVisibility(Flag);
10272 GVFlags.Visibility = Flag;
10273 break;
10275 Lex.Lex();
10276 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10277 return true;
10278 GVFlags.NotEligibleToImport = Flag;
10279 break;
10280 case lltok::kw_live:
10281 Lex.Lex();
10282 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10283 return true;
10284 GVFlags.Live = Flag;
10285 break;
10286 case lltok::kw_dsoLocal:
10287 Lex.Lex();
10288 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10289 return true;
10290 GVFlags.DSOLocal = Flag;
10291 break;
10293 Lex.Lex();
10294 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10295 return true;
10296 GVFlags.CanAutoHide = Flag;
10297 break;
10299 Lex.Lex();
10300 if (parseToken(lltok::colon, "expected ':'"))
10301 return true;
10303 if (parseOptionalImportType(Lex.getKind(), IK))
10304 return true;
10305 GVFlags.ImportType = static_cast<unsigned>(IK);
10306 Lex.Lex();
10307 break;
10308 default:
10309 return error(Lex.getLoc(), "expected gv flag type");
10310 }
10311 } while (EatIfPresent(lltok::comma));
10312
10313 if (parseToken(lltok::rparen, "expected ')' here"))
10314 return true;
10315
10316 return false;
10317}
10318
10319/// GVarFlags
10320/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10321/// ',' 'writeonly' ':' Flag
10322/// ',' 'constant' ':' Flag ')'
10323bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10325 Lex.Lex();
10326
10327 if (parseToken(lltok::colon, "expected ':' here") ||
10328 parseToken(lltok::lparen, "expected '(' here"))
10329 return true;
10330
10331 auto ParseRest = [this](unsigned int &Val) {
10332 Lex.Lex();
10333 if (parseToken(lltok::colon, "expected ':'"))
10334 return true;
10335 return parseFlag(Val);
10336 };
10337
10338 do {
10339 unsigned Flag = 0;
10340 switch (Lex.getKind()) {
10341 case lltok::kw_readonly:
10342 if (ParseRest(Flag))
10343 return true;
10344 GVarFlags.MaybeReadOnly = Flag;
10345 break;
10346 case lltok::kw_writeonly:
10347 if (ParseRest(Flag))
10348 return true;
10349 GVarFlags.MaybeWriteOnly = Flag;
10350 break;
10351 case lltok::kw_constant:
10352 if (ParseRest(Flag))
10353 return true;
10354 GVarFlags.Constant = Flag;
10355 break;
10357 if (ParseRest(Flag))
10358 return true;
10359 GVarFlags.VCallVisibility = Flag;
10360 break;
10361 default:
10362 return error(Lex.getLoc(), "expected gvar flag type");
10363 }
10364 } while (EatIfPresent(lltok::comma));
10365 return parseToken(lltok::rparen, "expected ')' here");
10366}
10367
10368/// ModuleReference
10369/// ::= 'module' ':' UInt
10370bool LLParser::parseModuleReference(StringRef &ModulePath) {
10371 // parse module id.
10372 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10373 parseToken(lltok::colon, "expected ':' here") ||
10374 parseToken(lltok::SummaryID, "expected module ID"))
10375 return true;
10376
10377 unsigned ModuleID = Lex.getUIntVal();
10378 auto I = ModuleIdMap.find(ModuleID);
10379 // We should have already parsed all module IDs
10380 assert(I != ModuleIdMap.end());
10381 ModulePath = I->second;
10382 return false;
10383}
10384
10385/// GVReference
10386/// ::= SummaryID
10387bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10388 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10389 if (!ReadOnly)
10390 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10391 if (parseToken(lltok::SummaryID, "expected GV ID"))
10392 return true;
10393
10394 GVId = Lex.getUIntVal();
10395 // Check if we already have a VI for this GV
10396 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10397 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10398 VI = NumberedValueInfos[GVId];
10399 } else
10400 // We will create a forward reference to the stored location.
10401 VI = ValueInfo(false, FwdVIRef);
10402
10403 if (ReadOnly)
10404 VI.setReadOnly();
10405 if (WriteOnly)
10406 VI.setWriteOnly();
10407 return false;
10408}
10409
10410/// OptionalAllocs
10411/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10412/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10413/// ',' MemProfs ')'
10414/// Version ::= UInt32
10415bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10417 Lex.Lex();
10418
10419 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10420 parseToken(lltok::lparen, "expected '(' in allocs"))
10421 return true;
10422
10423 // parse each alloc
10424 do {
10425 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10426 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10427 parseToken(lltok::colon, "expected ':'") ||
10428 parseToken(lltok::lparen, "expected '(' in versions"))
10429 return true;
10430
10431 SmallVector<uint8_t> Versions;
10432 do {
10433 uint8_t V = 0;
10434 if (parseAllocType(V))
10435 return true;
10436 Versions.push_back(V);
10437 } while (EatIfPresent(lltok::comma));
10438
10439 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10440 parseToken(lltok::comma, "expected ',' in alloc"))
10441 return true;
10442
10443 std::vector<MIBInfo> MIBs;
10444 if (parseMemProfs(MIBs))
10445 return true;
10446
10447 Allocs.push_back({Versions, MIBs});
10448
10449 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10450 return true;
10451 } while (EatIfPresent(lltok::comma));
10452
10453 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10454 return true;
10455
10456 return false;
10457}
10458
10459/// MemProfs
10460/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10461/// MemProf ::= '(' 'type' ':' AllocType
10462/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10463/// StackId ::= UInt64
10464bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10466 Lex.Lex();
10467
10468 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10469 parseToken(lltok::lparen, "expected '(' in memprof"))
10470 return true;
10471
10472 // parse each MIB
10473 do {
10474 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10475 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10476 parseToken(lltok::colon, "expected ':'"))
10477 return true;
10478
10479 uint8_t AllocType;
10480 if (parseAllocType(AllocType))
10481 return true;
10482
10483 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10484 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10485 parseToken(lltok::colon, "expected ':'") ||
10486 parseToken(lltok::lparen, "expected '(' in stackIds"))
10487 return true;
10488
10489 SmallVector<unsigned> StackIdIndices;
10490 do {
10491 uint64_t StackId = 0;
10492 if (parseUInt64(StackId))
10493 return true;
10494 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10495 } while (EatIfPresent(lltok::comma));
10496
10497 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10498 return true;
10499
10500 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10501
10502 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10503 return true;
10504 } while (EatIfPresent(lltok::comma));
10505
10506 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10507 return true;
10508
10509 return false;
10510}
10511
10512/// AllocType
10513/// := ('none'|'notcold'|'cold'|'hot')
10514bool LLParser::parseAllocType(uint8_t &AllocType) {
10515 switch (Lex.getKind()) {
10516 case lltok::kw_none:
10518 break;
10519 case lltok::kw_notcold:
10521 break;
10522 case lltok::kw_cold:
10524 break;
10525 case lltok::kw_hot:
10526 AllocType = (uint8_t)AllocationType::Hot;
10527 break;
10528 default:
10529 return error(Lex.getLoc(), "invalid alloc type");
10530 }
10531 Lex.Lex();
10532 return false;
10533}
10534
10535/// OptionalCallsites
10536/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10537/// Callsite ::= '(' 'callee' ':' GVReference
10538/// ',' 'clones' ':' '(' Version [',' Version]* ')'
10539/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10540/// Version ::= UInt32
10541/// StackId ::= UInt64
10542bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10544 Lex.Lex();
10545
10546 if (parseToken(lltok::colon, "expected ':' in callsites") ||
10547 parseToken(lltok::lparen, "expected '(' in callsites"))
10548 return true;
10549
10550 IdToIndexMapType IdToIndexMap;
10551 // parse each callsite
10552 do {
10553 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10554 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10555 parseToken(lltok::colon, "expected ':'"))
10556 return true;
10557
10558 ValueInfo VI;
10559 unsigned GVId = 0;
10560 LocTy Loc = Lex.getLoc();
10561 if (!EatIfPresent(lltok::kw_null)) {
10562 if (parseGVReference(VI, GVId))
10563 return true;
10564 }
10565
10566 if (parseToken(lltok::comma, "expected ',' in callsite") ||
10567 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10568 parseToken(lltok::colon, "expected ':'") ||
10569 parseToken(lltok::lparen, "expected '(' in clones"))
10570 return true;
10571
10572 SmallVector<unsigned> Clones;
10573 do {
10574 unsigned V = 0;
10575 if (parseUInt32(V))
10576 return true;
10577 Clones.push_back(V);
10578 } while (EatIfPresent(lltok::comma));
10579
10580 if (parseToken(lltok::rparen, "expected ')' in clones") ||
10581 parseToken(lltok::comma, "expected ',' in callsite") ||
10582 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
10583 parseToken(lltok::colon, "expected ':'") ||
10584 parseToken(lltok::lparen, "expected '(' in stackIds"))
10585 return true;
10586
10587 SmallVector<unsigned> StackIdIndices;
10588 do {
10589 uint64_t StackId = 0;
10590 if (parseUInt64(StackId))
10591 return true;
10592 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10593 } while (EatIfPresent(lltok::comma));
10594
10595 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10596 return true;
10597
10598 // Keep track of the Callsites array index needing a forward reference.
10599 // We will save the location of the ValueInfo needing an update, but
10600 // can only do so once the SmallVector is finalized.
10601 if (VI.getRef() == FwdVIRef)
10602 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10603 Callsites.push_back({VI, Clones, StackIdIndices});
10604
10605 if (parseToken(lltok::rparen, "expected ')' in callsite"))
10606 return true;
10607 } while (EatIfPresent(lltok::comma));
10608
10609 // Now that the Callsites vector is finalized, it is safe to save the
10610 // locations of any forward GV references that need updating later.
10611 for (auto I : IdToIndexMap) {
10612 auto &Infos = ForwardRefValueInfos[I.first];
10613 for (auto P : I.second) {
10614 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
10615 "Forward referenced ValueInfo expected to be empty");
10616 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
10617 }
10618 }
10619
10620 if (parseToken(lltok::rparen, "expected ')' in callsites"))
10621 return true;
10622
10623 return false;
10624}
static int64_t upperBound(StackOffset Size)
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseMap class.
@ Default
Definition: DwarfDebug.cpp:87
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:507
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
#define _
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
Definition: LLParser.cpp:1736
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)
Definition: LLParser.cpp:1131
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
Definition: LLParser.cpp:1639
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
Definition: LLParser.cpp:2470
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
Definition: LLParser.cpp:9161
cl::opt< bool > WriteNewDbgInfoFormat
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
Definition: LLParser.cpp:2005
bool WriteNewDbgInfoFormatToBitcode
Definition: BasicBlock.cpp:47
static unsigned keywordToFPClassTest(lltok::Kind Tok)
Definition: LLParser.cpp:2551
llvm::cl::opt< bool > UseNewDbgInfoFormat
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
Definition: LLParser.cpp:2481
static bool isSanitizer(lltok::Kind Kind)
Definition: LLParser.cpp:1289
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition: LLParser.cpp:140
#define PARSE_MD_FIELDS()
Definition: LLParser.cpp:5136
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
Definition: LLParser.cpp:1521
static ValueInfo EmptyVI
Definition: LLParser.cpp:8802
#define GET_OR_DISTINCT(CLASS, ARGS)
Definition: LLParser.cpp:5150
bool isOldDbgFormatIntrinsic(StringRef Name)
Definition: LLParser.cpp:6272
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
Definition: LLParser.cpp:1120
static std::string getTypeString(Type *T)
Definition: LLParser.cpp:71
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
Definition: LLParser.cpp:1124
static const auto FwdVIRef
Definition: LLParser.cpp:9159
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
llvm::cl::opt< bool > UseNewDbgInfoFormat
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:49
This file contains some templates that are useful if you are working with the STL at all.
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.
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:40
Value * RHS
Value * LHS
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:1028
Class for arbitrary precision integers.
Definition: APInt.h:77
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1499
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1447
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:454
bool getBoolValue() const
Convert APInt to a boolean value.
Definition: APInt.h:450
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1216
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:23
APSInt extOrTrunc(uint32_t width) const
Definition: APSInt.h:119
APSInt extend(uint32_t width) const
Definition: APSInt.h:112
bool isSigned() const
Definition: APSInt.h:77
an instruction to allocate memory on the stack
Definition: Instructions.h:60
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:148
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Definition: Instructions.h:141
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:659
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:494
void setWeak(bool IsWeak)
Definition: Instructions.h:555
static bool isValidFailureOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:565
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
Definition: Instructions.h:550
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:560
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:695
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
Definition: Instructions.h:822
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:707
@ Add
*p = old + v
Definition: Instructions.h:711
@ FAdd
*p = old + v
Definition: Instructions.h:732
@ Min
*p = old <signed v ? old : v
Definition: Instructions.h:725
@ Or
*p = old | v
Definition: Instructions.h:719
@ Sub
*p = old - v
Definition: Instructions.h:713
@ And
*p = old & v
Definition: Instructions.h:715
@ Xor
*p = old ^ v
Definition: Instructions.h:721
@ FSub
*p = old - v
Definition: Instructions.h:735
@ UIncWrap
Increment one up to a maximum value.
Definition: Instructions.h:747
@ Max
*p = old >signed v ? old : v
Definition: Instructions.h:723
@ UMin
*p = old <unsigned v ? old : v
Definition: Instructions.h:729
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
Definition: Instructions.h:743
@ UMax
*p = old >unsigned v ? old : v
Definition: Instructions.h:727
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
Definition: Instructions.h:739
@ UDecWrap
Decrement one until a minimum value or zero.
Definition: Instructions.h:751
@ Nand
*p = ~(old & v)
Definition: Instructions.h:717
static StringRef getOperationName(BinOp Op)
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const
Definition: Attributes.h:642
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
Definition: Attributes.h:577
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
Definition: Attributes.h:805
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
AttributeList removeFnAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the function index from this attribute list.
Definition: Attributes.h:675
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:842
static bool canUseAsRetAttr(AttrKind Kind)
Definition: Attributes.cpp:749
static bool isTypeAttrKind(AttrKind Kind)
Definition: Attributes.h:105
static bool canUseAsFnAttr(AttrKind Kind)
Definition: Attributes.cpp:741
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
@ None
No attributes have been set.
Definition: Attributes.h:88
static bool canUseAsParamAttr(AttrKind Kind)
Definition: Attributes.cpp:745
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:451
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:202
static 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 BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1833
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1527
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1546
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static 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 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=std::nullopt, 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:757
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:760
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:774
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:786
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:787
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:763
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:772
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:761
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:762
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:781
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:780
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:784
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:771
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:765
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:768
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:782
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:769
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:764
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:766
@ ICMP_EQ
equal
Definition: InstrTypes.h:778
@ ICMP_NE
not equal
Definition: InstrTypes.h:779
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:785
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:773
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:783
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:770
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:759
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:767
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1292
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2900
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2478
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:2146
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2500
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2523
static 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.
Definition: Constants.cpp:2264
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:1240
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
Definition: Constants.cpp:1589
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:850
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:124
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:857
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition: Constants.h:149
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1762
static ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
Definition: Constants.cpp:2008
static std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
Definition: ConstantRange.h:47
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
Definition: ConstantRange.h:84
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1357
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1450
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1399
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
static DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
Basic type, like 'int' or 'float'.
Debug common block.
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
Build a DICompositeType with the given ODR identifier.
Enumeration value.
DWARF expression.
static std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Debug lexical block.
Debug location.
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Debug lexical block.
Tagged DWARF-like metadata node.
static DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
String type, Fortran CHARACTER(n)
Subprogram description.
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Array subrange.
Type array for a subprogram.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
Definition: Constants.cpp:1906
This class represents an Operation in the Expression.
static Expected< DataLayout > parse(StringRef LayoutDescription)
Parse a data layout string and return the layout.
Definition: DataLayout.cpp:223
static DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Base class for non-instruction debug metadata records that have positions within IR.
Kind
Subclass discriminator.
static 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...
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
unsigned size() const
Definition: DenseMap.h:99
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:308
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
Class representing an expression and its matching format.
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static 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)
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
bool any() const
Definition: FMF.h:57
An instruction for ordering other memory operations.
Definition: Instructions.h:419
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:126
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition: Type.cpp:358
static 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:165
void setPrefixData(Constant *PrefixData)
Definition: Function.cpp:1949
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
Definition: Function.cpp:927
void setGC(std::string Str)
Definition: Function.cpp:790
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1939
arg_iterator arg_begin()
Definition: Function.h:831
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:353
void setPrologueData(Constant *PrologueData)
Definition: Function.cpp:1959
void setCallingConv(CallingConv::ID CC)
Definition: Function.h:278
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
Generic tagged DWARF-like metadata node.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:914
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Definition: Instructions.h:937
static 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:95
static 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:544
static 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:601
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:137
void setComdat(Comdat *C)
Definition: Globals.cpp:206
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:267
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1521
const SanitizerMetadata & getSanitizerMetadata() const
Definition: Globals.cpp:237
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:409
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:231
void setDLLStorageClass(DLLStorageClassTypes C)
Definition: GlobalValue.h:284
void setThreadLocalMode(ThreadLocalMode Val)
Definition: GlobalValue.h:267
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition: GlobalValue.h:73
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition: GlobalValue.h:76
@ DLLImportStorageClass
Function to be imported from DLL.
Definition: GlobalValue.h:75
bool hasSanitizerMetadata() const
Definition: GlobalValue.h:355
unsigned getAddressSpace() const
Definition: GlobalValue.h:205
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:595
void setDSOLocal(bool Local)
Definition: GlobalValue.h:303
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:91
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:66
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ ProtectedVisibility
The GV is protected.
Definition: GlobalValue.h:69
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:418
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:254
void setSanitizerMetadata(SanitizerMetadata Meta)
Definition: Globals.cpp:243
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
Definition: Globals.cpp:178
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
Type * getValueType() const
Definition: GlobalValue.h:296
void setPartition(StringRef Part)
Definition: Globals.cpp:220
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:485
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition: Globals.cpp:521
void setExternallyInitialized(bool Val)
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static 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 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...
Definition: InlineAsm.cpp:273
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static 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)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
Definition: Instruction.h:277
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1635
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.
Definition: IntrinsicInst.h:48
Invoke instruction.
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:52
unsigned getUIntVal() const
Definition: LLLexer.h:61
lltok::Kind getKind() const
Definition: LLLexer.h:58
bool Error(LocTy ErrorLoc, const Twine &Msg) const
Definition: LLLexer.cpp:28
const std::string & getStrVal() const
Definition: LLLexer.h:59
Type * getTyVal() const
Definition: LLLexer.h:60
LocTy getLoc() const
Definition: LLLexer.h:57
const APSInt & getAPSIntVal() const
Definition: LLLexer.h:62
void setIgnoreColonInIdentifiers(bool val)
Definition: LLLexer.h:65
const APFloat & getAPFloatVal() const
Definition: LLLexer.h:63
LLLexer::LocTy LocTy
Definition: LLParser.h:106
LLVMContext & getContext()
Definition: LLParser.h:204
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition: LLParser.cpp:111
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition: LLParser.cpp:98
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition: LLParser.cpp:79
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
static 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...
An instruction for reading from memory.
Definition: Instructions.h:173
Metadata node.
Definition: Metadata.h:1067
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1549
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
A single uniqued string.
Definition: Metadata.h:720
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:600
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition: Metadata.h:1509
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1498
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition: Metadata.h:1518
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
Definition: ModRef.h:122
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition: ModRef.h:170
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
Definition: ModRef.h:132
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
Definition: ModRef.h:138
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
Definition: ModRef.h:127
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
Definition: ModRef.h:145
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
Definition: ModRef.h:117
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
Definition: ModRef.h:112
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:176
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1729
void addOperand(MDNode *M)
Definition: Metadata.cpp:1387
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
Definition: Constants.cpp:1964
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:764
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1814
Resume the propagation of an exception.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition: SMLoc.h:23
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
static 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.
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
static 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.
Definition: SmallPtrSet.h:344
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:479
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:299
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:289
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
iterator end()
Definition: StringMap.h:220
iterator find(StringRef Key)
Definition: StringMap.h:233
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
Class to represent struct types.
Definition: DerivedTypes.h:216
static 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:373
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
Definition: Type.cpp:445
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:513
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:597
bool containsScalableVectorType(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Returns true if this struct contains a scalable vector.
Definition: Type.cpp:400
Multiway switch.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
static TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types=std::nullopt, ArrayRef< unsigned > Ints=std::nullopt)
Return a target extension type having the specified name and optional type and integer parameters.
Definition: Type.cpp:796
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Definition: DerivedTypes.h:769
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:252
bool isLabelTy() const
Return true if this is 'label'.
Definition: Type.h:219
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:255
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:154
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:146
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:281
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:295
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:143
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:262
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:246
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
bool isTokenTy() const
Return true if this is 'token'.
Definition: Type.h:225
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:216
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:140
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition: Type.h:222
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1795
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:495
LLVM Value Representation.
Definition: Value.h:74
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:807
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:110
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:683
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:676
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition: ilist_node.h:132
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:679
unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition: Dwarf.cpp:165
unsigned getAttributeEncoding(StringRef EncodingString)
Definition: Dwarf.cpp:274
unsigned getTag(StringRef TagString)
Definition: Dwarf.cpp:32
unsigned getCallingConvention(StringRef LanguageString)
Definition: Dwarf.cpp:481
unsigned getLanguage(StringRef LanguageString)
Definition: Dwarf.cpp:404
unsigned getVirtuality(StringRef VirtualityString)
Definition: Dwarf.cpp:385
unsigned getMacinfo(StringRef MacinfoString)
Definition: Dwarf.cpp:553
#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 TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Key
PAL metadata keys.
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.
Definition: BitmaskEnum.h:121
@ Entry
Definition: COFF.h:811
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.
Definition: CallingConv.h:221
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Definition: CallingConv.h:151
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
Definition: CallingConv.h:268
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:197
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
Definition: CallingConv.h:188
@ AVR_SIGNAL
Used for AVR signal routines.
Definition: CallingConv.h:179
@ Swift
Calling convention for Swift.
Definition: CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:200
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
Definition: CallingConv.h:224
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
Definition: CallingConv.h:107
@ 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.
Definition: CallingConv.h:176
@ 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.
Definition: CallingConv.h:232
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
Definition: CallingConv.h:166
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:249
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:206
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:111
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:191
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:241
@ CXX_FAST_TLS
Used for access functions.
Definition: CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
Definition: CallingConv.h:173
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:238
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:245
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition: CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
@ 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.
Definition: CallingConv.h:271
@ X86_ThisCall
Similar to X86_StdCall.
Definition: CallingConv.h:122
@ PTX_Device
Call to a PTX device function.
Definition: CallingConv.h:129
@ SPIR_KERNEL
Used for SPIR kernel functions.
Definition: CallingConv.h:144
@ 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.
Definition: CallingConv.h:138
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
Definition: CallingConv.h:117
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
Definition: CallingConv.h:163
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
Definition: CallingConv.h:147
@ 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.
Definition: CallingConv.h:218
@ 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.
Definition: CallingConv.h:159
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
Definition: CallingConv.h:125
@ 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.
Definition: CallingConv.h:255
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:213
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
Definition: CallingConv.h:114
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
Definition: CallingConv.h:203
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
Definition: CallingConv.h:252
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
Definition: CallingConv.h:103
bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Definition: Function.cpp:1780
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1484
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:148
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:57
@ FS
Definition: X86.h:206
@ GS
Definition: X86.h:205
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ DW_CC_hi_user
Definition: Dwarf.h:743
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_ATE_hi_user
Definition: Dwarf.h:161
@ DW_LANG_hi_user
Definition: Dwarf.h:212
MacinfoRecordType
Definition: Dwarf.h:787
@ DW_MACINFO_vendor_ext
Definition: Dwarf.h:793
@ DW_VIRTUALITY_max
Definition: Dwarf.h:198
@ DW_TAG_hi_user
Definition: Dwarf.h:107
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition: Dwarf.h:47
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition: Dwarf.h:49
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition: Dwarf.h:48
@ kw_samesize
Definition: LLToken.h:237
@ kw_msp430_intrcc
Definition: LLToken.h:152
@ kw_acquire
Definition: LLToken.h:97
@ kw_cxx_fast_tlscc
Definition: LLToken.h:171
@ kw_extractvalue
Definition: LLToken.h:345
@ kw_dso_preemptable
Definition: LLToken.h:51
@ DwarfVirtuality
Definition: LLToken.h:480
@ kw_arm_apcscc
Definition: LLToken.h:144
@ kw_inteldialect
Definition: LLToken.h:127
@ kw_x86_stdcallcc
Definition: LLToken.h:139
@ kw_constant
Definition: LLToken.h:48
@ kw_graalcc
Definition: LLToken.h:185
@ kw_initialexec
Definition: LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition: LLToken.h:150
@ kw_mustBeUnreachable
Definition: LLToken.h:391
@ kw_internal
Definition: LLToken.h:54
@ kw_hhvm_ccc
Definition: LLToken.h:170
@ kw_ptrtoint
Definition: LLToken.h:307
@ kw_anyregcc
Definition: LLToken.h:161
@ kw_no_sanitize_hwaddress
Definition: LLToken.h:459
@ kw_win64cc
Definition: LLToken.h:160
@ kw_datalayout
Definition: LLToken.h:92
@ kw_wpdResolutions
Definition: LLToken.h:430
@ kw_cleanup
Definition: LLToken.h:315
@ kw_ptrauth
Definition: LLToken.h:350
@ kw_canAutoHide
Definition: LLToken.h:375
@ kw_alwaysInline
Definition: LLToken.h:387
@ kw_notail
Definition: LLToken.h:87
@ kw_insertelement
Definition: LLToken.h:342
@ kw_linkonce
Definition: LLToken.h:55
@ kw_fptrunc
Definition: LLToken.h:300
@ kw_inaccessiblememonly
Definition: LLToken.h:206
@ kw_amdgpu_gfx
Definition: LLToken.h:182
@ kw_getelementptr
Definition: LLToken.h:339
@ kw_m68k_rtdcc
Definition: LLToken.h:184
@ kw_preserve_nonecc
Definition: LLToken.h:166
@ kw_x86_fastcallcc
Definition: LLToken.h:140
@ kw_readOnly
Definition: LLToken.h:383
@ kw_varFlags
Definition: LLToken.h:444
@ kw_partition
Definition: LLToken.h:120
@ kw_visibility
Definition: LLToken.h:371
@ kw_vFuncId
Definition: LLToken.h:411
@ kw_noUnwind
Definition: LLToken.h:388
@ kw_disjoint
Definition: LLToken.h:114
@ kw_bitMask
Definition: LLToken.h:427
@ kw_unordered
Definition: LLToken.h:95
@ kw_singleImpl
Definition: LLToken.h:433
@ kw_swiftcc
Definition: LLToken.h:162
@ kw_localexec
Definition: LLToken.h:75
@ kw_cfguard_checkcc
Definition: LLToken.h:138
@ kw_stackIds
Definition: LLToken.h:448
@ kw_typeCheckedLoadConstVCalls
Definition: LLToken.h:410
@ kw_private
Definition: LLToken.h:53
@ kw_aarch64_sve_vector_pcs
Definition: LLToken.h:148
@ kw_amdgpu_kernel
Definition: LLToken.h:181
@ kw_acq_rel
Definition: LLToken.h:99
@ kw_uselistorder
Definition: LLToken.h:358
@ MetadataVar
Definition: LLToken.h:476
@ kw_blockcount
Definition: LLToken.h:369
@ kw_notEligibleToImport
Definition: LLToken.h:372
@ kw_noRecurse
Definition: LLToken.h:384
@ kw_dsoLocal
Definition: LLToken.h:374
@ kw_linkonce_odr
Definition: LLToken.h:56
@ kw_protected
Definition: LLToken.h:66
@ kw_variable
Definition: LLToken.h:400
@ kw_dllexport
Definition: LLToken.h:61
@ kw_hotness
Definition: LLToken.h:396
@ kw_x86_vectorcallcc
Definition: LLToken.h:142
@ kw_ptx_device
Definition: LLToken.h:156
@ kw_personality
Definition: LLToken.h:314
@ kw_catchpad
Definition: LLToken.h:329
@ kw_spir_func
Definition: LLToken.h:158
@ kw_inbounds
Definition: LLToken.h:115
@ kw_atomic
Definition: LLToken.h:94
@ kw_readNone
Definition: LLToken.h:382
@ kw_declaration
Definition: LLToken.h:378
@ kw_define
Definition: LLToken.h:46
@ DwarfAttEncoding
Definition: LLToken.h:479
@ kw_critical
Definition: LLToken.h:398
@ kw_external
Definition: LLToken.h:71
@ kw_largest
Definition: LLToken.h:235
@ kw_amdgpu_hs
Definition: LLToken.h:174
@ kw_spir_kernel
Definition: LLToken.h:157
@ kw_local_unnamed_addr
Definition: LLToken.h:68
@ kw_amdgpu_es
Definition: LLToken.h:175
@ kw_hasUnknownCall
Definition: LLToken.h:390
@ LocalVarID
Definition: LLToken.h:467
@ kw_seq_cst
Definition: LLToken.h:100
@ kw_unwind
Definition: LLToken.h:91
@ kw_distinct
Definition: LLToken.h:355
@ kw_linkage
Definition: LLToken.h:370
@ kw_amdgpu_gs
Definition: LLToken.h:176
@ kw_x86_intrcc
Definition: LLToken.h:168
@ kw_addrspacecast
Definition: LLToken.h:309
@ kw_callsites
Definition: LLToken.h:446
@ kw_zeroinitializer
Definition: LLToken.h:76
@ StringConstant
Definition: LLToken.h:477
@ kw_x86_thiscallcc
Definition: LLToken.h:141
@ kw_false
Definition: LLToken.h:44
@ kw_unnamed_addr
Definition: LLToken.h:67
@ kw_uselistorder_bb
Definition: LLToken.h:359
@ NameTableKind
Definition: LLToken.h:484
@ kw_amdgpu_vs
Definition: LLToken.h:172
@ kw_inlineBits
Definition: LLToken.h:428
@ kw_weak_odr
Definition: LLToken.h:58
@ kw_udec_wrap
Definition: LLToken.h:270
@ kw_resByArg
Definition: LLToken.h:436
@ kw_inttoptr
Definition: LLToken.h:306
@ kw_dllimport
Definition: LLToken.h:60
@ kw_argmemonly
Definition: LLToken.h:205
@ kw_blockaddress
Definition: LLToken.h:347
@ kw_landingpad
Definition: LLToken.h:313
@ kw_aarch64_vector_pcs
Definition: LLToken.h:147
@ kw_amdgpu_cs
Definition: LLToken.h:178
@ kw_syncscope
Definition: LLToken.h:101
@ kw_noInline
Definition: LLToken.h:386
@ kw_source_filename
Definition: LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition: LLToken.h:409
@ kw_inrange
Definition: LLToken.h:117
@ kw_ptx_kernel
Definition: LLToken.h:155
@ kw_summaries
Definition: LLToken.h:367
@ kw_extractelement
Definition: LLToken.h:341
@ kw_branchFunnel
Definition: LLToken.h:434
@ kw_typeidCompatibleVTable
Definition: LLToken.h:415
@ kw_bitcast
Definition: LLToken.h:308
@ kw_declare
Definition: LLToken.h:45
@ kw_allOnes
Definition: LLToken.h:423
@ kw_vTableFuncs
Definition: LLToken.h:401
@ ChecksumKind
Definition: LLToken.h:489
@ DwarfMacinfo
Definition: LLToken.h:488
@ kw_volatile
Definition: LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition: LLToken.h:408
@ kw_function
Definition: LLToken.h:379
@ kw_default
Definition: LLToken.h:64
@ kw_no_sanitize_address
Definition: LLToken.h:456
@ kw_inaccessiblemem_or_argmemonly
Definition: LLToken.h:207
@ kw_uinc_wrap
Definition: LLToken.h:269
@ kw_externally_initialized
Definition: LLToken.h:69
@ kw_sanitize_address_dyninit
Definition: LLToken.h:462
@ kw_atomicrmw
Definition: LLToken.h:338
@ kw_hidden
Definition: LLToken.h:65
@ EmissionKind
Definition: LLToken.h:483
@ kw_amdgpu_cs_chain_preserve
Definition: LLToken.h:180
@ kw_readwrite
Definition: LLToken.h:200
@ kw_within
Definition: LLToken.h:83
@ kw_section
Definition: LLToken.h:119
@ kw_triple
Definition: LLToken.h:89
@ kw_thread_local
Definition: LLToken.h:72
@ kw_catchswitch
Definition: LLToken.h:327
@ kw_extern_weak
Definition: LLToken.h:70
@ kw_arm_aapcscc
Definition: LLToken.h:145
@ kw_memProf
Definition: LLToken.h:451
@ kw_alignLog2
Definition: LLToken.h:425
@ kw_cleanuppad
Definition: LLToken.h:330
@ kw_available_externally
Definition: LLToken.h:63
@ kw_singleImplName
Definition: LLToken.h:435
@ kw_typeTests
Definition: LLToken.h:406
@ kw_versions
Definition: LLToken.h:450
@ kw_notcold
Definition: LLToken.h:452
@ kw_mayThrow
Definition: LLToken.h:389
@ kw_swifttailcc
Definition: LLToken.h:163
@ kw_monotonic
Definition: LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition: LLToken.h:407
@ kw_amdgpu_ls
Definition: LLToken.h:173
@ kw_caller
Definition: LLToken.h:82
@ kw_vscale
Definition: LLToken.h:41
@ kw_target
Definition: LLToken.h:88
@ kw_attributes
Definition: LLToken.h:189
@ kw_code_model
Definition: LLToken.h:121
@ kw_cmpxchg
Definition: LLToken.h:337
@ kw_funcFlags
Definition: LLToken.h:381
@ kw_localdynamic
Definition: LLToken.h:73
@ kw_uniformRetVal
Definition: LLToken.h:438
@ kw_sideeffect
Definition: LLToken.h:126
@ kw_amdgpu_ps
Definition: LLToken.h:177
@ kw_sizeM1BitWidth
Definition: LLToken.h:424
@ kw_catchret
Definition: LLToken.h:328
@ kw_nodeduplicate
Definition: LLToken.h:236
@ kw_avr_signalcc
Definition: LLToken.h:154
@ kw_exactmatch
Definition: LLToken.h:234
@ kw_aliasee
Definition: LLToken.h:403
@ kw_common
Definition: LLToken.h:62
@ kw_unreachable
Definition: LLToken.h:325
@ kw_intel_ocl_bicc
Definition: LLToken.h:137
@ kw_global
Definition: LLToken.h:47
@ kw_dso_local
Definition: LLToken.h:50
@ kw_undef
Definition: LLToken.h:77
@ kw_addrspace
Definition: LLToken.h:118
@ kw_release
Definition: LLToken.h:98
@ kw_returnDoesNotAlias
Definition: LLToken.h:385
@ kw_aarch64_sme_preservemost_from_x0
Definition: LLToken.h:149
@ kw_preserve_allcc
Definition: LLToken.h:165
@ kw_importType
Definition: LLToken.h:376
@ dotdotdot
Definition: LLToken.h:24
@ kw_cleanupret
Definition: LLToken.h:326
@ kw_shufflevector
Definition: LLToken.h:343
@ kw_riscv_vector_cc
Definition: LLToken.h:186
@ kw_avr_intrcc
Definition: LLToken.h:153
@ kw_definition
Definition: LLToken.h:377
@ kw_prologue
Definition: LLToken.h:130
@ kw_virtualConstProp
Definition: LLToken.h:440
@ kw_vcall_visibility
Definition: LLToken.h:429
@ kw_poison
Definition: LLToken.h:78
@ kw_appending
Definition: LLToken.h:59
@ kw_inaccessiblemem
Definition: LLToken.h:202
@ kw_preserve_mostcc
Definition: LLToken.h:164
@ kw_arm_aapcs_vfpcc
Definition: LLToken.h:146
@ kw_typeTestRes
Definition: LLToken.h:417
@ kw_unknown
Definition: LLToken.h:397
@ kw_x86_regcallcc
Definition: LLToken.h:143
@ kw_typeIdInfo
Definition: LLToken.h:405
@ kw_amdgpu_cs_chain
Definition: LLToken.h:179
@ kw_dso_local_equivalent
Definition: LLToken.h:348
@ kw_x86_64_sysvcc
Definition: LLToken.h:159
@ DbgRecordType
Definition: LLToken.h:490
@ kw_summary
Definition: LLToken.h:416
@ kw_virtFunc
Definition: LLToken.h:402
@ kw_musttail
Definition: LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition: LLToken.h:151
@ kw_byteArray
Definition: LLToken.h:420
@ kw_uniqueRetVal
Definition: LLToken.h:439
@ kw_insertvalue
Definition: LLToken.h:346
@ kw_indirectbr
Definition: LLToken.h:322
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
void UpgradeSectionAttributes(Module &M)
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:1680
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
@ Done
Definition: Threading.h:61
AllocFnKind
Definition: Attributes.h:49
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
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:656
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:280
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
UWTableKind
Definition: CodeGen.h:120
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:275
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition: ModRef.h:268
bool isPointerTy(const Type *T)
Definition: SPIRVUtils.h:120
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
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:1914
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
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:1849
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:271
static constexpr roundingMode rmNearestTiesToEven
Definition: APFloat.h:246
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:272
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:269
static const fltSemantics & BFloat() LLVM_READNONE
Definition: APFloat.cpp:270
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Class to accumulate and hold information about a callee.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
A specification for a virtual function call with all constant integer arguments.
Flags specific to function summaries.
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
All type identifier related information.
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....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
A utility class that uses RAII to save and restore the value of a variable.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition: SlotMapping.h:33
std::map< unsigned, Type * > Types
Definition: SlotMapping.h:37
StringMap< Type * > NamedTypes
Definition: SlotMapping.h:36
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition: SlotMapping.h:35
NumberedValues< GlobalValue * > GlobalValues
Definition: SlotMapping.h:34
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:53
unsigned UIntVal
Definition: LLParser.h:75
@ t_Constant
Definition: LLParser.h:67
@ t_PackedConstantStruct
Definition: LLParser.h:71
@ t_GlobalID
Definition: LLParser.h:56
@ t_EmptyArray
Definition: LLParser.h:66
@ t_GlobalName
Definition: LLParser.h:58
@ t_ConstantStruct
Definition: LLParser.h:70
@ t_LocalName
Definition: LLParser.h:57
@ t_ConstantSplat
Definition: LLParser.h:68
@ t_InlineAsm
Definition: LLParser.h:69
FunctionType * FTy
Definition: LLParser.h:76
LLLexer::LocTy Loc
Definition: LLParser.h:74
enum llvm::ValID::@38 Kind
std::string StrVal
Definition: LLParser.h:77
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
Utility type to build an inheritance chain that makes it easy to rank overload candidates.
Definition: STLExtras.h:1479