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