LLVM 19.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
28#include "llvm/IR/Constants.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalIFunc.h"
34#include "llvm/IR/InlineAsm.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/Metadata.h"
41#include "llvm/IR/Module.h"
42#include "llvm/IR/Operator.h"
43#include "llvm/IR/Value.h"
48#include "llvm/Support/ModRef.h"
51#include <algorithm>
52#include <cassert>
53#include <cstring>
54#include <optional>
55#include <vector>
56
57using namespace llvm;
58
60 "allow-incomplete-ir", cl::init(false), cl::Hidden,
62 "Allow incomplete IR on a best effort basis (references to unknown "
63 "metadata will be dropped)"));
64
69
70static std::string getTypeString(Type *T) {
71 std::string Result;
72 raw_string_ostream Tmp(Result);
73 Tmp << *T;
74 return Tmp.str();
75}
76
77// Whatever debug info format we parsed, we should convert to the expected debug
78// info format immediately afterwards.
79bool LLParser::finalizeDebugInfoFormat(Module *M) {
80 // We should have already returned an error if we observed both intrinsics and
81 // records in this IR.
82 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
83 "Mixed debug intrinsics/records seen without a parsing error?");
85 UseNewDbgInfoFormat = SeenNewDbgInfoFormat;
86 WriteNewDbgInfoFormatToBitcode = SeenNewDbgInfoFormat;
87 WriteNewDbgInfoFormat = SeenNewDbgInfoFormat;
88 } else if (M) {
89 M->setIsNewDbgInfoFormat(false);
90 }
91 return false;
92}
93
94/// Run: module ::= toplevelentity*
96 DataLayoutCallbackTy DataLayoutCallback) {
97 // Prime the lexer.
98 Lex.Lex();
99
100 if (Context.shouldDiscardValueNames())
101 return error(
102 Lex.getLoc(),
103 "Can't read textual IR with a Context that discards named Values");
104
105 if (M) {
106 if (parseTargetDefinitions(DataLayoutCallback))
107 return true;
108 }
109
110 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
111 validateEndOfIndex() || finalizeDebugInfoFormat(M);
112}
113
115 const SlotMapping *Slots) {
116 restoreParsingState(Slots);
117 Lex.Lex();
118
119 Type *Ty = nullptr;
120 if (parseType(Ty) || parseConstantValue(Ty, C))
121 return true;
122 if (Lex.getKind() != lltok::Eof)
123 return error(Lex.getLoc(), "expected end of string");
124 return false;
125}
126
127bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
128 const SlotMapping *Slots) {
129 restoreParsingState(Slots);
130 Lex.Lex();
131
132 Read = 0;
133 SMLoc Start = Lex.getLoc();
134 Ty = nullptr;
135 if (parseType(Ty))
136 return true;
137 SMLoc End = Lex.getLoc();
138 Read = End.getPointer() - Start.getPointer();
139
140 return false;
141}
142
143void LLParser::restoreParsingState(const SlotMapping *Slots) {
144 if (!Slots)
145 return;
146 NumberedVals = Slots->GlobalValues;
147 NumberedMetadata = Slots->MetadataNodes;
148 for (const auto &I : Slots->NamedTypes)
149 NamedTypes.insert(
150 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
151 for (const auto &I : Slots->Types)
152 NumberedTypes.insert(
153 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
154}
155
157 // White-list intrinsics that are safe to drop.
158 if (!isa<DbgInfoIntrinsic>(II) &&
159 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
160 return;
161
163 for (Value *V : II->args())
164 if (auto *MV = dyn_cast<MetadataAsValue>(V))
165 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
166 if (MD->isTemporary())
167 MVs.push_back(MV);
168
169 if (!MVs.empty()) {
170 assert(II->use_empty() && "Cannot have uses");
171 II->eraseFromParent();
172
173 // Also remove no longer used MetadataAsValue wrappers.
174 for (MetadataAsValue *MV : MVs)
175 if (MV->use_empty())
176 delete MV;
177 }
178}
179
180void LLParser::dropUnknownMetadataReferences() {
181 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
182 for (Function &F : *M) {
183 F.eraseMetadataIf(Pred);
185 I.eraseMetadataIf(Pred);
186
187 if (auto *II = dyn_cast<IntrinsicInst>(&I))
189 }
190 }
191
192 for (GlobalVariable &GV : M->globals())
193 GV.eraseMetadataIf(Pred);
194
195 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
196 // Check whether there is only a single use left, which would be in our
197 // own NumberedMetadata.
198 if (Info.first->getNumTemporaryUses() == 1) {
199 NumberedMetadata.erase(ID);
200 ForwardRefMDNodes.erase(ID);
201 }
202 }
203}
204
205/// validateEndOfModule - Do final validity and basic correctness checks at the
206/// end of the module.
207bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
208 if (!M)
209 return false;
210 // Handle any function attribute group forward references.
211 for (const auto &RAG : ForwardRefAttrGroups) {
212 Value *V = RAG.first;
213 const std::vector<unsigned> &Attrs = RAG.second;
214 AttrBuilder B(Context);
215
216 for (const auto &Attr : Attrs) {
217 auto R = NumberedAttrBuilders.find(Attr);
218 if (R != NumberedAttrBuilders.end())
219 B.merge(R->second);
220 }
221
222 if (Function *Fn = dyn_cast<Function>(V)) {
223 AttributeList AS = Fn->getAttributes();
224 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
225 AS = AS.removeFnAttributes(Context);
226
227 FnAttrs.merge(B);
228
229 // If the alignment was parsed as an attribute, move to the alignment
230 // field.
231 if (MaybeAlign A = FnAttrs.getAlignment()) {
232 Fn->setAlignment(*A);
233 FnAttrs.removeAttribute(Attribute::Alignment);
234 }
235
236 AS = AS.addFnAttributes(Context, FnAttrs);
237 Fn->setAttributes(AS);
238 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
239 AttributeList AS = CI->getAttributes();
240 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
241 AS = AS.removeFnAttributes(Context);
242 FnAttrs.merge(B);
243 AS = AS.addFnAttributes(Context, FnAttrs);
244 CI->setAttributes(AS);
245 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
246 AttributeList AS = II->getAttributes();
247 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
248 AS = AS.removeFnAttributes(Context);
249 FnAttrs.merge(B);
250 AS = AS.addFnAttributes(Context, FnAttrs);
251 II->setAttributes(AS);
252 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
253 AttributeList AS = CBI->getAttributes();
254 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
255 AS = AS.removeFnAttributes(Context);
256 FnAttrs.merge(B);
257 AS = AS.addFnAttributes(Context, FnAttrs);
258 CBI->setAttributes(AS);
259 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
260 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
261 Attrs.merge(B);
262 GV->setAttributes(AttributeSet::get(Context,Attrs));
263 } else {
264 llvm_unreachable("invalid object with forward attribute group reference");
265 }
266 }
267
268 // If there are entries in ForwardRefBlockAddresses at this point, the
269 // function was never defined.
270 if (!ForwardRefBlockAddresses.empty())
271 return error(ForwardRefBlockAddresses.begin()->first.Loc,
272 "expected function name in blockaddress");
273
274 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
275 GlobalValue *FwdRef) {
276 GlobalValue *GV = nullptr;
277 if (GVRef.Kind == ValID::t_GlobalName) {
278 GV = M->getNamedValue(GVRef.StrVal);
279 } else {
280 GV = NumberedVals.get(GVRef.UIntVal);
281 }
282
283 if (!GV)
284 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
285 "' referenced by dso_local_equivalent");
286
287 if (!GV->getValueType()->isFunctionTy())
288 return error(GVRef.Loc,
289 "expected a function, alias to function, or ifunc "
290 "in dso_local_equivalent");
291
292 auto *Equiv = DSOLocalEquivalent::get(GV);
293 FwdRef->replaceAllUsesWith(Equiv);
294 FwdRef->eraseFromParent();
295 return false;
296 };
297
298 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
299 // point, they are references after the function was defined. Resolve those
300 // now.
301 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
302 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
303 return true;
304 }
305 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
306 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
307 return true;
308 }
309 ForwardRefDSOLocalEquivalentIDs.clear();
310 ForwardRefDSOLocalEquivalentNames.clear();
311
312 for (const auto &NT : NumberedTypes)
313 if (NT.second.second.isValid())
314 return error(NT.second.second,
315 "use of undefined type '%" + Twine(NT.first) + "'");
316
317 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
318 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
319 if (I->second.second.isValid())
320 return error(I->second.second,
321 "use of undefined type named '" + I->getKey() + "'");
322
323 if (!ForwardRefComdats.empty())
324 return error(ForwardRefComdats.begin()->second,
325 "use of undefined comdat '$" +
326 ForwardRefComdats.begin()->first + "'");
327
328 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
329 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
330 FunctionType *FTy = nullptr;
331 for (Use &U : V->uses()) {
332 auto *CB = dyn_cast<CallBase>(U.getUser());
333 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
334 return nullptr;
335 FTy = CB->getFunctionType();
336 }
337 return FTy;
338 };
339
340 auto GetDeclarationType = [&](StringRef Name, Value *V) -> Type * {
341 // Automatically create declarations for intrinsics. Intrinsics can only
342 // be called directly, so the call function type directly determines the
343 // declaration function type.
344 if (Name.starts_with("llvm."))
345 // Don't do anything if the intrinsic is called with different function
346 // types. This would result in a verifier error anyway.
347 return GetCommonFunctionType(V);
348
349 if (AllowIncompleteIR) {
350 // If incomplete IR is allowed, also add declarations for
351 // non-intrinsics. First check whether this global is only used in
352 // calls with the same type, in which case we'll insert a function.
353 if (auto *Ty = GetCommonFunctionType(V))
354 return Ty;
355
356 // Otherwise, fall back to using a dummy i8 type.
357 return Type::getInt8Ty(Context);
358 }
359 return nullptr;
360 };
361
362 if (Type *Ty = GetDeclarationType(Name, Info.first)) {
363 GlobalValue *GV;
364 if (auto *FTy = dyn_cast<FunctionType>(Ty))
366 else
367 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
369 /*Initializer*/ nullptr, Name);
370 Info.first->replaceAllUsesWith(GV);
371 Info.first->eraseFromParent();
372 ForwardRefVals.erase(Name);
373 }
374 }
375
376 if (!ForwardRefVals.empty())
377 return error(ForwardRefVals.begin()->second.second,
378 "use of undefined value '@" + ForwardRefVals.begin()->first +
379 "'");
380
381 if (!ForwardRefValIDs.empty())
382 return error(ForwardRefValIDs.begin()->second.second,
383 "use of undefined value '@" +
384 Twine(ForwardRefValIDs.begin()->first) + "'");
385
386 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
387 dropUnknownMetadataReferences();
388
389 if (!ForwardRefMDNodes.empty())
390 return error(ForwardRefMDNodes.begin()->second.second,
391 "use of undefined metadata '!" +
392 Twine(ForwardRefMDNodes.begin()->first) + "'");
393
394 // Resolve metadata cycles.
395 for (auto &N : NumberedMetadata) {
396 if (N.second && !N.second->isResolved())
397 N.second->resolveCycles();
398 }
399
400 for (auto *Inst : InstsWithTBAATag) {
401 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
402 // With incomplete IR, the tbaa metadata may have been dropped.
404 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
405 if (MD) {
406 auto *UpgradedMD = UpgradeTBAANode(*MD);
407 if (MD != UpgradedMD)
408 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
409 }
410 }
411
412 // Look for intrinsic functions and CallInst that need to be upgraded. We use
413 // make_early_inc_range here because we may remove some functions.
416
417 if (UpgradeDebugInfo)
419
422
423 if (!Slots)
424 return false;
425 // Initialize the slot mapping.
426 // Because by this point we've parsed and validated everything, we can "steal"
427 // the mapping from LLParser as it doesn't need it anymore.
428 Slots->GlobalValues = std::move(NumberedVals);
429 Slots->MetadataNodes = std::move(NumberedMetadata);
430 for (const auto &I : NamedTypes)
431 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
432 for (const auto &I : NumberedTypes)
433 Slots->Types.insert(std::make_pair(I.first, I.second.first));
434
435 return false;
436}
437
438/// Do final validity and basic correctness checks at the end of the index.
439bool LLParser::validateEndOfIndex() {
440 if (!Index)
441 return false;
442
443 if (!ForwardRefValueInfos.empty())
444 return error(ForwardRefValueInfos.begin()->second.front().second,
445 "use of undefined summary '^" +
446 Twine(ForwardRefValueInfos.begin()->first) + "'");
447
448 if (!ForwardRefAliasees.empty())
449 return error(ForwardRefAliasees.begin()->second.front().second,
450 "use of undefined summary '^" +
451 Twine(ForwardRefAliasees.begin()->first) + "'");
452
453 if (!ForwardRefTypeIds.empty())
454 return error(ForwardRefTypeIds.begin()->second.front().second,
455 "use of undefined type id summary '^" +
456 Twine(ForwardRefTypeIds.begin()->first) + "'");
457
458 return false;
459}
460
461//===----------------------------------------------------------------------===//
462// Top-Level Entities
463//===----------------------------------------------------------------------===//
464
465bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
466 // Delay parsing of the data layout string until the target triple is known.
467 // Then, pass both the the target triple and the tentative data layout string
468 // to DataLayoutCallback, allowing to override the DL string.
469 // This enables importing modules with invalid DL strings.
470 std::string TentativeDLStr = M->getDataLayoutStr();
471 LocTy DLStrLoc;
472
473 bool Done = false;
474 while (!Done) {
475 switch (Lex.getKind()) {
476 case lltok::kw_target:
477 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
478 return true;
479 break;
481 if (parseSourceFileName())
482 return true;
483 break;
484 default:
485 Done = true;
486 }
487 }
488 // Run the override callback to potentially change the data layout string, and
489 // parse the data layout string.
490 if (auto LayoutOverride =
491 DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
492 TentativeDLStr = *LayoutOverride;
493 DLStrLoc = {};
494 }
495 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
496 if (!MaybeDL)
497 return error(DLStrLoc, toString(MaybeDL.takeError()));
498 M->setDataLayout(MaybeDL.get());
499 return false;
500}
501
502bool LLParser::parseTopLevelEntities() {
503 // If there is no Module, then parse just the summary index entries.
504 if (!M) {
505 while (true) {
506 switch (Lex.getKind()) {
507 case lltok::Eof:
508 return false;
509 case lltok::SummaryID:
510 if (parseSummaryEntry())
511 return true;
512 break;
514 if (parseSourceFileName())
515 return true;
516 break;
517 default:
518 // Skip everything else
519 Lex.Lex();
520 }
521 }
522 }
523 while (true) {
524 switch (Lex.getKind()) {
525 default:
526 return tokError("expected top-level entity");
527 case lltok::Eof: return false;
529 if (parseDeclare())
530 return true;
531 break;
532 case lltok::kw_define:
533 if (parseDefine())
534 return true;
535 break;
536 case lltok::kw_module:
537 if (parseModuleAsm())
538 return true;
539 break;
541 if (parseUnnamedType())
542 return true;
543 break;
544 case lltok::LocalVar:
545 if (parseNamedType())
546 return true;
547 break;
548 case lltok::GlobalID:
549 if (parseUnnamedGlobal())
550 return true;
551 break;
552 case lltok::GlobalVar:
553 if (parseNamedGlobal())
554 return true;
555 break;
556 case lltok::ComdatVar: if (parseComdat()) return true; break;
557 case lltok::exclaim:
558 if (parseStandaloneMetadata())
559 return true;
560 break;
561 case lltok::SummaryID:
562 if (parseSummaryEntry())
563 return true;
564 break;
566 if (parseNamedMetadata())
567 return true;
568 break;
570 if (parseUnnamedAttrGrp())
571 return true;
572 break;
574 if (parseUseListOrder())
575 return true;
576 break;
578 if (parseUseListOrderBB())
579 return true;
580 break;
581 }
582 }
583}
584
585/// toplevelentity
586/// ::= 'module' 'asm' STRINGCONSTANT
587bool LLParser::parseModuleAsm() {
589 Lex.Lex();
590
591 std::string AsmStr;
592 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
593 parseStringConstant(AsmStr))
594 return true;
595
596 M->appendModuleInlineAsm(AsmStr);
597 return false;
598}
599
600/// toplevelentity
601/// ::= 'target' 'triple' '=' STRINGCONSTANT
602/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
603bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
604 LocTy &DLStrLoc) {
606 std::string Str;
607 switch (Lex.Lex()) {
608 default:
609 return tokError("unknown target property");
610 case lltok::kw_triple:
611 Lex.Lex();
612 if (parseToken(lltok::equal, "expected '=' after target triple") ||
613 parseStringConstant(Str))
614 return true;
615 M->setTargetTriple(Str);
616 return false;
618 Lex.Lex();
619 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
620 return true;
621 DLStrLoc = Lex.getLoc();
622 if (parseStringConstant(TentativeDLStr))
623 return true;
624 return false;
625 }
626}
627
628/// toplevelentity
629/// ::= 'source_filename' '=' STRINGCONSTANT
630bool LLParser::parseSourceFileName() {
632 Lex.Lex();
633 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
634 parseStringConstant(SourceFileName))
635 return true;
636 if (M)
637 M->setSourceFileName(SourceFileName);
638 return false;
639}
640
641/// parseUnnamedType:
642/// ::= LocalVarID '=' 'type' type
643bool LLParser::parseUnnamedType() {
644 LocTy TypeLoc = Lex.getLoc();
645 unsigned TypeID = Lex.getUIntVal();
646 Lex.Lex(); // eat LocalVarID;
647
648 if (parseToken(lltok::equal, "expected '=' after name") ||
649 parseToken(lltok::kw_type, "expected 'type' after '='"))
650 return true;
651
652 Type *Result = nullptr;
653 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
654 return true;
655
656 if (!isa<StructType>(Result)) {
657 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
658 if (Entry.first)
659 return error(TypeLoc, "non-struct types may not be recursive");
660 Entry.first = Result;
661 Entry.second = SMLoc();
662 }
663
664 return false;
665}
666
667/// toplevelentity
668/// ::= LocalVar '=' 'type' type
669bool LLParser::parseNamedType() {
670 std::string Name = Lex.getStrVal();
671 LocTy NameLoc = Lex.getLoc();
672 Lex.Lex(); // eat LocalVar.
673
674 if (parseToken(lltok::equal, "expected '=' after name") ||
675 parseToken(lltok::kw_type, "expected 'type' after name"))
676 return true;
677
678 Type *Result = nullptr;
679 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
680 return true;
681
682 if (!isa<StructType>(Result)) {
683 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
684 if (Entry.first)
685 return error(NameLoc, "non-struct types may not be recursive");
686 Entry.first = Result;
687 Entry.second = SMLoc();
688 }
689
690 return false;
691}
692
693/// toplevelentity
694/// ::= 'declare' FunctionHeader
695bool LLParser::parseDeclare() {
697 Lex.Lex();
698
699 std::vector<std::pair<unsigned, MDNode *>> MDs;
700 while (Lex.getKind() == lltok::MetadataVar) {
701 unsigned MDK;
702 MDNode *N;
703 if (parseMetadataAttachment(MDK, N))
704 return true;
705 MDs.push_back({MDK, N});
706 }
707
708 Function *F;
709 unsigned FunctionNumber = -1;
710 SmallVector<unsigned> UnnamedArgNums;
711 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
712 return true;
713 for (auto &MD : MDs)
714 F->addMetadata(MD.first, *MD.second);
715 return false;
716}
717
718/// toplevelentity
719/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
720bool LLParser::parseDefine() {
722 Lex.Lex();
723
724 Function *F;
725 unsigned FunctionNumber = -1;
726 SmallVector<unsigned> UnnamedArgNums;
727 return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
728 parseOptionalFunctionMetadata(*F) ||
729 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
730}
731
732/// parseGlobalType
733/// ::= 'constant'
734/// ::= 'global'
735bool LLParser::parseGlobalType(bool &IsConstant) {
736 if (Lex.getKind() == lltok::kw_constant)
737 IsConstant = true;
738 else if (Lex.getKind() == lltok::kw_global)
739 IsConstant = false;
740 else {
741 IsConstant = false;
742 return tokError("expected 'global' or 'constant'");
743 }
744 Lex.Lex();
745 return false;
746}
747
748bool LLParser::parseOptionalUnnamedAddr(
749 GlobalVariable::UnnamedAddr &UnnamedAddr) {
750 if (EatIfPresent(lltok::kw_unnamed_addr))
752 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
754 else
755 UnnamedAddr = GlobalValue::UnnamedAddr::None;
756 return false;
757}
758
759/// parseUnnamedGlobal:
760/// OptionalVisibility (ALIAS | IFUNC) ...
761/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
762/// OptionalDLLStorageClass
763/// ... -> global variable
764/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
765/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
766/// OptionalVisibility
767/// OptionalDLLStorageClass
768/// ... -> global variable
769bool LLParser::parseUnnamedGlobal() {
770 unsigned VarID;
771 std::string Name;
772 LocTy NameLoc = Lex.getLoc();
773
774 // Handle the GlobalID form.
775 if (Lex.getKind() == lltok::GlobalID) {
776 VarID = Lex.getUIntVal();
777 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
778 return true;
779
780 Lex.Lex(); // eat GlobalID;
781 if (parseToken(lltok::equal, "expected '=' after name"))
782 return true;
783 } else {
784 VarID = NumberedVals.getNext();
785 }
786
787 bool HasLinkage;
788 unsigned Linkage, Visibility, DLLStorageClass;
789 bool DSOLocal;
791 GlobalVariable::UnnamedAddr UnnamedAddr;
792 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
793 DSOLocal) ||
794 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
795 return true;
796
797 switch (Lex.getKind()) {
798 default:
799 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
800 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
801 case lltok::kw_alias:
802 case lltok::kw_ifunc:
803 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
804 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
805 }
806}
807
808/// parseNamedGlobal:
809/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
810/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
811/// OptionalVisibility OptionalDLLStorageClass
812/// ... -> global variable
813bool LLParser::parseNamedGlobal() {
815 LocTy NameLoc = Lex.getLoc();
816 std::string Name = Lex.getStrVal();
817 Lex.Lex();
818
819 bool HasLinkage;
820 unsigned Linkage, Visibility, DLLStorageClass;
821 bool DSOLocal;
823 GlobalVariable::UnnamedAddr UnnamedAddr;
824 if (parseToken(lltok::equal, "expected '=' in global variable") ||
825 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, -1, NameLoc, Linkage, HasLinkage, Visibility,
833 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
834 case lltok::kw_alias:
835 case lltok::kw_ifunc:
836 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
837 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
838 }
839}
840
841bool LLParser::parseComdat() {
843 std::string Name = Lex.getStrVal();
844 LocTy NameLoc = Lex.getLoc();
845 Lex.Lex();
846
847 if (parseToken(lltok::equal, "expected '=' here"))
848 return true;
849
850 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
851 return tokError("expected comdat type");
852
854 switch (Lex.getKind()) {
855 default:
856 return tokError("unknown selection kind");
857 case lltok::kw_any:
858 SK = Comdat::Any;
859 break;
862 break;
864 SK = Comdat::Largest;
865 break;
868 break;
870 SK = Comdat::SameSize;
871 break;
872 }
873 Lex.Lex();
874
875 // See if the comdat was forward referenced, if so, use the comdat.
876 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
878 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
879 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
880
881 Comdat *C;
882 if (I != ComdatSymTab.end())
883 C = &I->second;
884 else
885 C = M->getOrInsertComdat(Name);
886 C->setSelectionKind(SK);
887
888 return false;
889}
890
891// MDString:
892// ::= '!' STRINGCONSTANT
893bool LLParser::parseMDString(MDString *&Result) {
894 std::string Str;
895 if (parseStringConstant(Str))
896 return true;
897 Result = MDString::get(Context, Str);
898 return false;
899}
900
901// MDNode:
902// ::= '!' MDNodeNumber
903bool LLParser::parseMDNodeID(MDNode *&Result) {
904 // !{ ..., !42, ... }
905 LocTy IDLoc = Lex.getLoc();
906 unsigned MID = 0;
907 if (parseUInt32(MID))
908 return true;
909
910 // If not a forward reference, just return it now.
911 if (NumberedMetadata.count(MID)) {
912 Result = NumberedMetadata[MID];
913 return false;
914 }
915
916 // Otherwise, create MDNode forward reference.
917 auto &FwdRef = ForwardRefMDNodes[MID];
918 FwdRef = std::make_pair(MDTuple::getTemporary(Context, std::nullopt), IDLoc);
919
920 Result = FwdRef.first.get();
921 NumberedMetadata[MID].reset(Result);
922 return false;
923}
924
925/// parseNamedMetadata:
926/// !foo = !{ !1, !2 }
927bool LLParser::parseNamedMetadata() {
929 std::string Name = Lex.getStrVal();
930 Lex.Lex();
931
932 if (parseToken(lltok::equal, "expected '=' here") ||
933 parseToken(lltok::exclaim, "Expected '!' here") ||
934 parseToken(lltok::lbrace, "Expected '{' here"))
935 return true;
936
937 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
938 if (Lex.getKind() != lltok::rbrace)
939 do {
940 MDNode *N = nullptr;
941 // parse DIExpressions inline as a special case. They are still MDNodes,
942 // so they can still appear in named metadata. Remove this logic if they
943 // become plain Metadata.
944 if (Lex.getKind() == lltok::MetadataVar &&
945 Lex.getStrVal() == "DIExpression") {
946 if (parseDIExpression(N, /*IsDistinct=*/false))
947 return true;
948 // DIArgLists should only appear inline in a function, as they may
949 // contain LocalAsMetadata arguments which require a function context.
950 } else if (Lex.getKind() == lltok::MetadataVar &&
951 Lex.getStrVal() == "DIArgList") {
952 return tokError("found DIArgList outside of function");
953 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
954 parseMDNodeID(N)) {
955 return true;
956 }
957 NMD->addOperand(N);
958 } while (EatIfPresent(lltok::comma));
959
960 return parseToken(lltok::rbrace, "expected end of metadata node");
961}
962
963/// parseStandaloneMetadata:
964/// !42 = !{...}
965bool LLParser::parseStandaloneMetadata() {
966 assert(Lex.getKind() == lltok::exclaim);
967 Lex.Lex();
968 unsigned MetadataID = 0;
969
970 MDNode *Init;
971 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
972 return true;
973
974 // Detect common error, from old metadata syntax.
975 if (Lex.getKind() == lltok::Type)
976 return tokError("unexpected type in metadata definition");
977
978 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
979 if (Lex.getKind() == lltok::MetadataVar) {
980 if (parseSpecializedMDNode(Init, IsDistinct))
981 return true;
982 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
983 parseMDTuple(Init, IsDistinct))
984 return true;
985
986 // See if this was forward referenced, if so, handle it.
987 auto FI = ForwardRefMDNodes.find(MetadataID);
988 if (FI != ForwardRefMDNodes.end()) {
989 auto *ToReplace = FI->second.first.get();
990 // DIAssignID has its own special forward-reference "replacement" for
991 // attachments (the temporary attachments are never actually attached).
992 if (isa<DIAssignID>(Init)) {
993 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
994 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
995 "Inst unexpectedly already has DIAssignID attachment");
996 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
997 }
998 }
999
1000 ToReplace->replaceAllUsesWith(Init);
1001 ForwardRefMDNodes.erase(FI);
1002
1003 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1004 } else {
1005 if (NumberedMetadata.count(MetadataID))
1006 return tokError("Metadata id is already used");
1007 NumberedMetadata[MetadataID].reset(Init);
1008 }
1009
1010 return false;
1011}
1012
1013// Skips a single module summary entry.
1014bool LLParser::skipModuleSummaryEntry() {
1015 // Each module summary entry consists of a tag for the entry
1016 // type, followed by a colon, then the fields which may be surrounded by
1017 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1018 // support is in place we will look for the tokens corresponding to the
1019 // expected tags.
1020 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1021 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1023 return tokError(
1024 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1025 "start of summary entry");
1026 if (Lex.getKind() == lltok::kw_flags)
1027 return parseSummaryIndexFlags();
1028 if (Lex.getKind() == lltok::kw_blockcount)
1029 return parseBlockCount();
1030 Lex.Lex();
1031 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1032 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1033 return true;
1034 // Now walk through the parenthesized entry, until the number of open
1035 // parentheses goes back down to 0 (the first '(' was parsed above).
1036 unsigned NumOpenParen = 1;
1037 do {
1038 switch (Lex.getKind()) {
1039 case lltok::lparen:
1040 NumOpenParen++;
1041 break;
1042 case lltok::rparen:
1043 NumOpenParen--;
1044 break;
1045 case lltok::Eof:
1046 return tokError("found end of file while parsing summary entry");
1047 default:
1048 // Skip everything in between parentheses.
1049 break;
1050 }
1051 Lex.Lex();
1052 } while (NumOpenParen > 0);
1053 return false;
1054}
1055
1056/// SummaryEntry
1057/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1058bool LLParser::parseSummaryEntry() {
1060 unsigned SummaryID = Lex.getUIntVal();
1061
1062 // For summary entries, colons should be treated as distinct tokens,
1063 // not an indication of the end of a label token.
1065
1066 Lex.Lex();
1067 if (parseToken(lltok::equal, "expected '=' here"))
1068 return true;
1069
1070 // If we don't have an index object, skip the summary entry.
1071 if (!Index)
1072 return skipModuleSummaryEntry();
1073
1074 bool result = false;
1075 switch (Lex.getKind()) {
1076 case lltok::kw_gv:
1077 result = parseGVEntry(SummaryID);
1078 break;
1079 case lltok::kw_module:
1080 result = parseModuleEntry(SummaryID);
1081 break;
1082 case lltok::kw_typeid:
1083 result = parseTypeIdEntry(SummaryID);
1084 break;
1086 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1087 break;
1088 case lltok::kw_flags:
1089 result = parseSummaryIndexFlags();
1090 break;
1092 result = parseBlockCount();
1093 break;
1094 default:
1095 result = error(Lex.getLoc(), "unexpected summary kind");
1096 break;
1097 }
1098 Lex.setIgnoreColonInIdentifiers(false);
1099 return result;
1100}
1101
1102static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
1105}
1106static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
1109}
1110
1111// If there was an explicit dso_local, update GV. In the absence of an explicit
1112// dso_local we keep the default value.
1113static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1114 if (DSOLocal)
1115 GV.setDSOLocal(true);
1116}
1117
1118/// parseAliasOrIFunc:
1119/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1120/// OptionalVisibility OptionalDLLStorageClass
1121/// OptionalThreadLocal OptionalUnnamedAddr
1122/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1123///
1124/// AliaseeOrResolver
1125/// ::= TypeAndValue
1126///
1127/// SymbolAttrs
1128/// ::= ',' 'partition' StringConstant
1129///
1130/// Everything through OptionalUnnamedAddr has already been parsed.
1131///
1132bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1133 LocTy NameLoc, unsigned L, unsigned Visibility,
1134 unsigned DLLStorageClass, bool DSOLocal,
1136 GlobalVariable::UnnamedAddr UnnamedAddr) {
1137 bool IsAlias;
1138 if (Lex.getKind() == lltok::kw_alias)
1139 IsAlias = true;
1140 else if (Lex.getKind() == lltok::kw_ifunc)
1141 IsAlias = false;
1142 else
1143 llvm_unreachable("Not an alias or ifunc!");
1144 Lex.Lex();
1145
1147
1148 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1149 return error(NameLoc, "invalid linkage type for alias");
1150
1151 if (!isValidVisibilityForLinkage(Visibility, L))
1152 return error(NameLoc,
1153 "symbol with local linkage must have default visibility");
1154
1155 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1156 return error(NameLoc,
1157 "symbol with local linkage cannot have a DLL storage class");
1158
1159 Type *Ty;
1160 LocTy ExplicitTypeLoc = Lex.getLoc();
1161 if (parseType(Ty) ||
1162 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1163 return true;
1164
1165 Constant *Aliasee;
1166 LocTy AliaseeLoc = Lex.getLoc();
1167 if (Lex.getKind() != lltok::kw_bitcast &&
1170 Lex.getKind() != lltok::kw_inttoptr) {
1171 if (parseGlobalTypeAndValue(Aliasee))
1172 return true;
1173 } else {
1174 // The bitcast dest type is not present, it is implied by the dest type.
1175 ValID ID;
1176 if (parseValID(ID, /*PFS=*/nullptr))
1177 return true;
1178 if (ID.Kind != ValID::t_Constant)
1179 return error(AliaseeLoc, "invalid aliasee");
1180 Aliasee = ID.ConstantVal;
1181 }
1182
1183 Type *AliaseeType = Aliasee->getType();
1184 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1185 if (!PTy)
1186 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1187 unsigned AddrSpace = PTy->getAddressSpace();
1188
1189 GlobalValue *GVal = nullptr;
1190
1191 // See if the alias was forward referenced, if so, prepare to replace the
1192 // forward reference.
1193 if (!Name.empty()) {
1194 auto I = ForwardRefVals.find(Name);
1195 if (I != ForwardRefVals.end()) {
1196 GVal = I->second.first;
1197 ForwardRefVals.erase(Name);
1198 } else if (M->getNamedValue(Name)) {
1199 return error(NameLoc, "redefinition of global '@" + Name + "'");
1200 }
1201 } else {
1202 auto I = ForwardRefValIDs.find(NameID);
1203 if (I != ForwardRefValIDs.end()) {
1204 GVal = I->second.first;
1205 ForwardRefValIDs.erase(I);
1206 }
1207 }
1208
1209 // Okay, create the alias/ifunc but do not insert it into the module yet.
1210 std::unique_ptr<GlobalAlias> GA;
1211 std::unique_ptr<GlobalIFunc> GI;
1212 GlobalValue *GV;
1213 if (IsAlias) {
1214 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1216 Aliasee, /*Parent*/ nullptr));
1217 GV = GA.get();
1218 } else {
1219 GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1221 Aliasee, /*Parent*/ nullptr));
1222 GV = GI.get();
1223 }
1224 GV->setThreadLocalMode(TLM);
1227 GV->setUnnamedAddr(UnnamedAddr);
1228 maybeSetDSOLocal(DSOLocal, *GV);
1229
1230 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1231 // Now parse them if there are any.
1232 while (Lex.getKind() == lltok::comma) {
1233 Lex.Lex();
1234
1235 if (Lex.getKind() == lltok::kw_partition) {
1236 Lex.Lex();
1237 GV->setPartition(Lex.getStrVal());
1238 if (parseToken(lltok::StringConstant, "expected partition string"))
1239 return true;
1240 } else {
1241 return tokError("unknown alias or ifunc property!");
1242 }
1243 }
1244
1245 if (Name.empty())
1246 NumberedVals.add(NameID, GV);
1247
1248 if (GVal) {
1249 // Verify that types agree.
1250 if (GVal->getType() != GV->getType())
1251 return error(
1252 ExplicitTypeLoc,
1253 "forward reference and definition of alias have different types");
1254
1255 // If they agree, just RAUW the old value with the alias and remove the
1256 // forward ref info.
1257 GVal->replaceAllUsesWith(GV);
1258 GVal->eraseFromParent();
1259 }
1260
1261 // Insert into the module, we know its name won't collide now.
1262 if (IsAlias)
1263 M->insertAlias(GA.release());
1264 else
1265 M->insertIFunc(GI.release());
1266 assert(GV->getName() == Name && "Should not be a name conflict!");
1267
1268 return false;
1269}
1270
1271static bool isSanitizer(lltok::Kind Kind) {
1272 switch (Kind) {
1275 case lltok::kw_sanitize_memtag:
1277 return true;
1278 default:
1279 return false;
1280 }
1281}
1282
1283bool LLParser::parseSanitizer(GlobalVariable *GV) {
1286 if (GV->hasSanitizerMetadata())
1287 Meta = GV->getSanitizerMetadata();
1288
1289 switch (Lex.getKind()) {
1291 Meta.NoAddress = true;
1292 break;
1294 Meta.NoHWAddress = true;
1295 break;
1296 case lltok::kw_sanitize_memtag:
1297 Meta.Memtag = true;
1298 break;
1300 Meta.IsDynInit = true;
1301 break;
1302 default:
1303 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1304 }
1305 GV->setSanitizerMetadata(Meta);
1306 Lex.Lex();
1307 return false;
1308}
1309
1310/// parseGlobal
1311/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1312/// OptionalVisibility OptionalDLLStorageClass
1313/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1314/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1315/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1316/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1317/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1318/// Const OptionalAttrs
1319///
1320/// Everything up to and including OptionalUnnamedAddr has been parsed
1321/// already.
1322///
1323bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1324 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1325 unsigned Visibility, unsigned DLLStorageClass,
1326 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1327 GlobalVariable::UnnamedAddr UnnamedAddr) {
1328 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1329 return error(NameLoc,
1330 "symbol with local linkage must have default visibility");
1331
1332 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1333 return error(NameLoc,
1334 "symbol with local linkage cannot have a DLL storage class");
1335
1336 unsigned AddrSpace;
1337 bool IsConstant, IsExternallyInitialized;
1338 LocTy IsExternallyInitializedLoc;
1339 LocTy TyLoc;
1340
1341 Type *Ty = nullptr;
1342 if (parseOptionalAddrSpace(AddrSpace) ||
1343 parseOptionalToken(lltok::kw_externally_initialized,
1344 IsExternallyInitialized,
1345 &IsExternallyInitializedLoc) ||
1346 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1347 return true;
1348
1349 // If the linkage is specified and is external, then no initializer is
1350 // present.
1351 Constant *Init = nullptr;
1352 if (!HasLinkage ||
1354 (GlobalValue::LinkageTypes)Linkage)) {
1355 if (parseGlobalValue(Ty, Init))
1356 return true;
1357 }
1358
1360 return error(TyLoc, "invalid type for global variable");
1361
1362 GlobalValue *GVal = nullptr;
1363
1364 // See if the global was forward referenced, if so, use the global.
1365 if (!Name.empty()) {
1366 auto I = ForwardRefVals.find(Name);
1367 if (I != ForwardRefVals.end()) {
1368 GVal = I->second.first;
1369 ForwardRefVals.erase(I);
1370 } else if (M->getNamedValue(Name)) {
1371 return error(NameLoc, "redefinition of global '@" + Name + "'");
1372 }
1373 } else {
1374 // Handle @"", where a name is syntactically specified, but semantically
1375 // missing.
1376 if (NameID == (unsigned)-1)
1377 NameID = NumberedVals.getNext();
1378
1379 auto I = ForwardRefValIDs.find(NameID);
1380 if (I != ForwardRefValIDs.end()) {
1381 GVal = I->second.first;
1382 ForwardRefValIDs.erase(I);
1383 }
1384 }
1385
1387 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1389
1390 if (Name.empty())
1391 NumberedVals.add(NameID, GV);
1392
1393 // Set the parsed properties on the global.
1394 if (Init)
1395 GV->setInitializer(Init);
1396 GV->setConstant(IsConstant);
1398 maybeSetDSOLocal(DSOLocal, *GV);
1401 GV->setExternallyInitialized(IsExternallyInitialized);
1402 GV->setThreadLocalMode(TLM);
1403 GV->setUnnamedAddr(UnnamedAddr);
1404
1405 if (GVal) {
1406 if (GVal->getAddressSpace() != AddrSpace)
1407 return error(
1408 TyLoc,
1409 "forward reference and definition of global have different types");
1410
1411 GVal->replaceAllUsesWith(GV);
1412 GVal->eraseFromParent();
1413 }
1414
1415 // parse attributes on the global.
1416 while (Lex.getKind() == lltok::comma) {
1417 Lex.Lex();
1418
1419 if (Lex.getKind() == lltok::kw_section) {
1420 Lex.Lex();
1421 GV->setSection(Lex.getStrVal());
1422 if (parseToken(lltok::StringConstant, "expected global section string"))
1423 return true;
1424 } else if (Lex.getKind() == lltok::kw_partition) {
1425 Lex.Lex();
1426 GV->setPartition(Lex.getStrVal());
1427 if (parseToken(lltok::StringConstant, "expected partition string"))
1428 return true;
1429 } else if (Lex.getKind() == lltok::kw_align) {
1430 MaybeAlign Alignment;
1431 if (parseOptionalAlignment(Alignment))
1432 return true;
1433 if (Alignment)
1434 GV->setAlignment(*Alignment);
1435 } else if (Lex.getKind() == lltok::kw_code_model) {
1437 if (parseOptionalCodeModel(CodeModel))
1438 return true;
1439 GV->setCodeModel(CodeModel);
1440 } else if (Lex.getKind() == lltok::MetadataVar) {
1441 if (parseGlobalObjectMetadataAttachment(*GV))
1442 return true;
1443 } else if (isSanitizer(Lex.getKind())) {
1444 if (parseSanitizer(GV))
1445 return true;
1446 } else {
1447 Comdat *C;
1448 if (parseOptionalComdat(Name, C))
1449 return true;
1450 if (C)
1451 GV->setComdat(C);
1452 else
1453 return tokError("unknown global variable property!");
1454 }
1455 }
1456
1457 AttrBuilder Attrs(M->getContext());
1458 LocTy BuiltinLoc;
1459 std::vector<unsigned> FwdRefAttrGrps;
1460 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1461 return true;
1462 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1463 GV->setAttributes(AttributeSet::get(Context, Attrs));
1464 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1465 }
1466
1467 return false;
1468}
1469
1470/// parseUnnamedAttrGrp
1471/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1472bool LLParser::parseUnnamedAttrGrp() {
1474 LocTy AttrGrpLoc = Lex.getLoc();
1475 Lex.Lex();
1476
1477 if (Lex.getKind() != lltok::AttrGrpID)
1478 return tokError("expected attribute group id");
1479
1480 unsigned VarID = Lex.getUIntVal();
1481 std::vector<unsigned> unused;
1482 LocTy BuiltinLoc;
1483 Lex.Lex();
1484
1485 if (parseToken(lltok::equal, "expected '=' here") ||
1486 parseToken(lltok::lbrace, "expected '{' here"))
1487 return true;
1488
1489 auto R = NumberedAttrBuilders.find(VarID);
1490 if (R == NumberedAttrBuilders.end())
1491 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1492
1493 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1494 parseToken(lltok::rbrace, "expected end of attribute group"))
1495 return true;
1496
1497 if (!R->second.hasAttributes())
1498 return error(AttrGrpLoc, "attribute group has no attributes");
1499
1500 return false;
1501}
1502
1504 switch (Kind) {
1505#define GET_ATTR_NAMES
1506#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1507 case lltok::kw_##DISPLAY_NAME: \
1508 return Attribute::ENUM_NAME;
1509#include "llvm/IR/Attributes.inc"
1510 default:
1511 return Attribute::None;
1512 }
1513}
1514
1515bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1516 bool InAttrGroup) {
1517 if (Attribute::isTypeAttrKind(Attr))
1518 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1519
1520 switch (Attr) {
1521 case Attribute::Alignment: {
1522 MaybeAlign Alignment;
1523 if (InAttrGroup) {
1524 uint32_t Value = 0;
1525 Lex.Lex();
1526 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1527 return true;
1528 Alignment = Align(Value);
1529 } else {
1530 if (parseOptionalAlignment(Alignment, true))
1531 return true;
1532 }
1533 B.addAlignmentAttr(Alignment);
1534 return false;
1535 }
1536 case Attribute::StackAlignment: {
1537 unsigned Alignment;
1538 if (InAttrGroup) {
1539 Lex.Lex();
1540 if (parseToken(lltok::equal, "expected '=' here") ||
1541 parseUInt32(Alignment))
1542 return true;
1543 } else {
1544 if (parseOptionalStackAlignment(Alignment))
1545 return true;
1546 }
1547 B.addStackAlignmentAttr(Alignment);
1548 return false;
1549 }
1550 case Attribute::AllocSize: {
1551 unsigned ElemSizeArg;
1552 std::optional<unsigned> NumElemsArg;
1553 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1554 return true;
1555 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1556 return false;
1557 }
1558 case Attribute::VScaleRange: {
1559 unsigned MinValue, MaxValue;
1560 if (parseVScaleRangeArguments(MinValue, MaxValue))
1561 return true;
1562 B.addVScaleRangeAttr(MinValue,
1563 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1564 return false;
1565 }
1566 case Attribute::Dereferenceable: {
1567 uint64_t Bytes;
1568 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1569 return true;
1570 B.addDereferenceableAttr(Bytes);
1571 return false;
1572 }
1573 case Attribute::DereferenceableOrNull: {
1574 uint64_t Bytes;
1575 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1576 return true;
1577 B.addDereferenceableOrNullAttr(Bytes);
1578 return false;
1579 }
1580 case Attribute::UWTable: {
1582 if (parseOptionalUWTableKind(Kind))
1583 return true;
1584 B.addUWTableAttr(Kind);
1585 return false;
1586 }
1587 case Attribute::AllocKind: {
1589 if (parseAllocKind(Kind))
1590 return true;
1591 B.addAllocKindAttr(Kind);
1592 return false;
1593 }
1594 case Attribute::Memory: {
1595 std::optional<MemoryEffects> ME = parseMemoryAttr();
1596 if (!ME)
1597 return true;
1598 B.addMemoryAttr(*ME);
1599 return false;
1600 }
1601 case Attribute::NoFPClass: {
1602 if (FPClassTest NoFPClass =
1603 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1604 B.addNoFPClassAttr(NoFPClass);
1605 return false;
1606 }
1607
1608 return true;
1609 }
1610 case Attribute::Range:
1611 return parseRangeAttr(B);
1612 default:
1613 B.addAttribute(Attr);
1614 Lex.Lex();
1615 return false;
1616 }
1617}
1618
1620 switch (Kind) {
1621 case lltok::kw_readnone:
1622 ME &= MemoryEffects::none();
1623 return true;
1624 case lltok::kw_readonly:
1626 return true;
1627 case lltok::kw_writeonly:
1629 return true;
1632 return true;
1635 return true;
1638 return true;
1639 default:
1640 return false;
1641 }
1642}
1643
1644/// parseFnAttributeValuePairs
1645/// ::= <attr> | <attr> '=' <value>
1646bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1647 std::vector<unsigned> &FwdRefAttrGrps,
1648 bool InAttrGrp, LocTy &BuiltinLoc) {
1649 bool HaveError = false;
1650
1651 B.clear();
1652
1654 while (true) {
1655 lltok::Kind Token = Lex.getKind();
1656 if (Token == lltok::rbrace)
1657 break; // Finished.
1658
1659 if (Token == lltok::StringConstant) {
1660 if (parseStringAttribute(B))
1661 return true;
1662 continue;
1663 }
1664
1665 if (Token == lltok::AttrGrpID) {
1666 // Allow a function to reference an attribute group:
1667 //
1668 // define void @foo() #1 { ... }
1669 if (InAttrGrp) {
1670 HaveError |= error(
1671 Lex.getLoc(),
1672 "cannot have an attribute group reference in an attribute group");
1673 } else {
1674 // Save the reference to the attribute group. We'll fill it in later.
1675 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1676 }
1677 Lex.Lex();
1678 continue;
1679 }
1680
1681 SMLoc Loc = Lex.getLoc();
1682 if (Token == lltok::kw_builtin)
1683 BuiltinLoc = Loc;
1684
1685 if (upgradeMemoryAttr(ME, Token)) {
1686 Lex.Lex();
1687 continue;
1688 }
1689
1691 if (Attr == Attribute::None) {
1692 if (!InAttrGrp)
1693 break;
1694 return error(Lex.getLoc(), "unterminated attribute group");
1695 }
1696
1697 if (parseEnumAttribute(Attr, B, InAttrGrp))
1698 return true;
1699
1700 // As a hack, we allow function alignment to be initially parsed as an
1701 // attribute on a function declaration/definition or added to an attribute
1702 // group and later moved to the alignment field.
1703 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1704 HaveError |= error(Loc, "this attribute does not apply to functions");
1705 }
1706
1707 if (ME != MemoryEffects::unknown())
1708 B.addMemoryAttr(ME);
1709 return HaveError;
1710}
1711
1712//===----------------------------------------------------------------------===//
1713// GlobalValue Reference/Resolution Routines.
1714//===----------------------------------------------------------------------===//
1715
1717 // The used global type does not matter. We will later RAUW it with a
1718 // global/function of the correct type.
1719 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1722 PTy->getAddressSpace());
1723}
1724
1725Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1726 Value *Val) {
1727 Type *ValTy = Val->getType();
1728 if (ValTy == Ty)
1729 return Val;
1730 if (Ty->isLabelTy())
1731 error(Loc, "'" + Name + "' is not a basic block");
1732 else
1733 error(Loc, "'" + Name + "' defined with type '" +
1734 getTypeString(Val->getType()) + "' but expected '" +
1735 getTypeString(Ty) + "'");
1736 return nullptr;
1737}
1738
1739/// getGlobalVal - Get a value with the specified name or ID, creating a
1740/// forward reference record if needed. This can return null if the value
1741/// exists but does not have the right type.
1742GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1743 LocTy Loc) {
1744 PointerType *PTy = dyn_cast<PointerType>(Ty);
1745 if (!PTy) {
1746 error(Loc, "global variable reference must have pointer type");
1747 return nullptr;
1748 }
1749
1750 // Look this name up in the normal function symbol table.
1751 GlobalValue *Val =
1752 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1753
1754 // If this is a forward reference for the value, see if we already created a
1755 // forward ref record.
1756 if (!Val) {
1757 auto I = ForwardRefVals.find(Name);
1758 if (I != ForwardRefVals.end())
1759 Val = I->second.first;
1760 }
1761
1762 // If we have the value in the symbol table or fwd-ref table, return it.
1763 if (Val)
1764 return cast_or_null<GlobalValue>(
1765 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1766
1767 // Otherwise, create a new forward reference for this value and remember it.
1768 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1769 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1770 return FwdVal;
1771}
1772
1773GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1774 PointerType *PTy = dyn_cast<PointerType>(Ty);
1775 if (!PTy) {
1776 error(Loc, "global variable reference must have pointer type");
1777 return nullptr;
1778 }
1779
1780 GlobalValue *Val = NumberedVals.get(ID);
1781
1782 // If this is a forward reference for the value, see if we already created a
1783 // forward ref record.
1784 if (!Val) {
1785 auto I = ForwardRefValIDs.find(ID);
1786 if (I != ForwardRefValIDs.end())
1787 Val = I->second.first;
1788 }
1789
1790 // If we have the value in the symbol table or fwd-ref table, return it.
1791 if (Val)
1792 return cast_or_null<GlobalValue>(
1793 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1794
1795 // Otherwise, create a new forward reference for this value and remember it.
1796 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1797 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1798 return FwdVal;
1799}
1800
1801//===----------------------------------------------------------------------===//
1802// Comdat Reference/Resolution Routines.
1803//===----------------------------------------------------------------------===//
1804
1805Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1806 // Look this name up in the comdat symbol table.
1807 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1809 if (I != ComdatSymTab.end())
1810 return &I->second;
1811
1812 // Otherwise, create a new forward reference for this value and remember it.
1813 Comdat *C = M->getOrInsertComdat(Name);
1814 ForwardRefComdats[Name] = Loc;
1815 return C;
1816}
1817
1818//===----------------------------------------------------------------------===//
1819// Helper Routines.
1820//===----------------------------------------------------------------------===//
1821
1822/// parseToken - If the current token has the specified kind, eat it and return
1823/// success. Otherwise, emit the specified error and return failure.
1824bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1825 if (Lex.getKind() != T)
1826 return tokError(ErrMsg);
1827 Lex.Lex();
1828 return false;
1829}
1830
1831/// parseStringConstant
1832/// ::= StringConstant
1833bool LLParser::parseStringConstant(std::string &Result) {
1834 if (Lex.getKind() != lltok::StringConstant)
1835 return tokError("expected string constant");
1836 Result = Lex.getStrVal();
1837 Lex.Lex();
1838 return false;
1839}
1840
1841/// parseUInt32
1842/// ::= uint32
1843bool LLParser::parseUInt32(uint32_t &Val) {
1844 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1845 return tokError("expected integer");
1846 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1847 if (Val64 != unsigned(Val64))
1848 return tokError("expected 32-bit integer (too large)");
1849 Val = Val64;
1850 Lex.Lex();
1851 return false;
1852}
1853
1854/// parseUInt64
1855/// ::= uint64
1856bool LLParser::parseUInt64(uint64_t &Val) {
1857 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1858 return tokError("expected integer");
1859 Val = Lex.getAPSIntVal().getLimitedValue();
1860 Lex.Lex();
1861 return false;
1862}
1863
1864/// parseTLSModel
1865/// := 'localdynamic'
1866/// := 'initialexec'
1867/// := 'localexec'
1868bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1869 switch (Lex.getKind()) {
1870 default:
1871 return tokError("expected localdynamic, initialexec or localexec");
1874 break;
1877 break;
1880 break;
1881 }
1882
1883 Lex.Lex();
1884 return false;
1885}
1886
1887/// parseOptionalThreadLocal
1888/// := /*empty*/
1889/// := 'thread_local'
1890/// := 'thread_local' '(' tlsmodel ')'
1891bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1893 if (!EatIfPresent(lltok::kw_thread_local))
1894 return false;
1895
1897 if (Lex.getKind() == lltok::lparen) {
1898 Lex.Lex();
1899 return parseTLSModel(TLM) ||
1900 parseToken(lltok::rparen, "expected ')' after thread local model");
1901 }
1902 return false;
1903}
1904
1905/// parseOptionalAddrSpace
1906/// := /*empty*/
1907/// := 'addrspace' '(' uint32 ')'
1908bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1909 AddrSpace = DefaultAS;
1910 if (!EatIfPresent(lltok::kw_addrspace))
1911 return false;
1912
1913 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1914 if (Lex.getKind() == lltok::StringConstant) {
1915 auto AddrSpaceStr = Lex.getStrVal();
1916 if (AddrSpaceStr == "A") {
1917 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1918 } else if (AddrSpaceStr == "G") {
1919 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1920 } else if (AddrSpaceStr == "P") {
1921 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1922 } else {
1923 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1924 }
1925 Lex.Lex();
1926 return false;
1927 }
1928 if (Lex.getKind() != lltok::APSInt)
1929 return tokError("expected integer or string constant");
1930 SMLoc Loc = Lex.getLoc();
1931 if (parseUInt32(AddrSpace))
1932 return true;
1933 if (!isUInt<24>(AddrSpace))
1934 return error(Loc, "invalid address space, must be a 24-bit integer");
1935 return false;
1936 };
1937
1938 return parseToken(lltok::lparen, "expected '(' in address space") ||
1939 ParseAddrspaceValue(AddrSpace) ||
1940 parseToken(lltok::rparen, "expected ')' in address space");
1941}
1942
1943/// parseStringAttribute
1944/// := StringConstant
1945/// := StringConstant '=' StringConstant
1946bool LLParser::parseStringAttribute(AttrBuilder &B) {
1947 std::string Attr = Lex.getStrVal();
1948 Lex.Lex();
1949 std::string Val;
1950 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1951 return true;
1952 B.addAttribute(Attr, Val);
1953 return false;
1954}
1955
1956/// Parse a potentially empty list of parameter or return attributes.
1957bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1958 bool HaveError = false;
1959
1960 B.clear();
1961
1962 while (true) {
1963 lltok::Kind Token = Lex.getKind();
1964 if (Token == lltok::StringConstant) {
1965 if (parseStringAttribute(B))
1966 return true;
1967 continue;
1968 }
1969
1970 SMLoc Loc = Lex.getLoc();
1972 if (Attr == Attribute::None)
1973 return HaveError;
1974
1975 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1976 return true;
1977
1978 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1979 HaveError |= error(Loc, "this attribute does not apply to parameters");
1980 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1981 HaveError |= error(Loc, "this attribute does not apply to return values");
1982 }
1983}
1984
1985static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1986 HasLinkage = true;
1987 switch (Kind) {
1988 default:
1989 HasLinkage = false;
1991 case lltok::kw_private:
1993 case lltok::kw_internal:
1995 case lltok::kw_weak:
1997 case lltok::kw_weak_odr:
1999 case lltok::kw_linkonce:
2007 case lltok::kw_common:
2011 case lltok::kw_external:
2013 }
2014}
2015
2016/// parseOptionalLinkage
2017/// ::= /*empty*/
2018/// ::= 'private'
2019/// ::= 'internal'
2020/// ::= 'weak'
2021/// ::= 'weak_odr'
2022/// ::= 'linkonce'
2023/// ::= 'linkonce_odr'
2024/// ::= 'available_externally'
2025/// ::= 'appending'
2026/// ::= 'common'
2027/// ::= 'extern_weak'
2028/// ::= 'external'
2029bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2030 unsigned &Visibility,
2031 unsigned &DLLStorageClass, bool &DSOLocal) {
2032 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2033 if (HasLinkage)
2034 Lex.Lex();
2035 parseOptionalDSOLocal(DSOLocal);
2036 parseOptionalVisibility(Visibility);
2037 parseOptionalDLLStorageClass(DLLStorageClass);
2038
2039 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2040 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2041 }
2042
2043 return false;
2044}
2045
2046void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2047 switch (Lex.getKind()) {
2048 default:
2049 DSOLocal = false;
2050 break;
2052 DSOLocal = true;
2053 Lex.Lex();
2054 break;
2056 DSOLocal = false;
2057 Lex.Lex();
2058 break;
2059 }
2060}
2061
2062/// parseOptionalVisibility
2063/// ::= /*empty*/
2064/// ::= 'default'
2065/// ::= 'hidden'
2066/// ::= 'protected'
2067///
2068void LLParser::parseOptionalVisibility(unsigned &Res) {
2069 switch (Lex.getKind()) {
2070 default:
2072 return;
2073 case lltok::kw_default:
2075 break;
2076 case lltok::kw_hidden:
2078 break;
2081 break;
2082 }
2083 Lex.Lex();
2084}
2085
2086bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2088 switch (Kind) {
2089 default:
2090 return tokError("unknown import kind. Expect definition or declaration.");
2093 return false;
2096 return false;
2097 }
2098}
2099
2100/// parseOptionalDLLStorageClass
2101/// ::= /*empty*/
2102/// ::= 'dllimport'
2103/// ::= 'dllexport'
2104///
2105void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2106 switch (Lex.getKind()) {
2107 default:
2109 return;
2112 break;
2115 break;
2116 }
2117 Lex.Lex();
2118}
2119
2120/// parseOptionalCallingConv
2121/// ::= /*empty*/
2122/// ::= 'ccc'
2123/// ::= 'fastcc'
2124/// ::= 'intel_ocl_bicc'
2125/// ::= 'coldcc'
2126/// ::= 'cfguard_checkcc'
2127/// ::= 'x86_stdcallcc'
2128/// ::= 'x86_fastcallcc'
2129/// ::= 'x86_thiscallcc'
2130/// ::= 'x86_vectorcallcc'
2131/// ::= 'arm_apcscc'
2132/// ::= 'arm_aapcscc'
2133/// ::= 'arm_aapcs_vfpcc'
2134/// ::= 'aarch64_vector_pcs'
2135/// ::= 'aarch64_sve_vector_pcs'
2136/// ::= 'aarch64_sme_preservemost_from_x0'
2137/// ::= 'aarch64_sme_preservemost_from_x2'
2138/// ::= 'msp430_intrcc'
2139/// ::= 'avr_intrcc'
2140/// ::= 'avr_signalcc'
2141/// ::= 'ptx_kernel'
2142/// ::= 'ptx_device'
2143/// ::= 'spir_func'
2144/// ::= 'spir_kernel'
2145/// ::= 'x86_64_sysvcc'
2146/// ::= 'win64cc'
2147/// ::= 'anyregcc'
2148/// ::= 'preserve_mostcc'
2149/// ::= 'preserve_allcc'
2150/// ::= 'preserve_nonecc'
2151/// ::= 'ghccc'
2152/// ::= 'swiftcc'
2153/// ::= 'swifttailcc'
2154/// ::= 'x86_intrcc'
2155/// ::= 'hhvmcc'
2156/// ::= 'hhvm_ccc'
2157/// ::= 'cxx_fast_tlscc'
2158/// ::= 'amdgpu_vs'
2159/// ::= 'amdgpu_ls'
2160/// ::= 'amdgpu_hs'
2161/// ::= 'amdgpu_es'
2162/// ::= 'amdgpu_gs'
2163/// ::= 'amdgpu_ps'
2164/// ::= 'amdgpu_cs'
2165/// ::= 'amdgpu_cs_chain'
2166/// ::= 'amdgpu_cs_chain_preserve'
2167/// ::= 'amdgpu_kernel'
2168/// ::= 'tailcc'
2169/// ::= 'm68k_rtdcc'
2170/// ::= 'graalcc'
2171/// ::= 'riscv_vector_cc'
2172/// ::= 'cc' UINT
2173///
2174bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2175 switch (Lex.getKind()) {
2176 default: CC = CallingConv::C; return false;
2177 case lltok::kw_ccc: CC = CallingConv::C; break;
2178 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2179 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2192 break;
2195 break;
2198 break;
2213 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2217 case lltok::kw_hhvmcc:
2219 break;
2220 case lltok::kw_hhvm_ccc:
2222 break;
2234 break;
2237 break;
2239 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2244 break;
2245 case lltok::kw_cc: {
2246 Lex.Lex();
2247 return parseUInt32(CC);
2248 }
2249 }
2250
2251 Lex.Lex();
2252 return false;
2253}
2254
2255/// parseMetadataAttachment
2256/// ::= !dbg !42
2257bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2258 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2259
2260 std::string Name = Lex.getStrVal();
2261 Kind = M->getMDKindID(Name);
2262 Lex.Lex();
2263
2264 return parseMDNode(MD);
2265}
2266
2267/// parseInstructionMetadata
2268/// ::= !dbg !42 (',' !dbg !57)*
2269bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2270 do {
2271 if (Lex.getKind() != lltok::MetadataVar)
2272 return tokError("expected metadata after comma");
2273
2274 unsigned MDK;
2275 MDNode *N;
2276 if (parseMetadataAttachment(MDK, N))
2277 return true;
2278
2279 if (MDK == LLVMContext::MD_DIAssignID)
2280 TempDIAssignIDAttachments[N].push_back(&Inst);
2281 else
2282 Inst.setMetadata(MDK, N);
2283
2284 if (MDK == LLVMContext::MD_tbaa)
2285 InstsWithTBAATag.push_back(&Inst);
2286
2287 // If this is the end of the list, we're done.
2288 } while (EatIfPresent(lltok::comma));
2289 return false;
2290}
2291
2292/// parseGlobalObjectMetadataAttachment
2293/// ::= !dbg !57
2294bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2295 unsigned MDK;
2296 MDNode *N;
2297 if (parseMetadataAttachment(MDK, N))
2298 return true;
2299
2300 GO.addMetadata(MDK, *N);
2301 return false;
2302}
2303
2304/// parseOptionalFunctionMetadata
2305/// ::= (!dbg !57)*
2306bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2307 while (Lex.getKind() == lltok::MetadataVar)
2308 if (parseGlobalObjectMetadataAttachment(F))
2309 return true;
2310 return false;
2311}
2312
2313/// parseOptionalAlignment
2314/// ::= /* empty */
2315/// ::= 'align' 4
2316bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2317 Alignment = std::nullopt;
2318 if (!EatIfPresent(lltok::kw_align))
2319 return false;
2320 LocTy AlignLoc = Lex.getLoc();
2321 uint64_t Value = 0;
2322
2323 LocTy ParenLoc = Lex.getLoc();
2324 bool HaveParens = false;
2325 if (AllowParens) {
2326 if (EatIfPresent(lltok::lparen))
2327 HaveParens = true;
2328 }
2329
2330 if (parseUInt64(Value))
2331 return true;
2332
2333 if (HaveParens && !EatIfPresent(lltok::rparen))
2334 return error(ParenLoc, "expected ')'");
2335
2336 if (!isPowerOf2_64(Value))
2337 return error(AlignLoc, "alignment is not a power of two");
2339 return error(AlignLoc, "huge alignments are not supported yet");
2340 Alignment = Align(Value);
2341 return false;
2342}
2343
2344/// parseOptionalCodeModel
2345/// ::= /* empty */
2346/// ::= 'code_model' "large"
2347bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2348 Lex.Lex();
2349 auto StrVal = Lex.getStrVal();
2350 auto ErrMsg = "expected global code model string";
2351 if (StrVal == "tiny")
2352 model = CodeModel::Tiny;
2353 else if (StrVal == "small")
2354 model = CodeModel::Small;
2355 else if (StrVal == "kernel")
2356 model = CodeModel::Kernel;
2357 else if (StrVal == "medium")
2358 model = CodeModel::Medium;
2359 else if (StrVal == "large")
2360 model = CodeModel::Large;
2361 else
2362 return tokError(ErrMsg);
2363 if (parseToken(lltok::StringConstant, ErrMsg))
2364 return true;
2365 return false;
2366}
2367
2368/// parseOptionalDerefAttrBytes
2369/// ::= /* empty */
2370/// ::= AttrKind '(' 4 ')'
2371///
2372/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2373bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2374 uint64_t &Bytes) {
2375 assert((AttrKind == lltok::kw_dereferenceable ||
2376 AttrKind == lltok::kw_dereferenceable_or_null) &&
2377 "contract!");
2378
2379 Bytes = 0;
2380 if (!EatIfPresent(AttrKind))
2381 return false;
2382 LocTy ParenLoc = Lex.getLoc();
2383 if (!EatIfPresent(lltok::lparen))
2384 return error(ParenLoc, "expected '('");
2385 LocTy DerefLoc = Lex.getLoc();
2386 if (parseUInt64(Bytes))
2387 return true;
2388 ParenLoc = Lex.getLoc();
2389 if (!EatIfPresent(lltok::rparen))
2390 return error(ParenLoc, "expected ')'");
2391 if (!Bytes)
2392 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2393 return false;
2394}
2395
2396bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2397 Lex.Lex();
2399 if (!EatIfPresent(lltok::lparen))
2400 return false;
2401 LocTy KindLoc = Lex.getLoc();
2402 if (Lex.getKind() == lltok::kw_sync)
2404 else if (Lex.getKind() == lltok::kw_async)
2406 else
2407 return error(KindLoc, "expected unwind table kind");
2408 Lex.Lex();
2409 return parseToken(lltok::rparen, "expected ')'");
2410}
2411
2412bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2413 Lex.Lex();
2414 LocTy ParenLoc = Lex.getLoc();
2415 if (!EatIfPresent(lltok::lparen))
2416 return error(ParenLoc, "expected '('");
2417 LocTy KindLoc = Lex.getLoc();
2418 std::string Arg;
2419 if (parseStringConstant(Arg))
2420 return error(KindLoc, "expected allockind value");
2421 for (StringRef A : llvm::split(Arg, ",")) {
2422 if (A == "alloc") {
2424 } else if (A == "realloc") {
2426 } else if (A == "free") {
2428 } else if (A == "uninitialized") {
2430 } else if (A == "zeroed") {
2432 } else if (A == "aligned") {
2434 } else {
2435 return error(KindLoc, Twine("unknown allockind ") + A);
2436 }
2437 }
2438 ParenLoc = Lex.getLoc();
2439 if (!EatIfPresent(lltok::rparen))
2440 return error(ParenLoc, "expected ')'");
2441 if (Kind == AllocFnKind::Unknown)
2442 return error(KindLoc, "expected allockind value");
2443 return false;
2444}
2445
2446static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2447 switch (Tok) {
2448 case lltok::kw_argmem:
2449 return IRMemLocation::ArgMem;
2452 default:
2453 return std::nullopt;
2454 }
2455}
2456
2457static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2458 switch (Tok) {
2459 case lltok::kw_none:
2460 return ModRefInfo::NoModRef;
2461 case lltok::kw_read:
2462 return ModRefInfo::Ref;
2463 case lltok::kw_write:
2464 return ModRefInfo::Mod;
2466 return ModRefInfo::ModRef;
2467 default:
2468 return std::nullopt;
2469 }
2470}
2471
2472std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2474
2475 // We use syntax like memory(argmem: read), so the colon should not be
2476 // interpreted as a label terminator.
2478 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2479
2480 Lex.Lex();
2481 if (!EatIfPresent(lltok::lparen)) {
2482 tokError("expected '('");
2483 return std::nullopt;
2484 }
2485
2486 bool SeenLoc = false;
2487 do {
2488 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2489 if (Loc) {
2490 Lex.Lex();
2491 if (!EatIfPresent(lltok::colon)) {
2492 tokError("expected ':' after location");
2493 return std::nullopt;
2494 }
2495 }
2496
2497 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2498 if (!MR) {
2499 if (!Loc)
2500 tokError("expected memory location (argmem, inaccessiblemem) "
2501 "or access kind (none, read, write, readwrite)");
2502 else
2503 tokError("expected access kind (none, read, write, readwrite)");
2504 return std::nullopt;
2505 }
2506
2507 Lex.Lex();
2508 if (Loc) {
2509 SeenLoc = true;
2510 ME = ME.getWithModRef(*Loc, *MR);
2511 } else {
2512 if (SeenLoc) {
2513 tokError("default access kind must be specified first");
2514 return std::nullopt;
2515 }
2516 ME = MemoryEffects(*MR);
2517 }
2518
2519 if (EatIfPresent(lltok::rparen))
2520 return ME;
2521 } while (EatIfPresent(lltok::comma));
2522
2523 tokError("unterminated memory attribute");
2524 return std::nullopt;
2525}
2526
2527static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2528 switch (Tok) {
2529 case lltok::kw_all:
2530 return fcAllFlags;
2531 case lltok::kw_nan:
2532 return fcNan;
2533 case lltok::kw_snan:
2534 return fcSNan;
2535 case lltok::kw_qnan:
2536 return fcQNan;
2537 case lltok::kw_inf:
2538 return fcInf;
2539 case lltok::kw_ninf:
2540 return fcNegInf;
2541 case lltok::kw_pinf:
2542 return fcPosInf;
2543 case lltok::kw_norm:
2544 return fcNormal;
2545 case lltok::kw_nnorm:
2546 return fcNegNormal;
2547 case lltok::kw_pnorm:
2548 return fcPosNormal;
2549 case lltok::kw_sub:
2550 return fcSubnormal;
2551 case lltok::kw_nsub:
2552 return fcNegSubnormal;
2553 case lltok::kw_psub:
2554 return fcPosSubnormal;
2555 case lltok::kw_zero:
2556 return fcZero;
2557 case lltok::kw_nzero:
2558 return fcNegZero;
2559 case lltok::kw_pzero:
2560 return fcPosZero;
2561 default:
2562 return 0;
2563 }
2564}
2565
2566unsigned LLParser::parseNoFPClassAttr() {
2567 unsigned Mask = fcNone;
2568
2569 Lex.Lex();
2570 if (!EatIfPresent(lltok::lparen)) {
2571 tokError("expected '('");
2572 return 0;
2573 }
2574
2575 do {
2576 uint64_t Value = 0;
2577 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2578 if (TestMask != 0) {
2579 Mask |= TestMask;
2580 // TODO: Disallow overlapping masks to avoid copy paste errors
2581 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2582 !parseUInt64(Value)) {
2583 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2584 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2585 return 0;
2586 }
2587
2588 if (!EatIfPresent(lltok::rparen)) {
2589 error(Lex.getLoc(), "expected ')'");
2590 return 0;
2591 }
2592
2593 return Value;
2594 } else {
2595 error(Lex.getLoc(), "expected nofpclass test mask");
2596 return 0;
2597 }
2598
2599 Lex.Lex();
2600 if (EatIfPresent(lltok::rparen))
2601 return Mask;
2602 } while (1);
2603
2604 llvm_unreachable("unterminated nofpclass attribute");
2605}
2606
2607/// parseOptionalCommaAlign
2608/// ::=
2609/// ::= ',' align 4
2610///
2611/// This returns with AteExtraComma set to true if it ate an excess comma at the
2612/// end.
2613bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2614 bool &AteExtraComma) {
2615 AteExtraComma = false;
2616 while (EatIfPresent(lltok::comma)) {
2617 // Metadata at the end is an early exit.
2618 if (Lex.getKind() == lltok::MetadataVar) {
2619 AteExtraComma = true;
2620 return false;
2621 }
2622
2623 if (Lex.getKind() != lltok::kw_align)
2624 return error(Lex.getLoc(), "expected metadata or 'align'");
2625
2626 if (parseOptionalAlignment(Alignment))
2627 return true;
2628 }
2629
2630 return false;
2631}
2632
2633/// parseOptionalCommaAddrSpace
2634/// ::=
2635/// ::= ',' addrspace(1)
2636///
2637/// This returns with AteExtraComma set to true if it ate an excess comma at the
2638/// end.
2639bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2640 bool &AteExtraComma) {
2641 AteExtraComma = false;
2642 while (EatIfPresent(lltok::comma)) {
2643 // Metadata at the end is an early exit.
2644 if (Lex.getKind() == lltok::MetadataVar) {
2645 AteExtraComma = true;
2646 return false;
2647 }
2648
2649 Loc = Lex.getLoc();
2650 if (Lex.getKind() != lltok::kw_addrspace)
2651 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2652
2653 if (parseOptionalAddrSpace(AddrSpace))
2654 return true;
2655 }
2656
2657 return false;
2658}
2659
2660bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2661 std::optional<unsigned> &HowManyArg) {
2662 Lex.Lex();
2663
2664 auto StartParen = Lex.getLoc();
2665 if (!EatIfPresent(lltok::lparen))
2666 return error(StartParen, "expected '('");
2667
2668 if (parseUInt32(BaseSizeArg))
2669 return true;
2670
2671 if (EatIfPresent(lltok::comma)) {
2672 auto HowManyAt = Lex.getLoc();
2673 unsigned HowMany;
2674 if (parseUInt32(HowMany))
2675 return true;
2676 if (HowMany == BaseSizeArg)
2677 return error(HowManyAt,
2678 "'allocsize' indices can't refer to the same parameter");
2679 HowManyArg = HowMany;
2680 } else
2681 HowManyArg = std::nullopt;
2682
2683 auto EndParen = Lex.getLoc();
2684 if (!EatIfPresent(lltok::rparen))
2685 return error(EndParen, "expected ')'");
2686 return false;
2687}
2688
2689bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2690 unsigned &MaxValue) {
2691 Lex.Lex();
2692
2693 auto StartParen = Lex.getLoc();
2694 if (!EatIfPresent(lltok::lparen))
2695 return error(StartParen, "expected '('");
2696
2697 if (parseUInt32(MinValue))
2698 return true;
2699
2700 if (EatIfPresent(lltok::comma)) {
2701 if (parseUInt32(MaxValue))
2702 return true;
2703 } else
2704 MaxValue = MinValue;
2705
2706 auto EndParen = Lex.getLoc();
2707 if (!EatIfPresent(lltok::rparen))
2708 return error(EndParen, "expected ')'");
2709 return false;
2710}
2711
2712/// parseScopeAndOrdering
2713/// if isAtomic: ::= SyncScope? AtomicOrdering
2714/// else: ::=
2715///
2716/// This sets Scope and Ordering to the parsed values.
2717bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2718 AtomicOrdering &Ordering) {
2719 if (!IsAtomic)
2720 return false;
2721
2722 return parseScope(SSID) || parseOrdering(Ordering);
2723}
2724
2725/// parseScope
2726/// ::= syncscope("singlethread" | "<target scope>")?
2727///
2728/// This sets synchronization scope ID to the ID of the parsed value.
2729bool LLParser::parseScope(SyncScope::ID &SSID) {
2730 SSID = SyncScope::System;
2731 if (EatIfPresent(lltok::kw_syncscope)) {
2732 auto StartParenAt = Lex.getLoc();
2733 if (!EatIfPresent(lltok::lparen))
2734 return error(StartParenAt, "Expected '(' in syncscope");
2735
2736 std::string SSN;
2737 auto SSNAt = Lex.getLoc();
2738 if (parseStringConstant(SSN))
2739 return error(SSNAt, "Expected synchronization scope name");
2740
2741 auto EndParenAt = Lex.getLoc();
2742 if (!EatIfPresent(lltok::rparen))
2743 return error(EndParenAt, "Expected ')' in syncscope");
2744
2745 SSID = Context.getOrInsertSyncScopeID(SSN);
2746 }
2747
2748 return false;
2749}
2750
2751/// parseOrdering
2752/// ::= AtomicOrdering
2753///
2754/// This sets Ordering to the parsed value.
2755bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2756 switch (Lex.getKind()) {
2757 default:
2758 return tokError("Expected ordering on atomic instruction");
2759 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2760 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2761 // Not specified yet:
2762 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2763 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2764 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2765 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2766 case lltok::kw_seq_cst:
2768 break;
2769 }
2770 Lex.Lex();
2771 return false;
2772}
2773
2774/// parseOptionalStackAlignment
2775/// ::= /* empty */
2776/// ::= 'alignstack' '(' 4 ')'
2777bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2778 Alignment = 0;
2779 if (!EatIfPresent(lltok::kw_alignstack))
2780 return false;
2781 LocTy ParenLoc = Lex.getLoc();
2782 if (!EatIfPresent(lltok::lparen))
2783 return error(ParenLoc, "expected '('");
2784 LocTy AlignLoc = Lex.getLoc();
2785 if (parseUInt32(Alignment))
2786 return true;
2787 ParenLoc = Lex.getLoc();
2788 if (!EatIfPresent(lltok::rparen))
2789 return error(ParenLoc, "expected ')'");
2790 if (!isPowerOf2_32(Alignment))
2791 return error(AlignLoc, "stack alignment is not a power of two");
2792 return false;
2793}
2794
2795/// parseIndexList - This parses the index list for an insert/extractvalue
2796/// instruction. This sets AteExtraComma in the case where we eat an extra
2797/// comma at the end of the line and find that it is followed by metadata.
2798/// Clients that don't allow metadata can call the version of this function that
2799/// only takes one argument.
2800///
2801/// parseIndexList
2802/// ::= (',' uint32)+
2803///
2804bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2805 bool &AteExtraComma) {
2806 AteExtraComma = false;
2807
2808 if (Lex.getKind() != lltok::comma)
2809 return tokError("expected ',' as start of index list");
2810
2811 while (EatIfPresent(lltok::comma)) {
2812 if (Lex.getKind() == lltok::MetadataVar) {
2813 if (Indices.empty())
2814 return tokError("expected index");
2815 AteExtraComma = true;
2816 return false;
2817 }
2818 unsigned Idx = 0;
2819 if (parseUInt32(Idx))
2820 return true;
2821 Indices.push_back(Idx);
2822 }
2823
2824 return false;
2825}
2826
2827//===----------------------------------------------------------------------===//
2828// Type Parsing.
2829//===----------------------------------------------------------------------===//
2830
2831/// parseType - parse a type.
2832bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2833 SMLoc TypeLoc = Lex.getLoc();
2834 switch (Lex.getKind()) {
2835 default:
2836 return tokError(Msg);
2837 case lltok::Type:
2838 // Type ::= 'float' | 'void' (etc)
2839 Result = Lex.getTyVal();
2840 Lex.Lex();
2841
2842 // Handle "ptr" opaque pointer type.
2843 //
2844 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2845 if (Result->isPointerTy()) {
2846 unsigned AddrSpace;
2847 if (parseOptionalAddrSpace(AddrSpace))
2848 return true;
2849 Result = PointerType::get(getContext(), AddrSpace);
2850
2851 // Give a nice error for 'ptr*'.
2852 if (Lex.getKind() == lltok::star)
2853 return tokError("ptr* is invalid - use ptr instead");
2854
2855 // Fall through to parsing the type suffixes only if this 'ptr' is a
2856 // function return. Otherwise, return success, implicitly rejecting other
2857 // suffixes.
2858 if (Lex.getKind() != lltok::lparen)
2859 return false;
2860 }
2861 break;
2862 case lltok::kw_target: {
2863 // Type ::= TargetExtType
2864 if (parseTargetExtType(Result))
2865 return true;
2866 break;
2867 }
2868 case lltok::lbrace:
2869 // Type ::= StructType
2870 if (parseAnonStructType(Result, false))
2871 return true;
2872 break;
2873 case lltok::lsquare:
2874 // Type ::= '[' ... ']'
2875 Lex.Lex(); // eat the lsquare.
2876 if (parseArrayVectorType(Result, false))
2877 return true;
2878 break;
2879 case lltok::less: // Either vector or packed struct.
2880 // Type ::= '<' ... '>'
2881 Lex.Lex();
2882 if (Lex.getKind() == lltok::lbrace) {
2883 if (parseAnonStructType(Result, true) ||
2884 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2885 return true;
2886 } else if (parseArrayVectorType(Result, true))
2887 return true;
2888 break;
2889 case lltok::LocalVar: {
2890 // Type ::= %foo
2891 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2892
2893 // If the type hasn't been defined yet, create a forward definition and
2894 // remember where that forward def'n was seen (in case it never is defined).
2895 if (!Entry.first) {
2896 Entry.first = StructType::create(Context, Lex.getStrVal());
2897 Entry.second = Lex.getLoc();
2898 }
2899 Result = Entry.first;
2900 Lex.Lex();
2901 break;
2902 }
2903
2904 case lltok::LocalVarID: {
2905 // Type ::= %4
2906 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2907
2908 // If the type hasn't been defined yet, create a forward definition and
2909 // remember where that forward def'n was seen (in case it never is defined).
2910 if (!Entry.first) {
2911 Entry.first = StructType::create(Context);
2912 Entry.second = Lex.getLoc();
2913 }
2914 Result = Entry.first;
2915 Lex.Lex();
2916 break;
2917 }
2918 }
2919
2920 // parse the type suffixes.
2921 while (true) {
2922 switch (Lex.getKind()) {
2923 // End of type.
2924 default:
2925 if (!AllowVoid && Result->isVoidTy())
2926 return error(TypeLoc, "void type only allowed for function results");
2927 return false;
2928
2929 // Type ::= Type '*'
2930 case lltok::star:
2931 if (Result->isLabelTy())
2932 return tokError("basic block pointers are invalid");
2933 if (Result->isVoidTy())
2934 return tokError("pointers to void are invalid - use i8* instead");
2936 return tokError("pointer to this type is invalid");
2938 Lex.Lex();
2939 break;
2940
2941 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2942 case lltok::kw_addrspace: {
2943 if (Result->isLabelTy())
2944 return tokError("basic block pointers are invalid");
2945 if (Result->isVoidTy())
2946 return tokError("pointers to void are invalid; use i8* instead");
2948 return tokError("pointer to this type is invalid");
2949 unsigned AddrSpace;
2950 if (parseOptionalAddrSpace(AddrSpace) ||
2951 parseToken(lltok::star, "expected '*' in address space"))
2952 return true;
2953
2954 Result = PointerType::get(Result, AddrSpace);
2955 break;
2956 }
2957
2958 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2959 case lltok::lparen:
2960 if (parseFunctionType(Result))
2961 return true;
2962 break;
2963 }
2964 }
2965}
2966
2967/// parseParameterList
2968/// ::= '(' ')'
2969/// ::= '(' Arg (',' Arg)* ')'
2970/// Arg
2971/// ::= Type OptionalAttributes Value OptionalAttributes
2972bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2973 PerFunctionState &PFS, bool IsMustTailCall,
2974 bool InVarArgsFunc) {
2975 if (parseToken(lltok::lparen, "expected '(' in call"))
2976 return true;
2977
2978 while (Lex.getKind() != lltok::rparen) {
2979 // If this isn't the first argument, we need a comma.
2980 if (!ArgList.empty() &&
2981 parseToken(lltok::comma, "expected ',' in argument list"))
2982 return true;
2983
2984 // parse an ellipsis if this is a musttail call in a variadic function.
2985 if (Lex.getKind() == lltok::dotdotdot) {
2986 const char *Msg = "unexpected ellipsis in argument list for ";
2987 if (!IsMustTailCall)
2988 return tokError(Twine(Msg) + "non-musttail call");
2989 if (!InVarArgsFunc)
2990 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2991 Lex.Lex(); // Lex the '...', it is purely for readability.
2992 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2993 }
2994
2995 // parse the argument.
2996 LocTy ArgLoc;
2997 Type *ArgTy = nullptr;
2998 Value *V;
2999 if (parseType(ArgTy, ArgLoc))
3000 return true;
3001
3002 AttrBuilder ArgAttrs(M->getContext());
3003
3004 if (ArgTy->isMetadataTy()) {
3005 if (parseMetadataAsValue(V, PFS))
3006 return true;
3007 } else {
3008 // Otherwise, handle normal operands.
3009 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3010 return true;
3011 }
3012 ArgList.push_back(ParamInfo(
3013 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3014 }
3015
3016 if (IsMustTailCall && InVarArgsFunc)
3017 return tokError("expected '...' at end of argument list for musttail call "
3018 "in varargs function");
3019
3020 Lex.Lex(); // Lex the ')'.
3021 return false;
3022}
3023
3024/// parseRequiredTypeAttr
3025/// ::= attrname(<ty>)
3026bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3027 Attribute::AttrKind AttrKind) {
3028 Type *Ty = nullptr;
3029 if (!EatIfPresent(AttrToken))
3030 return true;
3031 if (!EatIfPresent(lltok::lparen))
3032 return error(Lex.getLoc(), "expected '('");
3033 if (parseType(Ty))
3034 return true;
3035 if (!EatIfPresent(lltok::rparen))
3036 return error(Lex.getLoc(), "expected ')'");
3037
3038 B.addTypeAttr(AttrKind, Ty);
3039 return false;
3040}
3041
3042/// parseRangeAttr
3043/// ::= range(<ty> <n>,<n>)
3044bool LLParser::parseRangeAttr(AttrBuilder &B) {
3045 Lex.Lex();
3046
3047 APInt Lower;
3048 APInt Upper;
3049 Type *Ty = nullptr;
3050 LocTy TyLoc;
3051
3052 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3053 if (Lex.getKind() != lltok::APSInt)
3054 return tokError("expected integer");
3055 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3056 return tokError(
3057 "integer is too large for the bit width of specified type");
3058 Val = Lex.getAPSIntVal().extend(BitWidth);
3059 Lex.Lex();
3060 return false;
3061 };
3062
3063 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3064 return true;
3065 if (!Ty->isIntegerTy())
3066 return error(TyLoc, "the range must have integer type!");
3067
3068 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3069
3070 if (ParseAPSInt(BitWidth, Lower) ||
3071 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3072 return true;
3073 if (Lower == Upper)
3074 return tokError("the range should not represent the full or empty set!");
3075
3076 if (parseToken(lltok::rparen, "expected ')'"))
3077 return true;
3078
3079 B.addRangeAttr(ConstantRange(Lower, Upper));
3080 return false;
3081}
3082
3083/// parseOptionalOperandBundles
3084/// ::= /*empty*/
3085/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3086///
3087/// OperandBundle
3088/// ::= bundle-tag '(' ')'
3089/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3090///
3091/// bundle-tag ::= String Constant
3092bool LLParser::parseOptionalOperandBundles(
3093 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3094 LocTy BeginLoc = Lex.getLoc();
3095 if (!EatIfPresent(lltok::lsquare))
3096 return false;
3097
3098 while (Lex.getKind() != lltok::rsquare) {
3099 // If this isn't the first operand bundle, we need a comma.
3100 if (!BundleList.empty() &&
3101 parseToken(lltok::comma, "expected ',' in input list"))
3102 return true;
3103
3104 std::string Tag;
3105 if (parseStringConstant(Tag))
3106 return true;
3107
3108 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3109 return true;
3110
3111 std::vector<Value *> Inputs;
3112 while (Lex.getKind() != lltok::rparen) {
3113 // If this isn't the first input, we need a comma.
3114 if (!Inputs.empty() &&
3115 parseToken(lltok::comma, "expected ',' in input list"))
3116 return true;
3117
3118 Type *Ty = nullptr;
3119 Value *Input = nullptr;
3120 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3121 return true;
3122 Inputs.push_back(Input);
3123 }
3124
3125 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3126
3127 Lex.Lex(); // Lex the ')'.
3128 }
3129
3130 if (BundleList.empty())
3131 return error(BeginLoc, "operand bundle set must not be empty");
3132
3133 Lex.Lex(); // Lex the ']'.
3134 return false;
3135}
3136
3137bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3138 unsigned NextID, unsigned ID) const {
3139 if (ID < NextID)
3140 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3141 Twine(NextID) + "' or greater");
3142
3143 return false;
3144}
3145
3146/// parseArgumentList - parse the argument list for a function type or function
3147/// prototype.
3148/// ::= '(' ArgTypeListI ')'
3149/// ArgTypeListI
3150/// ::= /*empty*/
3151/// ::= '...'
3152/// ::= ArgTypeList ',' '...'
3153/// ::= ArgType (',' ArgType)*
3154///
3155bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3156 SmallVectorImpl<unsigned> &UnnamedArgNums,
3157 bool &IsVarArg) {
3158 unsigned CurValID = 0;
3159 IsVarArg = false;
3160 assert(Lex.getKind() == lltok::lparen);
3161 Lex.Lex(); // eat the (.
3162
3163 if (Lex.getKind() != lltok::rparen) {
3164 do {
3165 // Handle ... at end of arg list.
3166 if (EatIfPresent(lltok::dotdotdot)) {
3167 IsVarArg = true;
3168 break;
3169 }
3170
3171 // Otherwise must be an argument type.
3172 LocTy TypeLoc = Lex.getLoc();
3173 Type *ArgTy = nullptr;
3174 AttrBuilder Attrs(M->getContext());
3175 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3176 return true;
3177
3178 if (ArgTy->isVoidTy())
3179 return error(TypeLoc, "argument can not have void type");
3180
3181 std::string Name;
3182 if (Lex.getKind() == lltok::LocalVar) {
3183 Name = Lex.getStrVal();
3184 Lex.Lex();
3185 } else {
3186 unsigned ArgID;
3187 if (Lex.getKind() == lltok::LocalVarID) {
3188 ArgID = Lex.getUIntVal();
3189 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3190 return true;
3191 Lex.Lex();
3192 } else {
3193 ArgID = CurValID;
3194 }
3195 UnnamedArgNums.push_back(ArgID);
3196 CurValID = ArgID + 1;
3197 }
3198
3199 if (!ArgTy->isFirstClassType())
3200 return error(TypeLoc, "invalid type for function argument");
3201
3202 ArgList.emplace_back(TypeLoc, ArgTy,
3203 AttributeSet::get(ArgTy->getContext(), Attrs),
3204 std::move(Name));
3205 } while (EatIfPresent(lltok::comma));
3206 }
3207
3208 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3209}
3210
3211/// parseFunctionType
3212/// ::= Type ArgumentList OptionalAttrs
3213bool LLParser::parseFunctionType(Type *&Result) {
3214 assert(Lex.getKind() == lltok::lparen);
3215
3217 return tokError("invalid function return type");
3218
3220 bool IsVarArg;
3221 SmallVector<unsigned> UnnamedArgNums;
3222 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3223 return true;
3224
3225 // Reject names on the arguments lists.
3226 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3227 if (!ArgList[i].Name.empty())
3228 return error(ArgList[i].Loc, "argument name invalid in function type");
3229 if (ArgList[i].Attrs.hasAttributes())
3230 return error(ArgList[i].Loc,
3231 "argument attributes invalid in function type");
3232 }
3233
3234 SmallVector<Type*, 16> ArgListTy;
3235 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3236 ArgListTy.push_back(ArgList[i].Ty);
3237
3238 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3239 return false;
3240}
3241
3242/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3243/// other structs.
3244bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3246 if (parseStructBody(Elts))
3247 return true;
3248
3249 Result = StructType::get(Context, Elts, Packed);
3250 return false;
3251}
3252
3253/// parseStructDefinition - parse a struct in a 'type' definition.
3254bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3255 std::pair<Type *, LocTy> &Entry,
3256 Type *&ResultTy) {
3257 // If the type was already defined, diagnose the redefinition.
3258 if (Entry.first && !Entry.second.isValid())
3259 return error(TypeLoc, "redefinition of type");
3260
3261 // If we have opaque, just return without filling in the definition for the
3262 // struct. This counts as a definition as far as the .ll file goes.
3263 if (EatIfPresent(lltok::kw_opaque)) {
3264 // This type is being defined, so clear the location to indicate this.
3265 Entry.second = SMLoc();
3266
3267 // If this type number has never been uttered, create it.
3268 if (!Entry.first)
3269 Entry.first = StructType::create(Context, Name);
3270 ResultTy = Entry.first;
3271 return false;
3272 }
3273
3274 // If the type starts with '<', then it is either a packed struct or a vector.
3275 bool isPacked = EatIfPresent(lltok::less);
3276
3277 // If we don't have a struct, then we have a random type alias, which we
3278 // accept for compatibility with old files. These types are not allowed to be
3279 // forward referenced and not allowed to be recursive.
3280 if (Lex.getKind() != lltok::lbrace) {
3281 if (Entry.first)
3282 return error(TypeLoc, "forward references to non-struct type");
3283
3284 ResultTy = nullptr;
3285 if (isPacked)
3286 return parseArrayVectorType(ResultTy, true);
3287 return parseType(ResultTy);
3288 }
3289
3290 // This type is being defined, so clear the location to indicate this.
3291 Entry.second = SMLoc();
3292
3293 // If this type number has never been uttered, create it.
3294 if (!Entry.first)
3295 Entry.first = StructType::create(Context, Name);
3296
3297 StructType *STy = cast<StructType>(Entry.first);
3298
3300 if (parseStructBody(Body) ||
3301 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3302 return true;
3303
3304 STy->setBody(Body, isPacked);
3305 ResultTy = STy;
3306 return false;
3307}
3308
3309/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3310/// StructType
3311/// ::= '{' '}'
3312/// ::= '{' Type (',' Type)* '}'
3313/// ::= '<' '{' '}' '>'
3314/// ::= '<' '{' Type (',' Type)* '}' '>'
3315bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3316 assert(Lex.getKind() == lltok::lbrace);
3317 Lex.Lex(); // Consume the '{'
3318
3319 // Handle the empty struct.
3320 if (EatIfPresent(lltok::rbrace))
3321 return false;
3322
3323 LocTy EltTyLoc = Lex.getLoc();
3324 Type *Ty = nullptr;
3325 if (parseType(Ty))
3326 return true;
3327 Body.push_back(Ty);
3328
3330 return error(EltTyLoc, "invalid element type for struct");
3331
3332 while (EatIfPresent(lltok::comma)) {
3333 EltTyLoc = Lex.getLoc();
3334 if (parseType(Ty))
3335 return true;
3336
3338 return error(EltTyLoc, "invalid element type for struct");
3339
3340 Body.push_back(Ty);
3341 }
3342
3343 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3344}
3345
3346/// parseArrayVectorType - parse an array or vector type, assuming the first
3347/// token has already been consumed.
3348/// Type
3349/// ::= '[' APSINTVAL 'x' Types ']'
3350/// ::= '<' APSINTVAL 'x' Types '>'
3351/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3352bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3353 bool Scalable = false;
3354
3355 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3356 Lex.Lex(); // consume the 'vscale'
3357 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3358 return true;
3359
3360 Scalable = true;
3361 }
3362
3363 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3364 Lex.getAPSIntVal().getBitWidth() > 64)
3365 return tokError("expected number in address space");
3366
3367 LocTy SizeLoc = Lex.getLoc();
3369 Lex.Lex();
3370
3371 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3372 return true;
3373
3374 LocTy TypeLoc = Lex.getLoc();
3375 Type *EltTy = nullptr;
3376 if (parseType(EltTy))
3377 return true;
3378
3379 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3380 "expected end of sequential type"))
3381 return true;
3382
3383 if (IsVector) {
3384 if (Size == 0)
3385 return error(SizeLoc, "zero element vector is illegal");
3386 if ((unsigned)Size != Size)
3387 return error(SizeLoc, "size too large for vector");
3389 return error(TypeLoc, "invalid vector element type");
3390 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3391 } else {
3393 return error(TypeLoc, "invalid array element type");
3394 Result = ArrayType::get(EltTy, Size);
3395 }
3396 return false;
3397}
3398
3399/// parseTargetExtType - handle target extension type syntax
3400/// TargetExtType
3401/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3402///
3403/// TargetExtTypeParams
3404/// ::= /*empty*/
3405/// ::= ',' Type TargetExtTypeParams
3406///
3407/// TargetExtIntParams
3408/// ::= /*empty*/
3409/// ::= ',' uint32 TargetExtIntParams
3410bool LLParser::parseTargetExtType(Type *&Result) {
3411 Lex.Lex(); // Eat the 'target' keyword.
3412
3413 // Get the mandatory type name.
3414 std::string TypeName;
3415 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3416 parseStringConstant(TypeName))
3417 return true;
3418
3419 // Parse all of the integer and type parameters at the same time; the use of
3420 // SeenInt will allow us to catch cases where type parameters follow integer
3421 // parameters.
3422 SmallVector<Type *> TypeParams;
3423 SmallVector<unsigned> IntParams;
3424 bool SeenInt = false;
3425 while (Lex.getKind() == lltok::comma) {
3426 Lex.Lex(); // Eat the comma.
3427
3428 if (Lex.getKind() == lltok::APSInt) {
3429 SeenInt = true;
3430 unsigned IntVal;
3431 if (parseUInt32(IntVal))
3432 return true;
3433 IntParams.push_back(IntVal);
3434 } else if (SeenInt) {
3435 // The only other kind of parameter we support is type parameters, which
3436 // must precede the integer parameters. This is therefore an error.
3437 return tokError("expected uint32 param");
3438 } else {
3439 Type *TypeParam;
3440 if (parseType(TypeParam, /*AllowVoid=*/true))
3441 return true;
3442 TypeParams.push_back(TypeParam);
3443 }
3444 }
3445
3446 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3447 return true;
3448
3449 Result = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
3450 return false;
3451}
3452
3453//===----------------------------------------------------------------------===//
3454// Function Semantic Analysis.
3455//===----------------------------------------------------------------------===//
3456
3457LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3458 int functionNumber,
3459 ArrayRef<unsigned> UnnamedArgNums)
3460 : P(p), F(f), FunctionNumber(functionNumber) {
3461
3462 // Insert unnamed arguments into the NumberedVals list.
3463 auto It = UnnamedArgNums.begin();
3464 for (Argument &A : F.args()) {
3465 if (!A.hasName()) {
3466 unsigned ArgNum = *It++;
3467 NumberedVals.add(ArgNum, &A);
3468 }
3469 }
3470}
3471
3472LLParser::PerFunctionState::~PerFunctionState() {
3473 // If there were any forward referenced non-basicblock values, delete them.
3474
3475 for (const auto &P : ForwardRefVals) {
3476 if (isa<BasicBlock>(P.second.first))
3477 continue;
3478 P.second.first->replaceAllUsesWith(
3479 UndefValue::get(P.second.first->getType()));
3480 P.second.first->deleteValue();
3481 }
3482
3483 for (const auto &P : ForwardRefValIDs) {
3484 if (isa<BasicBlock>(P.second.first))
3485 continue;
3486 P.second.first->replaceAllUsesWith(
3487 UndefValue::get(P.second.first->getType()));
3488 P.second.first->deleteValue();
3489 }
3490}
3491
3492bool LLParser::PerFunctionState::finishFunction() {
3493 if (!ForwardRefVals.empty())
3494 return P.error(ForwardRefVals.begin()->second.second,
3495 "use of undefined value '%" + ForwardRefVals.begin()->first +
3496 "'");
3497 if (!ForwardRefValIDs.empty())
3498 return P.error(ForwardRefValIDs.begin()->second.second,
3499 "use of undefined value '%" +
3500 Twine(ForwardRefValIDs.begin()->first) + "'");
3501 return false;
3502}
3503
3504/// getVal - Get a value with the specified name or ID, creating a
3505/// forward reference record if needed. This can return null if the value
3506/// exists but does not have the right type.
3507Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3508 LocTy Loc) {
3509 // Look this name up in the normal function symbol table.
3510 Value *Val = F.getValueSymbolTable()->lookup(Name);
3511
3512 // If this is a forward reference for the value, see if we already created a
3513 // forward ref record.
3514 if (!Val) {
3515 auto I = ForwardRefVals.find(Name);
3516 if (I != ForwardRefVals.end())
3517 Val = I->second.first;
3518 }
3519
3520 // If we have the value in the symbol table or fwd-ref table, return it.
3521 if (Val)
3522 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3523
3524 // Don't make placeholders with invalid type.
3525 if (!Ty->isFirstClassType()) {
3526 P.error(Loc, "invalid use of a non-first-class type");
3527 return nullptr;
3528 }
3529
3530 // Otherwise, create a new forward reference for this value and remember it.
3531 Value *FwdVal;
3532 if (Ty->isLabelTy()) {
3533 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3534 } else {
3535 FwdVal = new Argument(Ty, Name);
3536 }
3537 if (FwdVal->getName() != Name) {
3538 P.error(Loc, "name is too long which can result in name collisions, "
3539 "consider making the name shorter or "
3540 "increasing -non-global-value-max-name-size");
3541 return nullptr;
3542 }
3543
3544 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3545 return FwdVal;
3546}
3547
3548Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3549 // Look this name up in the normal function symbol table.
3550 Value *Val = NumberedVals.get(ID);
3551
3552 // If this is a forward reference for the value, see if we already created a
3553 // forward ref record.
3554 if (!Val) {
3555 auto I = ForwardRefValIDs.find(ID);
3556 if (I != ForwardRefValIDs.end())
3557 Val = I->second.first;
3558 }
3559
3560 // If we have the value in the symbol table or fwd-ref table, return it.
3561 if (Val)
3562 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3563
3564 if (!Ty->isFirstClassType()) {
3565 P.error(Loc, "invalid use of a non-first-class type");
3566 return nullptr;
3567 }
3568
3569 // Otherwise, create a new forward reference for this value and remember it.
3570 Value *FwdVal;
3571 if (Ty->isLabelTy()) {
3572 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3573 } else {
3574 FwdVal = new Argument(Ty);
3575 }
3576
3577 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3578 return FwdVal;
3579}
3580
3581/// setInstName - After an instruction is parsed and inserted into its
3582/// basic block, this installs its name.
3583bool LLParser::PerFunctionState::setInstName(int NameID,
3584 const std::string &NameStr,
3585 LocTy NameLoc, Instruction *Inst) {
3586 // If this instruction has void type, it cannot have a name or ID specified.
3587 if (Inst->getType()->isVoidTy()) {
3588 if (NameID != -1 || !NameStr.empty())
3589 return P.error(NameLoc, "instructions returning void cannot have a name");
3590 return false;
3591 }
3592
3593 // If this was a numbered instruction, verify that the instruction is the
3594 // expected value and resolve any forward references.
3595 if (NameStr.empty()) {
3596 // If neither a name nor an ID was specified, just use the next ID.
3597 if (NameID == -1)
3598 NameID = NumberedVals.getNext();
3599
3600 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3601 NameID))
3602 return true;
3603
3604 auto FI = ForwardRefValIDs.find(NameID);
3605 if (FI != ForwardRefValIDs.end()) {
3606 Value *Sentinel = FI->second.first;
3607 if (Sentinel->getType() != Inst->getType())
3608 return P.error(NameLoc, "instruction forward referenced with type '" +
3609 getTypeString(FI->second.first->getType()) +
3610 "'");
3611
3612 Sentinel->replaceAllUsesWith(Inst);
3613 Sentinel->deleteValue();
3614 ForwardRefValIDs.erase(FI);
3615 }
3616
3617 NumberedVals.add(NameID, Inst);
3618 return false;
3619 }
3620
3621 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3622 auto FI = ForwardRefVals.find(NameStr);
3623 if (FI != ForwardRefVals.end()) {
3624 Value *Sentinel = FI->second.first;
3625 if (Sentinel->getType() != Inst->getType())
3626 return P.error(NameLoc, "instruction forward referenced with type '" +
3627 getTypeString(FI->second.first->getType()) +
3628 "'");
3629
3630 Sentinel->replaceAllUsesWith(Inst);
3631 Sentinel->deleteValue();
3632 ForwardRefVals.erase(FI);
3633 }
3634
3635 // Set the name on the instruction.
3636 Inst->setName(NameStr);
3637
3638 if (Inst->getName() != NameStr)
3639 return P.error(NameLoc, "multiple definition of local value named '" +
3640 NameStr + "'");
3641 return false;
3642}
3643
3644/// getBB - Get a basic block with the specified name or ID, creating a
3645/// forward reference record if needed.
3646BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3647 LocTy Loc) {
3648 return dyn_cast_or_null<BasicBlock>(
3649 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3650}
3651
3652BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3653 return dyn_cast_or_null<BasicBlock>(
3654 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3655}
3656
3657/// defineBB - Define the specified basic block, which is either named or
3658/// unnamed. If there is an error, this returns null otherwise it returns
3659/// the block being defined.
3660BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3661 int NameID, LocTy Loc) {
3662 BasicBlock *BB;
3663 if (Name.empty()) {
3664 if (NameID != -1) {
3665 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3666 return nullptr;
3667 } else {
3668 NameID = NumberedVals.getNext();
3669 }
3670 BB = getBB(NameID, Loc);
3671 if (!BB) {
3672 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3673 return nullptr;
3674 }
3675 } else {
3676 BB = getBB(Name, Loc);
3677 if (!BB) {
3678 P.error(Loc, "unable to create block named '" + Name + "'");
3679 return nullptr;
3680 }
3681 }
3682
3683 // Move the block to the end of the function. Forward ref'd blocks are
3684 // inserted wherever they happen to be referenced.
3685 F.splice(F.end(), &F, BB->getIterator());
3686
3687 // Remove the block from forward ref sets.
3688 if (Name.empty()) {
3689 ForwardRefValIDs.erase(NameID);
3690 NumberedVals.add(NameID, BB);
3691 } else {
3692 // BB forward references are already in the function symbol table.
3693 ForwardRefVals.erase(Name);
3694 }
3695
3696 return BB;
3697}
3698
3699//===----------------------------------------------------------------------===//
3700// Constants.
3701//===----------------------------------------------------------------------===//
3702
3703/// parseValID - parse an abstract value that doesn't necessarily have a
3704/// type implied. For example, if we parse "4" we don't know what integer type
3705/// it has. The value will later be combined with its type and checked for
3706/// basic correctness. PFS is used to convert function-local operands of
3707/// metadata (since metadata operands are not just parsed here but also
3708/// converted to values). PFS can be null when we are not parsing metadata
3709/// values inside a function.
3710bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3711 ID.Loc = Lex.getLoc();
3712 switch (Lex.getKind()) {
3713 default:
3714 return tokError("expected value token");
3715 case lltok::GlobalID: // @42
3716 ID.UIntVal = Lex.getUIntVal();
3717 ID.Kind = ValID::t_GlobalID;
3718 break;
3719 case lltok::GlobalVar: // @foo
3720 ID.StrVal = Lex.getStrVal();
3721 ID.Kind = ValID::t_GlobalName;
3722 break;
3723 case lltok::LocalVarID: // %42
3724 ID.UIntVal = Lex.getUIntVal();
3725 ID.Kind = ValID::t_LocalID;
3726 break;
3727 case lltok::LocalVar: // %foo
3728 ID.StrVal = Lex.getStrVal();
3729 ID.Kind = ValID::t_LocalName;
3730 break;
3731 case lltok::APSInt:
3732 ID.APSIntVal = Lex.getAPSIntVal();
3733 ID.Kind = ValID::t_APSInt;
3734 break;
3735 case lltok::APFloat:
3736 ID.APFloatVal = Lex.getAPFloatVal();
3737 ID.Kind = ValID::t_APFloat;
3738 break;
3739 case lltok::kw_true:
3740 ID.ConstantVal = ConstantInt::getTrue(Context);
3741 ID.Kind = ValID::t_Constant;
3742 break;
3743 case lltok::kw_false:
3744 ID.ConstantVal = ConstantInt::getFalse(Context);
3745 ID.Kind = ValID::t_Constant;
3746 break;
3747 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3748 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3749 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3750 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3751 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3752
3753 case lltok::lbrace: {
3754 // ValID ::= '{' ConstVector '}'
3755 Lex.Lex();
3757 if (parseGlobalValueVector(Elts) ||
3758 parseToken(lltok::rbrace, "expected end of struct constant"))
3759 return true;
3760
3761 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3762 ID.UIntVal = Elts.size();
3763 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3764 Elts.size() * sizeof(Elts[0]));
3766 return false;
3767 }
3768 case lltok::less: {
3769 // ValID ::= '<' ConstVector '>' --> Vector.
3770 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3771 Lex.Lex();
3772 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3773
3775 LocTy FirstEltLoc = Lex.getLoc();
3776 if (parseGlobalValueVector(Elts) ||
3777 (isPackedStruct &&
3778 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3779 parseToken(lltok::greater, "expected end of constant"))
3780 return true;
3781
3782 if (isPackedStruct) {
3783 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3784 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3785 Elts.size() * sizeof(Elts[0]));
3786 ID.UIntVal = Elts.size();
3788 return false;
3789 }
3790
3791 if (Elts.empty())
3792 return error(ID.Loc, "constant vector must not be empty");
3793
3794 if (!Elts[0]->getType()->isIntegerTy() &&
3795 !Elts[0]->getType()->isFloatingPointTy() &&
3796 !Elts[0]->getType()->isPointerTy())
3797 return error(
3798 FirstEltLoc,
3799 "vector elements must have integer, pointer or floating point type");
3800
3801 // Verify that all the vector elements have the same type.
3802 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3803 if (Elts[i]->getType() != Elts[0]->getType())
3804 return error(FirstEltLoc, "vector element #" + Twine(i) +
3805 " is not of type '" +
3806 getTypeString(Elts[0]->getType()));
3807
3808 ID.ConstantVal = ConstantVector::get(Elts);
3809 ID.Kind = ValID::t_Constant;
3810 return false;
3811 }
3812 case lltok::lsquare: { // Array Constant
3813 Lex.Lex();
3815 LocTy FirstEltLoc = Lex.getLoc();
3816 if (parseGlobalValueVector(Elts) ||
3817 parseToken(lltok::rsquare, "expected end of array constant"))
3818 return true;
3819
3820 // Handle empty element.
3821 if (Elts.empty()) {
3822 // Use undef instead of an array because it's inconvenient to determine
3823 // the element type at this point, there being no elements to examine.
3824 ID.Kind = ValID::t_EmptyArray;
3825 return false;
3826 }
3827
3828 if (!Elts[0]->getType()->isFirstClassType())
3829 return error(FirstEltLoc, "invalid array element type: " +
3830 getTypeString(Elts[0]->getType()));
3831
3832 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3833
3834 // Verify all elements are correct type!
3835 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3836 if (Elts[i]->getType() != Elts[0]->getType())
3837 return error(FirstEltLoc, "array element #" + Twine(i) +
3838 " is not of type '" +
3839 getTypeString(Elts[0]->getType()));
3840 }
3841
3842 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3843 ID.Kind = ValID::t_Constant;
3844 return false;
3845 }
3846 case lltok::kw_c: // c "foo"
3847 Lex.Lex();
3848 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3849 false);
3850 if (parseToken(lltok::StringConstant, "expected string"))
3851 return true;
3852 ID.Kind = ValID::t_Constant;
3853 return false;
3854
3855 case lltok::kw_asm: {
3856 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3857 // STRINGCONSTANT
3858 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3859 Lex.Lex();
3860 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3861 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3862 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3863 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3864 parseStringConstant(ID.StrVal) ||
3865 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3866 parseToken(lltok::StringConstant, "expected constraint string"))
3867 return true;
3868 ID.StrVal2 = Lex.getStrVal();
3869 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3870 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3871 ID.Kind = ValID::t_InlineAsm;
3872 return false;
3873 }
3874
3876 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3877 Lex.Lex();
3878
3879 ValID Fn, Label;
3880
3881 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3882 parseValID(Fn, PFS) ||
3883 parseToken(lltok::comma,
3884 "expected comma in block address expression") ||
3885 parseValID(Label, PFS) ||
3886 parseToken(lltok::rparen, "expected ')' in block address expression"))
3887 return true;
3888
3890 return error(Fn.Loc, "expected function name in blockaddress");
3891 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3892 return error(Label.Loc, "expected basic block name in blockaddress");
3893
3894 // Try to find the function (but skip it if it's forward-referenced).
3895 GlobalValue *GV = nullptr;
3896 if (Fn.Kind == ValID::t_GlobalID) {
3897 GV = NumberedVals.get(Fn.UIntVal);
3898 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3899 GV = M->getNamedValue(Fn.StrVal);
3900 }
3901 Function *F = nullptr;
3902 if (GV) {
3903 // Confirm that it's actually a function with a definition.
3904 if (!isa<Function>(GV))
3905 return error(Fn.Loc, "expected function name in blockaddress");
3906 F = cast<Function>(GV);
3907 if (F->isDeclaration())
3908 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3909 }
3910
3911 if (!F) {
3912 // Make a global variable as a placeholder for this reference.
3913 GlobalValue *&FwdRef =
3914 ForwardRefBlockAddresses.insert(std::make_pair(
3915 std::move(Fn),
3916 std::map<ValID, GlobalValue *>()))
3917 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3918 .first->second;
3919 if (!FwdRef) {
3920 unsigned FwdDeclAS;
3921 if (ExpectedTy) {
3922 // If we know the type that the blockaddress is being assigned to,
3923 // we can use the address space of that type.
3924 if (!ExpectedTy->isPointerTy())
3925 return error(ID.Loc,
3926 "type of blockaddress must be a pointer and not '" +
3927 getTypeString(ExpectedTy) + "'");
3928 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3929 } else if (PFS) {
3930 // Otherwise, we default the address space of the current function.
3931 FwdDeclAS = PFS->getFunction().getAddressSpace();
3932 } else {
3933 llvm_unreachable("Unknown address space for blockaddress");
3934 }
3935 FwdRef = new GlobalVariable(
3936 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3937 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3938 }
3939
3940 ID.ConstantVal = FwdRef;
3941 ID.Kind = ValID::t_Constant;
3942 return false;
3943 }
3944
3945 // We found the function; now find the basic block. Don't use PFS, since we
3946 // might be inside a constant expression.
3947 BasicBlock *BB;
3948 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3949 if (Label.Kind == ValID::t_LocalID)
3950 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3951 else
3952 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3953 if (!BB)
3954 return error(Label.Loc, "referenced value is not a basic block");
3955 } else {
3956 if (Label.Kind == ValID::t_LocalID)
3957 return error(Label.Loc, "cannot take address of numeric label after "
3958 "the function is defined");
3959 BB = dyn_cast_or_null<BasicBlock>(
3960 F->getValueSymbolTable()->lookup(Label.StrVal));
3961 if (!BB)
3962 return error(Label.Loc, "referenced value is not a basic block");
3963 }
3964
3965 ID.ConstantVal = BlockAddress::get(F, BB);
3966 ID.Kind = ValID::t_Constant;
3967 return false;
3968 }
3969
3971 // ValID ::= 'dso_local_equivalent' @foo
3972 Lex.Lex();
3973
3974 ValID Fn;
3975
3976 if (parseValID(Fn, PFS))
3977 return true;
3978
3980 return error(Fn.Loc,
3981 "expected global value name in dso_local_equivalent");
3982
3983 // Try to find the function (but skip it if it's forward-referenced).
3984 GlobalValue *GV = nullptr;
3985 if (Fn.Kind == ValID::t_GlobalID) {
3986 GV = NumberedVals.get(Fn.UIntVal);
3987 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3988 GV = M->getNamedValue(Fn.StrVal);
3989 }
3990
3991 if (!GV) {
3992 // Make a placeholder global variable as a placeholder for this reference.
3993 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
3994 ? ForwardRefDSOLocalEquivalentIDs
3995 : ForwardRefDSOLocalEquivalentNames;
3996 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;
3997 if (!FwdRef) {
3998 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3999 GlobalValue::InternalLinkage, nullptr, "",
4001 }
4002
4003 ID.ConstantVal = FwdRef;
4004 ID.Kind = ValID::t_Constant;
4005 return false;
4006 }
4007
4008 if (!GV->getValueType()->isFunctionTy())
4009 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4010 "in dso_local_equivalent");
4011
4012 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4013 ID.Kind = ValID::t_Constant;
4014 return false;
4015 }
4016
4017 case lltok::kw_no_cfi: {
4018 // ValID ::= 'no_cfi' @foo
4019 Lex.Lex();
4020
4021 if (parseValID(ID, PFS))
4022 return true;
4023
4024 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4025 return error(ID.Loc, "expected global value name in no_cfi");
4026
4027 ID.NoCFI = true;
4028 return false;
4029 }
4030
4031 case lltok::kw_trunc:
4032 case lltok::kw_bitcast:
4034 case lltok::kw_inttoptr:
4035 case lltok::kw_ptrtoint: {
4036 unsigned Opc = Lex.getUIntVal();
4037 Type *DestTy = nullptr;
4038 Constant *SrcVal;
4039 Lex.Lex();
4040 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4041 parseGlobalTypeAndValue(SrcVal) ||
4042 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4043 parseType(DestTy) ||
4044 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4045 return true;
4046 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4047 return error(ID.Loc, "invalid cast opcode for cast from '" +
4048 getTypeString(SrcVal->getType()) + "' to '" +
4049 getTypeString(DestTy) + "'");
4051 SrcVal, DestTy);
4052 ID.Kind = ValID::t_Constant;
4053 return false;
4054 }
4056 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4058 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4059 case lltok::kw_udiv:
4060 return error(ID.Loc, "udiv constexprs are no longer supported");
4061 case lltok::kw_sdiv:
4062 return error(ID.Loc, "sdiv constexprs are no longer supported");
4063 case lltok::kw_urem:
4064 return error(ID.Loc, "urem constexprs are no longer supported");
4065 case lltok::kw_srem:
4066 return error(ID.Loc, "srem constexprs are no longer supported");
4067 case lltok::kw_fadd:
4068 return error(ID.Loc, "fadd constexprs are no longer supported");
4069 case lltok::kw_fsub:
4070 return error(ID.Loc, "fsub constexprs are no longer supported");
4071 case lltok::kw_fmul:
4072 return error(ID.Loc, "fmul constexprs are no longer supported");
4073 case lltok::kw_fdiv:
4074 return error(ID.Loc, "fdiv constexprs are no longer supported");
4075 case lltok::kw_frem:
4076 return error(ID.Loc, "frem constexprs are no longer supported");
4077 case lltok::kw_and:
4078 return error(ID.Loc, "and constexprs are no longer supported");
4079 case lltok::kw_or:
4080 return error(ID.Loc, "or constexprs are no longer supported");
4081 case lltok::kw_lshr:
4082 return error(ID.Loc, "lshr constexprs are no longer supported");
4083 case lltok::kw_ashr:
4084 return error(ID.Loc, "ashr constexprs are no longer supported");
4085 case lltok::kw_fneg:
4086 return error(ID.Loc, "fneg constexprs are no longer supported");
4087 case lltok::kw_select:
4088 return error(ID.Loc, "select constexprs are no longer supported");
4089 case lltok::kw_zext:
4090 return error(ID.Loc, "zext constexprs are no longer supported");
4091 case lltok::kw_sext:
4092 return error(ID.Loc, "sext constexprs are no longer supported");
4093 case lltok::kw_fptrunc:
4094 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4095 case lltok::kw_fpext:
4096 return error(ID.Loc, "fpext constexprs are no longer supported");
4097 case lltok::kw_uitofp:
4098 return error(ID.Loc, "uitofp constexprs are no longer supported");
4099 case lltok::kw_sitofp:
4100 return error(ID.Loc, "sitofp constexprs are no longer supported");
4101 case lltok::kw_fptoui:
4102 return error(ID.Loc, "fptoui constexprs are no longer supported");
4103 case lltok::kw_fptosi:
4104 return error(ID.Loc, "fptosi constexprs are no longer supported");
4105 case lltok::kw_icmp:
4106 case lltok::kw_fcmp: {
4107 unsigned PredVal, Opc = Lex.getUIntVal();
4108 Constant *Val0, *Val1;
4109 Lex.Lex();
4110 if (parseCmpPredicate(PredVal, Opc) ||
4111 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
4112 parseGlobalTypeAndValue(Val0) ||
4113 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
4114 parseGlobalTypeAndValue(Val1) ||
4115 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
4116 return true;
4117
4118 if (Val0->getType() != Val1->getType())
4119 return error(ID.Loc, "compare operands must have the same type");
4120
4121 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
4122
4123 if (Opc == Instruction::FCmp) {
4124 if (!Val0->getType()->isFPOrFPVectorTy())
4125 return error(ID.Loc, "fcmp requires floating point operands");
4126 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
4127 } else {
4128 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
4129 if (!Val0->getType()->isIntOrIntVectorTy() &&
4130 !Val0->getType()->isPtrOrPtrVectorTy())
4131 return error(ID.Loc, "icmp requires pointer or integer operands");
4132 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
4133 }
4134 ID.Kind = ValID::t_Constant;
4135 return false;
4136 }
4137
4138 // Binary Operators.
4139 case lltok::kw_add:
4140 case lltok::kw_sub:
4141 case lltok::kw_mul:
4142 case lltok::kw_shl:
4143 case lltok::kw_xor: {
4144 bool NUW = false;
4145 bool NSW = false;
4146 unsigned Opc = Lex.getUIntVal();
4147 Constant *Val0, *Val1;
4148 Lex.Lex();
4149 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4150 Opc == Instruction::Mul || Opc == Instruction::Shl) {
4151 if (EatIfPresent(lltok::kw_nuw))
4152 NUW = true;
4153 if (EatIfPresent(lltok::kw_nsw)) {
4154 NSW = true;
4155 if (EatIfPresent(lltok::kw_nuw))
4156 NUW = true;
4157 }
4158 }
4159 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4160 parseGlobalTypeAndValue(Val0) ||
4161 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4162 parseGlobalTypeAndValue(Val1) ||
4163 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4164 return true;
4165 if (Val0->getType() != Val1->getType())
4166 return error(ID.Loc, "operands of constexpr must have same type");
4167 // Check that the type is valid for the operator.
4168 if (!Val0->getType()->isIntOrIntVectorTy())
4169 return error(ID.Loc,
4170 "constexpr requires integer or integer vector operands");
4171 unsigned Flags = 0;
4174 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4175 ID.Kind = ValID::t_Constant;
4176 return false;
4177 }
4178
4179 case lltok::kw_splat: {
4180 Lex.Lex();
4181 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4182 return true;
4183 Constant *C;
4184 if (parseGlobalTypeAndValue(C))
4185 return true;
4186 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4187 return true;
4188
4189 ID.ConstantVal = C;
4191 return false;
4192 }
4193
4198 unsigned Opc = Lex.getUIntVal();
4200 bool InBounds = false;
4201 bool HasInRange = false;
4202 APSInt InRangeStart;
4203 APSInt InRangeEnd;
4204 Type *Ty;
4205 Lex.Lex();
4206
4207 if (Opc == Instruction::GetElementPtr) {
4208 InBounds = EatIfPresent(lltok::kw_inbounds);
4209 if (EatIfPresent(lltok::kw_inrange)) {
4210 if (parseToken(lltok::lparen, "expected '('"))
4211 return true;
4212 if (Lex.getKind() != lltok::APSInt)
4213 return tokError("expected integer");
4214 InRangeStart = Lex.getAPSIntVal();
4215 Lex.Lex();
4216 if (parseToken(lltok::comma, "expected ','"))
4217 return true;
4218 if (Lex.getKind() != lltok::APSInt)
4219 return tokError("expected integer");
4220 InRangeEnd = Lex.getAPSIntVal();
4221 Lex.Lex();
4222 if (parseToken(lltok::rparen, "expected ')'"))
4223 return true;
4224 HasInRange = true;
4225 }
4226 }
4227
4228 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4229 return true;
4230
4231 if (Opc == Instruction::GetElementPtr) {
4232 if (parseType(Ty) ||
4233 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4234 return true;
4235 }
4236
4237 if (parseGlobalValueVector(Elts) ||
4238 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4239 return true;
4240
4241 if (Opc == Instruction::GetElementPtr) {
4242 if (Elts.size() == 0 ||
4243 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4244 return error(ID.Loc, "base of getelementptr must be a pointer");
4245
4246 Type *BaseType = Elts[0]->getType();
4247 std::optional<ConstantRange> InRange;
4248 if (HasInRange) {
4249 unsigned IndexWidth =
4250 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4251 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4252 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4253 if (InRangeStart.sge(InRangeEnd))
4254 return error(ID.Loc, "expected end to be larger than start");
4255 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4256 }
4257
4258 unsigned GEPWidth =
4259 BaseType->isVectorTy()
4260 ? cast<FixedVectorType>(BaseType)->getNumElements()
4261 : 0;
4262
4263 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4264 for (Constant *Val : Indices) {
4265 Type *ValTy = Val->getType();
4266 if (!ValTy->isIntOrIntVectorTy())
4267 return error(ID.Loc, "getelementptr index must be an integer");
4268 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4269 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4270 if (GEPWidth && (ValNumEl != GEPWidth))
4271 return error(
4272 ID.Loc,
4273 "getelementptr vector index has a wrong number of elements");
4274 // GEPWidth may have been unknown because the base is a scalar,
4275 // but it is known now.
4276 GEPWidth = ValNumEl;
4277 }
4278 }
4279
4280 SmallPtrSet<Type*, 4> Visited;
4281 if (!Indices.empty() && !Ty->isSized(&Visited))
4282 return error(ID.Loc, "base element of getelementptr must be sized");
4283
4284 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4285 return error(ID.Loc, "invalid getelementptr indices");
4286
4287 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
4288 InBounds, InRange);
4289 } else if (Opc == Instruction::ShuffleVector) {
4290 if (Elts.size() != 3)
4291 return error(ID.Loc, "expected three operands to shufflevector");
4292 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4293 return error(ID.Loc, "invalid operands to shufflevector");
4295 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
4296 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4297 } else if (Opc == Instruction::ExtractElement) {
4298 if (Elts.size() != 2)
4299 return error(ID.Loc, "expected two operands to extractelement");
4300 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4301 return error(ID.Loc, "invalid extractelement operands");
4302 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4303 } else {
4304 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4305 if (Elts.size() != 3)
4306 return error(ID.Loc, "expected three operands to insertelement");
4307 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4308 return error(ID.Loc, "invalid insertelement operands");
4309 ID.ConstantVal =
4310 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4311 }
4312
4313 ID.Kind = ValID::t_Constant;
4314 return false;
4315 }
4316 }
4317
4318 Lex.Lex();
4319 return false;
4320}
4321
4322/// parseGlobalValue - parse a global value with the specified type.
4323bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4324 C = nullptr;
4325 ValID ID;
4326 Value *V = nullptr;
4327 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4328 convertValIDToValue(Ty, ID, V, nullptr);
4329 if (V && !(C = dyn_cast<Constant>(V)))
4330 return error(ID.Loc, "global values must be constants");
4331 return Parsed;
4332}
4333
4334bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4335 Type *Ty = nullptr;
4336 return parseType(Ty) || parseGlobalValue(Ty, V);
4337}
4338
4339bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4340 C = nullptr;
4341
4342 LocTy KwLoc = Lex.getLoc();
4343 if (!EatIfPresent(lltok::kw_comdat))
4344 return false;
4345
4346 if (EatIfPresent(lltok::lparen)) {
4347 if (Lex.getKind() != lltok::ComdatVar)
4348 return tokError("expected comdat variable");
4349 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4350 Lex.Lex();
4351 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4352 return true;
4353 } else {
4354 if (GlobalName.empty())
4355 return tokError("comdat cannot be unnamed");
4356 C = getComdat(std::string(GlobalName), KwLoc);
4357 }
4358
4359 return false;
4360}
4361
4362/// parseGlobalValueVector
4363/// ::= /*empty*/
4364/// ::= TypeAndValue (',' TypeAndValue)*
4365bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4366 // Empty list.
4367 if (Lex.getKind() == lltok::rbrace ||
4368 Lex.getKind() == lltok::rsquare ||
4369 Lex.getKind() == lltok::greater ||
4370 Lex.getKind() == lltok::rparen)
4371 return false;
4372
4373 do {
4374 // Let the caller deal with inrange.
4375 if (Lex.getKind() == lltok::kw_inrange)
4376 return false;
4377
4378 Constant *C;
4379 if (parseGlobalTypeAndValue(C))
4380 return true;
4381 Elts.push_back(C);
4382 } while (EatIfPresent(lltok::comma));
4383
4384 return false;
4385}
4386
4387bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4389 if (parseMDNodeVector(Elts))
4390 return true;
4391
4392 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4393 return false;
4394}
4395
4396/// MDNode:
4397/// ::= !{ ... }
4398/// ::= !7
4399/// ::= !DILocation(...)
4400bool LLParser::parseMDNode(MDNode *&N) {
4401 if (Lex.getKind() == lltok::MetadataVar)
4402 return parseSpecializedMDNode(N);
4403
4404 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4405}
4406
4407bool LLParser::parseMDNodeTail(MDNode *&N) {
4408 // !{ ... }
4409 if (Lex.getKind() == lltok::lbrace)
4410 return parseMDTuple(N);
4411
4412 // !42
4413 return parseMDNodeID(N);
4414}
4415
4416namespace {
4417
4418/// Structure to represent an optional metadata field.
4419template <class FieldTy> struct MDFieldImpl {
4420 typedef MDFieldImpl ImplTy;
4421 FieldTy Val;
4422 bool Seen;
4423
4424 void assign(FieldTy Val) {
4425 Seen = true;
4426 this->Val = std::move(Val);
4427 }
4428
4429 explicit MDFieldImpl(FieldTy Default)
4430 : Val(std::move(Default)), Seen(false) {}
4431};
4432
4433/// Structure to represent an optional metadata field that
4434/// can be of either type (A or B) and encapsulates the
4435/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4436/// to reimplement the specifics for representing each Field.
4437template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4438 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4439 FieldTypeA A;
4440 FieldTypeB B;
4441 bool Seen;
4442
4443 enum {
4444 IsInvalid = 0,
4445 IsTypeA = 1,
4446 IsTypeB = 2
4447 } WhatIs;
4448
4449 void assign(FieldTypeA A) {
4450 Seen = true;
4451 this->A = std::move(A);
4452 WhatIs = IsTypeA;
4453 }
4454
4455 void assign(FieldTypeB B) {
4456 Seen = true;
4457 this->B = std::move(B);
4458 WhatIs = IsTypeB;
4459 }
4460
4461 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4462 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4463 WhatIs(IsInvalid) {}
4464};
4465
4466struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4467 uint64_t Max;
4468
4469 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4470 : ImplTy(Default), Max(Max) {}
4471};
4472
4473struct LineField : public MDUnsignedField {
4474 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4475};
4476
4477struct ColumnField : public MDUnsignedField {
4478 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4479};
4480
4481struct DwarfTagField : public MDUnsignedField {
4482 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4483 DwarfTagField(dwarf::Tag DefaultTag)
4484 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4485};
4486
4487struct DwarfMacinfoTypeField : public MDUnsignedField {
4488 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4489 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4490 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4491};
4492
4493struct DwarfAttEncodingField : public MDUnsignedField {
4494 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4495};
4496
4497struct DwarfVirtualityField : public MDUnsignedField {
4498 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4499};
4500
4501struct DwarfLangField : public MDUnsignedField {
4502 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4503};
4504
4505struct DwarfCCField : public MDUnsignedField {
4506 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4507};
4508
4509struct EmissionKindField : public MDUnsignedField {
4510 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4511};
4512
4513struct NameTableKindField : public MDUnsignedField {
4514 NameTableKindField()
4515 : MDUnsignedField(
4516 0, (unsigned)
4517 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4518};
4519
4520struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4521 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4522};
4523
4524struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4525 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4526};
4527
4528struct MDAPSIntField : public MDFieldImpl<APSInt> {
4529 MDAPSIntField() : ImplTy(APSInt()) {}
4530};
4531
4532struct MDSignedField : public MDFieldImpl<int64_t> {
4533 int64_t Min = INT64_MIN;
4534 int64_t Max = INT64_MAX;
4535
4536 MDSignedField(int64_t Default = 0)
4537 : ImplTy(Default) {}
4538 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4539 : ImplTy(Default), Min(Min), Max(Max) {}
4540};
4541
4542struct MDBoolField : public MDFieldImpl<bool> {
4543 MDBoolField(bool Default = false) : ImplTy(Default) {}
4544};
4545
4546struct MDField : public MDFieldImpl<Metadata *> {
4547 bool AllowNull;
4548
4549 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4550};
4551
4552struct MDStringField : public MDFieldImpl<MDString *> {
4553 bool AllowEmpty;
4554 MDStringField(bool AllowEmpty = true)
4555 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4556};
4557
4558struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4559 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4560};
4561
4562struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4563 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4564};
4565
4566struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4567 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4568 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4569
4570 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4571 bool AllowNull = true)
4572 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4573
4574 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4575 bool isMDField() const { return WhatIs == IsTypeB; }
4576 int64_t getMDSignedValue() const {
4577 assert(isMDSignedField() && "Wrong field type");
4578 return A.Val;
4579 }
4580 Metadata *getMDFieldValue() const {
4581 assert(isMDField() && "Wrong field type");
4582 return B.Val;
4583 }
4584};
4585
4586} // end anonymous namespace
4587
4588namespace llvm {
4589
4590template <>
4591bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4592 if (Lex.getKind() != lltok::APSInt)
4593 return tokError("expected integer");
4594
4595 Result.assign(Lex.getAPSIntVal());
4596 Lex.Lex();
4597 return false;
4598}
4599
4600template <>
4601bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4602 MDUnsignedField &Result) {
4603 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4604 return tokError("expected unsigned integer");
4605
4606 auto &U = Lex.getAPSIntVal();
4607 if (U.ugt(Result.Max))
4608 return tokError("value for '" + Name + "' too large, limit is " +
4609 Twine(Result.Max));
4610 Result.assign(U.getZExtValue());
4611 assert(Result.Val <= Result.Max && "Expected value in range");
4612 Lex.Lex();
4613 return false;
4614}
4615
4616template <>
4617bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4618 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4619}
4620template <>
4621bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4622 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4623}
4624
4625template <>
4626bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4627 if (Lex.getKind() == lltok::APSInt)
4628 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4629
4630 if (Lex.getKind() != lltok::DwarfTag)
4631 return tokError("expected DWARF tag");
4632
4633 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4635 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4636 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4637
4638 Result.assign(Tag);
4639 Lex.Lex();
4640 return false;
4641}
4642
4643template <>
4644bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4645 DwarfMacinfoTypeField &Result) {
4646 if (Lex.getKind() == lltok::APSInt)
4647 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4648
4649 if (Lex.getKind() != lltok::DwarfMacinfo)
4650 return tokError("expected DWARF macinfo type");
4651
4652 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4653 if (Macinfo == dwarf::DW_MACINFO_invalid)
4654 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4655 Lex.getStrVal() + "'");
4656 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4657
4658 Result.assign(Macinfo);
4659 Lex.Lex();
4660 return false;
4661}
4662
4663template <>
4664bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4665 DwarfVirtualityField &Result) {
4666 if (Lex.getKind() == lltok::APSInt)
4667 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4668
4669 if (Lex.getKind() != lltok::DwarfVirtuality)
4670 return tokError("expected DWARF virtuality code");
4671
4672 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4673 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4674 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4675 Lex.getStrVal() + "'");
4676 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4677 Result.assign(Virtuality);
4678 Lex.Lex();
4679 return false;
4680}
4681
4682template <>
4683bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4684 if (Lex.getKind() == lltok::APSInt)
4685 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4686
4687 if (Lex.getKind() != lltok::DwarfLang)
4688 return tokError("expected DWARF language");
4689
4690 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4691 if (!Lang)
4692 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4693 "'");
4694 assert(Lang <= Result.Max && "Expected valid DWARF language");
4695 Result.assign(Lang);
4696 Lex.Lex();
4697 return false;
4698}
4699
4700template <>
4701bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4702 if (Lex.getKind() == lltok::APSInt)
4703 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4704
4705 if (Lex.getKind() != lltok::DwarfCC)
4706 return tokError("expected DWARF calling convention");
4707
4708 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4709 if (!CC)
4710 return tokError("invalid DWARF calling convention" + Twine(" '") +
4711 Lex.getStrVal() + "'");
4712 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4713 Result.assign(CC);
4714 Lex.Lex();
4715 return false;
4716}
4717
4718template <>
4719bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4720 EmissionKindField &Result) {
4721 if (Lex.getKind() == lltok::APSInt)
4722 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4723
4724 if (Lex.getKind() != lltok::EmissionKind)
4725 return tokError("expected emission kind");
4726
4727 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4728 if (!Kind)
4729 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4730 "'");
4731 assert(*Kind <= Result.Max && "Expected valid emission kind");
4732 Result.assign(*Kind);
4733 Lex.Lex();
4734 return false;
4735}
4736
4737template <>
4738bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4739 NameTableKindField &Result) {
4740 if (Lex.getKind() == lltok::APSInt)
4741 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4742
4743 if (Lex.getKind() != lltok::NameTableKind)
4744 return tokError("expected nameTable kind");
4745
4746 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4747 if (!Kind)
4748 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4749 "'");
4750 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4751 Result.assign((unsigned)*Kind);
4752 Lex.Lex();
4753 return false;
4754}
4755
4756template <>
4757bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4758 DwarfAttEncodingField &Result) {
4759 if (Lex.getKind() == lltok::APSInt)
4760 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4761
4762 if (Lex.getKind() != lltok::DwarfAttEncoding)
4763 return tokError("expected DWARF type attribute encoding");
4764
4765 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4766 if (!Encoding)
4767 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4768 Lex.getStrVal() + "'");
4769 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4770 Result.assign(Encoding);
4771 Lex.Lex();
4772 return false;
4773}
4774
4775/// DIFlagField
4776/// ::= uint32
4777/// ::= DIFlagVector
4778/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4779template <>
4780bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4781
4782 // parser for a single flag.
4783 auto parseFlag = [&](DINode::DIFlags &Val) {
4784 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4785 uint32_t TempVal = static_cast<uint32_t>(Val);
4786 bool Res = parseUInt32(TempVal);
4787 Val = static_cast<DINode::DIFlags>(TempVal);
4788 return Res;
4789 }
4790
4791 if (Lex.getKind() != lltok::DIFlag)
4792 return tokError("expected debug info flag");
4793
4794 Val = DINode::getFlag(Lex.getStrVal());
4795 if (!Val)
4796 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4797 "'");
4798 Lex.Lex();
4799 return false;
4800 };
4801
4802 // parse the flags and combine them together.
4803 DINode::DIFlags Combined = DINode::FlagZero;
4804 do {
4805 DINode::DIFlags Val;
4806 if (parseFlag(Val))
4807 return true;
4808 Combined |= Val;
4809 } while (EatIfPresent(lltok::bar));
4810
4811 Result.assign(Combined);
4812 return false;
4813}
4814
4815/// DISPFlagField
4816/// ::= uint32
4817/// ::= DISPFlagVector
4818/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4819template <>
4820bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4821
4822 // parser for a single flag.
4823 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4824 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4825 uint32_t TempVal = static_cast<uint32_t>(Val);
4826 bool Res = parseUInt32(TempVal);
4827 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4828 return Res;
4829 }
4830
4831 if (Lex.getKind() != lltok::DISPFlag)
4832 return tokError("expected debug info flag");
4833
4834 Val = DISubprogram::getFlag(Lex.getStrVal());
4835 if (!Val)
4836 return tokError(Twine("invalid subprogram debug info flag '") +
4837 Lex.getStrVal() + "'");
4838 Lex.Lex();
4839 return false;
4840 };
4841
4842 // parse the flags and combine them together.
4843 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4844 do {
4846 if (parseFlag(Val))
4847 return true;
4848 Combined |= Val;
4849 } while (EatIfPresent(lltok::bar));
4850
4851 Result.assign(Combined);
4852 return false;
4853}
4854
4855template <>
4856bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4857 if (Lex.getKind() != lltok::APSInt)
4858 return tokError("expected signed integer");
4859
4860 auto &S = Lex.getAPSIntVal();
4861 if (S < Result.Min)
4862 return tokError("value for '" + Name + "' too small, limit is " +
4863 Twine(Result.Min));
4864 if (S > Result.Max)
4865 return tokError("value for '" + Name + "' too large, limit is " +
4866 Twine(Result.Max));
4867 Result.assign(S.getExtValue());
4868 assert(Result.Val >= Result.Min && "Expected value in range");
4869 assert(Result.Val <= Result.Max && "Expected value in range");
4870 Lex.Lex();
4871 return false;
4872}
4873
4874template <>
4875bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4876 switch (Lex.getKind()) {
4877 default:
4878 return tokError("expected 'true' or 'false'");
4879 case lltok::kw_true:
4880 Result.assign(true);
4881 break;
4882 case lltok::kw_false:
4883 Result.assign(false);
4884 break;
4885 }
4886 Lex.Lex();
4887 return false;
4888}
4889
4890template <>
4891bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4892 if (Lex.getKind() == lltok::kw_null) {
4893 if (!Result.AllowNull)
4894 return tokError("'" + Name + "' cannot be null");
4895 Lex.Lex();
4896 Result.assign(nullptr);
4897 return false;
4898 }
4899
4900 Metadata *MD;
4901 if (parseMetadata(MD, nullptr))
4902 return true;
4903
4904 Result.assign(MD);
4905 return false;
4906}
4907
4908template <>
4909bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4910 MDSignedOrMDField &Result) {
4911 // Try to parse a signed int.
4912 if (Lex.getKind() == lltok::APSInt) {
4913 MDSignedField Res = Result.A;
4914 if (!parseMDField(Loc, Name, Res)) {
4915 Result.assign(Res);
4916 return false;
4917 }
4918 return true;
4919 }
4920
4921 // Otherwise, try to parse as an MDField.
4922 MDField Res = Result.B;
4923 if (!parseMDField(Loc, Name, Res)) {
4924 Result.assign(Res);
4925 return false;
4926 }
4927
4928 return true;
4929}
4930
4931template <>
4932bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4933 LocTy ValueLoc = Lex.getLoc();
4934 std::string S;
4935 if (parseStringConstant(S))
4936 return true;
4937
4938 if (!Result.AllowEmpty && S.empty())
4939 return error(ValueLoc, "'" + Name + "' cannot be empty");
4940
4941 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4942 return false;
4943}
4944
4945template <>
4946bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4948 if (parseMDNodeVector(MDs))
4949 return true;
4950
4951 Result.assign(std::move(MDs));
4952 return false;
4953}
4954
4955template <>
4956bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4957 ChecksumKindField &Result) {
4958 std::optional<DIFile::ChecksumKind> CSKind =
4960
4961 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4962 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4963 "'");
4964
4965 Result.assign(*CSKind);
4966 Lex.Lex();
4967 return false;
4968}
4969
4970} // end namespace llvm
4971
4972template <class ParserTy>
4973bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4974 do {
4975 if (Lex.getKind() != lltok::LabelStr)
4976 return tokError("expected field label here");
4977
4978 if (ParseField())
4979 return true;
4980 } while (EatIfPresent(lltok::comma));
4981
4982 return false;
4983}
4984
4985template <class ParserTy>
4986bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4987 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4988 Lex.Lex();
4989
4990 if (parseToken(lltok::lparen, "expected '(' here"))
4991 return true;
4992 if (Lex.getKind() != lltok::rparen)
4993 if (parseMDFieldsImplBody(ParseField))
4994 return true;
4995
4996 ClosingLoc = Lex.getLoc();
4997 return parseToken(lltok::rparen, "expected ')' here");
4998}
4999
5000template <class FieldTy>
5001bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5002 if (Result.Seen)
5003 return tokError("field '" + Name + "' cannot be specified more than once");
5004
5005 LocTy Loc = Lex.getLoc();
5006 Lex.Lex();
5007 return parseMDField(Loc, Name, Result);
5008}
5009
5010bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5011 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5012
5013#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5014 if (Lex.getStrVal() == #CLASS) \
5015 return parse##CLASS(N, IsDistinct);
5016#include "llvm/IR/Metadata.def"
5017
5018 return tokError("expected metadata type");
5019}
5020
5021#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5022#define NOP_FIELD(NAME, TYPE, INIT)
5023#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5024 if (!NAME.Seen) \
5025 return error(ClosingLoc, "missing required field '" #NAME "'");
5026#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5027 if (Lex.getStrVal() == #NAME) \
5028 return parseMDField(#NAME, NAME);
5029#define PARSE_MD_FIELDS() \
5030 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5031 do { \
5032 LocTy ClosingLoc; \
5033 if (parseMDFieldsImpl( \
5034 [&]() -> bool { \
5035 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5036 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5037 "'"); \
5038 }, \
5039 ClosingLoc)) \
5040 return true; \
5041 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5042 } while (false)
5043#define GET_OR_DISTINCT(CLASS, ARGS) \
5044 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5045
5046/// parseDILocationFields:
5047/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5048/// isImplicitCode: true)
5049bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5050#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5051 OPTIONAL(line, LineField, ); \
5052 OPTIONAL(column, ColumnField, ); \
5053 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5054 OPTIONAL(inlinedAt, MDField, ); \
5055 OPTIONAL(isImplicitCode, MDBoolField, (false));
5057#undef VISIT_MD_FIELDS
5058
5059 Result =
5060 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5061 inlinedAt.Val, isImplicitCode.Val));
5062 return false;
5063}
5064
5065/// parseDIAssignID:
5066/// ::= distinct !DIAssignID()
5067bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5068 if (!IsDistinct)
5069 return Lex.Error("missing 'distinct', required for !DIAssignID()");
5070
5071 Lex.Lex();
5072
5073 // Now eat the parens.
5074 if (parseToken(lltok::lparen, "expected '(' here"))
5075 return true;
5076 if (parseToken(lltok::rparen, "expected ')' here"))
5077 return true;
5078
5080 return false;
5081}
5082
5083/// parseGenericDINode:
5084/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5085bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5086#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5087 REQUIRED(tag, DwarfTagField, ); \
5088 OPTIONAL(header, MDStringField, ); \
5089 OPTIONAL(operands, MDFieldList, );
5091#undef VISIT_MD_FIELDS
5092
5094 (Context, tag.Val, header.Val, operands.Val));
5095 return false;
5096}
5097
5098/// parseDISubrange:
5099/// ::= !DISubrange(count: 30, lowerBound: 2)
5100/// ::= !DISubrange(count: !node, lowerBound: 2)
5101/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5102bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5103#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5104 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5105 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5106 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5107 OPTIONAL(stride, MDSignedOrMDField, );
5109#undef VISIT_MD_FIELDS
5110
5111 Metadata *Count = nullptr;
5112 Metadata *LowerBound = nullptr;
5113 Metadata *UpperBound = nullptr;
5114 Metadata *Stride = nullptr;
5115
5116 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5117 if (Bound.isMDSignedField())
5119 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5120 if (Bound.isMDField())
5121 return Bound.getMDFieldValue();
5122 return nullptr;
5123 };
5124
5125 Count = convToMetadata(count);
5126 LowerBound = convToMetadata(lowerBound);
5127 UpperBound = convToMetadata(upperBound);
5128 Stride = convToMetadata(stride);
5129
5131 (Context, Count, LowerBound, UpperBound, Stride));
5132
5133 return false;
5134}
5135
5136/// parseDIGenericSubrange:
5137/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5138/// !node3)
5139bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5140#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5141 OPTIONAL(count, MDSignedOrMDField, ); \
5142 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5143 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5144 OPTIONAL(stride, MDSignedOrMDField, );
5146#undef VISIT_MD_FIELDS
5147
5148 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5149 if (Bound.isMDSignedField())
5150 return DIExpression::get(
5151 Context, {dwarf::DW_OP_consts,
5152 static_cast<uint64_t>(Bound.getMDSignedValue())});
5153 if (Bound.isMDField())
5154 return Bound.getMDFieldValue();
5155 return nullptr;
5156 };
5157
5158 Metadata *Count = ConvToMetadata(count);
5159 Metadata *LowerBound = ConvToMetadata(lowerBound);
5160 Metadata *UpperBound = ConvToMetadata(upperBound);
5161 Metadata *Stride = ConvToMetadata(stride);
5162
5164 (Context, Count, LowerBound, UpperBound, Stride));
5165
5166 return false;
5167}
5168
5169/// parseDIEnumerator:
5170/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5171bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5172#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5173 REQUIRED(name, MDStringField, ); \
5174 REQUIRED(value, MDAPSIntField, ); \
5175 OPTIONAL(isUnsigned, MDBoolField, (false));
5177#undef VISIT_MD_FIELDS
5178
5179 if (isUnsigned.Val && value.Val.isNegative())
5180 return tokError("unsigned enumerator with negative value");
5181
5182 APSInt Value(value.Val);
5183 // Add a leading zero so that unsigned values with the msb set are not
5184 // mistaken for negative values when used for signed enumerators.
5185 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5186 Value = Value.zext(Value.getBitWidth() + 1);
5187
5188 Result =
5189 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5190
5191 return false;
5192}
5193
5194/// parseDIBasicType:
5195/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5196/// encoding: DW_ATE_encoding, flags: 0)
5197bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5198#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5199 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5200 OPTIONAL(name, MDStringField, ); \
5201 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5202 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5203 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5204 OPTIONAL(flags, DIFlagField, );
5206#undef VISIT_MD_FIELDS
5207
5208 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
5209 align.Val, encoding.Val, flags.Val));
5210 return false;
5211}
5212
5213/// parseDIStringType:
5214/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5215bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5216#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5217 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5218 OPTIONAL(name, MDStringField, ); \
5219 OPTIONAL(stringLength, MDField, ); \
5220 OPTIONAL(stringLengthExpression, MDField, ); \
5221 OPTIONAL(stringLocationExpression, MDField, ); \
5222 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5223 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5224 OPTIONAL(encoding, DwarfAttEncodingField, );
5226#undef VISIT_MD_FIELDS
5227
5230 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5231 stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
5232 return false;
5233}
5234
5235/// parseDIDerivedType:
5236/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5237/// line: 7, scope: !1, baseType: !2, size: 32,
5238/// align: 32, offset: 0, flags: 0, extraData: !3,
5239/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5240/// ptrAuthIsAddressDiscriminated: true,
5241/// ptrAuthExtraDiscriminator: 0x1234,
5242/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5243/// )
5244bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5245#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5246 REQUIRED(tag, DwarfTagField, ); \
5247 OPTIONAL(name, MDStringField, ); \
5248 OPTIONAL(file, MDField, ); \
5249 OPTIONAL(line, LineField, ); \
5250 OPTIONAL(scope, MDField, ); \
5251 REQUIRED(baseType, MDField, ); \
5252 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5253 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5254 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5255 OPTIONAL(flags, DIFlagField, ); \
5256 OPTIONAL(extraData, MDField, ); \
5257 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5258 OPTIONAL(annotations, MDField, ); \
5259 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5260 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5261 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5262 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5263 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5265#undef VISIT_MD_FIELDS
5266
5267 std::optional<unsigned> DWARFAddressSpace;
5268 if (dwarfAddressSpace.Val != UINT32_MAX)
5269 DWARFAddressSpace = dwarfAddressSpace.Val;
5270 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5271 if (ptrAuthKey.Val)
5272 PtrAuthData.emplace(
5273 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5274 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5275 ptrAuthAuthenticatesNullValues.Val);
5276
5278 (Context, tag.Val, name.Val, file.Val, line.Val,
5279 scope.Val, baseType.Val, size.Val, align.Val,
5280 offset.Val, DWARFAddressSpace, PtrAuthData,
5281 flags.Val, extraData.Val, annotations.Val));
5282 return false;
5283}
5284
5285bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5286#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5287 REQUIRED(tag, DwarfTagField, ); \
5288 OPTIONAL(name, MDStringField, ); \
5289 OPTIONAL(file, MDField, ); \
5290 OPTIONAL(line, LineField, ); \
5291 OPTIONAL(scope, MDField, ); \
5292 OPTIONAL(baseType, MDField, ); \
5293 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5294 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5295 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5296 OPTIONAL(flags, DIFlagField, ); \
5297 OPTIONAL(elements, MDField, ); \
5298 OPTIONAL(runtimeLang, DwarfLangField, ); \
5299 OPTIONAL(vtableHolder, MDField, ); \
5300 OPTIONAL(templateParams, MDField, ); \
5301 OPTIONAL(identifier, MDStringField, ); \
5302 OPTIONAL(discriminator, MDField, ); \
5303 OPTIONAL(dataLocation, MDField, ); \
5304 OPTIONAL(associated, MDField, ); \
5305 OPTIONAL(allocated, MDField, ); \
5306 OPTIONAL(rank, MDSignedOrMDField, ); \
5307 OPTIONAL(annotations, MDField, );
5309#undef VISIT_MD_FIELDS
5310
5311 Metadata *Rank = nullptr;
5312 if (rank.isMDSignedField())
5314 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5315 else if (rank.isMDField())
5316 Rank = rank.getMDFieldValue();
5317
5318 // If this has an identifier try to build an ODR type.
5319 if (identifier.Val)
5320 if (auto *CT = DICompositeType::buildODRType(
5321 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5322 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
5323 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5324 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5325 Rank, annotations.Val)) {
5326 Result = CT;
5327 return false;
5328 }
5329
5330 // Create a new node, and save it in the context if it belongs in the type
5331 // map.
5334 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5335 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5336 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5337 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5338 annotations.Val));
5339 return false;
5340}
5341
5342bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5343#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5344 OPTIONAL(flags, DIFlagField, ); \
5345 OPTIONAL(cc, DwarfCCField, ); \
5346 REQUIRED(types, MDField, );
5348#undef VISIT_MD_FIELDS
5349
5351 (Context, flags.Val, cc.Val, types.Val));
5352 return false;
5353}
5354
5355/// parseDIFileType:
5356/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5357/// checksumkind: CSK_MD5,
5358/// checksum: "000102030405060708090a0b0c0d0e0f",
5359/// source: "source file contents")
5360bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5361 // The default constructed value for checksumkind is required, but will never
5362 // be used, as the parser checks if the field was actually Seen before using
5363 // the Val.
5364#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5365 REQUIRED(filename, MDStringField, ); \
5366 REQUIRED(directory, MDStringField, ); \
5367 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5368 OPTIONAL(checksum, MDStringField, ); \
5369 OPTIONAL(source, MDStringField, );
5371#undef VISIT_MD_FIELDS
5372
5373 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5374 if (checksumkind.Seen && checksum.Seen)
5375 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5376 else if (checksumkind.Seen || checksum.Seen)
5377 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
5378
5379 MDString *Source = nullptr;
5380 if (source.Seen)
5381 Source = source.Val;
5383 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5384 return false;
5385}
5386
5387/// parseDICompileUnit:
5388/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5389/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5390/// splitDebugFilename: "abc.debug",
5391/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5392/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5393/// sysroot: "/", sdk: "MacOSX.sdk")
5394bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5395 if (!IsDistinct)
5396 return Lex.Error("missing 'distinct', required for !DICompileUnit");
5397
5398#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5399 REQUIRED(language, DwarfLangField, ); \
5400 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5401 OPTIONAL(producer, MDStringField, ); \
5402 OPTIONAL(isOptimized, MDBoolField, ); \
5403 OPTIONAL(flags, MDStringField, ); \
5404 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5405 OPTIONAL(splitDebugFilename, MDStringField, ); \
5406 OPTIONAL(emissionKind, EmissionKindField, ); \
5407 OPTIONAL(enums, MDField, ); \
5408 OPTIONAL(retainedTypes, MDField, ); \
5409 OPTIONAL(globals, MDField, ); \
5410 OPTIONAL(imports, MDField, ); \
5411 OPTIONAL(macros, MDField, ); \
5412 OPTIONAL(dwoId, MDUnsignedField, ); \
5413 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5414 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5415 OPTIONAL(nameTableKind, NameTableKindField, ); \
5416 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5417 OPTIONAL(sysroot, MDStringField, ); \
5418 OPTIONAL(sdk, MDStringField, );
5420#undef VISIT_MD_FIELDS
5421
5423 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5424 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5425 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5426 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5427 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5428 return false;
5429}
5430
5431/// parseDISubprogram:
5432/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5433/// file: !1, line: 7, type: !2, isLocal: false,
5434/// isDefinition: true, scopeLine: 8, containingType: !3,
5435/// virtuality: DW_VIRTUALTIY_pure_virtual,
5436/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5437/// spFlags: 10, isOptimized: false, templateParams: !4,
5438/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5439/// annotations: !8)
5440bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5441 auto Loc = Lex.getLoc();
5442#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5443 OPTIONAL(scope, MDField, ); \
5444 OPTIONAL(name, MDStringField, ); \
5445 OPTIONAL(linkageName, MDStringField, ); \
5446 OPTIONAL(file, MDField, ); \
5447 OPTIONAL(line, LineField, ); \
5448 OPTIONAL(type, MDField, ); \
5449 OPTIONAL(isLocal, MDBoolField, ); \
5450 OPTIONAL(isDefinition, MDBoolField, (true)); \
5451 OPTIONAL(scopeLine, LineField, ); \
5452 OPTIONAL(containingType, MDField, ); \
5453 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5454 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5455 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5456 OPTIONAL(flags, DIFlagField, ); \
5457 OPTIONAL(spFlags, DISPFlagField, ); \
5458 OPTIONAL(isOptimized, MDBoolField, ); \
5459 OPTIONAL(unit, MDField, ); \
5460 OPTIONAL(templateParams, MDField, ); \
5461 OPTIONAL(declaration, MDField, ); \
5462 OPTIONAL(retainedNodes, MDField, ); \
5463 OPTIONAL(thrownTypes, MDField, ); \
5464 OPTIONAL(annotations, MDField, ); \
5465 OPTIONAL(targetFuncName, MDStringField, );
5467#undef VISIT_MD_FIELDS
5468
5469 // An explicit spFlags field takes precedence over individual fields in
5470 // older IR versions.
5471 DISubprogram::DISPFlags SPFlags =
5472 spFlags.Seen ? spFlags.Val
5473 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5474 isOptimized.Val, virtuality.Val);
5475 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5476 return Lex.Error(
5477 Loc,
5478 "missing 'distinct', required for !DISubprogram that is a Definition");
5481 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5482 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5483 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5484 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5485 targetFuncName.Val));
5486 return false;
5487}
5488
5489/// parseDILexicalBlock:
5490/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5491bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5492#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5493 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5494 OPTIONAL(file, MDField, ); \
5495 OPTIONAL(line, LineField, ); \
5496 OPTIONAL(column, ColumnField, );
5498#undef VISIT_MD_FIELDS
5499
5501 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5502 return false;
5503}
5504
5505/// parseDILexicalBlockFile:
5506/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5507bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5508#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5509 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5510 OPTIONAL(file, MDField, ); \
5511 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5513#undef VISIT_MD_FIELDS
5514
5516 (Context, scope.Val, file.Val, discriminator.Val));
5517 return false;
5518}
5519
5520/// parseDICommonBlock:
5521/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5522bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5523#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5524 REQUIRED(scope, MDField, ); \
5525 OPTIONAL(declaration, MDField, ); \
5526 OPTIONAL(name, MDStringField, ); \
5527 OPTIONAL(file, MDField, ); \
5528 OPTIONAL(line, LineField, );
5530#undef VISIT_MD_FIELDS
5531
5533 (Context, scope.Val, declaration.Val, name.Val,
5534 file.Val, line.Val));
5535 return false;
5536}
5537
5538/// parseDINamespace:
5539/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5540bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5541#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5542 REQUIRED(scope, MDField, ); \
5543 OPTIONAL(name, MDStringField, ); \
5544 OPTIONAL(exportSymbols, MDBoolField, );
5546#undef VISIT_MD_FIELDS
5547
5549 (Context, scope.Val, name.Val, exportSymbols.Val));
5550 return false;
5551}
5552
5553/// parseDIMacro:
5554/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5555/// "SomeValue")
5556bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5557#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5558 REQUIRED(type, DwarfMacinfoTypeField, ); \
5559 OPTIONAL(line, LineField, ); \
5560 REQUIRED(name, MDStringField, ); \
5561 OPTIONAL(value, MDStringField, );
5563#undef VISIT_MD_FIELDS
5564
5566 (Context, type.Val, line.Val, name.Val, value.Val));
5567 return false;
5568}
5569
5570/// parseDIMacroFile:
5571/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5572bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5573#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5574 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5575 OPTIONAL(line, LineField, ); \
5576 REQUIRED(file, MDField, ); \
5577 OPTIONAL(nodes, MDField, );
5579#undef VISIT_MD_FIELDS
5580
5582 (Context, type.Val, line.Val, file.Val, nodes.Val));
5583 return false;
5584}
5585
5586/// parseDIModule:
5587/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5588/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5589/// file: !1, line: 4, isDecl: false)
5590bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5591#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5592 REQUIRED(scope, MDField, ); \
5593 REQUIRED(name, MDStringField, ); \
5594 OPTIONAL(configMacros, MDStringField, ); \
5595 OPTIONAL(includePath, MDStringField, ); \
5596 OPTIONAL(apinotes, MDStringField, ); \
5597 OPTIONAL(file, MDField, ); \
5598 OPTIONAL(line, LineField, ); \
5599 OPTIONAL(isDecl, MDBoolField, );
5601#undef VISIT_MD_FIELDS
5602
5603 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5604 configMacros.Val, includePath.Val,
5605 apinotes.Val, line.Val, isDecl.Val));
5606 return false;
5607}
5608
5609/// parseDITemplateTypeParameter:
5610/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5611bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5612#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5613 OPTIONAL(name, MDStringField, ); \
5614 REQUIRED(type, MDField, ); \
5615 OPTIONAL(defaulted, MDBoolField, );
5617#undef VISIT_MD_FIELDS
5618
5620 (Context, name.Val, type.Val, defaulted.Val));
5621 return false;
5622}
5623
5624/// parseDITemplateValueParameter:
5625/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5626/// name: "V", type: !1, defaulted: false,
5627/// value: i32 7)
5628bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5629#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5630 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5631 OPTIONAL(name, MDStringField, ); \
5632 OPTIONAL(type, MDField, ); \
5633 OPTIONAL(defaulted, MDBoolField, ); \
5634 REQUIRED(value, MDField, );
5635
5637#undef VISIT_MD_FIELDS
5638
5641 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5642 return false;
5643}
5644
5645/// parseDIGlobalVariable:
5646/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5647/// file: !1, line: 7, type: !2, isLocal: false,
5648/// isDefinition: true, templateParams: !3,
5649/// declaration: !4, align: 8)
5650bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5651#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5652 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5653 OPTIONAL(scope, MDField, ); \
5654 OPTIONAL(linkageName, MDStringField, ); \
5655 OPTIONAL(file, MDField, ); \
5656 OPTIONAL(line, LineField, ); \
5657 OPTIONAL(type, MDField, ); \
5658 OPTIONAL(isLocal, MDBoolField, ); \
5659 OPTIONAL(isDefinition, MDBoolField, (true)); \
5660 OPTIONAL(templateParams, MDField, ); \
5661 OPTIONAL(declaration, MDField, ); \
5662 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5663 OPTIONAL(annotations, MDField, );
5665#undef VISIT_MD_FIELDS
5666
5667 Result =
5669 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5670 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5671 declaration.Val, templateParams.Val, align.Val,
5672 annotations.Val));
5673 return false;
5674}
5675
5676/// parseDILocalVariable:
5677/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5678/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5679/// align: 8)
5680/// ::= !DILocalVariable(scope: !0, name: "foo",
5681/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5682/// align: 8)
5683bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5684#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5685 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5686 OPTIONAL(name, MDStringField, ); \
5687 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5688 OPTIONAL(file, MDField, ); \
5689 OPTIONAL(line, LineField, ); \
5690 OPTIONAL(type, MDField, ); \
5691 OPTIONAL(flags, DIFlagField, ); \
5692 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5693 OPTIONAL(annotations, MDField, );
5695#undef VISIT_MD_FIELDS
5696
5698 (Context, scope.Val, name.Val, file.Val, line.Val,
5699 type.Val, arg.Val, flags.Val, align.Val,
5700 annotations.Val));
5701 return false;
5702}
5703
5704/// parseDILabel:
5705/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5706bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5707#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5708 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5709 REQUIRED(name, MDStringField, ); \
5710 REQUIRED(file, MDField, ); \
5711 REQUIRED(line, LineField, );
5713#undef VISIT_MD_FIELDS
5714
5716 (Context, scope.Val, name.Val, file.Val, line.Val));
5717 return false;
5718}
5719
5720/// parseDIExpression:
5721/// ::= !DIExpression(0, 7, -1)
5722bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5723 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5724 Lex.Lex();
5725
5726 if (parseToken(lltok::lparen, "expected '(' here"))
5727 return true;
5728
5730 if (Lex.getKind() != lltok::rparen)
5731 do {
5732 if (Lex.getKind() == lltok::DwarfOp) {
5733 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5734 Lex.Lex();
5735 Elements.push_back(Op);
5736 continue;
5737 }
5738 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5739 }
5740
5741 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5742 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5743 Lex.Lex();
5744 Elements.push_back(Op);
5745 continue;
5746 }
5747 return tokError(Twine("invalid DWARF attribute encoding '") +
5748 Lex.getStrVal() + "'");
5749 }
5750
5751 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5752 return tokError("expected unsigned integer");
5753
5754 auto &U = Lex.getAPSIntVal();
5755 if (U.ugt(UINT64_MAX))
5756 return tokError("element too large, limit is " + Twine(UINT64_MAX));
5757 Elements.push_back(U.getZExtValue());
5758 Lex.Lex();
5759 } while (EatIfPresent(lltok::comma));
5760
5761 if (parseToken(lltok::rparen, "expected ')' here"))
5762 return true;
5763
5764 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5765 return false;
5766}
5767
5768/// ParseDIArgList:
5769/// ::= !DIArgList(i32 7, i64 %0)
5770bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
5771 assert(PFS && "Expected valid function state");
5772 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5773 Lex.Lex();
5774
5775 if (parseToken(lltok::lparen, "expected '(' here"))
5776 return true;
5777
5779 if (Lex.getKind() != lltok::rparen)
5780 do {
5781 Metadata *MD;
5782 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5783 return true;
5784 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5785 } while (EatIfPresent(lltok::comma));
5786
5787 if (parseToken(lltok::rparen, "expected ')' here"))
5788 return true;
5789
5790 MD = DIArgList::get(Context, Args);
5791 return false;
5792}
5793
5794/// parseDIGlobalVariableExpression:
5795/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5796bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5797 bool IsDistinct) {
5798#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5799 REQUIRED(var, MDField, ); \
5800 REQUIRED(expr, MDField, );
5802#undef VISIT_MD_FIELDS
5803
5804 Result =
5805 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5806 return false;
5807}
5808
5809/// parseDIObjCProperty:
5810/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5811/// getter: "getFoo", attributes: 7, type: !2)
5812bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5813#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5814 OPTIONAL(name, MDStringField, ); \
5815 OPTIONAL(file, MDField, ); \
5816 OPTIONAL(line, LineField, ); \
5817 OPTIONAL(setter, MDStringField, ); \
5818 OPTIONAL(getter, MDStringField, ); \
5819 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5820 OPTIONAL(type, MDField, );
5822#undef VISIT_MD_FIELDS
5823
5825 (Context, name.Val, file.Val, line.Val, setter.Val,
5826 getter.Val, attributes.Val, type.Val));
5827 return false;
5828}
5829
5830/// parseDIImportedEntity:
5831/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5832/// line: 7, name: "foo", elements: !2)
5833bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5834#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5835 REQUIRED(tag, DwarfTagField, ); \
5836 REQUIRED(scope, MDField, ); \
5837 OPTIONAL(entity, MDField, ); \
5838 OPTIONAL(file, MDField, ); \
5839 OPTIONAL(line, LineField, ); \
5840 OPTIONAL(name, MDStringField, ); \
5841 OPTIONAL(elements, MDField, );
5843#undef VISIT_MD_FIELDS
5844
5846 (Context, tag.Val, scope.Val, entity.Val, file.Val,
5847 line.Val, name.Val, elements.Val));
5848 return false;
5849}
5850
5851#undef PARSE_MD_FIELD
5852#undef NOP_FIELD
5853#undef REQUIRE_FIELD
5854#undef DECLARE_FIELD
5855
5856/// parseMetadataAsValue
5857/// ::= metadata i32 %local
5858/// ::= metadata i32 @global
5859/// ::= metadata i32 7
5860/// ::= metadata !0
5861/// ::= metadata !{...}
5862/// ::= metadata !"string"
5863bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5864 // Note: the type 'metadata' has already been parsed.
5865 Metadata *MD;
5866 if (parseMetadata(MD, &PFS))
5867 return true;
5868
5869 V = MetadataAsValue::get(Context, MD);
5870 return false;
5871}
5872
5873/// parseValueAsMetadata
5874/// ::= i32 %local
5875/// ::= i32 @global
5876/// ::= i32 7
5877bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5878 PerFunctionState *PFS) {
5879 Type *Ty;
5880 LocTy Loc;
5881 if (parseType(Ty, TypeMsg, Loc))
5882 return true;
5883 if (Ty->isMetadataTy())
5884 return error(Loc, "invalid metadata-value-metadata roundtrip");
5885
5886 Value *V;
5887 if (parseValue(Ty, V, PFS))
5888 return true;
5889
5890 MD = ValueAsMetadata::get(V);
5891 return false;
5892}
5893
5894/// parseMetadata
5895/// ::= i32 %local
5896/// ::= i32 @global
5897/// ::= i32 7
5898/// ::= !42
5899/// ::= !{...}
5900/// ::= !"string"
5901/// ::= !DILocation(...)
5902bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5903 if (Lex.getKind() == lltok::MetadataVar) {
5904 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5905 // so parsing this requires a Function State.
5906 if (Lex.getStrVal() == "DIArgList") {
5907 Metadata *AL;
5908 if (parseDIArgList(AL, PFS))
5909 return true;
5910 MD = AL;
5911 return false;
5912 }
5913 MDNode *N;
5914 if (parseSpecializedMDNode(N)) {
5915 return true;
5916 }
5917 MD = N;
5918 return false;
5919 }
5920
5921 // ValueAsMetadata:
5922 // <type> <value>
5923 if (Lex.getKind() != lltok::exclaim)
5924 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5925
5926 // '!'.
5927 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5928 Lex.Lex();
5929
5930 // MDString:
5931 // ::= '!' STRINGCONSTANT
5932 if (Lex.getKind() == lltok::StringConstant) {
5933 MDString *S;
5934 if (parseMDString(S))
5935 return true;
5936 MD = S;
5937 return false;
5938 }
5939
5940 // MDNode:
5941 // !{ ... }
5942 // !7
5943 MDNode *N;
5944 if (parseMDNodeTail(N))
5945 return true;
5946 MD = N;
5947 return false;
5948}
5949
5950//===----------------------------------------------------------------------===//
5951// Function Parsing.
5952//===----------------------------------------------------------------------===//
5953
5954bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5955 PerFunctionState *PFS) {
5956 if (Ty->isFunctionTy())
5957 return error(ID.Loc, "functions are not values, refer to them as pointers");
5958
5959 switch (ID.Kind) {
5960 case ValID::t_LocalID:
5961 if (!PFS)
5962 return error(ID.Loc, "invalid use of function-local name");
5963 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
5964 return V == nullptr;
5965 case ValID::t_LocalName:
5966 if (!PFS)
5967 return error(ID.Loc, "invalid use of function-local name");
5968 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
5969 return V == nullptr;
5970 case ValID::t_InlineAsm: {
5971 if (!ID.FTy)
5972 return error(ID.Loc, "invalid type for inline asm constraint string");
5973 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
5974 return error(ID.Loc, toString(std::move(Err)));
5975 V = InlineAsm::get(
5976 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5977 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5978 return false;
5979 }
5981 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
5982 if (V && ID.NoCFI)
5983 V = NoCFIValue::get(cast<GlobalValue>(V));
5984 return V == nullptr;
5985 case ValID::t_GlobalID:
5986 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
5987 if (V && ID.NoCFI)
5988 V = NoCFIValue::get(cast<GlobalValue>(V));
5989 return V == nullptr;
5990 case ValID::t_APSInt:
5991 if (!Ty->isIntegerTy())
5992 return error(ID.Loc, "integer constant must have integer type");
5993 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5994 V = ConstantInt::get(Context, ID.APSIntVal);
5995 return false;
5996 case ValID::t_APFloat:
5997 if (!Ty->isFloatingPointTy() ||
5998 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5999 return error(ID.Loc, "floating point constant invalid for type");
6000
6001 // The lexer has no type info, so builds all half, bfloat, float, and double
6002 // FP constants as double. Fix this here. Long double does not need this.
6003 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6004 // Check for signaling before potentially converting and losing that info.
6005 bool IsSNAN = ID.APFloatVal.isSignaling();
6006 bool Ignored;
6007 if (Ty->isHalfTy())
6009 &Ignored);
6010 else if (Ty->isBFloatTy())
6011 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6012 &Ignored);
6013 else if (Ty->isFloatTy())
6015 &Ignored);
6016 if (IsSNAN) {
6017 // The convert call above may quiet an SNaN, so manufacture another
6018 // SNaN. The bitcast works because the payload (significand) parameter
6019 // is truncated to fit.
6020 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6021 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6022 ID.APFloatVal.isNegative(), &Payload);
6023 }
6024 }
6025 V = ConstantFP::get(Context, ID.APFloatVal);
6026
6027 if (V->getType() != Ty)
6028 return error(ID.Loc, "floating point constant does not have type '" +
6029 getTypeString(Ty) + "'");
6030
6031 return false;
6032 case ValID::t_Null:
6033 if (!Ty->isPointerTy())
6034 return error(ID.Loc, "null must be a pointer type");
6035 V = ConstantPointerNull::get(cast<PointerType>(Ty));
6036 return false;
6037 case ValID::t_Undef:
6038 // FIXME: LabelTy should not be a first-class type.
6039 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6040 return error(ID.Loc, "invalid type for undef constant");
6041 V = UndefValue::get(Ty);
6042 return false;
6044 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6045 return error(ID.Loc, "invalid empty array initializer");
6046 V = UndefValue::get(Ty);
6047 return false;
6048 case ValID::t_Zero:
6049 // FIXME: LabelTy should not be a first-class type.
6050 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6051 return error(ID.Loc, "invalid type for null constant");
6052 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6053 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6054 return error(ID.Loc, "invalid type for null constant");
6056 return false;
6057 case ValID::t_None:
6058 if (!Ty->isTokenTy())
6059 return error(ID.Loc, "invalid type for none constant");
6061 return false;
6062 case ValID::t_Poison:
6063 // FIXME: LabelTy should not be a first-class type.
6064 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6065 return error(ID.Loc, "invalid type for poison constant");
6066 V = PoisonValue::get(Ty);
6067 return false;
6068 case ValID::t_Constant:
6069 if (ID.ConstantVal->getType() != Ty)
6070 return error(ID.Loc, "constant expression type mismatch: got type '" +
6071 getTypeString(ID.ConstantVal->getType()) +
6072 "' but expected '" + getTypeString(Ty) + "'");
6073 V = ID.ConstantVal;
6074 return false;
6076 if (!Ty->isVectorTy())
6077 return error(ID.Loc, "vector constant must have vector type");
6078 if (ID.ConstantVal->getType() != Ty->getScalarType())
6079 return error(ID.Loc, "constant expression type mismatch: got type '" +
6080 getTypeString(ID.ConstantVal->getType()) +
6081 "' but expected '" +
6082 getTypeString(Ty->getScalarType()) + "'");
6083 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6084 ID.ConstantVal);
6085 return false;
6088 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6089 if (ST->getNumElements() != ID.UIntVal)
6090 return error(ID.Loc,
6091 "initializer with struct type has wrong # elements");
6092 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6093 return error(ID.Loc, "packed'ness of initializer and type don't match");
6094
6095 // Verify that the elements are compatible with the structtype.
6096 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6097 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6098 return error(
6099 ID.Loc,
6100 "element " + Twine(i) +
6101 " of struct initializer doesn't match struct element type");
6102
6104 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6105 } else
6106 return error(ID.Loc, "constant expression type mismatch");
6107 return false;
6108 }
6109 llvm_unreachable("Invalid ValID");
6110}
6111
6112bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6113 C = nullptr;
6114 ValID ID;
6115 auto Loc = Lex.getLoc();
6116 if (parseValID(ID, /*PFS=*/nullptr))
6117 return true;
6118 switch (ID.Kind) {
6119 case ValID::t_APSInt:
6120 case ValID::t_APFloat:
6121 case ValID::t_Undef:
6122 case ValID::t_Constant:
6126 Value *V;
6127 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6128 return true;
6129 assert(isa<Constant>(V) && "Expected a constant value");
6130 C = cast<Constant>(V);
6131 return false;
6132 }
6133 case ValID::t_Null:
6135 return false;
6136 default:
6137 return error(Loc, "expected a constant value");
6138 }
6139}
6140
6141bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6142 V = nullptr;
6143 ValID ID;
6144 return parseValID(ID, PFS, Ty) ||
6145 convertValIDToValue(Ty, ID, V, PFS);
6146}
6147
6148bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6149 Type *Ty = nullptr;
6150 return parseType(Ty) || parseValue(Ty, V, PFS);
6151}
6152
6153bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6154 PerFunctionState &PFS) {
6155 Value *V;
6156 Loc = Lex.getLoc();
6157 if (parseTypeAndValue(V, PFS))
6158 return true;
6159 if (!isa<BasicBlock>(V))
6160 return error(Loc, "expected a basic block");
6161 BB = cast<BasicBlock>(V);
6162 return false;
6163}
6164
6166 // Exit early for the common (non-debug-intrinsic) case.
6167 // We can make this the only check when we begin supporting all "llvm.dbg"
6168 // intrinsics in the new debug info format.
6169 if (!Name.starts_with("llvm.dbg."))
6170 return false;
6172 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6173 FnID == Intrinsic::dbg_assign;
6174}
6175
6176/// FunctionHeader
6177/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6178/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6179/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6180/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6181bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6182 unsigned &FunctionNumber,
6183 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6184 // parse the linkage.
6185 LocTy LinkageLoc = Lex.getLoc();
6186 unsigned Linkage;
6187 unsigned Visibility;
6188 unsigned DLLStorageClass;
6189 bool DSOLocal;
6190 AttrBuilder RetAttrs(M->getContext());
6191 unsigned CC;
6192 bool HasLinkage;
6193 Type *RetType = nullptr;
6194 LocTy RetTypeLoc = Lex.getLoc();
6195 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6196 DSOLocal) ||
6197 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6198 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6199 return true;
6200
6201 // Verify that the linkage is ok.
6202 switch ((GlobalValue::LinkageTypes)Linkage) {
6204 break; // always ok.
6206 if (IsDefine)
6207 return error(LinkageLoc, "invalid linkage for function definition");
6208 break;
6216 if (!IsDefine)
6217 return error(LinkageLoc, "invalid linkage for function declaration");
6218 break;
6221 return error(LinkageLoc, "invalid function linkage type");
6222 }
6223
6224 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6225 return error(LinkageLoc,
6226 "symbol with local linkage must have default visibility");
6227
6228 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6229 return error(LinkageLoc,
6230 "symbol with local linkage cannot have a DLL storage class");
6231
6232 if (!FunctionType::isValidReturnType(RetType))
6233 return error(RetTypeLoc, "invalid function return type");
6234
6235 LocTy NameLoc = Lex.getLoc();
6236
6237 std::string FunctionName;
6238 if (Lex.getKind() == lltok::GlobalVar) {
6239 FunctionName = Lex.getStrVal();
6240 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6241 FunctionNumber = Lex.getUIntVal();
6242 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6243 FunctionNumber))
6244 return true;
6245 } else {
6246 return tokError("expected function name");
6247 }
6248
6249 Lex.Lex();
6250
6251 if (Lex.getKind() != lltok::lparen)
6252 return tokError("expected '(' in function argument list");
6253
6255 bool IsVarArg;
6256 AttrBuilder FuncAttrs(M->getContext());
6257 std::vector<unsigned> FwdRefAttrGrps;
6258 LocTy BuiltinLoc;
6259 std::string Section;
6260 std::string Partition;
6261 MaybeAlign Alignment;
6262 std::string GC;
6264 unsigned AddrSpace = 0;
6265 Constant *Prefix = nullptr;
6266 Constant *Prologue = nullptr;
6267 Constant *PersonalityFn = nullptr;
6268 Comdat *C;
6269
6270 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6271 parseOptionalUnnamedAddr(UnnamedAddr) ||
6272 parseOptionalProgramAddrSpace(AddrSpace) ||
6273 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6274 BuiltinLoc) ||
6275 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6276 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6277 parseOptionalComdat(FunctionName, C) ||
6278 parseOptionalAlignment(Alignment) ||
6279 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6280 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6281 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6282 (EatIfPresent(lltok::kw_personality) &&
6283 parseGlobalTypeAndValue(PersonalityFn)))
6284 return true;
6285
6286 if (FuncAttrs.contains(Attribute::Builtin))
6287 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6288
6289 // If the alignment was parsed as an attribute, move to the alignment field.
6290 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6291 Alignment = A;
6292 FuncAttrs.removeAttribute(Attribute::Alignment);
6293 }
6294
6295 // Okay, if we got here, the function is syntactically valid. Convert types
6296 // and do semantic checks.
6297 std::vector<Type*> ParamTypeList;
6299
6300 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6301 ParamTypeList.push_back(ArgList[i].Ty);
6302 Attrs.push_back(ArgList[i].Attrs);
6303 }
6304
6305 AttributeList PAL =
6306 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6307 AttributeSet::get(Context, RetAttrs), Attrs);
6308
6309 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6310 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6311
6312 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6313 PointerType *PFT = PointerType::get(FT, AddrSpace);
6314
6315 Fn = nullptr;
6316 GlobalValue *FwdFn = nullptr;
6317 if (!FunctionName.empty()) {
6318 // If this was a definition of a forward reference, remove the definition
6319 // from the forward reference table and fill in the forward ref.
6320 auto FRVI = ForwardRefVals.find(FunctionName);
6321 if (FRVI != ForwardRefVals.end()) {
6322 FwdFn = FRVI->second.first;
6323 if (FwdFn->getType() != PFT)
6324 return error(FRVI->second.second,
6325 "invalid forward reference to "
6326 "function '" +
6327 FunctionName +
6328 "' with wrong type: "
6329 "expected '" +
6330 getTypeString(PFT) + "' but was '" +
6331 getTypeString(FwdFn->getType()) + "'");
6332 ForwardRefVals.erase(FRVI);
6333 } else if ((Fn = M->getFunction(FunctionName))) {
6334 // Reject redefinitions.
6335 return error(NameLoc,
6336 "invalid redefinition of function '" + FunctionName + "'");
6337 } else if (M->getNamedValue(FunctionName)) {
6338 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6339 }
6340
6341 } else {
6342 // Handle @"", where a name is syntactically specified, but semantically
6343 // missing.
6344 if (FunctionNumber == (unsigned)-1)
6345 FunctionNumber = NumberedVals.getNext();
6346
6347 // If this is a definition of a forward referenced function, make sure the
6348 // types agree.
6349 auto I = ForwardRefValIDs.find(FunctionNumber);
6350 if (I != ForwardRefValIDs.end()) {
6351 FwdFn = I->second.first;
6352 if (FwdFn->getType() != PFT)
6353 return error(NameLoc, "type of definition and forward reference of '@" +
6354 Twine(FunctionNumber) +
6355 "' disagree: "
6356 "expected '" +
6357 getTypeString(PFT) + "' but was '" +
6358 getTypeString(FwdFn->getType()) + "'");
6359 ForwardRefValIDs.erase(I);
6360 }
6361 }
6362
6364 FunctionName, M);
6365
6366 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6367
6368 if (FunctionName.empty())
6369 NumberedVals.add(FunctionNumber, Fn);
6370
6372 maybeSetDSOLocal(DSOLocal, *Fn);
6375 Fn->setCallingConv(CC);
6376 Fn->setAttributes(PAL);
6377 Fn->setUnnamedAddr(UnnamedAddr);
6378 if (Alignment)
6379 Fn->setAlignment(*Alignment);
6380 Fn->setSection(Section);
6381 Fn->setPartition(Partition);
6382 Fn->setComdat(C);
6383 Fn->setPersonalityFn(PersonalityFn);
6384 if (!GC.empty()) Fn->setGC(GC);
6385 Fn->setPrefixData(Prefix);
6386 Fn->setPrologueData(Prologue);
6387 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6388
6389 // Add all of the arguments we parsed to the function.
6390 Function::arg_iterator ArgIt = Fn->arg_begin();
6391 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6392 // If the argument has a name, insert it into the argument symbol table.
6393 if (ArgList[i].Name.empty()) continue;
6394
6395 // Set the name, if it conflicted, it will be auto-renamed.
6396 ArgIt->setName(ArgList[i].Name);
6397
6398 if (ArgIt->getName() != ArgList[i].Name)
6399 return error(ArgList[i].Loc,
6400 "redefinition of argument '%" + ArgList[i].Name + "'");
6401 }
6402
6403 if (FwdFn) {
6404 FwdFn->replaceAllUsesWith(Fn);
6405 FwdFn->eraseFromParent();
6406 }
6407
6408 if (IsDefine)
6409 return false;
6410
6411 // Check the declaration has no block address forward references.
6412 ValID ID;
6413 if (FunctionName.empty()) {
6414 ID.Kind = ValID::t_GlobalID;
6415 ID.UIntVal = FunctionNumber;
6416 } else {
6417 ID.Kind = ValID::t_GlobalName;
6418 ID.StrVal = FunctionName;
6419 }
6420 auto Blocks = ForwardRefBlockAddresses.find(ID);
6421 if (Blocks != ForwardRefBlockAddresses.end())
6422 return error(Blocks->first.Loc,
6423 "cannot take blockaddress inside a declaration");
6424 return false;
6425}
6426
6427bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6428 ValID ID;
6429 if (FunctionNumber == -1) {
6430 ID.Kind = ValID::t_GlobalName;
6431 ID.StrVal = std::string(F.getName());
6432 } else {
6433 ID.Kind = ValID::t_GlobalID;
6434 ID.UIntVal = FunctionNumber;
6435 }
6436
6437 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6438 if (Blocks == P.ForwardRefBlockAddresses.end())
6439 return false;
6440
6441 for (const auto &I : Blocks->second) {
6442 const ValID &BBID = I.first;
6443 GlobalValue *GV = I.second;
6444
6445 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6446 "Expected local id or name");
6447 BasicBlock *BB;
6448 if (BBID.Kind == ValID::t_LocalName)
6449 BB = getBB(BBID.StrVal, BBID.Loc);
6450 else
6451 BB = getBB(BBID.UIntVal, BBID.Loc);
6452 if (!BB)
6453 return P.error(BBID.Loc, "referenced value is not a basic block");
6454
6455 Value *ResolvedVal = BlockAddress::get(&F, BB);
6456 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6457 ResolvedVal);
6458 if (!ResolvedVal)
6459 return true;
6460 GV->replaceAllUsesWith(ResolvedVal);
6461 GV->eraseFromParent();
6462 }
6463
6464 P.ForwardRefBlockAddresses.erase(Blocks);
6465 return false;
6466}
6467
6468/// parseFunctionBody
6469/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6470bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6471 ArrayRef<unsigned> UnnamedArgNums) {
6472 if (Lex.getKind() != lltok::lbrace)
6473 return tokError("expected '{' in function body");
6474 Lex.Lex(); // eat the {.
6475
6476 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
6477
6478 // Resolve block addresses and allow basic blocks to be forward-declared
6479 // within this function.
6480 if (PFS.resolveForwardRefBlockAddresses())
6481 return true;
6482 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6483
6484 // We need at least one basic block.
6485 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6486 return tokError("function body requires at least one basic block");
6487
6488 while (Lex.getKind() != lltok::rbrace &&
6490 if (parseBasicBlock(PFS))
6491 return true;
6492
6493 while (Lex.getKind() != lltok::rbrace)
6494 if (parseUseListOrder(&PFS))
6495 return true;
6496
6497 // Eat the }.
6498 Lex.Lex();
6499
6500 // Verify function is ok.
6501 return PFS.finishFunction();
6502}
6503
6504/// parseBasicBlock
6505/// ::= (LabelStr|LabelID)? Instruction*
6506bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6507 // If this basic block starts out with a name, remember it.
6508 std::string Name;
6509 int NameID = -1;
6510 LocTy NameLoc = Lex.getLoc();
6511 if (Lex.getKind() == lltok::LabelStr) {
6512 Name = Lex.getStrVal();
6513 Lex.Lex();
6514 } else if (Lex.getKind() == lltok::LabelID) {
6515 NameID = Lex.getUIntVal();
6516 Lex.Lex();
6517 }
6518
6519 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6520 if (!BB)
6521 return true;
6522
6523 std::string NameStr;
6524
6525 // Parse the instructions and debug values in this block until we get a
6526 // terminator.
6527 Instruction *Inst;
6528 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
6529 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
6530 SmallVector<DbgRecordPtr> TrailingDbgRecord;
6531 do {
6532 // Handle debug records first - there should always be an instruction
6533 // following the debug records, i.e. they cannot appear after the block
6534 // terminator.
6535 while (Lex.getKind() == lltok::hash) {
6536 if (SeenOldDbgInfoFormat)
6537 return error(Lex.getLoc(), "debug record should not appear in a module "
6538 "containing debug info intrinsics");
6539 if (!SeenNewDbgInfoFormat)
6540 M->setNewDbgInfoFormatFlag(true);
6541 SeenNewDbgInfoFormat = true;
6542 Lex.Lex();
6543
6544 DbgRecord *DR;
6545 if (parseDebugRecord(DR, PFS))
6546 return true;
6547 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6548 }
6549
6550 // This instruction may have three possibilities for a name: a) none
6551 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6552 LocTy NameLoc = Lex.getLoc();
6553 int NameID = -1;
6554 NameStr = "";
6555
6556 if (Lex.getKind() == lltok::LocalVarID) {
6557 NameID = Lex.getUIntVal();
6558 Lex.Lex();
6559 if (parseToken(lltok::equal, "expected '=' after instruction id"))
6560 return true;
6561 } else if (Lex.getKind() == lltok::LocalVar) {
6562 NameStr = Lex.getStrVal();
6563 Lex.Lex();
6564 if (parseToken(lltok::equal, "expected '=' after instruction name"))
6565 return true;
6566 }
6567
6568 switch (parseInstruction(Inst, BB, PFS)) {
6569 default:
6570 llvm_unreachable("Unknown parseInstruction result!");
6571 case InstError: return true;
6572 case InstNormal:
6573 Inst->insertInto(BB, BB->end());
6574
6575 // With a normal result, we check to see if the instruction is followed by
6576 // a comma and metadata.
6577 if (EatIfPresent(lltok::comma))
6578 if (parseInstructionMetadata(*Inst))
6579 return true;
6580 break;
6581 case InstExtraComma:
6582 Inst->insertInto(BB, BB->end());
6583
6584 // If the instruction parser ate an extra comma at the end of it, it
6585 // *must* be followed by metadata.
6586 if (parseInstructionMetadata(*Inst))
6587 return true;
6588 break;
6589 }
6590
6591 // Set the name on the instruction.
6592 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6593 return true;
6594
6595 // Attach any preceding debug values to this instruction.
6596 for (DbgRecordPtr &DR : TrailingDbgRecord)
6597 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
6598 TrailingDbgRecord.clear();
6599 } while (!Inst->isTerminator());
6600
6601 assert(TrailingDbgRecord.empty() &&
6602 "All debug values should have been attached to an instruction.");
6603
6604 return false;
6605}
6606
6607/// parseDebugRecord
6608/// ::= #dbg_label '(' MDNode ')'
6609/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
6610/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
6611bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
6612 using RecordKind = DbgRecord::Kind;
6613 using LocType = DbgVariableRecord::LocationType;
6614 LocTy DVRLoc = Lex.getLoc();
6615 if (Lex.getKind() != lltok::DbgRecordType)
6616 return error(DVRLoc, "expected debug record type here");
6618 .Case("declare", RecordKind::ValueKind)
6619 .Case("value", RecordKind::ValueKind)
6620 .Case("assign", RecordKind::ValueKind)
6621 .Case("label", RecordKind::LabelKind);
6622
6623 // Parsing labels is trivial; parse here and early exit, otherwise go into the
6624 // full DbgVariableRecord processing stage.
6625 if (RecordType == RecordKind::LabelKind) {
6626 Lex.Lex();
6627 if (parseToken(lltok::lparen, "Expected '(' here"))
6628 return true;
6629 MDNode *Label;
6630 if (parseMDNode(Label))
6631 return true;
6632 if (parseToken(lltok::comma, "Expected ',' here"))
6633 return true;
6634 MDNode *DbgLoc;
6635 if (parseMDNode(DbgLoc))
6636 return true;
6637 if (parseToken(lltok::rparen, "Expected ')' here"))
6638 return true;
6640 return false;
6641 }
6642
6644 .Case("declare", LocType::Declare)
6645 .Case("value", LocType::Value)
6646 .Case("assign", LocType::Assign);
6647
6648 Lex.Lex();
6649 if (parseToken(lltok::lparen, "Expected '(' here"))
6650 return true;
6651
6652 // Parse Value field.
6653 Metadata *ValLocMD;
6654 if (parseMetadata(ValLocMD, &PFS))
6655 return true;
6656 if (parseToken(lltok::comma, "Expected ',' here"))
6657 return true;
6658
6659 // Parse Variable field.
6660 MDNode *Variable;
6661 if (parseMDNode(Variable))
6662 return true;
6663 if (parseToken(lltok::comma, "Expected ',' here"))
6664 return true;
6665
6666 // Parse Expression field.
6668 if (parseMDNode(Expression))
6669 return true;
6670 if (parseToken(lltok::comma, "Expected ',' here"))
6671 return true;
6672
6673 // Parse additional fields for #dbg_assign.
6674 MDNode *AssignID = nullptr;
6675 Metadata *AddressLocation = nullptr;
6676 MDNode *AddressExpression = nullptr;
6677 if (ValueType == LocType::Assign) {
6678 // Parse DIAssignID.
6679 if (parseMDNode(AssignID))
6680 return true;
6681 if (parseToken(lltok::comma, "Expected ',' here"))
6682 return true;
6683
6684 // Parse address ValueAsMetadata.
6685 if (parseMetadata(AddressLocation, &PFS))
6686 return true;
6687 if (parseToken(lltok::comma, "Expected ',' here"))
6688 return true;
6689
6690 // Parse address DIExpression.
6691 if (parseMDNode(AddressExpression))
6692 return true;
6693 if (parseToken(lltok::comma, "Expected ',' here"))
6694 return true;
6695 }
6696
6697 /// Parse DILocation.
6699 if (parseMDNode(DebugLoc))
6700 return true;
6701
6702 if (parseToken(lltok::rparen, "Expected ')' here"))
6703 return true;
6705 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
6706 AddressExpression, DebugLoc);
6707 return false;
6708}
6709//===----------------------------------------------------------------------===//
6710// Instruction Parsing.
6711//===----------------------------------------------------------------------===//
6712
6713/// parseInstruction - parse one of the many different instructions.
6714///
6715int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6716 PerFunctionState &PFS) {
6717 lltok::Kind Token = Lex.getKind();
6718 if (Token == lltok::Eof)
6719 return tokError("found end of file when expecting more instructions");
6720 LocTy Loc = Lex.getLoc();
6721 unsigned KeywordVal = Lex.getUIntVal();
6722 Lex.Lex(); // Eat the keyword.
6723
6724 switch (Token) {
6725 default:
6726 return error(Loc, "expected instruction opcode");
6727 // Terminator Instructions.
6728 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6729 case lltok::kw_ret:
6730 return parseRet(Inst, BB, PFS);
6731 case lltok::kw_br:
6732 return parseBr(Inst, PFS);
6733 case lltok::kw_switch:
6734 return parseSwitch(Inst, PFS);
6736 return parseIndirectBr(Inst, PFS);
6737 case lltok::kw_invoke:
6738 return parseInvoke(Inst, PFS);
6739 case lltok::kw_resume:
6740 return parseResume(Inst, PFS);
6742 return parseCleanupRet(Inst, PFS);
6743 case lltok::kw_catchret:
6744 return parseCatchRet(Inst, PFS);
6746 return parseCatchSwitch(Inst, PFS);
6747 case lltok::kw_catchpad:
6748 return parseCatchPad(Inst, PFS);
6750 return parseCleanupPad(Inst, PFS);
6751 case lltok::kw_callbr:
6752 return parseCallBr(Inst, PFS);
6753 // Unary Operators.
6754 case lltok::kw_fneg: {
6755 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6756 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6757 if (Res != 0)
6758 return Res;
6759 if (FMF.any())
6760 Inst->setFastMathFlags(FMF);
6761 return false;
6762 }
6763 // Binary Operators.
6764 case lltok::kw_add:
6765 case lltok::kw_sub:
6766 case lltok::kw_mul:
6767 case lltok::kw_shl: {
6768 bool NUW = EatIfPresent(lltok::kw_nuw);
6769 bool NSW = EatIfPresent(lltok::kw_nsw);
6770 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6771
6772 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6773 return true;
6774
6775 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6776 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6777 return false;
6778 }
6779 case lltok::kw_fadd:
6780 case lltok::kw_fsub:
6781 case lltok::kw_fmul:
6782 case lltok::kw_fdiv:
6783 case lltok::kw_frem: {
6784 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6785 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6786 if (Res != 0)
6787 return Res;
6788 if (FMF.any())
6789 Inst->setFastMathFlags(FMF);
6790 return 0;
6791 }
6792
6793 case lltok::kw_sdiv:
6794 case lltok::kw_udiv:
6795 case lltok::kw_lshr:
6796 case lltok::kw_ashr: {
6797 bool Exact = EatIfPresent(lltok::kw_exact);
6798
6799 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6800 return true;
6801 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6802 return false;
6803 }
6804
6805 case lltok::kw_urem:
6806 case lltok::kw_srem:
6807 return parseArithmetic(Inst, PFS, KeywordVal,
6808 /*IsFP*/ false);
6809 case lltok::kw_or: {
6810 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
6811 if (parseLogical(Inst, PFS, KeywordVal))
6812 return true;
6813 if (Disjoint)
6814 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
6815 return false;
6816 }
6817 case lltok::kw_and:
6818 case lltok::kw_xor:
6819 return parseLogical(Inst, PFS, KeywordVal);
6820 case lltok::kw_icmp:
6821 return parseCompare(Inst, PFS, KeywordVal);
6822 case lltok::kw_fcmp: {
6823 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6824 int Res = parseCompare(Inst, PFS, KeywordVal);
6825 if (Res != 0)
6826 return Res;
6827 if (FMF.any())
6828 Inst->setFastMathFlags(FMF);
6829 return 0;
6830 }
6831
6832 // Casts.
6833 case lltok::kw_uitofp:
6834 case lltok::kw_zext: {
6835 bool NonNeg = EatIfPresent(lltok::kw_nneg);
6836 bool Res = parseCast(Inst, PFS, KeywordVal);
6837 if (Res != 0)
6838 return Res;
6839 if (NonNeg)
6840 Inst->setNonNeg();
6841 return 0;
6842 }
6843 case lltok::kw_trunc: {
6844 bool NUW = EatIfPresent(lltok::kw_nuw);
6845 bool NSW = EatIfPresent(lltok::kw_nsw);
6846 if (!NUW)
6847 NUW = EatIfPresent(lltok::kw_nuw);
6848 if (parseCast(Inst, PFS, KeywordVal))
6849 return true;
6850 if (NUW)
6851 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
6852 if (NSW)
6853 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
6854 return false;
6855 }
6856 case lltok::kw_sext:
6857 case lltok::kw_fptrunc:
6858 case lltok::kw_fpext:
6859 case lltok::kw_bitcast:
6861 case lltok::kw_sitofp:
6862 case lltok::kw_fptoui:
6863 case lltok::kw_fptosi:
6864 case lltok::kw_inttoptr:
6865 case lltok::kw_ptrtoint:
6866 return parseCast(Inst, PFS, KeywordVal);
6867 // Other.
6868 case lltok::kw_select: {
6869 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6870 int Res = parseSelect(Inst, PFS);
6871 if (Res != 0)
6872 return Res;
6873 if (FMF.any()) {
6874 if (!isa<FPMathOperator>(Inst))
6875 return error(Loc, "fast-math-flags specified for select without "
6876 "floating-point scalar or vector return type");
6877 Inst->setFastMathFlags(FMF);
6878 }
6879 return 0;
6880 }
6881 case lltok::kw_va_arg:
6882 return parseVAArg(Inst, PFS);
6884 return parseExtractElement(Inst, PFS);
6886 return parseInsertElement(Inst, PFS);
6888 return parseShuffleVector(Inst, PFS);
6889 case lltok::kw_phi: {
6890 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6891 int Res = parsePHI(Inst, PFS);
6892 if (Res != 0)
6893 return Res;
6894 if (FMF.any()) {
6895 if (!isa<FPMathOperator>(Inst))
6896 return error(Loc, "fast-math-flags specified for phi without "
6897 "floating-point scalar or vector return type");
6898 Inst->setFastMathFlags(FMF);
6899 }
6900 return 0;
6901 }
6903 return parseLandingPad(Inst, PFS);
6904 case lltok::kw_freeze:
6905 return parseFreeze(Inst, PFS);
6906 // Call.
6907 case lltok::kw_call:
6908 return parseCall(Inst, PFS, CallInst::TCK_None);
6909 case lltok::kw_tail:
6910 return parseCall(Inst, PFS, CallInst::TCK_Tail);
6911 case lltok::kw_musttail:
6912 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6913 case lltok::kw_notail:
6914 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6915 // Memory.
6916 case lltok::kw_alloca:
6917 return parseAlloc(Inst, PFS);
6918 case lltok::kw_load:
6919 return parseLoad(Inst, PFS);
6920 case lltok::kw_store:
6921 return parseStore(Inst, PFS);
6922 case lltok::kw_cmpxchg:
6923 return parseCmpXchg(Inst, PFS);
6925 return parseAtomicRMW(Inst, PFS);
6926 case lltok::kw_fence:
6927 return parseFence(Inst, PFS);
6929 return parseGetElementPtr(Inst, PFS);
6931 return parseExtractValue(Inst, PFS);
6933 return parseInsertValue(Inst, PFS);
6934 }
6935}
6936
6937/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6938bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6939 if (Opc == Instruction::FCmp) {
6940 switch (Lex.getKind()) {
6941 default:
6942 return tokError("expected fcmp predicate (e.g. 'oeq')");
6943 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6944 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6945 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6946 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6947 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6948 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6949 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6950 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6951 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6952 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6953 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6954 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6955 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6956 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6957 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6958 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6959 }
6960 } else {
6961 switch (Lex.getKind()) {
6962 default:
6963 return tokError("expected icmp predicate (e.g. 'eq')");
6964 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
6965 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
6966 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6967 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6968 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6969 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6970 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6971 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6972 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6973 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6974 }
6975 }
6976 Lex.Lex();
6977 return false;
6978}
6979
6980//===----------------------------------------------------------------------===//
6981// Terminator Instructions.
6982//===----------------------------------------------------------------------===//
6983
6984/// parseRet - parse a return instruction.
6985/// ::= 'ret' void (',' !dbg, !1)*
6986/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6987bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6988 PerFunctionState &PFS) {
6989 SMLoc TypeLoc = Lex.getLoc();
6990 Type *Ty = nullptr;
6991 if (parseType(Ty, true /*void allowed*/))
6992 return true;
6993
6994 Type *ResType = PFS.getFunction().getReturnType();
6995
6996 if (Ty->isVoidTy()) {
6997 if (!ResType->isVoidTy())
6998 return error(TypeLoc, "value doesn't match function result type '" +
6999 getTypeString(ResType) + "'");
7000
7001 Inst = ReturnInst::Create(Context);
7002 return false;
7003 }
7004
7005 Value *RV;
7006 if (parseValue(Ty, RV, PFS))
7007 return true;
7008
7009 if (ResType != RV->getType())
7010 return error(TypeLoc, "value doesn't match function result type '" +
7011 getTypeString(ResType) + "'");
7012
7013 Inst = ReturnInst::Create(Context, RV);
7014 return false;
7015}
7016
7017/// parseBr
7018/// ::= 'br' TypeAndValue
7019/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7020bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7021 LocTy Loc, Loc2;
7022 Value *Op0;
7023 BasicBlock *Op1, *Op2;
7024 if (parseTypeAndValue(Op0, Loc, PFS))
7025 return true;
7026
7027 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7028 Inst = BranchInst::Create(BB);
7029 return false;
7030 }
7031
7032 if (Op0->getType() != Type::getInt1Ty(Context))
7033 return error(Loc, "branch condition must have 'i1' type");
7034
7035 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7036 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7037 parseToken(lltok::comma, "expected ',' after true destination") ||
7038 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7039 return true;
7040
7041 Inst = BranchInst::Create(Op1, Op2, Op0);
7042 return false;
7043}
7044
7045/// parseSwitch
7046/// Instruction
7047/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7048/// JumpTable
7049/// ::= (TypeAndValue ',' TypeAndValue)*
7050bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7051 LocTy CondLoc, BBLoc;
7052 Value *Cond;
7053 BasicBlock *DefaultBB;
7054 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7055 parseToken(lltok::comma, "expected ',' after switch condition") ||
7056 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7057 parseToken(lltok::lsquare, "expected '[' with switch table"))
7058 return true;
7059
7060 if (!Cond->getType()->isIntegerTy())
7061 return error(CondLoc, "switch condition must have integer type");
7062
7063 // parse the jump table pairs.
7064 SmallPtrSet<Value*, 32> SeenCases;
7066 while (Lex.getKind() != lltok::rsquare) {
7067 Value *Constant;
7068 BasicBlock *DestBB;
7069
7070 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7071 parseToken(lltok::comma, "expected ',' after case value") ||
7072 parseTypeAndBasicBlock(DestBB, PFS))
7073 return true;
7074
7075 if (!SeenCases.insert(Constant).second)
7076 return error(CondLoc, "duplicate case value in switch");
7077 if (!isa<ConstantInt>(Constant))
7078 return error(CondLoc, "case value is not a constant integer");
7079
7080 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7081 }
7082
7083 Lex.Lex(); // Eat the ']'.
7084
7085 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7086 for (unsigned i = 0, e = Table.size(); i != e; ++i)
7087 SI->addCase(Table[i].first, Table[i].second);
7088 Inst = SI;
7089 return false;
7090}
7091
7092/// parseIndirectBr
7093/// Instruction
7094/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7095bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7096 LocTy AddrLoc;
7097 Value *Address;
7098 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7099 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7100 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7101 return true;
7102
7103 if (!Address->getType()->isPointerTy())
7104 return error(AddrLoc, "indirectbr address must have pointer type");
7105
7106 // parse the destination list.
7108
7109 if (Lex.getKind() != lltok::rsquare) {
7110 BasicBlock *DestBB;
7111 if (parseTypeAndBasicBlock(DestBB, PFS))
7112 return true;
7113 DestList.push_back(DestBB);
7114
7115 while (EatIfPresent(lltok::comma)) {
7116 if (parseTypeAndBasicBlock(DestBB, PFS))
7117 return true;
7118 DestList.push_back(DestBB);
7119 }
7120 }
7121
7122 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7123 return true;
7124
7126 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
7127 IBI->addDestination(DestList[i]);
7128 Inst = IBI;
7129 return false;
7130}
7131
7132// If RetType is a non-function pointer type, then this is the short syntax
7133// for the call, which means that RetType is just the return type. Infer the
7134// rest of the function argument types from the arguments that are present.
7135bool LLParser::resolveFunctionType(Type *RetType,
7136 const SmallVector<ParamInfo, 16> &ArgList,
7137 FunctionType *&FuncTy) {
7138 FuncTy = dyn_cast<FunctionType>(RetType);
7139 if (!FuncTy) {
7140 // Pull out the types of all of the arguments...
7141 std::vector<Type*> ParamTypes;
7142 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7143 ParamTypes.push_back(ArgList[i].V->getType());
7144
7145 if (!FunctionType::isValidReturnType(RetType))
7146 return true;
7147
7148 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7149 }
7150 return false;
7151}
7152
7153/// parseInvoke
7154/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7155/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7156bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7157 LocTy CallLoc = Lex.getLoc();
7158 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7159 std::vector<unsigned> FwdRefAttrGrps;
7160 LocTy NoBuiltinLoc;
7161 unsigned CC;
7162 unsigned InvokeAddrSpace;
7163 Type *RetType = nullptr;
7164 LocTy RetTypeLoc;
7165 ValID CalleeID;
7168
7169 BasicBlock *NormalBB, *UnwindBB;
7170 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7171 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7172 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7173 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7174 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7175 NoBuiltinLoc) ||
7176 parseOptionalOperandBundles(BundleList, PFS) ||
7177 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7178 parseTypeAndBasicBlock(NormalBB, PFS) ||
7179 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7180 parseTypeAndBasicBlock(UnwindBB, PFS))
7181 return true;
7182
7183 // If RetType is a non-function pointer type, then this is the short syntax
7184 // for the call, which means that RetType is just the return type. Infer the
7185 // rest of the function argument types from the arguments that are present.
7186 FunctionType *Ty;
7187 if (resolveFunctionType(RetType, ArgList, Ty))
7188 return error(RetTypeLoc, "Invalid result type for LLVM function");
7189
7190 CalleeID.FTy = Ty;
7191
7192 // Look up the callee.
7193 Value *Callee;
7194 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
7195 Callee, &PFS))
7196 return true;
7197
7198 // Set up the Attribute for the function.
7201
7202 // Loop through FunctionType's arguments and ensure they are specified
7203 // correctly. Also, gather any parameter attributes.
7204 FunctionType::param_iterator I = Ty->param_begin();
7205 FunctionType::param_iterator E = Ty->param_end();
7206 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7207 Type *ExpectedTy = nullptr;
7208 if (I != E) {
7209 ExpectedTy = *I++;
7210 } else if (!Ty->isVarArg()) {
7211 return error(ArgList[i].Loc, "too many arguments specified");
7212 }
7213
7214 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7215 return error(ArgList[i].Loc, "argument is not of expected type '" +
7216 getTypeString(ExpectedTy) + "'");
7217 Args.push_back(ArgList[i].V);
7218 ArgAttrs.push_back(ArgList[i].Attrs);
7219 }
7220
7221 if (I != E)
7222 return error(CallLoc, "not enough parameters specified for call");
7223
7224 // Finish off the Attribute and check them
7225 AttributeList PAL =
7226 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7227 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7228
7229 InvokeInst *II =
7230 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7231 II->setCallingConv(CC);
7232 II->setAttributes(PAL);
7233 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7234 Inst = II;
7235 return false;
7236}
7237
7238/// parseResume
7239/// ::= 'resume' TypeAndValue
7240bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7241 Value *Exn; LocTy ExnLoc;
7242 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7243 return true;
7244
7245 ResumeInst *RI = ResumeInst::Create(Exn);
7246 Inst = RI;
7247 return false;
7248}
7249
7250bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7251 PerFunctionState &PFS) {
7252 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7253 return true;
7254
7255 while (Lex.getKind() != lltok::rsquare) {
7256 // If this isn't the first argument, we need a comma.
7257 if (!Args.empty() &&
7258 parseToken(lltok::comma, "expected ',' in argument list"))
7259 return true;
7260
7261 // parse the argument.
7262 LocTy ArgLoc;
7263 Type *ArgTy = nullptr;
7264 if (parseType(ArgTy, ArgLoc))
7265 return true;
7266
7267 Value *V;
7268 if (ArgTy->isMetadataTy()) {
7269 if (parseMetadataAsValue(V, PFS))
7270 return true;
7271 } else {
7272 if (parseValue(ArgTy, V, PFS))
7273 return true;
7274 }
7275 Args.push_back(V);
7276 }
7277
7278 Lex.Lex(); // Lex the ']'.
7279 return false;
7280}
7281
7282/// parseCleanupRet
7283/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7284bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7285 Value *CleanupPad = nullptr;
7286
7287 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7288 return true;
7289
7290 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7291 return true;
7292
7293 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7294 return true;
7295
7296 BasicBlock *UnwindBB = nullptr;
7297 if (Lex.getKind() == lltok::kw_to) {
7298 Lex.Lex();
7299 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7300 return true;
7301 } else {
7302 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7303 return true;
7304 }
7305 }
7306
7307 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7308 return false;
7309}
7310
7311/// parseCatchRet
7312/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7313bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7314 Value *CatchPad = nullptr;
7315
7316 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7317 return true;
7318
7319 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7320 return true;
7321
7322 BasicBlock *BB;
7323 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7324 parseTypeAndBasicBlock(BB, PFS))
7325 return true;
7326
7327 Inst = CatchReturnInst::Create(CatchPad, BB);
7328 return false;
7329}
7330
7331/// parseCatchSwitch
7332/// ::= 'catchswitch' within Parent
7333bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7334 Value *ParentPad;
7335
7336 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7337 return true;
7338
7339 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7340 Lex.getKind() != lltok::LocalVarID)
7341 return tokError("expected scope value for catchswitch");
7342
7343 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7344 return true;
7345
7346 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7347 return true;
7348
7350 do {
7351 BasicBlock *DestBB;
7352 if (parseTypeAndBasicBlock(DestBB, PFS))
7353 return true;
7354 Table.push_back(DestBB);
7355 } while (EatIfPresent(lltok::comma));
7356
7357 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7358 return true;
7359
7360 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7361 return true;
7362
7363 BasicBlock *UnwindBB = nullptr;
7364 if (EatIfPresent(lltok::kw_to)) {
7365 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7366 return true;
7367 } else {
7368 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7369 return true;
7370 }
7371
7372 auto *CatchSwitch =
7373 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7374 for (BasicBlock *DestBB : Table)
7375 CatchSwitch->addHandler(DestBB);
7376 Inst = CatchSwitch;
7377 return false;
7378}
7379
7380/// parseCatchPad
7381/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7382bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7383 Value *CatchSwitch = nullptr;
7384
7385 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7386 return true;
7387
7388 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7389 return tokError("expected scope value for catchpad");
7390
7391 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7392 return true;
7393
7395 if (parseExceptionArgs(Args, PFS))
7396 return true;
7397
7398 Inst = CatchPadInst::Create(CatchSwitch, Args);
7399 return false;
7400}
7401
7402/// parseCleanupPad
7403/// ::= 'cleanuppad' within Parent ParamList
7404bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7405 Value *ParentPad = nullptr;
7406
7407 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7408 return true;
7409
7410 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7411 Lex.getKind() != lltok::LocalVarID)
7412 return tokError("expected scope value for cleanuppad");
7413
7414 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7415 return true;
7416
7418 if (parseExceptionArgs(Args, PFS))
7419 return true;
7420
7421 Inst = CleanupPadInst::Create(ParentPad, Args);
7422 return false;
7423}
7424
7425//===----------------------------------------------------------------------===//
7426// Unary Operators.
7427//===----------------------------------------------------------------------===//
7428
7429/// parseUnaryOp
7430/// ::= UnaryOp TypeAndValue ',' Value
7431///
7432/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7433/// operand is allowed.
7434bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7435 unsigned Opc, bool IsFP) {
7436 LocTy Loc; Value *LHS;
7437 if (parseTypeAndValue(LHS, Loc, PFS))
7438 return true;
7439
7440 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7442
7443 if (!Valid)
7444 return error(Loc, "invalid operand type for instruction");
7445
7447 return false;
7448}
7449
7450/// parseCallBr
7451/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7452/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7453/// '[' LabelList ']'
7454bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7455 LocTy CallLoc = Lex.getLoc();
7456 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7457 std::vector<unsigned> FwdRefAttrGrps;
7458 LocTy NoBuiltinLoc;
7459 unsigned CC;
7460 Type *RetType = nullptr;
7461 LocTy RetTypeLoc;
7462 ValID CalleeID;
7465
7466 BasicBlock *DefaultDest;
7467 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7468 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7469 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7470 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7471 NoBuiltinLoc) ||
7472 parseOptionalOperandBundles(BundleList, PFS) ||
7473 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7474 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7475 parseToken(lltok::lsquare, "expected '[' in callbr"))
7476 return true;
7477
7478 // parse the destination list.
7479 SmallVector<BasicBlock *, 16> IndirectDests;
7480
7481 if (Lex.getKind() != lltok::rsquare) {
7482 BasicBlock *DestBB;
7483 if (parseTypeAndBasicBlock(DestBB, PFS))
7484 return true;
7485 IndirectDests.push_back(DestBB);
7486
7487 while (EatIfPresent(lltok::comma)) {
7488 if (parseTypeAndBasicBlock(DestBB, PFS))
7489 return true;
7490 IndirectDests.push_back(DestBB);
7491 }
7492 }
7493
7494 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7495 return true;
7496
7497 // If RetType is a non-function pointer type, then this is the short syntax
7498 // for the call, which means that RetType is just the return type. Infer the
7499 // rest of the function argument types from the arguments that are present.
7500 FunctionType *Ty;
7501 if (resolveFunctionType(RetType, ArgList, Ty))
7502 return error(RetTypeLoc, "Invalid result type for LLVM function");
7503
7504 CalleeID.FTy = Ty;
7505
7506 // Look up the callee.
7507 Value *Callee;
7508 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
7509 return true;
7510
7511 // Set up the Attribute for the function.
7514
7515 // Loop through FunctionType's arguments and ensure they are specified
7516 // correctly. Also, gather any parameter attributes.
7517 FunctionType::param_iterator I = Ty->param_begin();
7518 FunctionType::param_iterator E = Ty->param_end();
7519 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7520 Type *ExpectedTy = nullptr;
7521 if (I != E) {
7522 ExpectedTy = *I++;
7523 } else if (!Ty->isVarArg()) {
7524 return error(ArgList[i].Loc, "too many arguments specified");
7525 }
7526
7527 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7528 return error(ArgList[i].Loc, "argument is not of expected type '" +
7529 getTypeString(ExpectedTy) + "'");
7530 Args.push_back(ArgList[i].V);
7531 ArgAttrs.push_back(ArgList[i].Attrs);
7532 }
7533
7534 if (I != E)
7535 return error(CallLoc, "not enough parameters specified for call");
7536
7537 // Finish off the Attribute and check them
7538 AttributeList PAL =
7539 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7540 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7541
7542 CallBrInst *CBI =
7543 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
7544 BundleList);
7545 CBI->setCallingConv(CC);
7546 CBI->setAttributes(PAL);
7547 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7548 Inst = CBI;
7549 return false;
7550}
7551
7552//===----------------------------------------------------------------------===//
7553// Binary Operators.
7554//===----------------------------------------------------------------------===//
7555
7556/// parseArithmetic
7557/// ::= ArithmeticOps TypeAndValue ',' Value
7558///
7559/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7560/// operand is allowed.
7561bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
7562 unsigned Opc, bool IsFP) {
7563 LocTy Loc; Value *LHS, *RHS;
7564 if (parseTypeAndValue(LHS, Loc, PFS) ||
7565 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
7566 parseValue(LHS->getType(), RHS, PFS))
7567 return true;
7568
7569 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7571
7572 if (!Valid)
7573 return error(Loc, "invalid operand type for instruction");
7574
7575 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7576 return false;
7577}
7578
7579/// parseLogical
7580/// ::= ArithmeticOps TypeAndValue ',' Value {
7581bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
7582 unsigned Opc) {
7583 LocTy Loc; Value *LHS, *RHS;
7584 if (parseTypeAndValue(LHS, Loc, PFS) ||
7585 parseToken(lltok::comma, "expected ',' in logical operation") ||
7586 parseValue(LHS->getType(), RHS, PFS))
7587 return true;
7588
7589 if (!LHS->getType()->isIntOrIntVectorTy())
7590 return error(Loc,
7591 "instruction requires integer or integer vector operands");
7592
7593 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7594 return false;
7595}
7596
7597/// parseCompare
7598/// ::= 'icmp' IPredicates TypeAndValue ',' Value
7599/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
7600bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7601 unsigned Opc) {
7602 // parse the integer/fp comparison predicate.
7603 LocTy Loc;
7604 unsigned Pred;
7605 Value *LHS, *RHS;
7606 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7607 parseToken(lltok::comma, "expected ',' after compare value") ||
7608 parseValue(LHS->getType(), RHS, PFS))
7609 return true;
7610
7611 if (Opc == Instruction::FCmp) {
7612 if (!LHS->getType()->isFPOrFPVectorTy())
7613 return error(Loc, "fcmp requires floating point operands");
7614 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7615 } else {
7616 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7617 if (!LHS->getType()->isIntOrIntVectorTy() &&
7619 return error(Loc, "icmp requires integer operands");
7620 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7621 }
7622 return false;
7623}
7624
7625//===----------------------------------------------------------------------===//
7626// Other Instructions.
7627//===----------------------------------------------------------------------===//
7628
7629/// parseCast
7630/// ::= CastOpc TypeAndValue 'to' Type
7631bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7632 unsigned Opc) {
7633 LocTy Loc;
7634 Value *Op;
7635 Type *DestTy = nullptr;
7636 if (parseTypeAndValue(Op, Loc, PFS) ||
7637 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7638 parseType(DestTy))
7639 return true;
7640
7641 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
7643 return error(Loc, "invalid cast opcode for cast from '" +
7644 getTypeString(Op->getType()) + "' to '" +
7645 getTypeString(DestTy) + "'");
7646 }
7647 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7648 return false;
7649}
7650
7651/// parseSelect
7652/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7653bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7654 LocTy Loc;
7655 Value *Op0, *Op1, *Op2;
7656 if (parseTypeAndValue(Op0, Loc, PFS) ||
7657 parseToken(lltok::comma, "expected ',' after select condition") ||
7658 parseTypeAndValue(Op1, PFS) ||
7659 parseToken(lltok::comma, "expected ',' after select value") ||
7660 parseTypeAndValue(Op2, PFS))
7661 return true;
7662
7663 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7664 return error(Loc, Reason);
7665
7666 Inst = SelectInst::Create(Op0, Op1, Op2);
7667 return false;
7668}
7669
7670/// parseVAArg
7671/// ::= 'va_arg' TypeAndValue ',' Type
7672bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7673 Value *Op;
7674 Type *EltTy = nullptr;
7675 LocTy TypeLoc;
7676 if (parseTypeAndValue(Op, PFS) ||
7677 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7678 parseType(EltTy, TypeLoc))
7679 return true;
7680
7681 if (!EltTy->isFirstClassType())
7682 return error(TypeLoc, "va_arg requires operand with first class type");
7683
7684 Inst = new VAArgInst(Op, EltTy);
7685 return false;
7686}
7687
7688/// parseExtractElement
7689/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
7690bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7691 LocTy Loc;
7692 Value *Op0, *Op1;
7693 if (parseTypeAndValue(Op0, Loc, PFS) ||
7694 parseToken(lltok::comma, "expected ',' after extract value") ||
7695 parseTypeAndValue(Op1, PFS))
7696 return true;
7697
7699 return error(Loc, "invalid extractelement operands");
7700
7701 Inst = ExtractElementInst::Create(Op0, Op1);
7702 return false;
7703}
7704
7705/// parseInsertElement
7706/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7707bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7708 LocTy Loc;
7709 Value *Op0, *Op1, *Op2;
7710 if (parseTypeAndValue(Op0, Loc, PFS) ||
7711 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7712 parseTypeAndValue(Op1, PFS) ||
7713 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7714 parseTypeAndValue(Op2, PFS))
7715 return true;
7716
7717 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7718 return error(Loc, "invalid insertelement operands");
7719
7720 Inst = InsertElementInst::Create(Op0, Op1, Op2);
7721 return false;
7722}
7723
7724/// parseShuffleVector
7725/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7726bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7727 LocTy Loc;
7728 Value *Op0, *Op1, *Op2;
7729 if (parseTypeAndValue(Op0, Loc, PFS) ||
7730 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7731 parseTypeAndValue(Op1, PFS) ||
7732 parseToken(lltok::comma, "expected ',' after shuffle value") ||
7733 parseTypeAndValue(Op2, PFS))
7734 return true;
7735
7736 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7737 return error(Loc, "invalid shufflevector operands");
7738
7739 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7740 return false;
7741}
7742
7743/// parsePHI
7744/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7745int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7746 Type *Ty = nullptr; LocTy TypeLoc;
7747 Value *Op0, *Op1;
7748
7749 if (parseType(Ty, TypeLoc))
7750 return true;
7751
7752 if (!Ty->isFirstClassType())
7753 return error(TypeLoc, "phi node must have first class type");
7754
7755 bool First = true;
7756 bool AteExtraComma = false;
7758
7759 while (true) {
7760 if (First) {
7761 if (Lex.getKind() != lltok::lsquare)
7762 break;
7763 First = false;
7764 } else if (!EatIfPresent(lltok::comma))
7765 break;
7766
7767 if (Lex.getKind() == lltok::MetadataVar) {
7768 AteExtraComma = true;
7769 break;
7770 }
7771
7772 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7773 parseValue(Ty, Op0, PFS) ||
7774 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7775 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7776 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7777 return true;
7778
7779 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7780 }
7781
7782 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7783 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7784 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7785 Inst = PN;
7786 return AteExtraComma ? InstExtraComma : InstNormal;
7787}
7788
7789/// parseLandingPad
7790/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7791/// Clause
7792/// ::= 'catch' TypeAndValue
7793/// ::= 'filter'
7794/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7795bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7796 Type *Ty = nullptr; LocTy TyLoc;
7797
7798 if (parseType(Ty, TyLoc))
7799 return true;
7800
7801 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7802 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7803
7804 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7806 if (EatIfPresent(lltok::kw_catch))
7808 else if (EatIfPresent(lltok::kw_filter))
7810 else
7811 return tokError("expected 'catch' or 'filter' clause type");
7812
7813 Value *V;
7814 LocTy VLoc;
7815 if (parseTypeAndValue(V, VLoc, PFS))
7816 return true;
7817
7818 // A 'catch' type expects a non-array constant. A filter clause expects an
7819 // array constant.
7820 if (CT == LandingPadInst::Catch) {
7821 if (isa<ArrayType>(V->getType()))
7822 error(VLoc, "'catch' clause has an invalid type");
7823 } else {
7824 if (!isa<ArrayType>(V->getType()))
7825 error(VLoc, "'filter' clause has an invalid type");
7826 }
7827
7828 Constant *CV = dyn_cast<Constant>(V);
7829 if (!CV)
7830 return error(VLoc, "clause argument must be a constant");
7831 LP->addClause(CV);
7832 }
7833
7834 Inst = LP.release();
7835 return false;
7836}
7837
7838/// parseFreeze
7839/// ::= 'freeze' Type Value
7840bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7841 LocTy Loc;
7842 Value *Op;
7843 if (parseTypeAndValue(Op, Loc, PFS))
7844 return true;
7845
7846 Inst = new FreezeInst(Op);
7847 return false;
7848}
7849
7850/// parseCall
7851/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7852/// OptionalAttrs Type Value ParameterList OptionalAttrs
7853/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7854/// OptionalAttrs Type Value ParameterList OptionalAttrs
7855/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7856/// OptionalAttrs Type Value ParameterList OptionalAttrs
7857/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7858/// OptionalAttrs Type Value ParameterList OptionalAttrs
7859bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7861 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7862 std::vector<unsigned> FwdRefAttrGrps;
7863 LocTy BuiltinLoc;
7864 unsigned CallAddrSpace;
7865 unsigned CC;
7866 Type *RetType = nullptr;
7867 LocTy RetTypeLoc;
7868 ValID CalleeID;
7871 LocTy CallLoc = Lex.getLoc();
7872
7873 if (TCK != CallInst::TCK_None &&
7874 parseToken(lltok::kw_call,
7875 "expected 'tail call', 'musttail call', or 'notail call'"))
7876 return true;
7877
7878 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7879
7880 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7881 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7882 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7883 parseValID(CalleeID, &PFS) ||
7884 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7885 PFS.getFunction().isVarArg()) ||
7886 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7887 parseOptionalOperandBundles(BundleList, PFS))
7888 return true;
7889
7890 // If RetType is a non-function pointer type, then this is the short syntax
7891 // for the call, which means that RetType is just the return type. Infer the
7892 // rest of the function argument types from the arguments that are present.
7893 FunctionType *Ty;
7894 if (resolveFunctionType(RetType, ArgList, Ty))
7895 return error(RetTypeLoc, "Invalid result type for LLVM function");
7896
7897 CalleeID.FTy = Ty;
7898
7899 // Look up the callee.
7900 Value *Callee;
7901 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7902 &PFS))
7903 return true;
7904
7905 // Set up the Attribute for the function.
7907
7909
7910 // Loop through FunctionType's arguments and ensure they are specified
7911 // correctly. Also, gather any parameter attributes.
7912 FunctionType::param_iterator I = Ty->param_begin();
7913 FunctionType::param_iterator E = Ty->param_end();
7914 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7915 Type *ExpectedTy = nullptr;
7916 if (I != E) {
7917 ExpectedTy = *I++;
7918 } else if (!Ty->isVarArg()) {
7919 return error(ArgList[i].Loc, "too many arguments specified");
7920 }
7921
7922 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7923 return error(ArgList[i].Loc, "argument is not of expected type '" +
7924 getTypeString(ExpectedTy) + "'");
7925 Args.push_back(ArgList[i].V);
7926 Attrs.push_back(ArgList[i].Attrs);
7927 }
7928
7929 if (I != E)
7930 return error(CallLoc, "not enough parameters specified for call");
7931
7932 // Finish off the Attribute and check them
7933 AttributeList PAL =
7934 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7935 AttributeSet::get(Context, RetAttrs), Attrs);
7936
7937 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7938 CI->setTailCallKind(TCK);
7939 CI->setCallingConv(CC);
7940 if (FMF.any()) {
7941 if (!isa<FPMathOperator>(CI)) {
7942 CI->deleteValue();
7943 return error(CallLoc, "fast-math-flags specified for call without "
7944 "floating-point scalar or vector return type");
7945 }
7946 CI->setFastMathFlags(FMF);
7947 }
7948
7949 if (CalleeID.Kind == ValID::t_GlobalName &&
7950 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
7951 if (SeenNewDbgInfoFormat) {
7952 CI->deleteValue();
7953 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
7954 "using non-intrinsic debug info");
7955 }
7956 if (!SeenOldDbgInfoFormat)
7957 M->setNewDbgInfoFormatFlag(false);
7958 SeenOldDbgInfoFormat = true;
7959 }
7960 CI->setAttributes(PAL);
7961 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7962 Inst = CI;
7963 return false;
7964}
7965
7966//===----------------------------------------------------------------------===//
7967// Memory Instructions.
7968//===----------------------------------------------------------------------===//
7969
7970/// parseAlloc
7971/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7972/// (',' 'align' i32)? (',', 'addrspace(n))?
7973int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7974 Value *Size = nullptr;
7975 LocTy SizeLoc, TyLoc, ASLoc;
7976 MaybeAlign Alignment;
7977 unsigned AddrSpace = 0;
7978 Type *Ty = nullptr;
7979
7980 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7981 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7982
7983 if (parseType(Ty, TyLoc))
7984 return true;
7985
7987 return error(TyLoc, "invalid type for alloca");
7988
7989 bool AteExtraComma = false;
7990 if (EatIfPresent(lltok::comma)) {
7991 if (Lex.getKind() == lltok::kw_align) {
7992 if (parseOptionalAlignment(Alignment))
7993 return true;
7994 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7995 return true;
7996 } else if (Lex.getKind() == lltok::kw_addrspace) {
7997 ASLoc = Lex.getLoc();
7998 if (parseOptionalAddrSpace(AddrSpace))
7999 return true;
8000 } else if (Lex.getKind() == lltok::MetadataVar) {
8001 AteExtraComma = true;
8002 } else {
8003 if (parseTypeAndValue(Size, SizeLoc, PFS))
8004 return true;
8005 if (EatIfPresent(lltok::comma)) {
8006 if (Lex.getKind() == lltok::kw_align) {
8007 if (parseOptionalAlignment(Alignment))
8008 return true;
8009 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8010 return true;
8011 } else if (Lex.getKind() == lltok::kw_addrspace) {
8012 ASLoc = Lex.getLoc();
8013 if (parseOptionalAddrSpace(AddrSpace))
8014 return true;
8015 } else if (Lex.getKind() == lltok::MetadataVar) {
8016 AteExtraComma = true;
8017 }
8018 }
8019 }
8020 }
8021
8022 if (Size && !Size->getType()->isIntegerTy())
8023 return error(SizeLoc, "element count must have integer type");
8024
8025 SmallPtrSet<Type *, 4> Visited;
8026 if (!Alignment && !Ty->isSized(&Visited))
8027 return error(TyLoc, "Cannot allocate unsized type");
8028 if (!Alignment)
8029 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8030 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8031 AI->setUsedWithInAlloca(IsInAlloca);
8032 AI->setSwiftError(IsSwiftError);
8033 Inst = AI;
8034 return AteExtraComma ? InstExtraComma : InstNormal;
8035}
8036
8037/// parseLoad
8038/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8039/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8040/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8041int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8042 Value *Val; LocTy Loc;
8043 MaybeAlign Alignment;
8044 bool AteExtraComma = false;
8045 bool isAtomic = false;
8048
8049 if (Lex.getKind() == lltok::kw_atomic) {
8050 isAtomic = true;
8051 Lex.Lex();
8052 }
8053
8054 bool isVolatile = false;
8055 if (Lex.getKind() == lltok::kw_volatile) {
8056 isVolatile = true;
8057 Lex.Lex();
8058 }
8059
8060 Type *Ty;
8061 LocTy ExplicitTypeLoc = Lex.getLoc();
8062 if (parseType(Ty) ||
8063 parseToken(lltok::comma, "expected comma after load's type") ||
8064 parseTypeAndValue(Val, Loc, PFS) ||
8065 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8066 parseOptionalCommaAlign(Alignment, AteExtraComma))
8067 return true;
8068
8069 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8070 return error(Loc, "load operand must be a pointer to a first class type");
8071 if (isAtomic && !Alignment)
8072 return error(Loc, "atomic load must have explicit non-zero alignment");
8073 if (Ordering == AtomicOrdering::Release ||
8075 return error(Loc, "atomic load cannot use Release ordering");
8076
8077 SmallPtrSet<Type *, 4> Visited;
8078 if (!Alignment && !Ty->isSized(&Visited))
8079 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8080 if (!Alignment)
8081 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8082 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8083 return AteExtraComma ? InstExtraComma : InstNormal;
8084}
8085
8086/// parseStore
8087
8088/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8089/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8090/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8091int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8092 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8093 MaybeAlign Alignment;
8094 bool AteExtraComma = false;
8095 bool isAtomic = false;
8098
8099 if (Lex.getKind() == lltok::kw_atomic) {
8100 isAtomic = true;
8101 Lex.Lex();
8102 }
8103
8104 bool isVolatile = false;
8105 if (Lex.getKind() == lltok::kw_volatile) {
8106 isVolatile = true;
8107 Lex.Lex();
8108 }
8109
8110 if (parseTypeAndValue(Val, Loc, PFS) ||
8111 parseToken(lltok::comma, "expected ',' after store operand") ||
8112 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8113 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8114 parseOptionalCommaAlign(Alignment, AteExtraComma))
8115 return true;
8116
8117 if (!Ptr->getType()->isPointerTy())
8118 return error(PtrLoc, "store operand must be a pointer");
8119 if (!Val->getType()->isFirstClassType())
8120 return error(Loc, "store operand must be a first class value");
8121 if (isAtomic && !Alignment)
8122 return error(Loc, "atomic store must have explicit non-zero alignment");
8123 if (Ordering == AtomicOrdering::Acquire ||
8125 return error(Loc, "atomic store cannot use Acquire ordering");
8126 SmallPtrSet<Type *, 4> Visited;
8127 if (!Alignment && !Val->getType()->isSized(&Visited))
8128 return error(Loc, "storing unsized types is not allowed");
8129 if (!Alignment)
8130 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8131
8132 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8133 return AteExtraComma ? InstExtraComma : InstNormal;
8134}
8135
8136/// parseCmpXchg
8137/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8138/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8139/// 'Align'?
8140int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8141 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8142 bool AteExtraComma = false;
8143 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8144 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8146 bool isVolatile = false;
8147 bool isWeak = false;
8148 MaybeAlign Alignment;
8149
8150 if (EatIfPresent(lltok::kw_weak))
8151 isWeak = true;
8152
8153 if (EatIfPresent(lltok::kw_volatile))
8154 isVolatile = true;
8155
8156 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8157 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8158 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8159 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8160 parseTypeAndValue(New, NewLoc, PFS) ||
8161 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8162 parseOrdering(FailureOrdering) ||
8163 parseOptionalCommaAlign(Alignment, AteExtraComma))
8164 return true;
8165
8166 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8167 return tokError("invalid cmpxchg success ordering");
8168 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8169 return tokError("invalid cmpxchg failure ordering");
8170 if (!Ptr->getType()->isPointerTy())
8171 return error(PtrLoc, "cmpxchg operand must be a pointer");
8172 if (Cmp->getType() != New->getType())
8173 return error(NewLoc, "compare value and new value type do not match");
8174 if (!New->getType()->isFirstClassType())
8175 return error(NewLoc, "cmpxchg operand must be a first class value");
8176
8177 const Align DefaultAlignment(
8178 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8179 Cmp->getType()));
8180
8181 AtomicCmpXchgInst *CXI =
8182 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8183 SuccessOrdering, FailureOrdering, SSID);
8184 CXI->setVolatile(isVolatile);
8185 CXI->setWeak(isWeak);
8186
8187 Inst = CXI;
8188 return AteExtraComma ? InstExtraComma : InstNormal;
8189}
8190
8191/// parseAtomicRMW
8192/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8193/// 'singlethread'? AtomicOrdering
8194int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8195 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8196 bool AteExtraComma = false;
8199 bool isVolatile = false;
8200 bool IsFP = false;
8202 MaybeAlign Alignment;
8203
8204 if (EatIfPresent(lltok::kw_volatile))
8205 isVolatile = true;
8206
8207 switch (Lex.getKind()) {
8208 default:
8209 return tokError("expected binary operation in atomicrmw");
8223 break;
8226 break;
8227 case lltok::kw_fadd:
8229 IsFP = true;
8230 break;
8231 case lltok::kw_fsub:
8233 IsFP = true;
8234 break;
8235 case lltok::kw_fmax:
8237 IsFP = true;
8238 break;
8239 case lltok::kw_fmin:
8241 IsFP = true;
8242 break;
8243 }
8244 Lex.Lex(); // Eat the operation.
8245
8246 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8247 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8248 parseTypeAndValue(Val, ValLoc, PFS) ||
8249 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8250 parseOptionalCommaAlign(Alignment, AteExtraComma))
8251 return true;
8252
8253 if (Ordering == AtomicOrdering::Unordered)
8254 return tokError("atomicrmw cannot be unordered");
8255 if (!Ptr->getType()->isPointerTy())
8256 return error(PtrLoc, "atomicrmw operand must be a pointer");
8257 if (Val->getType()->isScalableTy())
8258 return error(ValLoc, "atomicrmw operand may not be scalable");
8259
8261 if (!Val->getType()->isIntegerTy() &&
8262 !Val->getType()->isFloatingPointTy() &&
8263 !Val->getType()->isPointerTy()) {
8264 return error(
8265 ValLoc,
8267 " operand must be an integer, floating point, or pointer type");
8268 }
8269 } else if (IsFP) {
8270 if (!Val->getType()->isFPOrFPVectorTy()) {
8271 return error(ValLoc, "atomicrmw " +
8273 " operand must be a floating point type");
8274 }
8275 } else {
8276 if (!Val->getType()->isIntegerTy()) {
8277 return error(ValLoc, "atomicrmw " +
8279 " operand must be an integer");
8280 }
8281 }
8282
8283 unsigned Size =
8284 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
8285 Val->getType());
8286 if (Size < 8 || (Size & (Size - 1)))
8287 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8288 " integer");
8289 const Align DefaultAlignment(
8290 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8291 Val->getType()));
8292 AtomicRMWInst *RMWI =
8293 new AtomicRMWInst(Operation, Ptr, Val,
8294 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8295 RMWI->setVolatile(isVolatile);
8296 Inst = RMWI;
8297 return AteExtraComma ? InstExtraComma : InstNormal;
8298}
8299
8300/// parseFence
8301/// ::= 'fence' 'singlethread'? AtomicOrdering
8302int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8305 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8306 return true;
8307
8308 if (Ordering == AtomicOrdering::Unordered)
8309 return tokError("fence cannot be unordered");
8310 if (Ordering == AtomicOrdering::Monotonic)
8311 return tokError("fence cannot be monotonic");
8312
8313 Inst = new FenceInst(Context, Ordering, SSID);
8314 return InstNormal;
8315}
8316
8317/// parseGetElementPtr
8318/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8319int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8320 Value *Ptr = nullptr;
8321 Value *Val = nullptr;
8322 LocTy Loc, EltLoc;
8323
8324 bool InBounds = EatIfPresent(lltok::kw_inbounds);
8325
8326 Type *Ty = nullptr;
8327 if (parseType(Ty) ||
8328 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8329 parseTypeAndValue(Ptr, Loc, PFS))
8330 return true;
8331
8332 Type *BaseType = Ptr->getType();
8333 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8334 if (!BasePointerType)
8335 return error(Loc, "base of getelementptr must be a pointer");
8336
8338 bool AteExtraComma = false;
8339 // GEP returns a vector of pointers if at least one of parameters is a vector.
8340 // All vector parameters should have the same vector width.
8341 ElementCount GEPWidth = BaseType->isVectorTy()
8342 ? cast<VectorType>(BaseType)->getElementCount()
8344
8345 while (EatIfPresent(lltok::comma)) {
8346 if (Lex.getKind() == lltok::MetadataVar) {
8347 AteExtraComma = true;
8348 break;
8349 }
8350 if (parseTypeAndValue(Val, EltLoc, PFS))
8351 return true;
8352 if (!Val->getType()->isIntOrIntVectorTy())
8353 return error(EltLoc, "getelementptr index must be an integer");
8354
8355 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8356 ElementCount ValNumEl = ValVTy->getElementCount();
8357 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8358 return error(
8359 EltLoc,
8360 "getelementptr vector index has a wrong number of elements");
8361 GEPWidth = ValNumEl;
8362 }
8363 Indices.push_back(Val);
8364 }
8365
8366 SmallPtrSet<Type*, 4> Visited;
8367 if (!Indices.empty() && !Ty->isSized(&Visited))
8368 return error(Loc, "base element of getelementptr must be sized");
8369
8370 auto *STy = dyn_cast<StructType>(Ty);
8371 if (STy && STy->containsScalableVectorType())
8372 return error(Loc, "getelementptr cannot target structure that contains "
8373 "scalable vector type");
8374
8375 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8376 return error(Loc, "invalid getelementptr indices");
8377 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
8378 if (InBounds)
8379 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
8380 return AteExtraComma ? InstExtraComma : InstNormal;
8381}
8382
8383/// parseExtractValue
8384/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8385int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8386 Value *Val; LocTy Loc;
8388 bool AteExtraComma;
8389 if (parseTypeAndValue(Val, Loc, PFS) ||
8390 parseIndexList(Indices, AteExtraComma))
8391 return true;
8392
8393 if (!Val->getType()->isAggregateType())
8394 return error(Loc, "extractvalue operand must be aggregate type");
8395
8396 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8397 return error(Loc, "invalid indices for extractvalue");
8398 Inst = ExtractValueInst::Create(Val, Indices);
8399 return AteExtraComma ? InstExtraComma : InstNormal;
8400}
8401
8402/// parseInsertValue
8403/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8404int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8405 Value *Val0, *Val1; LocTy Loc0, Loc1;
8407 bool AteExtraComma;
8408 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8409 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8410 parseTypeAndValue(Val1, Loc1, PFS) ||
8411 parseIndexList(Indices, AteExtraComma))
8412 return true;
8413
8414 if (!Val0->getType()->isAggregateType())
8415 return error(Loc0, "insertvalue operand must be aggregate type");
8416
8417 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8418 if (!IndexedType)
8419 return error(Loc0, "invalid indices for insertvalue");
8420 if (IndexedType != Val1->getType())
8421 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8422 getTypeString(Val1->getType()) + "' instead of '" +
8423 getTypeString(IndexedType) + "'");
8424 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8425 return AteExtraComma ? InstExtraComma : InstNormal;
8426}
8427
8428//===----------------------------------------------------------------------===//
8429// Embedded metadata.
8430//===----------------------------------------------------------------------===//
8431
8432/// parseMDNodeVector
8433/// ::= { Element (',' Element)* }
8434/// Element
8435/// ::= 'null' | Metadata
8436bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8437 if (parseToken(lltok::lbrace, "expected '{' here"))
8438 return true;
8439
8440 // Check for an empty list.
8441 if (EatIfPresent(lltok::rbrace))
8442 return false;
8443
8444 do {
8445 if (EatIfPresent(lltok::kw_null)) {
8446 Elts.push_back(nullptr);
8447 continue;
8448 }
8449
8450 Metadata *MD;
8451 if (parseMetadata(MD, nullptr))
8452 return true;
8453 Elts.push_back(MD);
8454 } while (EatIfPresent(lltok::comma));
8455
8456 return parseToken(lltok::rbrace, "expected end of metadata node");
8457}
8458
8459//===----------------------------------------------------------------------===//
8460// Use-list order directives.
8461//===----------------------------------------------------------------------===//
8462bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
8463 SMLoc Loc) {
8464 if (V->use_empty())
8465 return error(Loc, "value has no uses");
8466
8467 unsigned NumUses = 0;
8469 for (const Use &U : V->uses()) {
8470 if (++NumUses > Indexes.size())
8471 break;
8472 Order[&U] = Indexes[NumUses - 1];
8473 }
8474 if (NumUses < 2)
8475 return error(Loc, "value only has one use");
8476 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
8477 return error(Loc,
8478 "wrong number of indexes, expected " + Twine(V->getNumUses()));
8479
8480 V->sortUseList([&](const Use &L, const Use &R) {
8481 return Order.lookup(&L) < Order.lookup(&R);
8482 });
8483 return false;
8484}
8485
8486/// parseUseListOrderIndexes
8487/// ::= '{' uint32 (',' uint32)+ '}'
8488bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8489 SMLoc Loc = Lex.getLoc();
8490 if (parseToken(lltok::lbrace, "expected '{' here"))
8491 return true;
8492 if (Lex.getKind() == lltok::rbrace)
8493 return Lex.Error("expected non-empty list of uselistorder indexes");
8494
8495 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8496 // indexes should be distinct numbers in the range [0, size-1], and should
8497 // not be in order.
8498 unsigned Offset = 0;
8499 unsigned Max = 0;
8500 bool IsOrdered = true;
8501 assert(Indexes.empty() && "Expected empty order vector");
8502 do {
8503 unsigned Index;
8504 if (parseUInt32(Index))
8505 return true;
8506
8507 // Update consistency checks.
8508 Offset += Index - Indexes.size();
8509 Max = std::max(Max, Index);
8510 IsOrdered &= Index == Indexes.size();
8511
8512 Indexes.push_back(Index);
8513 } while (EatIfPresent(lltok::comma));
8514
8515 if (parseToken(lltok::rbrace, "expected '}' here"))
8516 return true;
8517
8518 if (Indexes.size() < 2)
8519 return error(Loc, "expected >= 2 uselistorder indexes");
8520 if (Offset != 0 || Max >= Indexes.size())
8521 return error(Loc,
8522 "expected distinct uselistorder indexes in range [0, size)");
8523 if (IsOrdered)
8524 return error(Loc, "expected uselistorder indexes to change the order");
8525
8526 return false;
8527}
8528
8529/// parseUseListOrder
8530/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8531bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8532 SMLoc Loc = Lex.getLoc();
8533 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
8534 return true;
8535
8536 Value *V;
8538 if (parseTypeAndValue(V, PFS) ||
8539 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
8540 parseUseListOrderIndexes(Indexes))
8541 return true;
8542
8543 return sortUseListOrder(V, Indexes, Loc);
8544}
8545
8546/// parseUseListOrderBB
8547/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8548bool LLParser::parseUseListOrderBB() {
8550 SMLoc Loc = Lex.getLoc();
8551 Lex.Lex();
8552
8553 ValID Fn, Label;
8555 if (parseValID(Fn, /*PFS=*/nullptr) ||
8556 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8557 parseValID(Label, /*PFS=*/nullptr) ||
8558 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8559 parseUseListOrderIndexes(Indexes))
8560 return true;
8561
8562 // Check the function.
8563 GlobalValue *GV;
8564 if (Fn.Kind == ValID::t_GlobalName)
8565 GV = M->getNamedValue(Fn.StrVal);
8566 else if (Fn.Kind == ValID::t_GlobalID)
8567 GV = NumberedVals.get(Fn.UIntVal);
8568 else
8569 return error(Fn.Loc, "expected function name in uselistorder_bb");
8570 if (!GV)
8571 return error(Fn.Loc,
8572 "invalid function forward reference in uselistorder_bb");
8573 auto *F = dyn_cast<Function>(GV);
8574 if (!F)
8575 return error(Fn.Loc, "expected function name in uselistorder_bb");
8576 if (F->isDeclaration())
8577 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
8578
8579 // Check the basic block.
8580 if (Label.Kind == ValID::t_LocalID)
8581 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
8582 if (Label.Kind != ValID::t_LocalName)
8583 return error(Label.Loc, "expected basic block name in uselistorder_bb");
8584 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
8585 if (!V)
8586 return error(Label.Loc, "invalid basic block in uselistorder_bb");
8587 if (!isa<BasicBlock>(V))
8588 return error(Label.Loc, "expected basic block in uselistorder_bb");
8589
8590 return sortUseListOrder(V, Indexes, Loc);
8591}
8592
8593/// ModuleEntry
8594/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8595/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8596bool LLParser::parseModuleEntry(unsigned ID) {
8598 Lex.Lex();
8599
8600 std::string Path;
8601 if (parseToken(lltok::colon, "expected ':' here") ||
8602 parseToken(lltok::lparen, "expected '(' here") ||
8603 parseToken(lltok::kw_path, "expected 'path' here") ||
8604 parseToken(lltok::colon, "expected ':' here") ||
8605 parseStringConstant(Path) ||
8606 parseToken(lltok::comma, "expected ',' here") ||
8607 parseToken(lltok::kw_hash, "expected 'hash' here") ||
8608 parseToken(lltok::colon, "expected ':' here") ||
8609 parseToken(lltok::lparen, "expected '(' here"))
8610 return true;
8611
8612 ModuleHash Hash;
8613 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8614 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8615 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8616 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8617 parseUInt32(Hash[4]))
8618 return true;
8619
8620 if (parseToken(lltok::rparen, "expected ')' here") ||
8621 parseToken(lltok::rparen, "expected ')' here"))
8622 return true;
8623
8624 auto ModuleEntry = Index->addModule(Path, Hash);
8625 ModuleIdMap[ID] = ModuleEntry->first();
8626
8627 return false;
8628}
8629
8630/// TypeIdEntry
8631/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8632bool LLParser::parseTypeIdEntry(unsigned ID) {
8634 Lex.Lex();
8635
8636 std::string Name;
8637 if (parseToken(lltok::colon, "expected ':' here") ||
8638 parseToken(lltok::lparen, "expected '(' here") ||
8639 parseToken(lltok::kw_name, "expected 'name' here") ||
8640 parseToken(lltok::colon, "expected ':' here") ||
8641 parseStringConstant(Name))
8642 return true;
8643
8644 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8645 if (parseToken(lltok::comma, "expected ',' here") ||
8646 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8647 return true;
8648
8649 // Check if this ID was forward referenced, and if so, update the
8650 // corresponding GUIDs.
8651 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8652 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8653 for (auto TIDRef : FwdRefTIDs->second) {
8654 assert(!*TIDRef.first &&
8655 "Forward referenced type id GUID expected to be 0");
8656 *TIDRef.first = GlobalValue::getGUID(Name);
8657 }
8658 ForwardRefTypeIds.erase(FwdRefTIDs);
8659 }
8660
8661 return false;
8662}
8663
8664/// TypeIdSummary
8665/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8666bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8667 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8668 parseToken(lltok::colon, "expected ':' here") ||
8669 parseToken(lltok::lparen, "expected '(' here") ||
8670 parseTypeTestResolution(TIS.TTRes))
8671 return true;
8672
8673 if (EatIfPresent(lltok::comma)) {
8674 // Expect optional wpdResolutions field
8675 if (parseOptionalWpdResolutions(TIS.WPDRes))
8676 return true;
8677 }
8678
8679 if (parseToken(lltok::rparen, "expected ')' here"))
8680 return true;
8681
8682 return false;
8683}
8684
8686 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8687
8688/// TypeIdCompatibleVtableEntry
8689/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8690/// TypeIdCompatibleVtableInfo
8691/// ')'
8692bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8694 Lex.Lex();
8695
8696 std::string Name;
8697 if (parseToken(lltok::colon, "expected ':' here") ||
8698 parseToken(lltok::lparen, "expected '(' here") ||
8699 parseToken(lltok::kw_name, "expected 'name' here") ||
8700 parseToken(lltok::colon, "expected ':' here") ||
8701 parseStringConstant(Name))
8702 return true;
8703
8705 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8706 if (parseToken(lltok::comma, "expected ',' here") ||
8707 parseToken(lltok::kw_summary, "expected 'summary' here") ||
8708 parseToken(lltok::colon, "expected ':' here") ||
8709 parseToken(lltok::lparen, "expected '(' here"))
8710 return true;
8711
8712 IdToIndexMapType IdToIndexMap;
8713 // parse each call edge
8714 do {
8716 if (parseToken(lltok::lparen, "expected '(' here") ||
8717 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8718 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8719 parseToken(lltok::comma, "expected ',' here"))
8720 return true;
8721
8722 LocTy Loc = Lex.getLoc();
8723 unsigned GVId;
8724 ValueInfo VI;
8725 if (parseGVReference(VI, GVId))
8726 return true;
8727
8728 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8729 // forward reference. We will save the location of the ValueInfo needing an
8730 // update, but can only do so once the std::vector is finalized.
8731 if (VI == EmptyVI)
8732 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8733 TI.push_back({Offset, VI});
8734
8735 if (parseToken(lltok::rparen, "expected ')' in call"))
8736 return true;
8737 } while (EatIfPresent(lltok::comma));
8738
8739 // Now that the TI vector is finalized, it is safe to save the locations
8740 // of any forward GV references that need updating later.
8741 for (auto I : IdToIndexMap) {
8742 auto &Infos = ForwardRefValueInfos[I.first];
8743 for (auto P : I.second) {
8744 assert(TI[P.first].VTableVI == EmptyVI &&
8745 "Forward referenced ValueInfo expected to be empty");
8746 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8747 }
8748 }
8749
8750 if (parseToken(lltok::rparen, "expected ')' here") ||
8751 parseToken(lltok::rparen, "expected ')' here"))
8752 return true;
8753
8754 // Check if this ID was forward referenced, and if so, update the
8755 // corresponding GUIDs.
8756 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8757 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8758 for (auto TIDRef : FwdRefTIDs->second) {
8759 assert(!*TIDRef.first &&
8760 "Forward referenced type id GUID expected to be 0");
8761 *TIDRef.first = GlobalValue::getGUID(Name);
8762 }
8763 ForwardRefTypeIds.erase(FwdRefTIDs);
8764 }
8765
8766 return false;
8767}
8768
8769/// TypeTestResolution
8770/// ::= 'typeTestRes' ':' '(' 'kind' ':'
8771/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8772/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8773/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8774/// [',' 'inlinesBits' ':' UInt64]? ')'
8775bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8776 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8777 parseToken(lltok::colon, "expected ':' here") ||
8778 parseToken(lltok::lparen, "expected '(' here") ||
8779 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8780 parseToken(lltok::colon, "expected ':' here"))
8781 return true;
8782
8783 switch (Lex.getKind()) {
8784 case lltok::kw_unknown:
8786 break;
8787 case lltok::kw_unsat:
8789 break;
8792 break;
8793 case lltok::kw_inline:
8795 break;
8796 case lltok::kw_single:
8798 break;
8799 case lltok::kw_allOnes:
8801 break;
8802 default:
8803 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8804 }
8805 Lex.Lex();
8806
8807 if (parseToken(lltok::comma, "expected ',' here") ||
8808 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8809 parseToken(lltok::colon, "expected ':' here") ||
8810 parseUInt32(TTRes.SizeM1BitWidth))
8811 return true;
8812
8813 // parse optional fields
8814 while (EatIfPresent(lltok::comma)) {
8815 switch (Lex.getKind()) {
8817 Lex.Lex();
8818 if (parseToken(lltok::colon, "expected ':'") ||
8819 parseUInt64(TTRes.AlignLog2))
8820 return true;
8821 break;
8822 case lltok::kw_sizeM1:
8823 Lex.Lex();
8824 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8825 return true;
8826 break;
8827 case lltok::kw_bitMask: {
8828 unsigned Val;
8829 Lex.Lex();
8830 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8831 return true;
8832 assert(Val <= 0xff);
8833 TTRes.BitMask = (uint8_t)Val;
8834 break;
8835 }
8837 Lex.Lex();
8838 if (parseToken(lltok::colon, "expected ':'") ||
8839 parseUInt64(TTRes.InlineBits))
8840 return true;
8841 break;
8842 default:
8843 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8844 }
8845 }
8846
8847 if (parseToken(lltok::rparen, "expected ')' here"))
8848 return true;
8849
8850 return false;
8851}
8852
8853/// OptionalWpdResolutions
8854/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8855/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8856bool LLParser::parseOptionalWpdResolutions(
8857 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8858 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8859 parseToken(lltok::colon, "expected ':' here") ||
8860 parseToken(lltok::lparen, "expected '(' here"))
8861 return true;
8862
8863 do {
8866 if (parseToken(lltok::lparen, "expected '(' here") ||
8867 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8868 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8869 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8870 parseToken(lltok::rparen, "expected ')' here"))
8871 return true;
8872 WPDResMap[Offset] = WPDRes;
8873 } while (EatIfPresent(lltok::comma));
8874
8875 if (parseToken(lltok::rparen, "expected ')' here"))
8876 return true;
8877
8878 return false;
8879}
8880
8881/// WpdRes
8882/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8883/// [',' OptionalResByArg]? ')'
8884/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8885/// ',' 'singleImplName' ':' STRINGCONSTANT ','
8886/// [',' OptionalResByArg]? ')'
8887/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8888/// [',' OptionalResByArg]? ')'
8889bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8890 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8891 parseToken(lltok::colon, "expected ':' here") ||
8892 parseToken(lltok::lparen, "expected '(' here") ||
8893 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8894 parseToken(lltok::colon, "expected ':' here"))
8895 return true;
8896
8897 switch (Lex.getKind()) {
8898 case lltok::kw_indir:
8900 break;
8903 break;
8906 break;
8907 default:
8908 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8909 }
8910 Lex.Lex();
8911
8912 // parse optional fields
8913 while (EatIfPresent(lltok::comma)) {
8914 switch (Lex.getKind()) {
8916 Lex.Lex();
8917 if (parseToken(lltok::colon, "expected ':' here") ||
8918 parseStringConstant(WPDRes.SingleImplName))
8919 return true;
8920 break;
8921 case lltok::kw_resByArg:
8922 if (parseOptionalResByArg(WPDRes.ResByArg))
8923 return true;
8924 break;
8925 default:
8926 return error(Lex.getLoc(),
8927 "expected optional WholeProgramDevirtResolution field");
8928 }
8929 }
8930
8931 if (parseToken(lltok::rparen, "expected ')' here"))
8932 return true;
8933
8934 return false;
8935}
8936
8937/// OptionalResByArg
8938/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8939/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8940/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8941/// 'virtualConstProp' )
8942/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8943/// [',' 'bit' ':' UInt32]? ')'
8944bool LLParser::parseOptionalResByArg(
8945 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8946 &ResByArg) {
8947 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8948 parseToken(lltok::colon, "expected ':' here") ||
8949 parseToken(lltok::lparen, "expected '(' here"))
8950 return true;
8951
8952 do {
8953 std::vector<uint64_t> Args;
8954 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8955 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8956 parseToken(lltok::colon, "expected ':' here") ||
8957 parseToken(lltok::lparen, "expected '(' here") ||
8958 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8959 parseToken(lltok::colon, "expected ':' here"))
8960 return true;
8961
8963 switch (Lex.getKind()) {
8964 case lltok::kw_indir:
8966 break;
8969 break;
8972 break;
8975 break;
8976 default:
8977 return error(Lex.getLoc(),
8978 "unexpected WholeProgramDevirtResolution::ByArg kind");
8979 }
8980 Lex.Lex();
8981
8982 // parse optional fields
8983 while (EatIfPresent(lltok::comma)) {
8984 switch (Lex.getKind()) {
8985 case lltok::kw_info:
8986 Lex.Lex();
8987 if (parseToken(lltok::colon, "expected ':' here") ||
8988 parseUInt64(ByArg.Info))
8989 return true;
8990 break;
8991 case lltok::kw_byte:
8992 Lex.Lex();
8993 if (parseToken(lltok::colon, "expected ':' here") ||
8994 parseUInt32(ByArg.Byte))
8995 return true;
8996 break;
8997 case lltok::kw_bit:
8998 Lex.Lex();
8999 if (parseToken(lltok::colon, "expected ':' here") ||
9000 parseUInt32(ByArg.Bit))
9001 return true;
9002 break;
9003 default:
9004 return error(Lex.getLoc(),
9005 "expected optional whole program devirt field");
9006 }
9007 }
9008
9009 if (parseToken(lltok::rparen, "expected ')' here"))
9010 return true;
9011
9012 ResByArg[Args] = ByArg;
9013 } while (EatIfPresent(lltok::comma));
9014
9015 if (parseToken(lltok::rparen, "expected ')' here"))
9016 return true;
9017
9018 return false;
9019}
9020
9021/// OptionalResByArg
9022/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9023bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9024 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9025 parseToken(lltok::colon, "expected ':' here") ||
9026 parseToken(lltok::lparen, "expected '(' here"))
9027 return true;
9028
9029 do {
9030 uint64_t Val;
9031 if (parseUInt64(Val))
9032 return true;
9033 Args.push_back(Val);
9034 } while (EatIfPresent(lltok::comma));
9035
9036 if (parseToken(lltok::rparen, "expected ')' here"))
9037 return true;
9038
9039 return false;
9040}
9041
9042static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9043
9044static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9045 bool ReadOnly = Fwd->isReadOnly();
9046 bool WriteOnly = Fwd->isWriteOnly();
9047 assert(!(ReadOnly && WriteOnly));
9048 *Fwd = Resolved;
9049 if (ReadOnly)
9050 Fwd->setReadOnly();
9051 if (WriteOnly)
9052 Fwd->setWriteOnly();
9053}
9054
9055/// Stores the given Name/GUID and associated summary into the Index.
9056/// Also updates any forward references to the associated entry ID.
9057bool LLParser::addGlobalValueToIndex(
9058 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9059 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9060 // First create the ValueInfo utilizing the Name or GUID.
9061 ValueInfo VI;
9062 if (GUID != 0) {
9063 assert(Name.empty());
9064 VI = Index->getOrInsertValueInfo(GUID);
9065 } else {
9066 assert(!Name.empty());
9067 if (M) {
9068 auto *GV = M->getNamedValue(Name);
9069 if (!GV)
9070 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9071
9072 VI = Index->getOrInsertValueInfo(GV);
9073 } else {
9074 assert(
9075 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9076 "Need a source_filename to compute GUID for local");
9077 GUID = GlobalValue::getGUID(
9078 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9079 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9080 }
9081 }
9082
9083 // Resolve forward references from calls/refs
9084 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9085 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9086 for (auto VIRef : FwdRefVIs->second) {
9087 assert(VIRef.first->getRef() == FwdVIRef &&
9088 "Forward referenced ValueInfo expected to be empty");
9089 resolveFwdRef(VIRef.first, VI);
9090 }
9091 ForwardRefValueInfos.erase(FwdRefVIs);
9092 }
9093
9094 // Resolve forward references from aliases
9095 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9096 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9097 for (auto AliaseeRef : FwdRefAliasees->second) {
9098 assert(!AliaseeRef.first->hasAliasee() &&
9099 "Forward referencing alias already has aliasee");
9100 assert(Summary && "Aliasee must be a definition");
9101 AliaseeRef.first->setAliasee(VI, Summary.get());
9102 }
9103 ForwardRefAliasees.erase(FwdRefAliasees);
9104 }
9105
9106 // Add the summary if one was provided.
9107 if (Summary)
9108 Index->addGlobalValueSummary(VI, std::move(Summary));
9109
9110 // Save the associated ValueInfo for use in later references by ID.
9111 if (ID == NumberedValueInfos.size())
9112 NumberedValueInfos.push_back(VI);
9113 else {
9114 // Handle non-continuous numbers (to make test simplification easier).
9115 if (ID > NumberedValueInfos.size())
9116 NumberedValueInfos.resize(ID + 1);
9117 NumberedValueInfos[ID] = VI;
9118 }
9119
9120 return false;
9121}
9122
9123/// parseSummaryIndexFlags
9124/// ::= 'flags' ':' UInt64
9125bool LLParser::parseSummaryIndexFlags() {
9126 assert(Lex.getKind() == lltok::kw_flags);
9127 Lex.Lex();
9128
9129 if (parseToken(lltok::colon, "expected ':' here"))
9130 return true;
9132 if (parseUInt64(Flags))
9133 return true;
9134 if (Index)
9135 Index->setFlags(Flags);
9136 return false;
9137}
9138
9139/// parseBlockCount
9140/// ::= 'blockcount' ':' UInt64
9141bool LLParser::parseBlockCount() {
9143 Lex.Lex();
9144
9145 if (parseToken(lltok::colon, "expected ':' here"))
9146 return true;
9147 uint64_t BlockCount;
9148 if (parseUInt64(BlockCount))
9149 return true;
9150 if (Index)
9151 Index->setBlockCount(BlockCount);
9152 return false;
9153}
9154
9155/// parseGVEntry
9156/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9157/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9158/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9159bool LLParser::parseGVEntry(unsigned ID) {
9160 assert(Lex.getKind() == lltok::kw_gv);
9161 Lex.Lex();
9162
9163 if (parseToken(lltok::colon, "expected ':' here") ||
9164 parseToken(lltok::lparen, "expected '(' here"))
9165 return true;
9166
9167 LocTy Loc = Lex.getLoc();
9168 std::string Name;
9169 GlobalValue::GUID GUID = 0;
9170 switch (Lex.getKind()) {
9171 case lltok::kw_name:
9172 Lex.Lex();
9173 if (parseToken(lltok::colon, "expected ':' here") ||
9174 parseStringConstant(Name))
9175 return true;
9176 // Can't create GUID/ValueInfo until we have the linkage.
9177 break;
9178 case lltok::kw_guid:
9179 Lex.Lex();
9180 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9181 return true;
9182 break;
9183 default:
9184 return error(Lex.getLoc(), "expected name or guid tag");
9185 }
9186
9187 if (!EatIfPresent(lltok::comma)) {
9188 // No summaries. Wrap up.
9189 if (parseToken(lltok::rparen, "expected ')' here"))
9190 return true;
9191 // This was created for a call to an external or indirect target.
9192 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9193 // created for indirect calls with VP. A Name with no GUID came from
9194 // an external definition. We pass ExternalLinkage since that is only
9195 // used when the GUID must be computed from Name, and in that case
9196 // the symbol must have external linkage.
9197 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9198 nullptr, Loc);
9199 }
9200
9201 // Have a list of summaries
9202 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9203 parseToken(lltok::colon, "expected ':' here") ||
9204 parseToken(lltok::lparen, "expected '(' here"))
9205 return true;
9206 do {
9207 switch (Lex.getKind()) {
9208 case lltok::kw_function:
9209 if (parseFunctionSummary(Name, GUID, ID))
9210 return true;
9211 break;
9212 case lltok::kw_variable:
9213 if (parseVariableSummary(Name, GUID, ID))
9214 return true;
9215 break;
9216 case lltok::kw_alias:
9217 if (parseAliasSummary(Name, GUID, ID))
9218 return true;
9219 break;
9220 default:
9221 return error(Lex.getLoc(), "expected summary type");
9222 }
9223 } while (EatIfPresent(lltok::comma));
9224
9225 if (parseToken(lltok::rparen, "expected ')' here") ||
9226 parseToken(lltok::rparen, "expected ')' here"))
9227 return true;
9228
9229 return false;
9230}
9231
9232/// FunctionSummary
9233/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9234/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9235/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9236/// [',' OptionalRefs]? ')'
9237bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9238 unsigned ID) {
9239 LocTy Loc = Lex.getLoc();
9241 Lex.Lex();
9242
9243 StringRef ModulePath;
9246 /*NotEligibleToImport=*/false,
9247 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9249 unsigned InstCount;
9250 std::vector<FunctionSummary::EdgeTy> Calls;
9251 FunctionSummary::TypeIdInfo TypeIdInfo;
9252 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9253 std::vector<ValueInfo> Refs;
9254 std::vector<CallsiteInfo> Callsites;
9255 std::vector<AllocInfo> Allocs;
9256 // Default is all-zeros (conservative values).
9257 FunctionSummary::FFlags FFlags = {};
9258 if (parseToken(lltok::colon, "expected ':' here") ||
9259 parseToken(lltok::lparen, "expected '(' here") ||
9260 parseModuleReference(ModulePath) ||
9261 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9262 parseToken(lltok::comma, "expected ',' here") ||
9263 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9264 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9265 return true;
9266
9267 // parse optional fields
9268 while (EatIfPresent(lltok::comma)) {
9269 switch (Lex.getKind()) {
9271 if (parseOptionalFFlags(FFlags))
9272 return true;
9273 break;
9274 case lltok::kw_calls:
9275 if (parseOptionalCalls(Calls))
9276 return true;
9277 break;
9279 if (parseOptionalTypeIdInfo(TypeIdInfo))
9280 return true;
9281 break;
9282 case lltok::kw_refs:
9283 if (parseOptionalRefs(Refs))
9284 return true;
9285 break;
9286 case lltok::kw_params:
9287 if (parseOptionalParamAccesses(ParamAccesses))
9288 return true;
9289 break;
9290 case lltok::kw_allocs:
9291 if (parseOptionalAllocs(Allocs))
9292 return true;
9293 break;
9295 if (parseOptionalCallsites(Callsites))
9296 return true;
9297 break;
9298 default:
9299 return error(Lex.getLoc(), "expected optional function summary field");
9300 }
9301 }
9302
9303 if (parseToken(lltok::rparen, "expected ')' here"))
9304 return true;
9305
9306 auto FS = std::make_unique<FunctionSummary>(
9307 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
9308 std::move(Calls), std::move(TypeIdInfo.TypeTests),
9309 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9310 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9311 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9312 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9313 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9314
9315 FS->setModulePath(ModulePath);
9316
9317 return addGlobalValueToIndex(Name, GUID,
9319 std::move(FS), Loc);
9320}
9321
9322/// VariableSummary
9323/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9324/// [',' OptionalRefs]? ')'
9325bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9326 unsigned ID) {
9327 LocTy Loc = Lex.getLoc();
9329 Lex.Lex();
9330
9331 StringRef ModulePath;
9334 /*NotEligibleToImport=*/false,
9335 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9337 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9338 /* WriteOnly */ false,
9339 /* Constant */ false,
9341 std::vector<ValueInfo> Refs;
9342 VTableFuncList VTableFuncs;
9343 if (parseToken(lltok::colon, "expected ':' here") ||
9344 parseToken(lltok::lparen, "expected '(' here") ||
9345 parseModuleReference(ModulePath) ||
9346 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9347 parseToken(lltok::comma, "expected ',' here") ||
9348 parseGVarFlags(GVarFlags))
9349 return true;
9350
9351 // parse optional fields
9352 while (EatIfPresent(lltok::comma)) {
9353 switch (Lex.getKind()) {
9355 if (parseOptionalVTableFuncs(VTableFuncs))
9356 return true;
9357 break;
9358 case lltok::kw_refs:
9359 if (parseOptionalRefs(Refs))
9360 return true;
9361 break;
9362 default:
9363 return error(Lex.getLoc(), "expected optional variable summary field");
9364 }
9365 }
9366
9367 if (parseToken(lltok::rparen, "expected ')' here"))
9368 return true;
9369
9370 auto GS =
9371 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9372
9373 GS->setModulePath(ModulePath);
9374 GS->setVTableFuncs(std::move(VTableFuncs));
9375
9376 return addGlobalValueToIndex(Name, GUID,
9378 std::move(GS), Loc);
9379}
9380
9381/// AliasSummary
9382/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9383/// 'aliasee' ':' GVReference ')'
9384bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9385 unsigned ID) {
9386 assert(Lex.getKind() == lltok::kw_alias);
9387 LocTy Loc = Lex.getLoc();
9388 Lex.Lex();
9389
9390 StringRef ModulePath;
9393 /*NotEligibleToImport=*/false,
9394 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9396 if (parseToken(lltok::colon, "expected ':' here") ||
9397 parseToken(lltok::lparen, "expected '(' here") ||
9398 parseModuleReference(ModulePath) ||
9399 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9400 parseToken(lltok::comma, "expected ',' here") ||
9401 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9402 parseToken(lltok::colon, "expected ':' here"))
9403 return true;
9404
9405 ValueInfo AliaseeVI;
9406 unsigned GVId;
9407 if (parseGVReference(AliaseeVI, GVId))
9408 return true;
9409
9410 if (parseToken(lltok::rparen, "expected ')' here"))
9411 return true;
9412
9413 auto AS = std::make_unique<AliasSummary>(GVFlags);
9414
9415 AS->setModulePath(ModulePath);
9416
9417 // Record forward reference if the aliasee is not parsed yet.
9418 if (AliaseeVI.getRef() == FwdVIRef) {
9419 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9420 } else {
9421 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9422 assert(Summary && "Aliasee must be a definition");
9423 AS->setAliasee(AliaseeVI, Summary);
9424 }
9425
9426 return addGlobalValueToIndex(Name, GUID,
9428 std::move(AS), Loc);
9429}
9430
9431/// Flag
9432/// ::= [0|1]
9433bool LLParser::parseFlag(unsigned &Val) {
9434 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9435 return tokError("expected integer");
9436 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9437 Lex.Lex();
9438 return false;
9439}
9440
9441/// OptionalFFlags
9442/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9443/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9444/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9445/// [',' 'noInline' ':' Flag]? ')'
9446/// [',' 'alwaysInline' ':' Flag]? ')'
9447/// [',' 'noUnwind' ':' Flag]? ')'
9448/// [',' 'mayThrow' ':' Flag]? ')'
9449/// [',' 'hasUnknownCall' ':' Flag]? ')'
9450/// [',' 'mustBeUnreachable' ':' Flag]? ')'
9451
9452bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9454 Lex.Lex();
9455
9456 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
9457 parseToken(lltok::lparen, "expected '(' in funcFlags"))
9458 return true;
9459
9460 do {
9461 unsigned Val = 0;
9462 switch (Lex.getKind()) {
9463 case lltok::kw_readNone:
9464 Lex.Lex();
9465 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9466 return true;
9467 FFlags.ReadNone = Val;
9468 break;
9469 case lltok::kw_readOnly:
9470 Lex.Lex();
9471 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9472 return true;
9473 FFlags.ReadOnly = Val;
9474 break;
9476 Lex.Lex();
9477 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9478 return true;
9479 FFlags.NoRecurse = Val;
9480 break;
9482 Lex.Lex();
9483 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9484 return true;
9485 FFlags.ReturnDoesNotAlias = Val;
9486 break;
9487 case lltok::kw_noInline:
9488 Lex.Lex();
9489 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9490 return true;
9491 FFlags.NoInline = Val;
9492 break;
9494 Lex.Lex();
9495 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9496 return true;
9497 FFlags.AlwaysInline = Val;
9498 break;
9499 case lltok::kw_noUnwind:
9500 Lex.Lex();
9501 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9502 return true;
9503 FFlags.NoUnwind = Val;
9504 break;
9505 case lltok::kw_mayThrow:
9506 Lex.Lex();
9507 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9508 return true;
9509 FFlags.MayThrow = Val;
9510 break;
9512 Lex.Lex();
9513 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9514 return true;
9515 FFlags.HasUnknownCall = Val;
9516 break;
9518 Lex.Lex();
9519 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9520 return true;
9521 FFlags.MustBeUnreachable = Val;
9522 break;
9523 default:
9524 return error(Lex.getLoc(), "expected function flag type");
9525 }
9526 } while (EatIfPresent(lltok::comma));
9527
9528 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
9529 return true;
9530
9531 return false;
9532}
9533
9534/// OptionalCalls
9535/// := 'calls' ':' '(' Call [',' Call]* ')'
9536/// Call ::= '(' 'callee' ':' GVReference
9537/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
9538/// [ ',' 'tail' ]? ')'
9539bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9540 assert(Lex.getKind() == lltok::kw_calls);
9541 Lex.Lex();
9542
9543 if (parseToken(lltok::colon, "expected ':' in calls") ||
9544 parseToken(lltok::lparen, "expected '(' in calls"))
9545 return true;
9546
9547 IdToIndexMapType IdToIndexMap;
9548 // parse each call edge
9549 do {
9550 ValueInfo VI;
9551 if (parseToken(lltok::lparen, "expected '(' in call") ||
9552 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
9553 parseToken(lltok::colon, "expected ':'"))
9554 return true;
9555
9556 LocTy Loc = Lex.getLoc();
9557 unsigned GVId;
9558 if (parseGVReference(VI, GVId))
9559 return true;
9560
9562 unsigned RelBF = 0;
9563 unsigned HasTailCall = false;
9564
9565 // parse optional fields
9566 while (EatIfPresent(lltok::comma)) {
9567 switch (Lex.getKind()) {
9568 case lltok::kw_hotness:
9569 Lex.Lex();
9570 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
9571 return true;
9572 break;
9573 case lltok::kw_relbf:
9574 Lex.Lex();
9575 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
9576 return true;
9577 break;
9578 case lltok::kw_tail:
9579 Lex.Lex();
9580 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
9581 return true;
9582 break;
9583 default:
9584 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
9585 }
9586 }
9587 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
9588 return tokError("Expected only one of hotness or relbf");
9589 // Keep track of the Call array index needing a forward reference.
9590 // We will save the location of the ValueInfo needing an update, but
9591 // can only do so once the std::vector is finalized.
9592 if (VI.getRef() == FwdVIRef)
9593 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9594 Calls.push_back(
9595 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
9596
9597 if (parseToken(lltok::rparen, "expected ')' in call"))
9598 return true;
9599 } while (EatIfPresent(lltok::comma));
9600
9601 // Now that the Calls vector is finalized, it is safe to save the locations
9602 // of any forward GV references that need updating later.
9603 for (auto I : IdToIndexMap) {
9604 auto &Infos = ForwardRefValueInfos[I.first];
9605 for (auto P : I.second) {
9606 assert(Calls[P.first].first.getRef() == FwdVIRef &&
9607 "Forward referenced ValueInfo expected to be empty");
9608 Infos.emplace_back(&Calls[P.first].first, P.second);
9609 }
9610 }
9611
9612 if (parseToken(lltok::rparen, "expected ')' in calls"))
9613 return true;
9614
9615 return false;
9616}
9617
9618/// Hotness
9619/// := ('unknown'|'cold'|'none'|'hot'|'critical')
9620bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
9621 switch (Lex.getKind()) {
9622 case lltok::kw_unknown:
9624 break;
9625 case lltok::kw_cold:
9627 break;
9628 case lltok::kw_none:
9630 break;
9631 case lltok::kw_hot:
9633 break;
9634 case lltok::kw_critical:
9636 break;
9637 default:
9638 return error(Lex.getLoc(), "invalid call edge hotness");
9639 }
9640 Lex.Lex();
9641 return false;
9642}
9643
9644/// OptionalVTableFuncs
9645/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9646/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9647bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
9649 Lex.Lex();
9650
9651 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
9652 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9653 return true;
9654
9655 IdToIndexMapType IdToIndexMap;
9656 // parse each virtual function pair
9657 do {
9658 ValueInfo VI;
9659 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9660 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9661 parseToken(lltok::colon, "expected ':'"))
9662 return true;
9663
9664 LocTy Loc = Lex.getLoc();
9665 unsigned GVId;
9666 if (parseGVReference(VI, GVId))
9667 return true;
9668
9670 if (parseToken(lltok::comma, "expected comma") ||
9671 parseToken(lltok::kw_offset, "expected offset") ||
9672 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9673 return true;
9674
9675 // Keep track of the VTableFuncs array index needing a forward reference.
9676 // We will save the location of the ValueInfo needing an update, but
9677 // can only do so once the std::vector is finalized.
9678 if (VI == EmptyVI)
9679 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9680 VTableFuncs.push_back({VI, Offset});
9681
9682 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9683 return true;
9684 } while (EatIfPresent(lltok::comma));
9685
9686 // Now that the VTableFuncs vector is finalized, it is safe to save the
9687 // locations of any forward GV references that need updating later.
9688 for (auto I : IdToIndexMap) {
9689 auto &Infos = ForwardRefValueInfos[I.first];
9690 for (auto P : I.second) {
9691 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9692 "Forward referenced ValueInfo expected to be empty");
9693 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9694 }
9695 }
9696
9697 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9698 return true;
9699
9700 return false;
9701}
9702
9703/// ParamNo := 'param' ':' UInt64
9704bool LLParser::parseParamNo(uint64_t &ParamNo) {
9705 if (parseToken(lltok::kw_param, "expected 'param' here") ||
9706 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9707 return true;
9708 return false;
9709}
9710
9711/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9712bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9713 APSInt Lower;
9714 APSInt Upper;
9715 auto ParseAPSInt = [&](APSInt &Val) {
9716 if (Lex.getKind() != lltok::APSInt)
9717 return tokError("expected integer");
9718 Val = Lex.getAPSIntVal();
9719 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9720 Val.setIsSigned(true);
9721 Lex.Lex();
9722 return false;
9723 };
9724 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9725 parseToken(lltok::colon, "expected ':' here") ||
9726 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9727 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9728 parseToken(lltok::rsquare, "expected ']' here"))
9729 return true;
9730
9731 ++Upper;
9732 Range =
9733 (Lower == Upper && !Lower.isMaxValue())
9734 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9736
9737 return false;
9738}
9739
9740/// ParamAccessCall
9741/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9742bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9743 IdLocListType &IdLocList) {
9744 if (parseToken(lltok::lparen, "expected '(' here") ||
9745 parseToken(lltok::kw_callee, "expected 'callee' here") ||
9746 parseToken(lltok::colon, "expected ':' here"))
9747 return true;
9748
9749 unsigned GVId;
9750 ValueInfo VI;
9751 LocTy Loc = Lex.getLoc();
9752 if (parseGVReference(VI, GVId))
9753 return true;
9754
9755 Call.Callee = VI;
9756 IdLocList.emplace_back(GVId, Loc);
9757
9758 if (parseToken(lltok::comma, "expected ',' here") ||
9759 parseParamNo(Call.ParamNo) ||
9760 parseToken(lltok::comma, "expected ',' here") ||
9761 parseParamAccessOffset(Call.Offsets))
9762 return true;
9763
9764 if (parseToken(lltok::rparen, "expected ')' here"))
9765 return true;
9766
9767 return false;
9768}
9769
9770/// ParamAccess
9771/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9772/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9773bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
9774 IdLocListType &IdLocList) {
9775 if (parseToken(lltok::lparen, "expected '(' here") ||
9776 parseParamNo(Param.ParamNo) ||
9777 parseToken(lltok::comma, "expected ',' here") ||
9778 parseParamAccessOffset(Param.Use))
9779 return true;
9780
9781 if (EatIfPresent(lltok::comma)) {
9782 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
9783 parseToken(lltok::colon, "expected ':' here") ||
9784 parseToken(lltok::lparen, "expected '(' here"))
9785 return true;
9786 do {
9788 if (parseParamAccessCall(Call, IdLocList))
9789 return true;
9790 Param.Calls.push_back(Call);
9791 } while (EatIfPresent(lltok::comma));
9792
9793 if (parseToken(lltok::rparen, "expected ')' here"))
9794 return true;
9795 }
9796
9797 if (parseToken(lltok::rparen, "expected ')' here"))
9798 return true;
9799
9800 return false;
9801}
9802
9803/// OptionalParamAccesses
9804/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9805bool LLParser::parseOptionalParamAccesses(
9806 std::vector<FunctionSummary::ParamAccess> &Params) {
9808 Lex.Lex();
9809
9810 if (parseToken(lltok::colon, "expected ':' here") ||
9811 parseToken(lltok::lparen, "expected '(' here"))
9812 return true;
9813
9814 IdLocListType VContexts;
9815 size_t CallsNum = 0;
9816 do {
9817 FunctionSummary::ParamAccess ParamAccess;
9818 if (parseParamAccess(ParamAccess, VContexts))
9819 return true;
9820 CallsNum += ParamAccess.Calls.size();
9821 assert(VContexts.size() == CallsNum);
9822 (void)CallsNum;
9823 Params.emplace_back(std::move(ParamAccess));
9824 } while (EatIfPresent(lltok::comma));
9825
9826 if (parseToken(lltok::rparen, "expected ')' here"))
9827 return true;
9828
9829 // Now that the Params is finalized, it is safe to save the locations
9830 // of any forward GV references that need updating later.
9831 IdLocListType::const_iterator ItContext = VContexts.begin();
9832 for (auto &PA : Params) {
9833 for (auto &C : PA.Calls) {
9834 if (C.Callee.getRef() == FwdVIRef)
9835 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9836 ItContext->second);
9837 ++ItContext;
9838 }
9839 }
9840 assert(ItContext == VContexts.end());
9841
9842 return false;
9843}
9844
9845/// OptionalRefs
9846/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9847bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9848 assert(Lex.getKind() == lltok::kw_refs);
9849 Lex.Lex();
9850
9851 if (parseToken(lltok::colon, "expected ':' in refs") ||
9852 parseToken(lltok::lparen, "expected '(' in refs"))
9853 return true;
9854
9855 struct ValueContext {
9856 ValueInfo VI;
9857 unsigned GVId;
9858 LocTy Loc;
9859 };
9860 std::vector<ValueContext> VContexts;
9861 // parse each ref edge
9862 do {
9863 ValueContext VC;
9864 VC.Loc = Lex.getLoc();
9865 if (parseGVReference(VC.VI, VC.GVId))
9866 return true;
9867 VContexts.push_back(VC);
9868 } while (EatIfPresent(lltok::comma));
9869
9870 // Sort value contexts so that ones with writeonly
9871 // and readonly ValueInfo are at the end of VContexts vector.
9872 // See FunctionSummary::specialRefCounts()
9873 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9874 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9875 });
9876
9877 IdToIndexMapType IdToIndexMap;
9878 for (auto &VC : VContexts) {
9879 // Keep track of the Refs array index needing a forward reference.
9880 // We will save the location of the ValueInfo needing an update, but
9881 // can only do so once the std::vector is finalized.
9882 if (VC.VI.getRef() == FwdVIRef)
9883 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9884 Refs.push_back(VC.VI);
9885 }
9886
9887 // Now that the Refs vector is finalized, it is safe to save the locations
9888 // of any forward GV references that need updating later.
9889 for (auto I : IdToIndexMap) {
9890 auto &Infos = ForwardRefValueInfos[I.first];
9891 for (auto P : I.second) {
9892 assert(Refs[P.first].getRef() == FwdVIRef &&
9893 "Forward referenced ValueInfo expected to be empty");
9894 Infos.emplace_back(&Refs[P.first], P.second);
9895 }
9896 }
9897
9898 if (parseToken(lltok::rparen, "expected ')' in refs"))
9899 return true;
9900
9901 return false;
9902}
9903
9904/// OptionalTypeIdInfo
9905/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9906/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
9907/// [',' TypeCheckedLoadConstVCalls]? ')'
9908bool LLParser::parseOptionalTypeIdInfo(
9909 FunctionSummary::TypeIdInfo &TypeIdInfo) {
9911 Lex.Lex();
9912
9913 if (parseToken(lltok::colon, "expected ':' here") ||
9914 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9915 return true;
9916
9917 do {
9918 switch (Lex.getKind()) {
9920 if (parseTypeTests(TypeIdInfo.TypeTests))
9921 return true;
9922 break;
9924 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9925 TypeIdInfo.TypeTestAssumeVCalls))
9926 return true;
9927 break;
9929 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9930 TypeIdInfo.TypeCheckedLoadVCalls))
9931 return true;
9932 break;
9934 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9935 TypeIdInfo.TypeTestAssumeConstVCalls))
9936 return true;
9937 break;
9939 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9940 TypeIdInfo.TypeCheckedLoadConstVCalls))
9941 return true;
9942 break;
9943 default:
9944 return error(Lex.getLoc(), "invalid typeIdInfo list type");
9945 }
9946 } while (EatIfPresent(lltok::comma));
9947
9948 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9949 return true;
9950
9951 return false;
9952}
9953
9954/// TypeTests
9955/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9956/// [',' (SummaryID | UInt64)]* ')'
9957bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9959 Lex.Lex();
9960
9961 if (parseToken(lltok::colon, "expected ':' here") ||
9962 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9963 return true;
9964
9965 IdToIndexMapType IdToIndexMap;
9966 do {
9967 GlobalValue::GUID GUID = 0;
9968 if (Lex.getKind() == lltok::SummaryID) {
9969 unsigned ID = Lex.getUIntVal();
9970 LocTy Loc = Lex.getLoc();
9971 // Keep track of the TypeTests array index needing a forward reference.
9972 // We will save the location of the GUID needing an update, but
9973 // can only do so once the std::vector is finalized.
9974 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9975 Lex.Lex();
9976 } else if (parseUInt64(GUID))
9977 return true;
9978 TypeTests.push_back(GUID);
9979 } while (EatIfPresent(lltok::comma));
9980
9981 // Now that the TypeTests vector is finalized, it is safe to save the
9982 // locations of any forward GV references that need updating later.
9983 for (auto I : IdToIndexMap) {
9984 auto &Ids = ForwardRefTypeIds[I.first];
9985 for (auto P : I.second) {
9986 assert(TypeTests[P.first] == 0 &&
9987 "Forward referenced type id GUID expected to be 0");
9988 Ids.emplace_back(&TypeTests[P.first], P.second);
9989 }
9990 }
9991
9992 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9993 return true;
9994
9995 return false;
9996}
9997
9998/// VFuncIdList
9999/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10000bool LLParser::parseVFuncIdList(
10001 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10002 assert(Lex.getKind() == Kind);
10003 Lex.Lex();
10004
10005 if (parseToken(lltok::colon, "expected ':' here") ||
10006 parseToken(lltok::lparen, "expected '(' here"))
10007 return true;
10008
10009 IdToIndexMapType IdToIndexMap;
10010 do {
10012 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10013 return true;
10014 VFuncIdList.push_back(VFuncId);
10015 } while (EatIfPresent(lltok::comma));
10016
10017 if (parseToken(lltok::rparen, "expected ')' here"))
10018 return true;
10019
10020 // Now that the VFuncIdList vector is finalized, it is safe to save the
10021 // locations of any forward GV references that need updating later.
10022 for (auto I : IdToIndexMap) {
10023 auto &Ids = ForwardRefTypeIds[I.first];
10024 for (auto P : I.second) {
10025 assert(VFuncIdList[P.first].GUID == 0 &&
10026 "Forward referenced type id GUID expected to be 0");
10027 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10028 }
10029 }
10030
10031 return false;
10032}
10033
10034/// ConstVCallList
10035/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10036bool LLParser::parseConstVCallList(
10037 lltok::Kind Kind,
10038 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10039 assert(Lex.getKind() == Kind);
10040 Lex.Lex();
10041
10042 if (parseToken(lltok::colon, "expected ':' here") ||
10043 parseToken(lltok::lparen, "expected '(' here"))
10044 return true;
10045
10046 IdToIndexMapType IdToIndexMap;
10047 do {
10048 FunctionSummary::ConstVCall ConstVCall;
10049 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10050 return true;
10051 ConstVCallList.push_back(ConstVCall);
10052 } while (EatIfPresent(lltok::comma));
10053
10054 if (parseToken(lltok::rparen, "expected ')' here"))
10055 return true;
10056
10057 // Now that the ConstVCallList vector is finalized, it is safe to save the
10058 // locations of any forward GV references that need updating later.
10059 for (auto I : IdToIndexMap) {
10060 auto &Ids = ForwardRefTypeIds[I.first];
10061 for (auto P : I.second) {
10062 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10063 "Forward referenced type id GUID expected to be 0");
10064 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10065 }
10066 }
10067
10068 return false;
10069}
10070
10071/// ConstVCall
10072/// ::= '(' VFuncId ',' Args ')'
10073bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10074 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10075 if (parseToken(lltok::lparen, "expected '(' here") ||
10076 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10077 return true;
10078
10079 if (EatIfPresent(lltok::comma))
10080 if (parseArgs(ConstVCall.Args))
10081 return true;
10082
10083 if (parseToken(lltok::rparen, "expected ')' here"))
10084 return true;
10085
10086 return false;
10087}
10088
10089/// VFuncId
10090/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10091/// 'offset' ':' UInt64 ')'
10092bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10093 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10095 Lex.Lex();
10096
10097 if (parseToken(lltok::colon, "expected ':' here") ||
10098 parseToken(lltok::lparen, "expected '(' here"))
10099 return true;
10100
10101 if (Lex.getKind() == lltok::SummaryID) {
10102 VFuncId.GUID = 0;
10103 unsigned ID = Lex.getUIntVal();
10104 LocTy Loc = Lex.getLoc();
10105 // Keep track of the array index needing a forward reference.
10106 // We will save the location of the GUID needing an update, but
10107 // can only do so once the caller's std::vector is finalized.
10108 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10109 Lex.Lex();
10110 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10111 parseToken(lltok::colon, "expected ':' here") ||
10112 parseUInt64(VFuncId.GUID))
10113 return true;
10114
10115 if (parseToken(lltok::comma, "expected ',' here") ||
10116 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10117 parseToken(lltok::colon, "expected ':' here") ||
10118 parseUInt64(VFuncId.Offset) ||
10119 parseToken(lltok::rparen, "expected ')' here"))
10120 return true;
10121
10122 return false;
10123}
10124
10125/// GVFlags
10126/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10127/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10128/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10129/// 'canAutoHide' ':' Flag ',' ')'
10130bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10131 assert(Lex.getKind() == lltok::kw_flags);
10132 Lex.Lex();
10133
10134 if (parseToken(lltok::colon, "expected ':' here") ||
10135 parseToken(lltok::lparen, "expected '(' here"))
10136 return true;
10137
10138 do {
10139 unsigned Flag = 0;
10140 switch (Lex.getKind()) {
10141 case lltok::kw_linkage:
10142 Lex.Lex();
10143 if (parseToken(lltok::colon, "expected ':'"))
10144 return true;
10145 bool HasLinkage;
10146 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10147 assert(HasLinkage && "Linkage not optional in summary entry");
10148 Lex.Lex();
10149 break;
10151 Lex.Lex();
10152 if (parseToken(lltok::colon, "expected ':'"))
10153 return true;
10154 parseOptionalVisibility(Flag);
10155 GVFlags.Visibility = Flag;
10156 break;
10158 Lex.Lex();
10159 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10160 return true;
10161 GVFlags.NotEligibleToImport = Flag;
10162 break;
10163 case lltok::kw_live:
10164 Lex.Lex();
10165 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10166 return true;
10167 GVFlags.Live = Flag;
10168 break;
10169 case lltok::kw_dsoLocal:
10170 Lex.Lex();
10171 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10172 return true;
10173 GVFlags.DSOLocal = Flag;
10174 break;
10176 Lex.Lex();
10177 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10178 return true;
10179 GVFlags.CanAutoHide = Flag;
10180 break;
10182 Lex.Lex();
10183 if (parseToken(lltok::colon, "expected ':'"))
10184 return true;
10186 if (parseOptionalImportType(Lex.getKind(), IK))
10187 return true;
10188 GVFlags.ImportType = static_cast<unsigned>(IK);
10189 Lex.Lex();
10190 break;
10191 default:
10192 return error(Lex.getLoc(), "expected gv flag type");
10193 }
10194 } while (EatIfPresent(lltok::comma));
10195
10196 if (parseToken(lltok::rparen, "expected ')' here"))
10197 return true;
10198
10199 return false;
10200}
10201
10202/// GVarFlags
10203/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10204/// ',' 'writeonly' ':' Flag
10205/// ',' 'constant' ':' Flag ')'
10206bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10208 Lex.Lex();
10209
10210 if (parseToken(lltok::colon, "expected ':' here") ||
10211 parseToken(lltok::lparen, "expected '(' here"))
10212 return true;
10213
10214 auto ParseRest = [this](unsigned int &Val) {
10215 Lex.Lex();
10216 if (parseToken(lltok::colon, "expected ':'"))
10217 return true;
10218 return parseFlag(Val);
10219 };
10220
10221 do {
10222 unsigned Flag = 0;
10223 switch (Lex.getKind()) {
10224 case lltok::kw_readonly:
10225 if (ParseRest(Flag))
10226 return true;
10227 GVarFlags.MaybeReadOnly = Flag;
10228 break;
10229 case lltok::kw_writeonly:
10230 if (ParseRest(Flag))
10231 return true;
10232 GVarFlags.MaybeWriteOnly = Flag;
10233 break;
10234 case lltok::kw_constant:
10235 if (ParseRest(Flag))
10236 return true;
10237 GVarFlags.Constant = Flag;
10238 break;
10240 if (ParseRest(Flag))
10241 return true;
10242 GVarFlags.VCallVisibility = Flag;
10243 break;
10244 default:
10245 return error(Lex.getLoc(), "expected gvar flag type");
10246 }
10247 } while (EatIfPresent(lltok::comma));
10248 return parseToken(lltok::rparen, "expected ')' here");
10249}
10250
10251/// ModuleReference
10252/// ::= 'module' ':' UInt
10253bool LLParser::parseModuleReference(StringRef &ModulePath) {
10254 // parse module id.
10255 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10256 parseToken(lltok::colon, "expected ':' here") ||
10257 parseToken(lltok::SummaryID, "expected module ID"))
10258 return true;
10259
10260 unsigned ModuleID = Lex.getUIntVal();
10261 auto I = ModuleIdMap.find(ModuleID);
10262 // We should have already parsed all module IDs
10263 assert(I != ModuleIdMap.end());
10264 ModulePath = I->second;
10265 return false;
10266}
10267
10268/// GVReference
10269/// ::= SummaryID
10270bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10271 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10272 if (!ReadOnly)
10273 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10274 if (parseToken(lltok::SummaryID, "expected GV ID"))
10275 return true;
10276
10277 GVId = Lex.getUIntVal();
10278 // Check if we already have a VI for this GV
10279 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10280 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10281 VI = NumberedValueInfos[GVId];
10282 } else
10283 // We will create a forward reference to the stored location.
10284 VI = ValueInfo(false, FwdVIRef);
10285
10286 if (ReadOnly)
10287 VI.setReadOnly();
10288 if (WriteOnly)
10289 VI.setWriteOnly();
10290 return false;
10291}
10292
10293/// OptionalAllocs
10294/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10295/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10296/// ',' MemProfs ')'
10297/// Version ::= UInt32
10298bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10300 Lex.Lex();
10301
10302 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10303 parseToken(lltok::lparen, "expected '(' in allocs"))
10304 return true;
10305
10306 // parse each alloc
10307 do {
10308 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10309 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10310 parseToken(lltok::colon, "expected ':'") ||
10311 parseToken(lltok::lparen, "expected '(' in versions"))
10312 return true;
10313
10314 SmallVector<uint8_t> Versions;
10315 do {
10316 uint8_t V = 0;
10317 if (parseAllocType(V))
10318 return true;
10319 Versions.push_back(V);
10320 } while (EatIfPresent(lltok::comma));
10321
10322 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10323 parseToken(lltok::comma, "expected ',' in alloc"))
10324 return true;
10325
10326 std::vector<MIBInfo> MIBs;
10327 if (parseMemProfs(MIBs))
10328 return true;
10329
10330 Allocs.push_back({Versions, MIBs});
10331
10332 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10333 return true;
10334 } while (EatIfPresent(lltok::comma));
10335
10336 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10337 return true;
10338
10339 return false;
10340}
10341
10342/// MemProfs
10343/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10344/// MemProf ::= '(' 'type' ':' AllocType
10345/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10346/// StackId ::= UInt64
10347bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10349 Lex.Lex();
10350
10351 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10352 parseToken(lltok::lparen, "expected '(' in memprof"))
10353 return true;
10354
10355 // parse each MIB
10356 do {
10357 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10358 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10359 parseToken(lltok::colon, "expected ':'"))
10360 return true;
10361
10362 uint8_t AllocType;
10363 if (parseAllocType(AllocType))
10364 return true;
10365
10366 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10367 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10368 parseToken(lltok::colon, "expected ':'") ||
10369 parseToken(lltok::lparen, "expected '(' in stackIds"))
10370 return true;
10371
10372 SmallVector<unsigned> StackIdIndices;
10373 do {
10374 uint64_t StackId = 0;
10375 if (parseUInt64(StackId))
10376 return true;
10377 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10378 } while (EatIfPresent(lltok::comma));
10379
10380 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10381 return true;
10382
10383 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10384
10385 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10386 return true;
10387 } while (EatIfPresent(lltok::comma));
10388
10389 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10390 return true;
10391
10392 return false;
10393}
10394
10395/// AllocType
10396/// := ('none'|'notcold'|'cold'|'hot')
10397bool LLParser::parseAllocType(uint8_t &AllocType) {
10398 switch (Lex.getKind()) {
10399 case lltok::kw_none:
10401 break;
10402 case lltok::kw_notcold:
10404 break;
10405 case lltok::kw_cold:
10407 break;
10408 case lltok::kw_hot:
10409 AllocType = (uint8_t)AllocationType::Hot;
10410 break;
10411 default:
10412 return error(Lex.getLoc(), "invalid alloc type");
10413 }
10414 Lex.Lex();
10415 return false;
10416}
10417
10418/// OptionalCallsites
10419/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10420/// Callsite ::= '(' 'callee' ':' GVReference
10421/// ',' 'clones' ':' '(' Version [',' Version]* ')'
10422/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10423/// Version ::= UInt32
10424/// StackId ::= UInt64
10425bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10427 Lex.Lex();
10428
10429 if (parseToken(lltok::colon, "expected ':' in callsites") ||
10430 parseToken(lltok::lparen, "expected '(' in callsites"))
10431 return true;
10432
10433 IdToIndexMapType IdToIndexMap;
10434 // parse each callsite
10435 do {
10436 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10437 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10438 parseToken(lltok::colon, "expected ':'"))
10439 return true;
10440
10441 ValueInfo VI;
10442 unsigned GVId = 0;
10443 LocTy Loc = Lex.getLoc();
10444 if (!EatIfPresent(lltok::kw_null)) {
10445 if (parseGVReference(VI, GVId))
10446 return true;
10447 }
10448
10449 if (parseToken(lltok::comma, "expected ',' in callsite") ||
10450 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10451 parseToken(lltok::colon, "expected ':'") ||
10452 parseToken(lltok::lparen, "expected '(' in clones"))
10453 return true;
10454
10455 SmallVector<unsigned> Clones;
10456 do {
10457 unsigned V = 0;
10458 if (parseUInt32(V))
10459 return true;
10460 Clones.push_back(V);
10461 } while (EatIfPresent(lltok::comma));
10462
10463 if (parseToken(lltok::rparen, "expected ')' in clones") ||
10464 parseToken(lltok::comma, "expected ',' in callsite") ||
10465 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
10466 parseToken(lltok::colon, "expected ':'") ||
10467 parseToken(lltok::lparen, "expected '(' in stackIds"))
10468 return true;
10469
10470 SmallVector<unsigned> StackIdIndices;
10471 do {
10472 uint64_t StackId = 0;
10473 if (parseUInt64(StackId))
10474 return true;
10475 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10476 } while (EatIfPresent(lltok::comma));
10477
10478 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10479 return true;
10480
10481 // Keep track of the Callsites array index needing a forward reference.
10482 // We will save the location of the ValueInfo needing an update, but
10483 // can only do so once the SmallVector is finalized.
10484 if (VI.getRef() == FwdVIRef)
10485 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10486 Callsites.push_back({VI, Clones, StackIdIndices});
10487
10488 if (parseToken(lltok::rparen, "expected ')' in callsite"))
10489 return true;
10490 } while (EatIfPresent(lltok::comma));
10491
10492 // Now that the Callsites vector is finalized, it is safe to save the
10493 // locations of any forward GV references that need updating later.
10494 for (auto I : IdToIndexMap) {
10495 auto &Infos = ForwardRefValueInfos[I.first];
10496 for (auto P : I.second) {
10497 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
10498 "Forward referenced ValueInfo expected to be empty");
10499 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
10500 }
10501 }
10502
10503 if (parseToken(lltok::rparen, "expected ')' in callsites"))
10504 return true;
10505
10506 return false;
10507}
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...
#define _
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
Definition: LLParser.cpp:1716
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:1113
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
Definition: LLParser.cpp:1619
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
Definition: LLParser.cpp:2446
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
Definition: LLParser.cpp:9044
cl::opt< bool > WriteNewDbgInfoFormat
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
Definition: LLParser.cpp:1985
bool WriteNewDbgInfoFormatToBitcode
Definition: BasicBlock.cpp:47
static unsigned keywordToFPClassTest(lltok::Kind Tok)
Definition: LLParser.cpp:2527
llvm::cl::opt< bool > UseNewDbgInfoFormat
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
Definition: LLParser.cpp:2457
static bool isSanitizer(lltok::Kind Kind)
Definition: LLParser.cpp:1271
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition: LLParser.cpp:156
#define PARSE_MD_FIELDS()
Definition: LLParser.cpp:5029
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
Definition: LLParser.cpp:1503
static ValueInfo EmptyVI
Definition: LLParser.cpp:8685
#define GET_OR_DISTINCT(CLASS, ARGS)
Definition: LLParser.cpp:5043
bool isOldDbgFormatIntrinsic(StringRef Name)
Definition: LLParser.cpp:6165
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
Definition: LLParser.cpp:1102
static std::string getTypeString(Type *T)
Definition: LLParser.cpp:70
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
Definition: LLParser.cpp:1106
static const auto FwdVIRef
Definition: LLParser.cpp:9042
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
#define P(N)
PowerPC Reduce CR logical Operation
llvm::cl::opt< bool > UseNewDbgInfoFormat
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:49
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
Value * RHS
Value * LHS
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:996
Class for arbitrary precision integers.
Definition: APInt.h:76
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1491
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1439
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:453
bool getBoolValue() const
Convert APInt to a boolean value.
Definition: APInt.h:449
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1215
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:59
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:159
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Definition: Instructions.h:152
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:659
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:539
void setWeak(bool IsWeak)
Definition: Instructions.h:608
static bool isValidFailureOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:618
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
Definition: Instructions.h:603
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:613
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:748
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
Definition: Instructions.h:881
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:760
@ Add
*p = old + v
Definition: Instructions.h:764
@ FAdd
*p = old + v
Definition: Instructions.h:785
@ Min
*p = old <signed v ? old : v
Definition: Instructions.h:778
@ Or
*p = old | v
Definition: Instructions.h:772
@ Sub
*p = old - v
Definition: Instructions.h:766
@ And
*p = old & v
Definition: Instructions.h:768
@ Xor
*p = old ^ v
Definition: Instructions.h:774
@ FSub
*p = old - v
Definition: Instructions.h:788
@ UIncWrap
Increment one up to a maximum value.
Definition: Instructions.h:800
@ Max
*p = old >signed v ? old : v
Definition: Instructions.h:776
@ UMin
*p = old <unsigned v ? old : v
Definition: Instructions.h:782
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
Definition: Instructions.h:796
@ UMax
*p = old >unsigned v ? old : v
Definition: Instructions.h:780
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
Definition: Instructions.h:792
@ UDecWrap
Decrement one until a minimum value or zero.
Definition: Instructions.h:804
@ Nand
*p = ~(old & v)
Definition: Instructions.h:770
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:625
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
Definition: Attributes.h:560
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
Definition: Attributes.h:783
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:658
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:774
static bool canUseAsRetAttr(AttrKind Kind)
Definition: Attributes.cpp:689
static bool isTypeAttrKind(AttrKind Kind)
Definition: Attributes.h:104
static bool canUseAsFnAttr(AttrKind Kind)
Definition: Attributes.cpp:681
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:85
@ None
No attributes have been set.
Definition: Attributes.h:87
static bool canUseAsParamAttr(AttrKind Kind)
Definition: Attributes.cpp:685
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator end()
Definition: BasicBlock.h:443
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:199
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
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:1846
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1804
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1823
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1678
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, BasicBlock::iterator InsertBefore)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setTailCallKind(TailCallKind TCK)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
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, BasicBlock::iterator InsertBefore)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, BasicBlock::iterator InsertBefore)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB, BasicBlock::iterator InsertBefore)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:993
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:996
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:1010
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:1022
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:1023
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:999
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:1008
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:997
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:998
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:1017
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:1016
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:1020
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:1007
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:1001
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:1004
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:1018
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:1005
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:1000
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:1002
@ ICMP_EQ
equal
Definition: InstrTypes.h:1014
@ ICMP_NE
not equal
Definition: InstrTypes.h:1015
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:1021
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:1009
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:1019
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:1006
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:995
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:1003
@ 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:1291
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2881
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
Definition: Constants.cpp:2427
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2452
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:2041
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2474
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:2402
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1200
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2497
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:2159
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
Definition: Constants.cpp:1602
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:849
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:123
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:856
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1775
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:1356
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1449
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1398
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
static DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
Basic type, like 'int' or 'float'.
Debug common block.
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
Build a DICompositeType with the given ODR identifier.
Enumeration value.
DWARF expression.
static std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Debug lexical block.
Debug location.
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Debug lexical block.
Tagged DWARF-like metadata node.
static DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
String type, Fortran CHARACTER(n)
Subprogram description.
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Array subrange.
Type array for a subprogram.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
Definition: Constants.cpp:1919
This class represents an Operation in the Expression.
static Expected< DataLayout > parse(StringRef LayoutDescription)
Parse a data layout string and return the layout.
Definition: DataLayout.cpp:223
static DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Base class for non-instruction debug metadata records that have positions within IR.
Kind
Subclass discriminator.
static DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
unsigned size() const
Definition: DenseMap.h:99
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:296
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:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
reference get()
Returns a reference to the stored T value.
Definition: Error.h:571
Class representing an expression and its matching format.
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
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, BasicBlock::iterator InsertBefore)
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:460
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:126
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition: Type.cpp:358
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:163
void setPrefixData(Constant *PrefixData)
Definition: Function.cpp:1911
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
Definition: Function.cpp:908
void setGC(std::string Str)
Definition: Function.cpp:771
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1901
arg_iterator arg_begin()
Definition: Function.h:814
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:342
void setPrologueData(Constant *PrologueData)
Definition: Function.cpp:1921
void setCallingConv(CallingConv::ID CC)
Definition: Function.h:267
Generic tagged DWARF-like metadata node.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition: GlobalAlias.h:95
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:525
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:582
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:128
void setComdat(Comdat *C)
Definition: Globals.cpp:197
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:258
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1522
const SanitizerMetadata & getSanitizerMetadata() const
Definition: Globals.cpp:228
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:86
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:234
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:169
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:211
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:466
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:502
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, BasicBlock::iterator InsertBefore)
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 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 InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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:255
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1636
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:47
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:54
Invoke instruction.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
lltok::Kind Lex()
Definition: LLLexer.h:52
unsigned getUIntVal() const
Definition: LLLexer.h:61
lltok::Kind getKind() const
Definition: LLLexer.h:58
bool Error(LocTy ErrorLoc, const Twine &Msg) const
Definition: LLLexer.cpp:28
const std::string & getStrVal() const
Definition: LLLexer.h:59
Type * getTyVal() const
Definition: LLLexer.h:60
LocTy getLoc() const
Definition: LLLexer.h:57
const APSInt & getAPSIntVal() const
Definition: LLLexer.h:62
void setIgnoreColonInIdentifiers(bool val)
Definition: LLLexer.h:65
const APFloat & getAPFloatVal() const
Definition: LLLexer.h:63
LLLexer::LocTy LocTy
Definition: LLParser.h:106
LLVMContext & getContext()
Definition: LLParser.h:204
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition: LLParser.cpp:127
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition: LLParser.cpp:114
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition: LLParser.cpp:95
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, BasicBlock::iterator InsertBefore)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
An instruction for reading from memory.
Definition: Instructions.h:184
Metadata node.
Definition: Metadata.h:1067
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1549
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
A single uniqued string.
Definition: Metadata.h:720
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:600
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition: Metadata.h:1509
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1498
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition: Metadata.h:1518
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
Definition: ModRef.h:122
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition: ModRef.h:170
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
Definition: ModRef.h:132
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
Definition: ModRef.h:138
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
Definition: ModRef.h:127
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
Definition: ModRef.h:145
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
Definition: ModRef.h:117
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
Definition: ModRef.h:112
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:176
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1729
void addOperand(MDNode *M)
Definition: Metadata.cpp:1388
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
Definition: Constants.cpp:1977
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, BasicBlock::iterator InsertBefore)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:764
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
Resume the propagation of an exception.
static ResumeInst * Create(Value *Exn, BasicBlock::iterator InsertBefore)
static ReturnInst * Create(LLVMContext &C, Value *retVal, BasicBlock::iterator InsertBefore)
Represents a location in source code.
Definition: SMLoc.h:23
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.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
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:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:299
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:127
iterator end()
Definition: StringMap.h:220
iterator find(StringRef Key)
Definition: StringMap.h:233
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
Class to represent struct types.
Definition: DerivedTypes.h:216
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:373
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
Definition: Type.cpp:445
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:513
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:597
bool containsScalableVectorType(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Returns true if this struct contains a scalable vector.
Definition: Type.cpp:400
Multiway switch.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, BasicBlock::iterator InsertBefore)
static TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types=std::nullopt, ArrayRef< unsigned > Ints=std::nullopt)
Return a target extension type having the specified name and optional type and integer parameters.
Definition: Type.cpp:796
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Definition: DerivedTypes.h:769
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:252
bool isLabelTy() const
Return true if this is 'label'.
Definition: Type.h:219
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:255
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:154
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:146
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:281
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:295
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:143
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:262
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:246
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
bool isTokenTy() const
Return true if this is 'token'.
Definition: Type.h:225
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:216
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:140
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition: Type.h:222
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name, BasicBlock::iterator InsertBefore)
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:1808
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:495
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
static constexpr uint64_t MaximumAlignment
Definition: Value.h:807
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:110
bool use_empty() const
Definition: Value.h:344
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:683
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:676
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition: ilist_node.h:109
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:678
unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition: Dwarf.cpp:161
unsigned getAttributeEncoding(StringRef EncodingString)
Definition: Dwarf.cpp:242
unsigned getTag(StringRef TagString)
Definition: Dwarf.cpp:32
unsigned getCallingConvention(StringRef LanguageString)
Definition: Dwarf.cpp:439
unsigned getLanguage(StringRef LanguageString)
Definition: Dwarf.cpp:372
unsigned getVirtuality(StringRef VirtualityString)
Definition: Dwarf.cpp:353
unsigned getMacinfo(StringRef MacinfoString)
Definition: Dwarf.cpp:511
#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.
const CustomOperand< const MCSubtargetInfo & > Msg[]
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
Definition: CallingConv.h:221
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Definition: CallingConv.h:151
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
Definition: CallingConv.h:268
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:197
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
Definition: CallingConv.h:188
@ AVR_SIGNAL
Used for AVR signal routines.
Definition: CallingConv.h:179
@ Swift
Calling convention for Swift.
Definition: CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:200
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
Definition: CallingConv.h:224
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
Definition: CallingConv.h:107
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition: CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
Definition: CallingConv.h:176
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition: CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition: CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
Definition: CallingConv.h:232
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
Definition: CallingConv.h:166
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:249
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:206
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:111
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:191
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:241
@ CXX_FAST_TLS
Used for access functions.
Definition: CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
Definition: CallingConv.h:173
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:238
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:245
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition: CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition: CallingConv.h:47
@ 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
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:148
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:57
@ FS
Definition: X86.h:206
@ GS
Definition: X86.h:205
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
@ DW_CC_hi_user
Definition: Dwarf.h:426
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_ATE_hi_user
Definition: Dwarf.h:158
@ DW_LANG_hi_user
Definition: Dwarf.h:209
MacinfoRecordType
Definition: Dwarf.h:470
@ DW_MACINFO_vendor_ext
Definition: Dwarf.h:476
@ DW_VIRTUALITY_max
Definition: Dwarf.h:195
@ 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:235
@ kw_msp430_intrcc
Definition: LLToken.h:150
@ kw_acquire
Definition: LLToken.h:97
@ kw_cxx_fast_tlscc
Definition: LLToken.h:169
@ kw_extractvalue
Definition: LLToken.h:343
@ kw_dso_preemptable
Definition: LLToken.h:51
@ DwarfVirtuality
Definition: LLToken.h:477
@ kw_arm_apcscc
Definition: LLToken.h:143
@ kw_inteldialect
Definition: LLToken.h:126
@ kw_x86_stdcallcc
Definition: LLToken.h:138
@ kw_constant
Definition: LLToken.h:48
@ kw_graalcc
Definition: LLToken.h:183
@ kw_initialexec
Definition: LLToken.h:74
@ kw_mustBeUnreachable
Definition: LLToken.h:388
@ kw_internal
Definition: LLToken.h:54
@ kw_hhvm_ccc
Definition: LLToken.h:168
@ kw_ptrtoint
Definition: LLToken.h:305
@ kw_anyregcc
Definition: LLToken.h:159
@ kw_no_sanitize_hwaddress
Definition: LLToken.h:456
@ kw_win64cc
Definition: LLToken.h:158
@ kw_datalayout
Definition: LLToken.h:92
@ kw_wpdResolutions
Definition: LLToken.h:427
@ kw_cleanup
Definition: LLToken.h:313
@ kw_canAutoHide
Definition: LLToken.h:372
@ kw_alwaysInline
Definition: LLToken.h:384
@ kw_notail
Definition: LLToken.h:87
@ kw_insertelement
Definition: LLToken.h:340
@ kw_linkonce
Definition: LLToken.h:55
@ kw_fptrunc
Definition: LLToken.h:298
@ kw_inaccessiblememonly
Definition: LLToken.h:204
@ kw_amdgpu_gfx
Definition: LLToken.h:180
@ kw_getelementptr
Definition: LLToken.h:337
@ kw_m68k_rtdcc
Definition: LLToken.h:182
@ kw_preserve_nonecc
Definition: LLToken.h:164
@ kw_x86_fastcallcc
Definition: LLToken.h:139
@ kw_readOnly
Definition: LLToken.h:380
@ kw_varFlags
Definition: LLToken.h:441
@ kw_partition
Definition: LLToken.h:119
@ kw_visibility
Definition: LLToken.h:368
@ kw_vFuncId
Definition: LLToken.h:408
@ kw_noUnwind
Definition: LLToken.h:385
@ kw_disjoint
Definition: LLToken.h:113
@ kw_bitMask
Definition: LLToken.h:424
@ kw_unordered
Definition: LLToken.h:95
@ kw_singleImpl
Definition: LLToken.h:430
@ kw_swiftcc
Definition: LLToken.h:160
@ kw_localexec
Definition: LLToken.h:75
@ kw_cfguard_checkcc
Definition: LLToken.h:137
@ kw_stackIds
Definition: LLToken.h:445
@ kw_typeCheckedLoadConstVCalls
Definition: LLToken.h:407
@ kw_private
Definition: LLToken.h:53
@ kw_aarch64_sve_vector_pcs
Definition: LLToken.h:147
@ kw_amdgpu_kernel
Definition: LLToken.h:179
@ kw_acq_rel
Definition: LLToken.h:99
@ kw_uselistorder
Definition: LLToken.h:355
@ MetadataVar
Definition: LLToken.h:473
@ kw_blockcount
Definition: LLToken.h:366
@ kw_notEligibleToImport
Definition: LLToken.h:369
@ kw_noRecurse
Definition: LLToken.h:381
@ kw_dsoLocal
Definition: LLToken.h:371
@ kw_linkonce_odr
Definition: LLToken.h:56
@ kw_protected
Definition: LLToken.h:66
@ kw_variable
Definition: LLToken.h:397
@ kw_dllexport
Definition: LLToken.h:61
@ kw_hotness
Definition: LLToken.h:393
@ kw_x86_vectorcallcc
Definition: LLToken.h:141
@ kw_ptx_device
Definition: LLToken.h:154
@ kw_personality
Definition: LLToken.h:312
@ kw_catchpad
Definition: LLToken.h:327
@ kw_spir_func
Definition: LLToken.h:156
@ kw_inbounds
Definition: LLToken.h:114
@ kw_atomic
Definition: LLToken.h:94
@ kw_readNone
Definition: LLToken.h:379
@ kw_declaration
Definition: LLToken.h:375
@ kw_define
Definition: LLToken.h:46
@ DwarfAttEncoding
Definition: LLToken.h:476
@ kw_critical
Definition: LLToken.h:395
@ kw_external
Definition: LLToken.h:71
@ kw_largest
Definition: LLToken.h:233
@ kw_amdgpu_hs
Definition: LLToken.h:172
@ kw_spir_kernel
Definition: LLToken.h:155
@ kw_local_unnamed_addr
Definition: LLToken.h:68
@ kw_amdgpu_es
Definition: LLToken.h:173
@ kw_hasUnknownCall
Definition: LLToken.h:387
@ LocalVarID
Definition: LLToken.h:464
@ kw_seq_cst
Definition: LLToken.h:100
@ kw_unwind
Definition: LLToken.h:91
@ kw_distinct
Definition: LLToken.h:352
@ kw_linkage
Definition: LLToken.h:367
@ kw_amdgpu_gs
Definition: LLToken.h:174
@ kw_x86_intrcc
Definition: LLToken.h:166
@ kw_addrspacecast
Definition: LLToken.h:307
@ kw_callsites
Definition: LLToken.h:443
@ kw_zeroinitializer
Definition: LLToken.h:76
@ StringConstant
Definition: LLToken.h:474
@ kw_x86_thiscallcc
Definition: LLToken.h:140
@ kw_false
Definition: LLToken.h:44
@ kw_unnamed_addr
Definition: LLToken.h:67
@ kw_uselistorder_bb
Definition: LLToken.h:356
@ NameTableKind
Definition: LLToken.h:481
@ kw_amdgpu_vs
Definition: LLToken.h:170
@ kw_inlineBits
Definition: LLToken.h:425
@ kw_weak_odr
Definition: LLToken.h:58
@ kw_udec_wrap
Definition: LLToken.h:268
@ kw_resByArg
Definition: LLToken.h:433
@ kw_inttoptr
Definition: LLToken.h:304
@ kw_dllimport
Definition: LLToken.h:60
@ kw_argmemonly
Definition: LLToken.h:203
@ kw_blockaddress
Definition: LLToken.h:345
@ kw_landingpad
Definition: LLToken.h:311
@ kw_aarch64_vector_pcs
Definition: LLToken.h:146
@ kw_amdgpu_cs
Definition: LLToken.h:176
@ kw_syncscope
Definition: LLToken.h:101
@ kw_noInline
Definition: LLToken.h:383
@ kw_source_filename
Definition: LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition: LLToken.h:406
@ kw_inrange
Definition: LLToken.h:116
@ kw_ptx_kernel
Definition: LLToken.h:153
@ kw_summaries
Definition: LLToken.h:364
@ kw_extractelement
Definition: LLToken.h:339
@ kw_branchFunnel
Definition: LLToken.h:431
@ kw_typeidCompatibleVTable
Definition: LLToken.h:412
@ kw_bitcast
Definition: LLToken.h:306
@ kw_declare
Definition: LLToken.h:45
@ kw_allOnes
Definition: LLToken.h:420
@ kw_vTableFuncs
Definition: LLToken.h:398
@ ChecksumKind
Definition: LLToken.h:486
@ DwarfMacinfo
Definition: LLToken.h:485
@ kw_volatile
Definition: LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition: LLToken.h:405
@ kw_function
Definition: LLToken.h:376
@ kw_default
Definition: LLToken.h:64
@ kw_no_sanitize_address
Definition: LLToken.h:453
@ kw_inaccessiblemem_or_argmemonly
Definition: LLToken.h:205
@ kw_uinc_wrap
Definition: LLToken.h:267
@ kw_externally_initialized
Definition: LLToken.h:69
@ kw_sanitize_address_dyninit
Definition: LLToken.h:459
@ kw_atomicrmw
Definition: LLToken.h:336
@ kw_hidden
Definition: LLToken.h:65
@ EmissionKind
Definition: LLToken.h:480
@ kw_amdgpu_cs_chain_preserve
Definition: LLToken.h:178
@ kw_readwrite
Definition: LLToken.h:198
@ kw_within
Definition: LLToken.h:83
@ kw_section
Definition: LLToken.h:118
@ kw_triple
Definition: LLToken.h:89
@ kw_thread_local
Definition: LLToken.h:72
@ kw_catchswitch
Definition: LLToken.h:325
@ kw_extern_weak
Definition: LLToken.h:70
@ kw_arm_aapcscc
Definition: LLToken.h:144
@ kw_memProf
Definition: LLToken.h:448
@ kw_alignLog2
Definition: LLToken.h:422
@ kw_cleanuppad
Definition: LLToken.h:328
@ kw_available_externally
Definition: LLToken.h:63
@ kw_singleImplName
Definition: LLToken.h:432
@ kw_typeTests
Definition: LLToken.h:403
@ kw_versions
Definition: LLToken.h:447
@ kw_notcold
Definition: LLToken.h:449
@ kw_mayThrow
Definition: LLToken.h:386
@ kw_swifttailcc
Definition: LLToken.h:161
@ kw_monotonic
Definition: LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition: LLToken.h:404
@ kw_amdgpu_ls
Definition: LLToken.h:171
@ kw_caller
Definition: LLToken.h:82
@ kw_vscale
Definition: LLToken.h:41
@ kw_target
Definition: LLToken.h:88
@ kw_attributes
Definition: LLToken.h:187
@ kw_code_model
Definition: LLToken.h:120
@ kw_cmpxchg
Definition: LLToken.h:335
@ kw_funcFlags
Definition: LLToken.h:378
@ kw_localdynamic
Definition: LLToken.h:73
@ kw_uniformRetVal
Definition: LLToken.h:435
@ kw_sideeffect
Definition: LLToken.h:125
@ kw_amdgpu_ps
Definition: LLToken.h:175
@ kw_sizeM1BitWidth
Definition: LLToken.h:421
@ kw_catchret
Definition: LLToken.h:326
@ kw_nodeduplicate
Definition: LLToken.h:234
@ kw_avr_signalcc
Definition: LLToken.h:152
@ kw_exactmatch
Definition: LLToken.h:232
@ kw_aliasee
Definition: LLToken.h:400
@ kw_common
Definition: LLToken.h:62
@ kw_unreachable
Definition: LLToken.h:323
@ kw_intel_ocl_bicc
Definition: LLToken.h:136
@ kw_global
Definition: LLToken.h:47
@ kw_dso_local
Definition: LLToken.h:50
@ kw_undef
Definition: LLToken.h:77
@ kw_addrspace
Definition: LLToken.h:117
@ kw_release
Definition: LLToken.h:98
@ kw_returnDoesNotAlias
Definition: LLToken.h:382
@ kw_aarch64_sme_preservemost_from_x0
Definition: LLToken.h:148
@ kw_preserve_allcc
Definition: LLToken.h:163
@ kw_importType
Definition: LLToken.h:373
@ dotdotdot
Definition: LLToken.h:24
@ kw_cleanupret
Definition: LLToken.h:324
@ kw_shufflevector
Definition: LLToken.h:341
@ kw_riscv_vector_cc
Definition: LLToken.h:184
@ kw_avr_intrcc
Definition: LLToken.h:151
@ kw_definition
Definition: LLToken.h:374
@ kw_prologue
Definition: LLToken.h:129
@ kw_virtualConstProp
Definition: LLToken.h:437
@ kw_vcall_visibility
Definition: LLToken.h:426
@ kw_poison
Definition: LLToken.h:78
@ kw_appending
Definition: LLToken.h:59
@ kw_inaccessiblemem
Definition: LLToken.h:200
@ kw_preserve_mostcc
Definition: LLToken.h:162
@ kw_arm_aapcs_vfpcc
Definition: LLToken.h:145
@ kw_typeTestRes
Definition: LLToken.h:414
@ kw_unknown
Definition: LLToken.h:394
@ kw_x86_regcallcc
Definition: LLToken.h:142
@ kw_typeIdInfo
Definition: LLToken.h:402
@ kw_amdgpu_cs_chain
Definition: LLToken.h:177
@ kw_dso_local_equivalent
Definition: LLToken.h:346
@ kw_x86_64_sysvcc
Definition: LLToken.h:157
@ DbgRecordType
Definition: LLToken.h:487
@ kw_summary
Definition: LLToken.h:413
@ kw_virtFunc
Definition: LLToken.h:399
@ kw_musttail
Definition: LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition: LLToken.h:149
@ kw_byteArray
Definition: LLToken.h:417
@ kw_uniqueRetVal
Definition: LLToken.h:436
@ kw_insertvalue
Definition: LLToken.h:344
@ kw_indirectbr
Definition: LLToken.h:320
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
void UpgradeSectionAttributes(Module &M)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1680
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
@ Done
Definition: Threading.h:61
AllocFnKind
Definition: Attributes.h:48
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:269
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:264
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition: ModRef.h:268
bool isPointerTy(const Type *T)
Definition: SPIRVUtils.h:116
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1914
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:249
static constexpr roundingMode rmNearestTiesToEven
Definition: APFloat.h:230
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:250
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:247
static const fltSemantics & BFloat() LLVM_READNONE
Definition: APFloat.cpp:248
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Class to accumulate and hold information about a callee.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
A specification for a virtual function call with all constant integer arguments.
Flags specific to function summaries.
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
All type identifier related information.
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
A utility class that uses RAII to save and restore the value of a variable.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition: SlotMapping.h:33
std::map< unsigned, Type * > Types
Definition: SlotMapping.h:37
StringMap< Type * > NamedTypes
Definition: SlotMapping.h:36
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition: SlotMapping.h:35
NumberedValues< GlobalValue * > GlobalValues
Definition: SlotMapping.h:34
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:53
unsigned UIntVal
Definition: LLParser.h:75
@ t_Constant
Definition: LLParser.h:67
@ t_PackedConstantStruct
Definition: LLParser.h:71
@ t_GlobalID
Definition: LLParser.h:56
@ t_EmptyArray
Definition: LLParser.h:66
@ t_GlobalName
Definition: LLParser.h:58
@ t_ConstantStruct
Definition: LLParser.h:70
@ t_LocalName
Definition: LLParser.h:57
@ t_ConstantSplat
Definition: LLParser.h:68
@ t_InlineAsm
Definition: LLParser.h:69
FunctionType * FTy
Definition: LLParser.h:76
LLLexer::LocTy Loc
Definition: LLParser.h:74
enum llvm::ValID::@36 Kind
std::string StrVal
Definition: LLParser.h:77
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
Utility type to build an inheritance chain that makes it easy to rank overload candidates.
Definition: STLExtras.h:1479