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