1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.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"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalObject.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/IR/ValueSymbolTable.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
57 static std::string getTypeString(Type *T) {
59 raw_string_ostream Tmp(Result);
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run() {
69 if (Context.shouldDiscardValueNames())
72 "Can't read textual IR with a Context that discards named Values");
74 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
78 bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
93 restoreParsingState(Slots);
97 SMLoc Start = Lex.getLoc();
101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
107 void LLParser::restoreParsingState(const SlotMapping *Slots) {
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
122 bool LLParser::ValidateEndOfModule() {
123 // Handle any function attribute group forward references.
124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
132 if (Function *Fn = dyn_cast<Function>(V)) {
133 AttributeList AS = Fn->getAttributes();
134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
139 // If the alignment was parsed as an attribute, move to the alignment
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
150 AttributeList AS = CI->getAttributes();
151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
158 AttributeList AS = II->getAttributes();
159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
164 II->setAttributes(AS);
165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166 AttrBuilder Attrs(GV->getAttributes());
168 GV->setAttributes(AttributeSet::get(Context,Attrs));
170 llvm_unreachable("invalid object with forward attribute group reference");
174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
204 Twine(ForwardRefValIDs.begin()->first) + "'");
206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
209 Twine(ForwardRefMDNodes.begin()->first) + "'");
211 // Resolve metadata cycles.
212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
240 if (UpgradeDebugInfo)
241 llvm::UpgradeDebugInfo(*M);
243 UpgradeModuleFlags(*M);
244 UpgradeSectionAttributes(*M);
248 // Initialize the slot mapping.
249 // Because by this point we've parsed and validated everything, we can "steal"
250 // the mapping from LLParser as it doesn't need it anymore.
251 Slots->GlobalValues = std::move(NumberedVals);
252 Slots->MetadataNodes = std::move(NumberedMetadata);
253 for (const auto &I : NamedTypes)
254 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
255 for (const auto &I : NumberedTypes)
256 Slots->Types.insert(std::make_pair(I.first, I.second.first));
261 //===----------------------------------------------------------------------===//
262 // Top-Level Entities
263 //===----------------------------------------------------------------------===//
265 bool LLParser::ParseTopLevelEntities() {
267 switch (Lex.getKind()) {
268 default: return TokError("expected top-level entity");
269 case lltok::Eof: return false;
270 case lltok::kw_declare: if (ParseDeclare()) return true; break;
271 case lltok::kw_define: if (ParseDefine()) return true; break;
272 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
273 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
274 case lltok::kw_source_filename:
275 if (ParseSourceFileName())
278 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
279 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
280 case lltok::LocalVar: if (ParseNamedType()) return true; break;
281 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
282 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
283 case lltok::ComdatVar: if (parseComdat()) return true; break;
284 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
285 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
287 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
288 case lltok::kw_uselistorder_bb:
289 if (ParseUseListOrderBB())
297 /// ::= 'module' 'asm' STRINGCONSTANT
298 bool LLParser::ParseModuleAsm() {
299 assert(Lex.getKind() == lltok::kw_module);
303 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
304 ParseStringConstant(AsmStr)) return true;
306 M->appendModuleInlineAsm(AsmStr);
311 /// ::= 'target' 'triple' '=' STRINGCONSTANT
312 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
313 bool LLParser::ParseTargetDefinition() {
314 assert(Lex.getKind() == lltok::kw_target);
317 default: return TokError("unknown target property");
318 case lltok::kw_triple:
320 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
321 ParseStringConstant(Str))
323 M->setTargetTriple(Str);
325 case lltok::kw_datalayout:
327 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
328 ParseStringConstant(Str))
330 M->setDataLayout(Str);
336 /// ::= 'source_filename' '=' STRINGCONSTANT
337 bool LLParser::ParseSourceFileName() {
338 assert(Lex.getKind() == lltok::kw_source_filename);
341 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
342 ParseStringConstant(Str))
344 M->setSourceFileName(Str);
349 /// ::= 'deplibs' '=' '[' ']'
350 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
351 /// FIXME: Remove in 4.0. Currently parse, but ignore.
352 bool LLParser::ParseDepLibs() {
353 assert(Lex.getKind() == lltok::kw_deplibs);
355 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
356 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
359 if (EatIfPresent(lltok::rsquare))
364 if (ParseStringConstant(Str)) return true;
365 } while (EatIfPresent(lltok::comma));
367 return ParseToken(lltok::rsquare, "expected ']' at end of list");
370 /// ParseUnnamedType:
371 /// ::= LocalVarID '=' 'type' type
372 bool LLParser::ParseUnnamedType() {
373 LocTy TypeLoc = Lex.getLoc();
374 unsigned TypeID = Lex.getUIntVal();
375 Lex.Lex(); // eat LocalVarID;
377 if (ParseToken(lltok::equal, "expected '=' after name") ||
378 ParseToken(lltok::kw_type, "expected 'type' after '='"))
381 Type *Result = nullptr;
382 if (ParseStructDefinition(TypeLoc, "",
383 NumberedTypes[TypeID], Result)) return true;
385 if (!isa<StructType>(Result)) {
386 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
388 return Error(TypeLoc, "non-struct types may not be recursive");
389 Entry.first = Result;
390 Entry.second = SMLoc();
397 /// ::= LocalVar '=' 'type' type
398 bool LLParser::ParseNamedType() {
399 std::string Name = Lex.getStrVal();
400 LocTy NameLoc = Lex.getLoc();
401 Lex.Lex(); // eat LocalVar.
403 if (ParseToken(lltok::equal, "expected '=' after name") ||
404 ParseToken(lltok::kw_type, "expected 'type' after name"))
407 Type *Result = nullptr;
408 if (ParseStructDefinition(NameLoc, Name,
409 NamedTypes[Name], Result)) return true;
411 if (!isa<StructType>(Result)) {
412 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
414 return Error(NameLoc, "non-struct types may not be recursive");
415 Entry.first = Result;
416 Entry.second = SMLoc();
423 /// ::= 'declare' FunctionHeader
424 bool LLParser::ParseDeclare() {
425 assert(Lex.getKind() == lltok::kw_declare);
428 std::vector<std::pair<unsigned, MDNode *>> MDs;
429 while (Lex.getKind() == lltok::MetadataVar) {
432 if (ParseMetadataAttachment(MDK, N))
434 MDs.push_back({MDK, N});
438 if (ParseFunctionHeader(F, false))
441 F->addMetadata(MD.first, *MD.second);
446 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
447 bool LLParser::ParseDefine() {
448 assert(Lex.getKind() == lltok::kw_define);
452 return ParseFunctionHeader(F, true) ||
453 ParseOptionalFunctionMetadata(*F) ||
454 ParseFunctionBody(*F);
460 bool LLParser::ParseGlobalType(bool &IsConstant) {
461 if (Lex.getKind() == lltok::kw_constant)
463 else if (Lex.getKind() == lltok::kw_global)
467 return TokError("expected 'global' or 'constant'");
473 bool LLParser::ParseOptionalUnnamedAddr(
474 GlobalVariable::UnnamedAddr &UnnamedAddr) {
475 if (EatIfPresent(lltok::kw_unnamed_addr))
476 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
477 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
478 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
480 UnnamedAddr = GlobalValue::UnnamedAddr::None;
484 /// ParseUnnamedGlobal:
485 /// OptionalVisibility (ALIAS | IFUNC) ...
486 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
487 /// OptionalDLLStorageClass
488 /// ... -> global variable
489 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
490 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
491 /// OptionalDLLStorageClass
492 /// ... -> global variable
493 bool LLParser::ParseUnnamedGlobal() {
494 unsigned VarID = NumberedVals.size();
496 LocTy NameLoc = Lex.getLoc();
498 // Handle the GlobalID form.
499 if (Lex.getKind() == lltok::GlobalID) {
500 if (Lex.getUIntVal() != VarID)
501 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
503 Lex.Lex(); // eat GlobalID;
505 if (ParseToken(lltok::equal, "expected '=' after name"))
510 unsigned Linkage, Visibility, DLLStorageClass;
512 GlobalVariable::ThreadLocalMode TLM;
513 GlobalVariable::UnnamedAddr UnnamedAddr;
514 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
516 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
519 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
520 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
521 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
523 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
524 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
527 /// ParseNamedGlobal:
528 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
529 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
530 /// OptionalVisibility OptionalDLLStorageClass
531 /// ... -> global variable
532 bool LLParser::ParseNamedGlobal() {
533 assert(Lex.getKind() == lltok::GlobalVar);
534 LocTy NameLoc = Lex.getLoc();
535 std::string Name = Lex.getStrVal();
539 unsigned Linkage, Visibility, DLLStorageClass;
541 GlobalVariable::ThreadLocalMode TLM;
542 GlobalVariable::UnnamedAddr UnnamedAddr;
543 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
544 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
546 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
549 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
550 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
551 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
553 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
554 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
557 bool LLParser::parseComdat() {
558 assert(Lex.getKind() == lltok::ComdatVar);
559 std::string Name = Lex.getStrVal();
560 LocTy NameLoc = Lex.getLoc();
563 if (ParseToken(lltok::equal, "expected '=' here"))
566 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
567 return TokError("expected comdat type");
569 Comdat::SelectionKind SK;
570 switch (Lex.getKind()) {
572 return TokError("unknown selection kind");
576 case lltok::kw_exactmatch:
577 SK = Comdat::ExactMatch;
579 case lltok::kw_largest:
580 SK = Comdat::Largest;
582 case lltok::kw_noduplicates:
583 SK = Comdat::NoDuplicates;
585 case lltok::kw_samesize:
586 SK = Comdat::SameSize;
591 // See if the comdat was forward referenced, if so, use the comdat.
592 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
593 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
594 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
595 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
598 if (I != ComdatSymTab.end())
601 C = M->getOrInsertComdat(Name);
602 C->setSelectionKind(SK);
608 // ::= '!' STRINGCONSTANT
609 bool LLParser::ParseMDString(MDString *&Result) {
611 if (ParseStringConstant(Str)) return true;
612 Result = MDString::get(Context, Str);
617 // ::= '!' MDNodeNumber
618 bool LLParser::ParseMDNodeID(MDNode *&Result) {
619 // !{ ..., !42, ... }
620 LocTy IDLoc = Lex.getLoc();
622 if (ParseUInt32(MID))
625 // If not a forward reference, just return it now.
626 if (NumberedMetadata.count(MID)) {
627 Result = NumberedMetadata[MID];
631 // Otherwise, create MDNode forward reference.
632 auto &FwdRef = ForwardRefMDNodes[MID];
633 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
635 Result = FwdRef.first.get();
636 NumberedMetadata[MID].reset(Result);
640 /// ParseNamedMetadata:
641 /// !foo = !{ !1, !2 }
642 bool LLParser::ParseNamedMetadata() {
643 assert(Lex.getKind() == lltok::MetadataVar);
644 std::string Name = Lex.getStrVal();
647 if (ParseToken(lltok::equal, "expected '=' here") ||
648 ParseToken(lltok::exclaim, "Expected '!' here") ||
649 ParseToken(lltok::lbrace, "Expected '{' here"))
652 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
653 if (Lex.getKind() != lltok::rbrace)
656 // Parse DIExpressions inline as a special case. They are still MDNodes,
657 // so they can still appear in named metadata. Remove this logic if they
658 // become plain Metadata.
659 if (Lex.getKind() == lltok::MetadataVar &&
660 Lex.getStrVal() == "DIExpression") {
661 if (ParseDIExpression(N, /*IsDistinct=*/false))
663 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
668 } while (EatIfPresent(lltok::comma));
670 return ParseToken(lltok::rbrace, "expected end of metadata node");
673 /// ParseStandaloneMetadata:
675 bool LLParser::ParseStandaloneMetadata() {
676 assert(Lex.getKind() == lltok::exclaim);
678 unsigned MetadataID = 0;
681 if (ParseUInt32(MetadataID) ||
682 ParseToken(lltok::equal, "expected '=' here"))
685 // Detect common error, from old metadata syntax.
686 if (Lex.getKind() == lltok::Type)
687 return TokError("unexpected type in metadata definition");
689 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
690 if (Lex.getKind() == lltok::MetadataVar) {
691 if (ParseSpecializedMDNode(Init, IsDistinct))
693 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
694 ParseMDTuple(Init, IsDistinct))
697 // See if this was forward referenced, if so, handle it.
698 auto FI = ForwardRefMDNodes.find(MetadataID);
699 if (FI != ForwardRefMDNodes.end()) {
700 FI->second.first->replaceAllUsesWith(Init);
701 ForwardRefMDNodes.erase(FI);
703 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
705 if (NumberedMetadata.count(MetadataID))
706 return TokError("Metadata id is already used");
707 NumberedMetadata[MetadataID].reset(Init);
713 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
714 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
715 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
718 /// parseIndirectSymbol:
719 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
720 /// OptionalVisibility OptionalDLLStorageClass
721 /// OptionalThreadLocal OptionalUnnamedAddr
722 // 'alias|ifunc' IndirectSymbol
727 /// Everything through OptionalUnnamedAddr has already been parsed.
729 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
730 unsigned L, unsigned Visibility,
731 unsigned DLLStorageClass, bool DSOLocal,
732 GlobalVariable::ThreadLocalMode TLM,
733 GlobalVariable::UnnamedAddr UnnamedAddr) {
735 if (Lex.getKind() == lltok::kw_alias)
737 else if (Lex.getKind() == lltok::kw_ifunc)
740 llvm_unreachable("Not an alias or ifunc!");
743 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
745 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
746 return Error(NameLoc, "invalid linkage type for alias");
748 if (!isValidVisibilityForLinkage(Visibility, L))
749 return Error(NameLoc,
750 "symbol with local linkage must have default visibility");
752 if (DSOLocal && !IsAlias) {
753 return Error(NameLoc,
754 "dso_local is invalid on ifunc");
758 LocTy ExplicitTypeLoc = Lex.getLoc();
760 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
764 LocTy AliaseeLoc = Lex.getLoc();
765 if (Lex.getKind() != lltok::kw_bitcast &&
766 Lex.getKind() != lltok::kw_getelementptr &&
767 Lex.getKind() != lltok::kw_addrspacecast &&
768 Lex.getKind() != lltok::kw_inttoptr) {
769 if (ParseGlobalTypeAndValue(Aliasee))
772 // The bitcast dest type is not present, it is implied by the dest type.
776 if (ID.Kind != ValID::t_Constant)
777 return Error(AliaseeLoc, "invalid aliasee");
778 Aliasee = ID.ConstantVal;
781 Type *AliaseeType = Aliasee->getType();
782 auto *PTy = dyn_cast<PointerType>(AliaseeType);
784 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
785 unsigned AddrSpace = PTy->getAddressSpace();
787 if (IsAlias && Ty != PTy->getElementType())
790 "explicit pointee type doesn't match operand's pointee type");
792 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
795 "explicit pointee type should be a function type");
797 GlobalValue *GVal = nullptr;
799 // See if the alias was forward referenced, if so, prepare to replace the
800 // forward reference.
802 GVal = M->getNamedValue(Name);
804 if (!ForwardRefVals.erase(Name))
805 return Error(NameLoc, "redefinition of global '@" + Name + "'");
808 auto I = ForwardRefValIDs.find(NumberedVals.size());
809 if (I != ForwardRefValIDs.end()) {
810 GVal = I->second.first;
811 ForwardRefValIDs.erase(I);
815 // Okay, create the alias but do not insert it into the module yet.
816 std::unique_ptr<GlobalIndirectSymbol> GA;
818 GA.reset(GlobalAlias::create(Ty, AddrSpace,
819 (GlobalValue::LinkageTypes)Linkage, Name,
820 Aliasee, /*Parent*/ nullptr));
822 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
823 (GlobalValue::LinkageTypes)Linkage, Name,
824 Aliasee, /*Parent*/ nullptr));
825 GA->setThreadLocalMode(TLM);
826 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
827 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
828 GA->setUnnamedAddr(UnnamedAddr);
829 GA->setDSOLocal(DSOLocal);
832 NumberedVals.push_back(GA.get());
835 // Verify that types agree.
836 if (GVal->getType() != GA->getType())
839 "forward reference and definition of alias have different types");
841 // If they agree, just RAUW the old value with the alias and remove the
843 GVal->replaceAllUsesWith(GA.get());
844 GVal->eraseFromParent();
847 // Insert into the module, we know its name won't collide now.
849 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
851 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
852 assert(GA->getName() == Name && "Should not be a name conflict!");
854 // The module owns this now
861 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
862 /// OptionalVisibility OptionalDLLStorageClass
863 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
864 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
865 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
866 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
867 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
868 /// Const OptionalAttrs
870 /// Everything up to and including OptionalUnnamedAddr has been parsed
873 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
874 unsigned Linkage, bool HasLinkage,
875 unsigned Visibility, unsigned DLLStorageClass,
876 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
877 GlobalVariable::UnnamedAddr UnnamedAddr) {
878 if (!isValidVisibilityForLinkage(Visibility, Linkage))
879 return Error(NameLoc,
880 "symbol with local linkage must have default visibility");
883 bool IsConstant, IsExternallyInitialized;
884 LocTy IsExternallyInitializedLoc;
888 if (ParseOptionalAddrSpace(AddrSpace) ||
889 ParseOptionalToken(lltok::kw_externally_initialized,
890 IsExternallyInitialized,
891 &IsExternallyInitializedLoc) ||
892 ParseGlobalType(IsConstant) ||
893 ParseType(Ty, TyLoc))
896 // If the linkage is specified and is external, then no initializer is
898 Constant *Init = nullptr;
900 !GlobalValue::isValidDeclarationLinkage(
901 (GlobalValue::LinkageTypes)Linkage)) {
902 if (ParseGlobalValue(Ty, Init))
906 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
907 return Error(TyLoc, "invalid type for global variable");
909 GlobalValue *GVal = nullptr;
911 // See if the global was forward referenced, if so, use the global.
913 GVal = M->getNamedValue(Name);
915 if (!ForwardRefVals.erase(Name))
916 return Error(NameLoc, "redefinition of global '@" + Name + "'");
919 auto I = ForwardRefValIDs.find(NumberedVals.size());
920 if (I != ForwardRefValIDs.end()) {
921 GVal = I->second.first;
922 ForwardRefValIDs.erase(I);
928 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
929 Name, nullptr, GlobalVariable::NotThreadLocal,
932 if (GVal->getValueType() != Ty)
934 "forward reference and definition of global have different types");
936 GV = cast<GlobalVariable>(GVal);
938 // Move the forward-reference to the correct spot in the module.
939 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
943 NumberedVals.push_back(GV);
945 // Set the parsed properties on the global.
947 GV->setInitializer(Init);
948 GV->setConstant(IsConstant);
949 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
950 GV->setDSOLocal(DSOLocal);
951 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
952 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
953 GV->setExternallyInitialized(IsExternallyInitialized);
954 GV->setThreadLocalMode(TLM);
955 GV->setUnnamedAddr(UnnamedAddr);
957 // Parse attributes on the global.
958 while (Lex.getKind() == lltok::comma) {
961 if (Lex.getKind() == lltok::kw_section) {
963 GV->setSection(Lex.getStrVal());
964 if (ParseToken(lltok::StringConstant, "expected global section string"))
966 } else if (Lex.getKind() == lltok::kw_align) {
968 if (ParseOptionalAlignment(Alignment)) return true;
969 GV->setAlignment(Alignment);
970 } else if (Lex.getKind() == lltok::MetadataVar) {
971 if (ParseGlobalObjectMetadataAttachment(*GV))
975 if (parseOptionalComdat(Name, C))
980 return TokError("unknown global variable property!");
986 std::vector<unsigned> FwdRefAttrGrps;
987 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
989 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
990 GV->setAttributes(AttributeSet::get(Context, Attrs));
991 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
997 /// ParseUnnamedAttrGrp
998 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
999 bool LLParser::ParseUnnamedAttrGrp() {
1000 assert(Lex.getKind() == lltok::kw_attributes);
1001 LocTy AttrGrpLoc = Lex.getLoc();
1004 if (Lex.getKind() != lltok::AttrGrpID)
1005 return TokError("expected attribute group id");
1007 unsigned VarID = Lex.getUIntVal();
1008 std::vector<unsigned> unused;
1012 if (ParseToken(lltok::equal, "expected '=' here") ||
1013 ParseToken(lltok::lbrace, "expected '{' here") ||
1014 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1016 ParseToken(lltok::rbrace, "expected end of attribute group"))
1019 if (!NumberedAttrBuilders[VarID].hasAttributes())
1020 return Error(AttrGrpLoc, "attribute group has no attributes");
1025 /// ParseFnAttributeValuePairs
1026 /// ::= <attr> | <attr> '=' <value>
1027 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1028 std::vector<unsigned> &FwdRefAttrGrps,
1029 bool inAttrGrp, LocTy &BuiltinLoc) {
1030 bool HaveError = false;
1035 lltok::Kind Token = Lex.getKind();
1036 if (Token == lltok::kw_builtin)
1037 BuiltinLoc = Lex.getLoc();
1040 if (!inAttrGrp) return HaveError;
1041 return Error(Lex.getLoc(), "unterminated attribute group");
1046 case lltok::AttrGrpID: {
1047 // Allow a function to reference an attribute group:
1049 // define void @foo() #1 { ... }
1053 "cannot have an attribute group reference in an attribute group");
1055 unsigned AttrGrpNum = Lex.getUIntVal();
1056 if (inAttrGrp) break;
1058 // Save the reference to the attribute group. We'll fill it in later.
1059 FwdRefAttrGrps.push_back(AttrGrpNum);
1062 // Target-dependent attributes:
1063 case lltok::StringConstant: {
1064 if (ParseStringAttribute(B))
1069 // Target-independent attributes:
1070 case lltok::kw_align: {
1071 // As a hack, we allow function alignment to be initially parsed as an
1072 // attribute on a function declaration/definition or added to an attribute
1073 // group and later moved to the alignment field.
1077 if (ParseToken(lltok::equal, "expected '=' here") ||
1078 ParseUInt32(Alignment))
1081 if (ParseOptionalAlignment(Alignment))
1084 B.addAlignmentAttr(Alignment);
1087 case lltok::kw_alignstack: {
1091 if (ParseToken(lltok::equal, "expected '=' here") ||
1092 ParseUInt32(Alignment))
1095 if (ParseOptionalStackAlignment(Alignment))
1098 B.addStackAlignmentAttr(Alignment);
1101 case lltok::kw_allocsize: {
1102 unsigned ElemSizeArg;
1103 Optional<unsigned> NumElemsArg;
1104 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1105 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1107 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1110 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1111 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1112 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1113 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1114 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1115 case lltok::kw_inaccessiblememonly:
1116 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1117 case lltok::kw_inaccessiblemem_or_argmemonly:
1118 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1119 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1120 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1121 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1122 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1123 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1124 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1125 case lltok::kw_noimplicitfloat:
1126 B.addAttribute(Attribute::NoImplicitFloat); break;
1127 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1128 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1129 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1130 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1131 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1132 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1133 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1134 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1135 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1136 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1137 case lltok::kw_returns_twice:
1138 B.addAttribute(Attribute::ReturnsTwice); break;
1139 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1140 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1141 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1142 case lltok::kw_sspstrong:
1143 B.addAttribute(Attribute::StackProtectStrong); break;
1144 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1145 case lltok::kw_sanitize_address:
1146 B.addAttribute(Attribute::SanitizeAddress); break;
1147 case lltok::kw_sanitize_hwaddress:
1148 B.addAttribute(Attribute::SanitizeHWAddress); break;
1149 case lltok::kw_sanitize_thread:
1150 B.addAttribute(Attribute::SanitizeThread); break;
1151 case lltok::kw_sanitize_memory:
1152 B.addAttribute(Attribute::SanitizeMemory); break;
1153 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1154 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1155 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1158 case lltok::kw_inreg:
1159 case lltok::kw_signext:
1160 case lltok::kw_zeroext:
1163 "invalid use of attribute on a function");
1165 case lltok::kw_byval:
1166 case lltok::kw_dereferenceable:
1167 case lltok::kw_dereferenceable_or_null:
1168 case lltok::kw_inalloca:
1169 case lltok::kw_nest:
1170 case lltok::kw_noalias:
1171 case lltok::kw_nocapture:
1172 case lltok::kw_nonnull:
1173 case lltok::kw_returned:
1174 case lltok::kw_sret:
1175 case lltok::kw_swifterror:
1176 case lltok::kw_swiftself:
1179 "invalid use of parameter-only attribute on a function");
1187 //===----------------------------------------------------------------------===//
1188 // GlobalValue Reference/Resolution Routines.
1189 //===----------------------------------------------------------------------===//
1191 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1192 const std::string &Name) {
1193 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1194 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1196 return new GlobalVariable(*M, PTy->getElementType(), false,
1197 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1198 nullptr, GlobalVariable::NotThreadLocal,
1199 PTy->getAddressSpace());
1202 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1203 /// forward reference record if needed. This can return null if the value
1204 /// exists but does not have the right type.
1205 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1207 PointerType *PTy = dyn_cast<PointerType>(Ty);
1209 Error(Loc, "global variable reference must have pointer type");
1213 // Look this name up in the normal function symbol table.
1215 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1217 // If this is a forward reference for the value, see if we already created a
1218 // forward ref record.
1220 auto I = ForwardRefVals.find(Name);
1221 if (I != ForwardRefVals.end())
1222 Val = I->second.first;
1225 // If we have the value in the symbol table or fwd-ref table, return it.
1227 if (Val->getType() == Ty) return Val;
1228 Error(Loc, "'@" + Name + "' defined with type '" +
1229 getTypeString(Val->getType()) + "'");
1233 // Otherwise, create a new forward reference for this value and remember it.
1234 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1235 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1239 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1240 PointerType *PTy = dyn_cast<PointerType>(Ty);
1242 Error(Loc, "global variable reference must have pointer type");
1246 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1248 // If this is a forward reference for the value, see if we already created a
1249 // forward ref record.
1251 auto I = ForwardRefValIDs.find(ID);
1252 if (I != ForwardRefValIDs.end())
1253 Val = I->second.first;
1256 // If we have the value in the symbol table or fwd-ref table, return it.
1258 if (Val->getType() == Ty) return Val;
1259 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1260 getTypeString(Val->getType()) + "'");
1264 // Otherwise, create a new forward reference for this value and remember it.
1265 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1266 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1270 //===----------------------------------------------------------------------===//
1271 // Comdat Reference/Resolution Routines.
1272 //===----------------------------------------------------------------------===//
1274 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1275 // Look this name up in the comdat symbol table.
1276 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1277 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1278 if (I != ComdatSymTab.end())
1281 // Otherwise, create a new forward reference for this value and remember it.
1282 Comdat *C = M->getOrInsertComdat(Name);
1283 ForwardRefComdats[Name] = Loc;
1287 //===----------------------------------------------------------------------===//
1289 //===----------------------------------------------------------------------===//
1291 /// ParseToken - If the current token has the specified kind, eat it and return
1292 /// success. Otherwise, emit the specified error and return failure.
1293 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1294 if (Lex.getKind() != T)
1295 return TokError(ErrMsg);
1300 /// ParseStringConstant
1301 /// ::= StringConstant
1302 bool LLParser::ParseStringConstant(std::string &Result) {
1303 if (Lex.getKind() != lltok::StringConstant)
1304 return TokError("expected string constant");
1305 Result = Lex.getStrVal();
1312 bool LLParser::ParseUInt32(uint32_t &Val) {
1313 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1314 return TokError("expected integer");
1315 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1316 if (Val64 != unsigned(Val64))
1317 return TokError("expected 32-bit integer (too large)");
1325 bool LLParser::ParseUInt64(uint64_t &Val) {
1326 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1327 return TokError("expected integer");
1328 Val = Lex.getAPSIntVal().getLimitedValue();
1334 /// := 'localdynamic'
1335 /// := 'initialexec'
1337 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1338 switch (Lex.getKind()) {
1340 return TokError("expected localdynamic, initialexec or localexec");
1341 case lltok::kw_localdynamic:
1342 TLM = GlobalVariable::LocalDynamicTLSModel;
1344 case lltok::kw_initialexec:
1345 TLM = GlobalVariable::InitialExecTLSModel;
1347 case lltok::kw_localexec:
1348 TLM = GlobalVariable::LocalExecTLSModel;
1356 /// ParseOptionalThreadLocal
1358 /// := 'thread_local'
1359 /// := 'thread_local' '(' tlsmodel ')'
1360 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1361 TLM = GlobalVariable::NotThreadLocal;
1362 if (!EatIfPresent(lltok::kw_thread_local))
1365 TLM = GlobalVariable::GeneralDynamicTLSModel;
1366 if (Lex.getKind() == lltok::lparen) {
1368 return ParseTLSModel(TLM) ||
1369 ParseToken(lltok::rparen, "expected ')' after thread local model");
1374 /// ParseOptionalAddrSpace
1376 /// := 'addrspace' '(' uint32 ')'
1377 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1379 if (!EatIfPresent(lltok::kw_addrspace))
1381 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1382 ParseUInt32(AddrSpace) ||
1383 ParseToken(lltok::rparen, "expected ')' in address space");
1386 /// ParseStringAttribute
1387 /// := StringConstant
1388 /// := StringConstant '=' StringConstant
1389 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1390 std::string Attr = Lex.getStrVal();
1393 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1395 B.addAttribute(Attr, Val);
1399 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1400 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1401 bool HaveError = false;
1406 lltok::Kind Token = Lex.getKind();
1408 default: // End of attributes.
1410 case lltok::StringConstant: {
1411 if (ParseStringAttribute(B))
1415 case lltok::kw_align: {
1417 if (ParseOptionalAlignment(Alignment))
1419 B.addAlignmentAttr(Alignment);
1422 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1423 case lltok::kw_dereferenceable: {
1425 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1427 B.addDereferenceableAttr(Bytes);
1430 case lltok::kw_dereferenceable_or_null: {
1432 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1434 B.addDereferenceableOrNullAttr(Bytes);
1437 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1438 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1439 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1440 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1441 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1442 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1443 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1444 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1445 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1446 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1447 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1448 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1449 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1450 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1451 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1453 case lltok::kw_alignstack:
1454 case lltok::kw_alwaysinline:
1455 case lltok::kw_argmemonly:
1456 case lltok::kw_builtin:
1457 case lltok::kw_inlinehint:
1458 case lltok::kw_jumptable:
1459 case lltok::kw_minsize:
1460 case lltok::kw_naked:
1461 case lltok::kw_nobuiltin:
1462 case lltok::kw_noduplicate:
1463 case lltok::kw_noimplicitfloat:
1464 case lltok::kw_noinline:
1465 case lltok::kw_nonlazybind:
1466 case lltok::kw_noredzone:
1467 case lltok::kw_noreturn:
1468 case lltok::kw_nounwind:
1469 case lltok::kw_optnone:
1470 case lltok::kw_optsize:
1471 case lltok::kw_returns_twice:
1472 case lltok::kw_sanitize_address:
1473 case lltok::kw_sanitize_hwaddress:
1474 case lltok::kw_sanitize_memory:
1475 case lltok::kw_sanitize_thread:
1477 case lltok::kw_sspreq:
1478 case lltok::kw_sspstrong:
1479 case lltok::kw_safestack:
1480 case lltok::kw_strictfp:
1481 case lltok::kw_uwtable:
1482 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1490 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1491 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1492 bool HaveError = false;
1497 lltok::Kind Token = Lex.getKind();
1499 default: // End of attributes.
1501 case lltok::StringConstant: {
1502 if (ParseStringAttribute(B))
1506 case lltok::kw_dereferenceable: {
1508 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1510 B.addDereferenceableAttr(Bytes);
1513 case lltok::kw_dereferenceable_or_null: {
1515 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1517 B.addDereferenceableOrNullAttr(Bytes);
1520 case lltok::kw_align: {
1522 if (ParseOptionalAlignment(Alignment))
1524 B.addAlignmentAttr(Alignment);
1527 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1528 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1529 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1530 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1531 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1534 case lltok::kw_byval:
1535 case lltok::kw_inalloca:
1536 case lltok::kw_nest:
1537 case lltok::kw_nocapture:
1538 case lltok::kw_returned:
1539 case lltok::kw_sret:
1540 case lltok::kw_swifterror:
1541 case lltok::kw_swiftself:
1542 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1545 case lltok::kw_alignstack:
1546 case lltok::kw_alwaysinline:
1547 case lltok::kw_argmemonly:
1548 case lltok::kw_builtin:
1549 case lltok::kw_cold:
1550 case lltok::kw_inlinehint:
1551 case lltok::kw_jumptable:
1552 case lltok::kw_minsize:
1553 case lltok::kw_naked:
1554 case lltok::kw_nobuiltin:
1555 case lltok::kw_noduplicate:
1556 case lltok::kw_noimplicitfloat:
1557 case lltok::kw_noinline:
1558 case lltok::kw_nonlazybind:
1559 case lltok::kw_noredzone:
1560 case lltok::kw_noreturn:
1561 case lltok::kw_nounwind:
1562 case lltok::kw_optnone:
1563 case lltok::kw_optsize:
1564 case lltok::kw_returns_twice:
1565 case lltok::kw_sanitize_address:
1566 case lltok::kw_sanitize_hwaddress:
1567 case lltok::kw_sanitize_memory:
1568 case lltok::kw_sanitize_thread:
1570 case lltok::kw_sspreq:
1571 case lltok::kw_sspstrong:
1572 case lltok::kw_safestack:
1573 case lltok::kw_strictfp:
1574 case lltok::kw_uwtable:
1575 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1578 case lltok::kw_readnone:
1579 case lltok::kw_readonly:
1580 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1587 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1592 return GlobalValue::ExternalLinkage;
1593 case lltok::kw_private:
1594 return GlobalValue::PrivateLinkage;
1595 case lltok::kw_internal:
1596 return GlobalValue::InternalLinkage;
1597 case lltok::kw_weak:
1598 return GlobalValue::WeakAnyLinkage;
1599 case lltok::kw_weak_odr:
1600 return GlobalValue::WeakODRLinkage;
1601 case lltok::kw_linkonce:
1602 return GlobalValue::LinkOnceAnyLinkage;
1603 case lltok::kw_linkonce_odr:
1604 return GlobalValue::LinkOnceODRLinkage;
1605 case lltok::kw_available_externally:
1606 return GlobalValue::AvailableExternallyLinkage;
1607 case lltok::kw_appending:
1608 return GlobalValue::AppendingLinkage;
1609 case lltok::kw_common:
1610 return GlobalValue::CommonLinkage;
1611 case lltok::kw_extern_weak:
1612 return GlobalValue::ExternalWeakLinkage;
1613 case lltok::kw_external:
1614 return GlobalValue::ExternalLinkage;
1618 /// ParseOptionalLinkage
1625 /// ::= 'linkonce_odr'
1626 /// ::= 'available_externally'
1629 /// ::= 'extern_weak'
1631 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1632 unsigned &Visibility,
1633 unsigned &DLLStorageClass,
1635 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1638 ParseOptionalDSOLocal(DSOLocal);
1639 ParseOptionalVisibility(Visibility);
1640 ParseOptionalDLLStorageClass(DLLStorageClass);
1642 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1643 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1649 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1650 switch (Lex.getKind()) {
1654 case lltok::kw_dso_local:
1658 case lltok::kw_dso_preemptable:
1665 /// ParseOptionalVisibility
1671 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1672 switch (Lex.getKind()) {
1674 Res = GlobalValue::DefaultVisibility;
1676 case lltok::kw_default:
1677 Res = GlobalValue::DefaultVisibility;
1679 case lltok::kw_hidden:
1680 Res = GlobalValue::HiddenVisibility;
1682 case lltok::kw_protected:
1683 Res = GlobalValue::ProtectedVisibility;
1689 /// ParseOptionalDLLStorageClass
1694 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1695 switch (Lex.getKind()) {
1697 Res = GlobalValue::DefaultStorageClass;
1699 case lltok::kw_dllimport:
1700 Res = GlobalValue::DLLImportStorageClass;
1702 case lltok::kw_dllexport:
1703 Res = GlobalValue::DLLExportStorageClass;
1709 /// ParseOptionalCallingConv
1713 /// ::= 'intel_ocl_bicc'
1715 /// ::= 'x86_stdcallcc'
1716 /// ::= 'x86_fastcallcc'
1717 /// ::= 'x86_thiscallcc'
1718 /// ::= 'x86_vectorcallcc'
1719 /// ::= 'arm_apcscc'
1720 /// ::= 'arm_aapcscc'
1721 /// ::= 'arm_aapcs_vfpcc'
1722 /// ::= 'msp430_intrcc'
1723 /// ::= 'avr_intrcc'
1724 /// ::= 'avr_signalcc'
1725 /// ::= 'ptx_kernel'
1726 /// ::= 'ptx_device'
1728 /// ::= 'spir_kernel'
1729 /// ::= 'x86_64_sysvcc'
1731 /// ::= 'webkit_jscc'
1733 /// ::= 'preserve_mostcc'
1734 /// ::= 'preserve_allcc'
1737 /// ::= 'x86_intrcc'
1740 /// ::= 'cxx_fast_tlscc'
1748 /// ::= 'amdgpu_kernel'
1751 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1752 switch (Lex.getKind()) {
1753 default: CC = CallingConv::C; return false;
1754 case lltok::kw_ccc: CC = CallingConv::C; break;
1755 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1756 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1757 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1758 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1759 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1760 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1761 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1762 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1763 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1764 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1765 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1766 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1767 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1768 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1769 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1770 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1771 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1772 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1773 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1774 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1775 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1776 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1777 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1778 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1779 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1780 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1781 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1782 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1783 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1784 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1785 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1786 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1787 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1788 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1789 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1790 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1791 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1792 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1793 case lltok::kw_cc: {
1795 return ParseUInt32(CC);
1803 /// ParseMetadataAttachment
1805 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1806 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1808 std::string Name = Lex.getStrVal();
1809 Kind = M->getMDKindID(Name);
1812 return ParseMDNode(MD);
1815 /// ParseInstructionMetadata
1816 /// ::= !dbg !42 (',' !dbg !57)*
1817 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1819 if (Lex.getKind() != lltok::MetadataVar)
1820 return TokError("expected metadata after comma");
1824 if (ParseMetadataAttachment(MDK, N))
1827 Inst.setMetadata(MDK, N);
1828 if (MDK == LLVMContext::MD_tbaa)
1829 InstsWithTBAATag.push_back(&Inst);
1831 // If this is the end of the list, we're done.
1832 } while (EatIfPresent(lltok::comma));
1836 /// ParseGlobalObjectMetadataAttachment
1838 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1841 if (ParseMetadataAttachment(MDK, N))
1844 GO.addMetadata(MDK, *N);
1848 /// ParseOptionalFunctionMetadata
1850 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1851 while (Lex.getKind() == lltok::MetadataVar)
1852 if (ParseGlobalObjectMetadataAttachment(F))
1857 /// ParseOptionalAlignment
1860 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1862 if (!EatIfPresent(lltok::kw_align))
1864 LocTy AlignLoc = Lex.getLoc();
1865 if (ParseUInt32(Alignment)) return true;
1866 if (!isPowerOf2_32(Alignment))
1867 return Error(AlignLoc, "alignment is not a power of two");
1868 if (Alignment > Value::MaximumAlignment)
1869 return Error(AlignLoc, "huge alignments are not supported yet");
1873 /// ParseOptionalDerefAttrBytes
1875 /// ::= AttrKind '(' 4 ')'
1877 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1878 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1880 assert((AttrKind == lltok::kw_dereferenceable ||
1881 AttrKind == lltok::kw_dereferenceable_or_null) &&
1885 if (!EatIfPresent(AttrKind))
1887 LocTy ParenLoc = Lex.getLoc();
1888 if (!EatIfPresent(lltok::lparen))
1889 return Error(ParenLoc, "expected '('");
1890 LocTy DerefLoc = Lex.getLoc();
1891 if (ParseUInt64(Bytes)) return true;
1892 ParenLoc = Lex.getLoc();
1893 if (!EatIfPresent(lltok::rparen))
1894 return Error(ParenLoc, "expected ')'");
1896 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1900 /// ParseOptionalCommaAlign
1904 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1906 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1907 bool &AteExtraComma) {
1908 AteExtraComma = false;
1909 while (EatIfPresent(lltok::comma)) {
1910 // Metadata at the end is an early exit.
1911 if (Lex.getKind() == lltok::MetadataVar) {
1912 AteExtraComma = true;
1916 if (Lex.getKind() != lltok::kw_align)
1917 return Error(Lex.getLoc(), "expected metadata or 'align'");
1919 if (ParseOptionalAlignment(Alignment)) return true;
1925 /// ParseOptionalCommaAddrSpace
1927 /// ::= ',' addrspace(1)
1929 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1931 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1933 bool &AteExtraComma) {
1934 AteExtraComma = false;
1935 while (EatIfPresent(lltok::comma)) {
1936 // Metadata at the end is an early exit.
1937 if (Lex.getKind() == lltok::MetadataVar) {
1938 AteExtraComma = true;
1943 if (Lex.getKind() != lltok::kw_addrspace)
1944 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1946 if (ParseOptionalAddrSpace(AddrSpace))
1953 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1954 Optional<unsigned> &HowManyArg) {
1957 auto StartParen = Lex.getLoc();
1958 if (!EatIfPresent(lltok::lparen))
1959 return Error(StartParen, "expected '('");
1961 if (ParseUInt32(BaseSizeArg))
1964 if (EatIfPresent(lltok::comma)) {
1965 auto HowManyAt = Lex.getLoc();
1967 if (ParseUInt32(HowMany))
1969 if (HowMany == BaseSizeArg)
1970 return Error(HowManyAt,
1971 "'allocsize' indices can't refer to the same parameter");
1972 HowManyArg = HowMany;
1976 auto EndParen = Lex.getLoc();
1977 if (!EatIfPresent(lltok::rparen))
1978 return Error(EndParen, "expected ')'");
1982 /// ParseScopeAndOrdering
1983 /// if isAtomic: ::= SyncScope? AtomicOrdering
1986 /// This sets Scope and Ordering to the parsed values.
1987 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
1988 AtomicOrdering &Ordering) {
1992 return ParseScope(SSID) || ParseOrdering(Ordering);
1996 /// ::= syncscope("singlethread" | "<target scope>")?
1998 /// This sets synchronization scope ID to the ID of the parsed value.
1999 bool LLParser::ParseScope(SyncScope::ID &SSID) {
2000 SSID = SyncScope::System;
2001 if (EatIfPresent(lltok::kw_syncscope)) {
2002 auto StartParenAt = Lex.getLoc();
2003 if (!EatIfPresent(lltok::lparen))
2004 return Error(StartParenAt, "Expected '(' in syncscope");
2007 auto SSNAt = Lex.getLoc();
2008 if (ParseStringConstant(SSN))
2009 return Error(SSNAt, "Expected synchronization scope name");
2011 auto EndParenAt = Lex.getLoc();
2012 if (!EatIfPresent(lltok::rparen))
2013 return Error(EndParenAt, "Expected ')' in syncscope");
2015 SSID = Context.getOrInsertSyncScopeID(SSN);
2022 /// ::= AtomicOrdering
2024 /// This sets Ordering to the parsed value.
2025 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2026 switch (Lex.getKind()) {
2027 default: return TokError("Expected ordering on atomic instruction");
2028 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2029 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2030 // Not specified yet:
2031 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2032 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2033 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2034 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2035 case lltok::kw_seq_cst:
2036 Ordering = AtomicOrdering::SequentiallyConsistent;
2043 /// ParseOptionalStackAlignment
2045 /// ::= 'alignstack' '(' 4 ')'
2046 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2048 if (!EatIfPresent(lltok::kw_alignstack))
2050 LocTy ParenLoc = Lex.getLoc();
2051 if (!EatIfPresent(lltok::lparen))
2052 return Error(ParenLoc, "expected '('");
2053 LocTy AlignLoc = Lex.getLoc();
2054 if (ParseUInt32(Alignment)) return true;
2055 ParenLoc = Lex.getLoc();
2056 if (!EatIfPresent(lltok::rparen))
2057 return Error(ParenLoc, "expected ')'");
2058 if (!isPowerOf2_32(Alignment))
2059 return Error(AlignLoc, "stack alignment is not a power of two");
2063 /// ParseIndexList - This parses the index list for an insert/extractvalue
2064 /// instruction. This sets AteExtraComma in the case where we eat an extra
2065 /// comma at the end of the line and find that it is followed by metadata.
2066 /// Clients that don't allow metadata can call the version of this function that
2067 /// only takes one argument.
2070 /// ::= (',' uint32)+
2072 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2073 bool &AteExtraComma) {
2074 AteExtraComma = false;
2076 if (Lex.getKind() != lltok::comma)
2077 return TokError("expected ',' as start of index list");
2079 while (EatIfPresent(lltok::comma)) {
2080 if (Lex.getKind() == lltok::MetadataVar) {
2081 if (Indices.empty()) return TokError("expected index");
2082 AteExtraComma = true;
2086 if (ParseUInt32(Idx)) return true;
2087 Indices.push_back(Idx);
2093 //===----------------------------------------------------------------------===//
2095 //===----------------------------------------------------------------------===//
2097 /// ParseType - Parse a type.
2098 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2099 SMLoc TypeLoc = Lex.getLoc();
2100 switch (Lex.getKind()) {
2102 return TokError(Msg);
2104 // Type ::= 'float' | 'void' (etc)
2105 Result = Lex.getTyVal();
2109 // Type ::= StructType
2110 if (ParseAnonStructType(Result, false))
2113 case lltok::lsquare:
2114 // Type ::= '[' ... ']'
2115 Lex.Lex(); // eat the lsquare.
2116 if (ParseArrayVectorType(Result, false))
2119 case lltok::less: // Either vector or packed struct.
2120 // Type ::= '<' ... '>'
2122 if (Lex.getKind() == lltok::lbrace) {
2123 if (ParseAnonStructType(Result, true) ||
2124 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2126 } else if (ParseArrayVectorType(Result, true))
2129 case lltok::LocalVar: {
2131 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2133 // If the type hasn't been defined yet, create a forward definition and
2134 // remember where that forward def'n was seen (in case it never is defined).
2136 Entry.first = StructType::create(Context, Lex.getStrVal());
2137 Entry.second = Lex.getLoc();
2139 Result = Entry.first;
2144 case lltok::LocalVarID: {
2146 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2148 // If the type hasn't been defined yet, create a forward definition and
2149 // remember where that forward def'n was seen (in case it never is defined).
2151 Entry.first = StructType::create(Context);
2152 Entry.second = Lex.getLoc();
2154 Result = Entry.first;
2160 // Parse the type suffixes.
2162 switch (Lex.getKind()) {
2165 if (!AllowVoid && Result->isVoidTy())
2166 return Error(TypeLoc, "void type only allowed for function results");
2169 // Type ::= Type '*'
2171 if (Result->isLabelTy())
2172 return TokError("basic block pointers are invalid");
2173 if (Result->isVoidTy())
2174 return TokError("pointers to void are invalid - use i8* instead");
2175 if (!PointerType::isValidElementType(Result))
2176 return TokError("pointer to this type is invalid");
2177 Result = PointerType::getUnqual(Result);
2181 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2182 case lltok::kw_addrspace: {
2183 if (Result->isLabelTy())
2184 return TokError("basic block pointers are invalid");
2185 if (Result->isVoidTy())
2186 return TokError("pointers to void are invalid; use i8* instead");
2187 if (!PointerType::isValidElementType(Result))
2188 return TokError("pointer to this type is invalid");
2190 if (ParseOptionalAddrSpace(AddrSpace) ||
2191 ParseToken(lltok::star, "expected '*' in address space"))
2194 Result = PointerType::get(Result, AddrSpace);
2198 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2200 if (ParseFunctionType(Result))
2207 /// ParseParameterList
2209 /// ::= '(' Arg (',' Arg)* ')'
2211 /// ::= Type OptionalAttributes Value OptionalAttributes
2212 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2213 PerFunctionState &PFS, bool IsMustTailCall,
2214 bool InVarArgsFunc) {
2215 if (ParseToken(lltok::lparen, "expected '(' in call"))
2218 while (Lex.getKind() != lltok::rparen) {
2219 // If this isn't the first argument, we need a comma.
2220 if (!ArgList.empty() &&
2221 ParseToken(lltok::comma, "expected ',' in argument list"))
2224 // Parse an ellipsis if this is a musttail call in a variadic function.
2225 if (Lex.getKind() == lltok::dotdotdot) {
2226 const char *Msg = "unexpected ellipsis in argument list for ";
2227 if (!IsMustTailCall)
2228 return TokError(Twine(Msg) + "non-musttail call");
2230 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2231 Lex.Lex(); // Lex the '...', it is purely for readability.
2232 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2235 // Parse the argument.
2237 Type *ArgTy = nullptr;
2238 AttrBuilder ArgAttrs;
2240 if (ParseType(ArgTy, ArgLoc))
2243 if (ArgTy->isMetadataTy()) {
2244 if (ParseMetadataAsValue(V, PFS))
2247 // Otherwise, handle normal operands.
2248 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2251 ArgList.push_back(ParamInfo(
2252 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2255 if (IsMustTailCall && InVarArgsFunc)
2256 return TokError("expected '...' at end of argument list for musttail call "
2257 "in varargs function");
2259 Lex.Lex(); // Lex the ')'.
2263 /// ParseOptionalOperandBundles
2265 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2268 /// ::= bundle-tag '(' ')'
2269 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2271 /// bundle-tag ::= String Constant
2272 bool LLParser::ParseOptionalOperandBundles(
2273 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2274 LocTy BeginLoc = Lex.getLoc();
2275 if (!EatIfPresent(lltok::lsquare))
2278 while (Lex.getKind() != lltok::rsquare) {
2279 // If this isn't the first operand bundle, we need a comma.
2280 if (!BundleList.empty() &&
2281 ParseToken(lltok::comma, "expected ',' in input list"))
2285 if (ParseStringConstant(Tag))
2288 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2291 std::vector<Value *> Inputs;
2292 while (Lex.getKind() != lltok::rparen) {
2293 // If this isn't the first input, we need a comma.
2294 if (!Inputs.empty() &&
2295 ParseToken(lltok::comma, "expected ',' in input list"))
2299 Value *Input = nullptr;
2300 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2302 Inputs.push_back(Input);
2305 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2307 Lex.Lex(); // Lex the ')'.
2310 if (BundleList.empty())
2311 return Error(BeginLoc, "operand bundle set must not be empty");
2313 Lex.Lex(); // Lex the ']'.
2317 /// ParseArgumentList - Parse the argument list for a function type or function
2319 /// ::= '(' ArgTypeListI ')'
2323 /// ::= ArgTypeList ',' '...'
2324 /// ::= ArgType (',' ArgType)*
2326 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2329 assert(Lex.getKind() == lltok::lparen);
2330 Lex.Lex(); // eat the (.
2332 if (Lex.getKind() == lltok::rparen) {
2334 } else if (Lex.getKind() == lltok::dotdotdot) {
2338 LocTy TypeLoc = Lex.getLoc();
2339 Type *ArgTy = nullptr;
2343 if (ParseType(ArgTy) ||
2344 ParseOptionalParamAttrs(Attrs)) return true;
2346 if (ArgTy->isVoidTy())
2347 return Error(TypeLoc, "argument can not have void type");
2349 if (Lex.getKind() == lltok::LocalVar) {
2350 Name = Lex.getStrVal();
2354 if (!FunctionType::isValidArgumentType(ArgTy))
2355 return Error(TypeLoc, "invalid type for function argument");
2357 ArgList.emplace_back(TypeLoc, ArgTy,
2358 AttributeSet::get(ArgTy->getContext(), Attrs),
2361 while (EatIfPresent(lltok::comma)) {
2362 // Handle ... at end of arg list.
2363 if (EatIfPresent(lltok::dotdotdot)) {
2368 // Otherwise must be an argument type.
2369 TypeLoc = Lex.getLoc();
2370 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2372 if (ArgTy->isVoidTy())
2373 return Error(TypeLoc, "argument can not have void type");
2375 if (Lex.getKind() == lltok::LocalVar) {
2376 Name = Lex.getStrVal();
2382 if (!ArgTy->isFirstClassType())
2383 return Error(TypeLoc, "invalid type for function argument");
2385 ArgList.emplace_back(TypeLoc, ArgTy,
2386 AttributeSet::get(ArgTy->getContext(), Attrs),
2391 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2394 /// ParseFunctionType
2395 /// ::= Type ArgumentList OptionalAttrs
2396 bool LLParser::ParseFunctionType(Type *&Result) {
2397 assert(Lex.getKind() == lltok::lparen);
2399 if (!FunctionType::isValidReturnType(Result))
2400 return TokError("invalid function return type");
2402 SmallVector<ArgInfo, 8> ArgList;
2404 if (ParseArgumentList(ArgList, isVarArg))
2407 // Reject names on the arguments lists.
2408 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2409 if (!ArgList[i].Name.empty())
2410 return Error(ArgList[i].Loc, "argument name invalid in function type");
2411 if (ArgList[i].Attrs.hasAttributes())
2412 return Error(ArgList[i].Loc,
2413 "argument attributes invalid in function type");
2416 SmallVector<Type*, 16> ArgListTy;
2417 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2418 ArgListTy.push_back(ArgList[i].Ty);
2420 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2424 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2426 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2427 SmallVector<Type*, 8> Elts;
2428 if (ParseStructBody(Elts)) return true;
2430 Result = StructType::get(Context, Elts, Packed);
2434 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2435 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2436 std::pair<Type*, LocTy> &Entry,
2438 // If the type was already defined, diagnose the redefinition.
2439 if (Entry.first && !Entry.second.isValid())
2440 return Error(TypeLoc, "redefinition of type");
2442 // If we have opaque, just return without filling in the definition for the
2443 // struct. This counts as a definition as far as the .ll file goes.
2444 if (EatIfPresent(lltok::kw_opaque)) {
2445 // This type is being defined, so clear the location to indicate this.
2446 Entry.second = SMLoc();
2448 // If this type number has never been uttered, create it.
2450 Entry.first = StructType::create(Context, Name);
2451 ResultTy = Entry.first;
2455 // If the type starts with '<', then it is either a packed struct or a vector.
2456 bool isPacked = EatIfPresent(lltok::less);
2458 // If we don't have a struct, then we have a random type alias, which we
2459 // accept for compatibility with old files. These types are not allowed to be
2460 // forward referenced and not allowed to be recursive.
2461 if (Lex.getKind() != lltok::lbrace) {
2463 return Error(TypeLoc, "forward references to non-struct type");
2467 return ParseArrayVectorType(ResultTy, true);
2468 return ParseType(ResultTy);
2471 // This type is being defined, so clear the location to indicate this.
2472 Entry.second = SMLoc();
2474 // If this type number has never been uttered, create it.
2476 Entry.first = StructType::create(Context, Name);
2478 StructType *STy = cast<StructType>(Entry.first);
2480 SmallVector<Type*, 8> Body;
2481 if (ParseStructBody(Body) ||
2482 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2485 STy->setBody(Body, isPacked);
2490 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2493 /// ::= '{' Type (',' Type)* '}'
2494 /// ::= '<' '{' '}' '>'
2495 /// ::= '<' '{' Type (',' Type)* '}' '>'
2496 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2497 assert(Lex.getKind() == lltok::lbrace);
2498 Lex.Lex(); // Consume the '{'
2500 // Handle the empty struct.
2501 if (EatIfPresent(lltok::rbrace))
2504 LocTy EltTyLoc = Lex.getLoc();
2506 if (ParseType(Ty)) return true;
2509 if (!StructType::isValidElementType(Ty))
2510 return Error(EltTyLoc, "invalid element type for struct");
2512 while (EatIfPresent(lltok::comma)) {
2513 EltTyLoc = Lex.getLoc();
2514 if (ParseType(Ty)) return true;
2516 if (!StructType::isValidElementType(Ty))
2517 return Error(EltTyLoc, "invalid element type for struct");
2522 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2525 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2526 /// token has already been consumed.
2528 /// ::= '[' APSINTVAL 'x' Types ']'
2529 /// ::= '<' APSINTVAL 'x' Types '>'
2530 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2531 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2532 Lex.getAPSIntVal().getBitWidth() > 64)
2533 return TokError("expected number in address space");
2535 LocTy SizeLoc = Lex.getLoc();
2536 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2539 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2542 LocTy TypeLoc = Lex.getLoc();
2543 Type *EltTy = nullptr;
2544 if (ParseType(EltTy)) return true;
2546 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2547 "expected end of sequential type"))
2552 return Error(SizeLoc, "zero element vector is illegal");
2553 if ((unsigned)Size != Size)
2554 return Error(SizeLoc, "size too large for vector");
2555 if (!VectorType::isValidElementType(EltTy))
2556 return Error(TypeLoc, "invalid vector element type");
2557 Result = VectorType::get(EltTy, unsigned(Size));
2559 if (!ArrayType::isValidElementType(EltTy))
2560 return Error(TypeLoc, "invalid array element type");
2561 Result = ArrayType::get(EltTy, Size);
2566 //===----------------------------------------------------------------------===//
2567 // Function Semantic Analysis.
2568 //===----------------------------------------------------------------------===//
2570 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2572 : P(p), F(f), FunctionNumber(functionNumber) {
2574 // Insert unnamed arguments into the NumberedVals list.
2575 for (Argument &A : F.args())
2577 NumberedVals.push_back(&A);
2580 LLParser::PerFunctionState::~PerFunctionState() {
2581 // If there were any forward referenced non-basicblock values, delete them.
2583 for (const auto &P : ForwardRefVals) {
2584 if (isa<BasicBlock>(P.second.first))
2586 P.second.first->replaceAllUsesWith(
2587 UndefValue::get(P.second.first->getType()));
2588 P.second.first->deleteValue();
2591 for (const auto &P : ForwardRefValIDs) {
2592 if (isa<BasicBlock>(P.second.first))
2594 P.second.first->replaceAllUsesWith(
2595 UndefValue::get(P.second.first->getType()));
2596 P.second.first->deleteValue();
2600 bool LLParser::PerFunctionState::FinishFunction() {
2601 if (!ForwardRefVals.empty())
2602 return P.Error(ForwardRefVals.begin()->second.second,
2603 "use of undefined value '%" + ForwardRefVals.begin()->first +
2605 if (!ForwardRefValIDs.empty())
2606 return P.Error(ForwardRefValIDs.begin()->second.second,
2607 "use of undefined value '%" +
2608 Twine(ForwardRefValIDs.begin()->first) + "'");
2612 /// GetVal - Get a value with the specified name or ID, creating a
2613 /// forward reference record if needed. This can return null if the value
2614 /// exists but does not have the right type.
2615 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2617 // Look this name up in the normal function symbol table.
2618 Value *Val = F.getValueSymbolTable()->lookup(Name);
2620 // If this is a forward reference for the value, see if we already created a
2621 // forward ref record.
2623 auto I = ForwardRefVals.find(Name);
2624 if (I != ForwardRefVals.end())
2625 Val = I->second.first;
2628 // If we have the value in the symbol table or fwd-ref table, return it.
2630 if (Val->getType() == Ty) return Val;
2631 if (Ty->isLabelTy())
2632 P.Error(Loc, "'%" + Name + "' is not a basic block");
2634 P.Error(Loc, "'%" + Name + "' defined with type '" +
2635 getTypeString(Val->getType()) + "'");
2639 // Don't make placeholders with invalid type.
2640 if (!Ty->isFirstClassType()) {
2641 P.Error(Loc, "invalid use of a non-first-class type");
2645 // Otherwise, create a new forward reference for this value and remember it.
2647 if (Ty->isLabelTy()) {
2648 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2650 FwdVal = new Argument(Ty, Name);
2653 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2657 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2658 // Look this name up in the normal function symbol table.
2659 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2661 // If this is a forward reference for the value, see if we already created a
2662 // forward ref record.
2664 auto I = ForwardRefValIDs.find(ID);
2665 if (I != ForwardRefValIDs.end())
2666 Val = I->second.first;
2669 // If we have the value in the symbol table or fwd-ref table, return it.
2671 if (Val->getType() == Ty) return Val;
2672 if (Ty->isLabelTy())
2673 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2675 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2676 getTypeString(Val->getType()) + "'");
2680 if (!Ty->isFirstClassType()) {
2681 P.Error(Loc, "invalid use of a non-first-class type");
2685 // Otherwise, create a new forward reference for this value and remember it.
2687 if (Ty->isLabelTy()) {
2688 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2690 FwdVal = new Argument(Ty);
2693 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2697 /// SetInstName - After an instruction is parsed and inserted into its
2698 /// basic block, this installs its name.
2699 bool LLParser::PerFunctionState::SetInstName(int NameID,
2700 const std::string &NameStr,
2701 LocTy NameLoc, Instruction *Inst) {
2702 // If this instruction has void type, it cannot have a name or ID specified.
2703 if (Inst->getType()->isVoidTy()) {
2704 if (NameID != -1 || !NameStr.empty())
2705 return P.Error(NameLoc, "instructions returning void cannot have a name");
2709 // If this was a numbered instruction, verify that the instruction is the
2710 // expected value and resolve any forward references.
2711 if (NameStr.empty()) {
2712 // If neither a name nor an ID was specified, just use the next ID.
2714 NameID = NumberedVals.size();
2716 if (unsigned(NameID) != NumberedVals.size())
2717 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2718 Twine(NumberedVals.size()) + "'");
2720 auto FI = ForwardRefValIDs.find(NameID);
2721 if (FI != ForwardRefValIDs.end()) {
2722 Value *Sentinel = FI->second.first;
2723 if (Sentinel->getType() != Inst->getType())
2724 return P.Error(NameLoc, "instruction forward referenced with type '" +
2725 getTypeString(FI->second.first->getType()) + "'");
2727 Sentinel->replaceAllUsesWith(Inst);
2728 Sentinel->deleteValue();
2729 ForwardRefValIDs.erase(FI);
2732 NumberedVals.push_back(Inst);
2736 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2737 auto FI = ForwardRefVals.find(NameStr);
2738 if (FI != ForwardRefVals.end()) {
2739 Value *Sentinel = FI->second.first;
2740 if (Sentinel->getType() != Inst->getType())
2741 return P.Error(NameLoc, "instruction forward referenced with type '" +
2742 getTypeString(FI->second.first->getType()) + "'");
2744 Sentinel->replaceAllUsesWith(Inst);
2745 Sentinel->deleteValue();
2746 ForwardRefVals.erase(FI);
2749 // Set the name on the instruction.
2750 Inst->setName(NameStr);
2752 if (Inst->getName() != NameStr)
2753 return P.Error(NameLoc, "multiple definition of local value named '" +
2758 /// GetBB - Get a basic block with the specified name or ID, creating a
2759 /// forward reference record if needed.
2760 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2762 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2763 Type::getLabelTy(F.getContext()), Loc));
2766 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2767 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2768 Type::getLabelTy(F.getContext()), Loc));
2771 /// DefineBB - Define the specified basic block, which is either named or
2772 /// unnamed. If there is an error, this returns null otherwise it returns
2773 /// the block being defined.
2774 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2778 BB = GetBB(NumberedVals.size(), Loc);
2780 BB = GetBB(Name, Loc);
2781 if (!BB) return nullptr; // Already diagnosed error.
2783 // Move the block to the end of the function. Forward ref'd blocks are
2784 // inserted wherever they happen to be referenced.
2785 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2787 // Remove the block from forward ref sets.
2789 ForwardRefValIDs.erase(NumberedVals.size());
2790 NumberedVals.push_back(BB);
2792 // BB forward references are already in the function symbol table.
2793 ForwardRefVals.erase(Name);
2799 //===----------------------------------------------------------------------===//
2801 //===----------------------------------------------------------------------===//
2803 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2804 /// type implied. For example, if we parse "4" we don't know what integer type
2805 /// it has. The value will later be combined with its type and checked for
2806 /// sanity. PFS is used to convert function-local operands of metadata (since
2807 /// metadata operands are not just parsed here but also converted to values).
2808 /// PFS can be null when we are not parsing metadata values inside a function.
2809 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2810 ID.Loc = Lex.getLoc();
2811 switch (Lex.getKind()) {
2812 default: return TokError("expected value token");
2813 case lltok::GlobalID: // @42
2814 ID.UIntVal = Lex.getUIntVal();
2815 ID.Kind = ValID::t_GlobalID;
2817 case lltok::GlobalVar: // @foo
2818 ID.StrVal = Lex.getStrVal();
2819 ID.Kind = ValID::t_GlobalName;
2821 case lltok::LocalVarID: // %42
2822 ID.UIntVal = Lex.getUIntVal();
2823 ID.Kind = ValID::t_LocalID;
2825 case lltok::LocalVar: // %foo
2826 ID.StrVal = Lex.getStrVal();
2827 ID.Kind = ValID::t_LocalName;
2830 ID.APSIntVal = Lex.getAPSIntVal();
2831 ID.Kind = ValID::t_APSInt;
2833 case lltok::APFloat:
2834 ID.APFloatVal = Lex.getAPFloatVal();
2835 ID.Kind = ValID::t_APFloat;
2837 case lltok::kw_true:
2838 ID.ConstantVal = ConstantInt::getTrue(Context);
2839 ID.Kind = ValID::t_Constant;
2841 case lltok::kw_false:
2842 ID.ConstantVal = ConstantInt::getFalse(Context);
2843 ID.Kind = ValID::t_Constant;
2845 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2846 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2847 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2848 case lltok::kw_none: ID.Kind = ValID::t_None; break;
2850 case lltok::lbrace: {
2851 // ValID ::= '{' ConstVector '}'
2853 SmallVector<Constant*, 16> Elts;
2854 if (ParseGlobalValueVector(Elts) ||
2855 ParseToken(lltok::rbrace, "expected end of struct constant"))
2858 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2859 ID.UIntVal = Elts.size();
2860 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2861 Elts.size() * sizeof(Elts[0]));
2862 ID.Kind = ValID::t_ConstantStruct;
2866 // ValID ::= '<' ConstVector '>' --> Vector.
2867 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2869 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2871 SmallVector<Constant*, 16> Elts;
2872 LocTy FirstEltLoc = Lex.getLoc();
2873 if (ParseGlobalValueVector(Elts) ||
2875 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2876 ParseToken(lltok::greater, "expected end of constant"))
2879 if (isPackedStruct) {
2880 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2881 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2882 Elts.size() * sizeof(Elts[0]));
2883 ID.UIntVal = Elts.size();
2884 ID.Kind = ValID::t_PackedConstantStruct;
2889 return Error(ID.Loc, "constant vector must not be empty");
2891 if (!Elts[0]->getType()->isIntegerTy() &&
2892 !Elts[0]->getType()->isFloatingPointTy() &&
2893 !Elts[0]->getType()->isPointerTy())
2894 return Error(FirstEltLoc,
2895 "vector elements must have integer, pointer or floating point type");
2897 // Verify that all the vector elements have the same type.
2898 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2899 if (Elts[i]->getType() != Elts[0]->getType())
2900 return Error(FirstEltLoc,
2901 "vector element #" + Twine(i) +
2902 " is not of type '" + getTypeString(Elts[0]->getType()));
2904 ID.ConstantVal = ConstantVector::get(Elts);
2905 ID.Kind = ValID::t_Constant;
2908 case lltok::lsquare: { // Array Constant
2910 SmallVector<Constant*, 16> Elts;
2911 LocTy FirstEltLoc = Lex.getLoc();
2912 if (ParseGlobalValueVector(Elts) ||
2913 ParseToken(lltok::rsquare, "expected end of array constant"))
2916 // Handle empty element.
2918 // Use undef instead of an array because it's inconvenient to determine
2919 // the element type at this point, there being no elements to examine.
2920 ID.Kind = ValID::t_EmptyArray;
2924 if (!Elts[0]->getType()->isFirstClassType())
2925 return Error(FirstEltLoc, "invalid array element type: " +
2926 getTypeString(Elts[0]->getType()));
2928 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2930 // Verify all elements are correct type!
2931 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2932 if (Elts[i]->getType() != Elts[0]->getType())
2933 return Error(FirstEltLoc,
2934 "array element #" + Twine(i) +
2935 " is not of type '" + getTypeString(Elts[0]->getType()));
2938 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2939 ID.Kind = ValID::t_Constant;
2942 case lltok::kw_c: // c "foo"
2944 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2946 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2947 ID.Kind = ValID::t_Constant;
2950 case lltok::kw_asm: {
2951 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2953 bool HasSideEffect, AlignStack, AsmDialect;
2955 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2956 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2957 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2958 ParseStringConstant(ID.StrVal) ||
2959 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2960 ParseToken(lltok::StringConstant, "expected constraint string"))
2962 ID.StrVal2 = Lex.getStrVal();
2963 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2964 (unsigned(AsmDialect)<<2);
2965 ID.Kind = ValID::t_InlineAsm;
2969 case lltok::kw_blockaddress: {
2970 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2975 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2977 ParseToken(lltok::comma, "expected comma in block address expression")||
2978 ParseValID(Label) ||
2979 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2982 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2983 return Error(Fn.Loc, "expected function name in blockaddress");
2984 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2985 return Error(Label.Loc, "expected basic block name in blockaddress");
2987 // Try to find the function (but skip it if it's forward-referenced).
2988 GlobalValue *GV = nullptr;
2989 if (Fn.Kind == ValID::t_GlobalID) {
2990 if (Fn.UIntVal < NumberedVals.size())
2991 GV = NumberedVals[Fn.UIntVal];
2992 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2993 GV = M->getNamedValue(Fn.StrVal);
2995 Function *F = nullptr;
2997 // Confirm that it's actually a function with a definition.
2998 if (!isa<Function>(GV))
2999 return Error(Fn.Loc, "expected function name in blockaddress");
3000 F = cast<Function>(GV);
3001 if (F->isDeclaration())
3002 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3006 // Make a global variable as a placeholder for this reference.
3007 GlobalValue *&FwdRef =
3008 ForwardRefBlockAddresses.insert(std::make_pair(
3010 std::map<ValID, GlobalValue *>()))
3011 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3014 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3015 GlobalValue::InternalLinkage, nullptr, "");
3016 ID.ConstantVal = FwdRef;
3017 ID.Kind = ValID::t_Constant;
3021 // We found the function; now find the basic block. Don't use PFS, since we
3022 // might be inside a constant expression.
3024 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3025 if (Label.Kind == ValID::t_LocalID)
3026 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3028 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3030 return Error(Label.Loc, "referenced value is not a basic block");
3032 if (Label.Kind == ValID::t_LocalID)
3033 return Error(Label.Loc, "cannot take address of numeric label after "
3034 "the function is defined");
3035 BB = dyn_cast_or_null<BasicBlock>(
3036 F->getValueSymbolTable()->lookup(Label.StrVal));
3038 return Error(Label.Loc, "referenced value is not a basic block");
3041 ID.ConstantVal = BlockAddress::get(F, BB);
3042 ID.Kind = ValID::t_Constant;
3046 case lltok::kw_trunc:
3047 case lltok::kw_zext:
3048 case lltok::kw_sext:
3049 case lltok::kw_fptrunc:
3050 case lltok::kw_fpext:
3051 case lltok::kw_bitcast:
3052 case lltok::kw_addrspacecast:
3053 case lltok::kw_uitofp:
3054 case lltok::kw_sitofp:
3055 case lltok::kw_fptoui:
3056 case lltok::kw_fptosi:
3057 case lltok::kw_inttoptr:
3058 case lltok::kw_ptrtoint: {
3059 unsigned Opc = Lex.getUIntVal();
3060 Type *DestTy = nullptr;
3063 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3064 ParseGlobalTypeAndValue(SrcVal) ||
3065 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3066 ParseType(DestTy) ||
3067 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3069 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3070 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3071 getTypeString(SrcVal->getType()) + "' to '" +
3072 getTypeString(DestTy) + "'");
3073 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3075 ID.Kind = ValID::t_Constant;
3078 case lltok::kw_extractvalue: {
3081 SmallVector<unsigned, 4> Indices;
3082 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3083 ParseGlobalTypeAndValue(Val) ||
3084 ParseIndexList(Indices) ||
3085 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3088 if (!Val->getType()->isAggregateType())
3089 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3090 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3091 return Error(ID.Loc, "invalid indices for extractvalue");
3092 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3093 ID.Kind = ValID::t_Constant;
3096 case lltok::kw_insertvalue: {
3098 Constant *Val0, *Val1;
3099 SmallVector<unsigned, 4> Indices;
3100 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3101 ParseGlobalTypeAndValue(Val0) ||
3102 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3103 ParseGlobalTypeAndValue(Val1) ||
3104 ParseIndexList(Indices) ||
3105 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3107 if (!Val0->getType()->isAggregateType())
3108 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3110 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3112 return Error(ID.Loc, "invalid indices for insertvalue");
3113 if (IndexedType != Val1->getType())
3114 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3115 getTypeString(Val1->getType()) +
3116 "' instead of '" + getTypeString(IndexedType) +
3118 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3119 ID.Kind = ValID::t_Constant;
3122 case lltok::kw_icmp:
3123 case lltok::kw_fcmp: {
3124 unsigned PredVal, Opc = Lex.getUIntVal();
3125 Constant *Val0, *Val1;
3127 if (ParseCmpPredicate(PredVal, Opc) ||
3128 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3129 ParseGlobalTypeAndValue(Val0) ||
3130 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3131 ParseGlobalTypeAndValue(Val1) ||
3132 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3135 if (Val0->getType() != Val1->getType())
3136 return Error(ID.Loc, "compare operands must have the same type");
3138 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3140 if (Opc == Instruction::FCmp) {
3141 if (!Val0->getType()->isFPOrFPVectorTy())
3142 return Error(ID.Loc, "fcmp requires floating point operands");
3143 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3145 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3146 if (!Val0->getType()->isIntOrIntVectorTy() &&
3147 !Val0->getType()->isPtrOrPtrVectorTy())
3148 return Error(ID.Loc, "icmp requires pointer or integer operands");
3149 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3151 ID.Kind = ValID::t_Constant;
3155 // Binary Operators.
3157 case lltok::kw_fadd:
3159 case lltok::kw_fsub:
3161 case lltok::kw_fmul:
3162 case lltok::kw_udiv:
3163 case lltok::kw_sdiv:
3164 case lltok::kw_fdiv:
3165 case lltok::kw_urem:
3166 case lltok::kw_srem:
3167 case lltok::kw_frem:
3169 case lltok::kw_lshr:
3170 case lltok::kw_ashr: {
3174 unsigned Opc = Lex.getUIntVal();
3175 Constant *Val0, *Val1;
3177 LocTy ModifierLoc = Lex.getLoc();
3178 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3179 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3180 if (EatIfPresent(lltok::kw_nuw))
3182 if (EatIfPresent(lltok::kw_nsw)) {
3184 if (EatIfPresent(lltok::kw_nuw))
3187 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3188 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3189 if (EatIfPresent(lltok::kw_exact))
3192 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3193 ParseGlobalTypeAndValue(Val0) ||
3194 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3195 ParseGlobalTypeAndValue(Val1) ||
3196 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3198 if (Val0->getType() != Val1->getType())
3199 return Error(ID.Loc, "operands of constexpr must have same type");
3200 if (!Val0->getType()->isIntOrIntVectorTy()) {
3202 return Error(ModifierLoc, "nuw only applies to integer operations");
3204 return Error(ModifierLoc, "nsw only applies to integer operations");
3206 // Check that the type is valid for the operator.
3208 case Instruction::Add:
3209 case Instruction::Sub:
3210 case Instruction::Mul:
3211 case Instruction::UDiv:
3212 case Instruction::SDiv:
3213 case Instruction::URem:
3214 case Instruction::SRem:
3215 case Instruction::Shl:
3216 case Instruction::AShr:
3217 case Instruction::LShr:
3218 if (!Val0->getType()->isIntOrIntVectorTy())
3219 return Error(ID.Loc, "constexpr requires integer operands");
3221 case Instruction::FAdd:
3222 case Instruction::FSub:
3223 case Instruction::FMul:
3224 case Instruction::FDiv:
3225 case Instruction::FRem:
3226 if (!Val0->getType()->isFPOrFPVectorTy())
3227 return Error(ID.Loc, "constexpr requires fp operands");
3229 default: llvm_unreachable("Unknown binary operator!");
3232 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3233 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3234 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3235 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3237 ID.Kind = ValID::t_Constant;
3241 // Logical Operations
3244 case lltok::kw_xor: {
3245 unsigned Opc = Lex.getUIntVal();
3246 Constant *Val0, *Val1;
3248 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3249 ParseGlobalTypeAndValue(Val0) ||
3250 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3251 ParseGlobalTypeAndValue(Val1) ||
3252 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3254 if (Val0->getType() != Val1->getType())
3255 return Error(ID.Loc, "operands of constexpr must have same type");
3256 if (!Val0->getType()->isIntOrIntVectorTy())
3257 return Error(ID.Loc,
3258 "constexpr requires integer or integer vector operands");
3259 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3260 ID.Kind = ValID::t_Constant;
3264 case lltok::kw_getelementptr:
3265 case lltok::kw_shufflevector:
3266 case lltok::kw_insertelement:
3267 case lltok::kw_extractelement:
3268 case lltok::kw_select: {
3269 unsigned Opc = Lex.getUIntVal();
3270 SmallVector<Constant*, 16> Elts;
3271 bool InBounds = false;
3275 if (Opc == Instruction::GetElementPtr)
3276 InBounds = EatIfPresent(lltok::kw_inbounds);
3278 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3281 LocTy ExplicitTypeLoc = Lex.getLoc();
3282 if (Opc == Instruction::GetElementPtr) {
3283 if (ParseType(Ty) ||
3284 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3288 Optional<unsigned> InRangeOp;
3289 if (ParseGlobalValueVector(
3290 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3291 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3294 if (Opc == Instruction::GetElementPtr) {
3295 if (Elts.size() == 0 ||
3296 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3297 return Error(ID.Loc, "base of getelementptr must be a pointer");
3299 Type *BaseType = Elts[0]->getType();
3300 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3301 if (Ty != BasePointerType->getElementType())
3304 "explicit pointee type doesn't match operand's pointee type");
3307 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3309 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3310 for (Constant *Val : Indices) {
3311 Type *ValTy = Val->getType();
3312 if (!ValTy->isIntOrIntVectorTy())
3313 return Error(ID.Loc, "getelementptr index must be an integer");
3314 if (ValTy->isVectorTy()) {
3315 unsigned ValNumEl = ValTy->getVectorNumElements();
3316 if (GEPWidth && (ValNumEl != GEPWidth))
3319 "getelementptr vector index has a wrong number of elements");
3320 // GEPWidth may have been unknown because the base is a scalar,
3321 // but it is known now.
3322 GEPWidth = ValNumEl;
3326 SmallPtrSet<Type*, 4> Visited;
3327 if (!Indices.empty() && !Ty->isSized(&Visited))
3328 return Error(ID.Loc, "base element of getelementptr must be sized");
3330 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3331 return Error(ID.Loc, "invalid getelementptr indices");
3334 if (*InRangeOp == 0)
3335 return Error(ID.Loc,
3336 "inrange keyword may not appear on pointer operand");
3340 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3341 InBounds, InRangeOp);
3342 } else if (Opc == Instruction::Select) {
3343 if (Elts.size() != 3)
3344 return Error(ID.Loc, "expected three operands to select");
3345 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3347 return Error(ID.Loc, Reason);
3348 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3349 } else if (Opc == Instruction::ShuffleVector) {
3350 if (Elts.size() != 3)
3351 return Error(ID.Loc, "expected three operands to shufflevector");
3352 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3353 return Error(ID.Loc, "invalid operands to shufflevector");
3355 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3356 } else if (Opc == Instruction::ExtractElement) {
3357 if (Elts.size() != 2)
3358 return Error(ID.Loc, "expected two operands to extractelement");
3359 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3360 return Error(ID.Loc, "invalid extractelement operands");
3361 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3363 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3364 if (Elts.size() != 3)
3365 return Error(ID.Loc, "expected three operands to insertelement");
3366 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3367 return Error(ID.Loc, "invalid insertelement operands");
3369 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3372 ID.Kind = ValID::t_Constant;
3381 /// ParseGlobalValue - Parse a global value with the specified type.
3382 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3386 bool Parsed = ParseValID(ID) ||
3387 ConvertValIDToValue(Ty, ID, V, nullptr);
3388 if (V && !(C = dyn_cast<Constant>(V)))
3389 return Error(ID.Loc, "global values must be constants");
3393 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3395 return ParseType(Ty) ||
3396 ParseGlobalValue(Ty, V);
3399 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3402 LocTy KwLoc = Lex.getLoc();
3403 if (!EatIfPresent(lltok::kw_comdat))
3406 if (EatIfPresent(lltok::lparen)) {
3407 if (Lex.getKind() != lltok::ComdatVar)
3408 return TokError("expected comdat variable");
3409 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3411 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3414 if (GlobalName.empty())
3415 return TokError("comdat cannot be unnamed");
3416 C = getComdat(GlobalName, KwLoc);
3422 /// ParseGlobalValueVector
3424 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3425 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3426 Optional<unsigned> *InRangeOp) {
3428 if (Lex.getKind() == lltok::rbrace ||
3429 Lex.getKind() == lltok::rsquare ||
3430 Lex.getKind() == lltok::greater ||
3431 Lex.getKind() == lltok::rparen)
3435 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3436 *InRangeOp = Elts.size();
3439 if (ParseGlobalTypeAndValue(C)) return true;
3441 } while (EatIfPresent(lltok::comma));
3446 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3447 SmallVector<Metadata *, 16> Elts;
3448 if (ParseMDNodeVector(Elts))
3451 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3458 /// ::= !DILocation(...)
3459 bool LLParser::ParseMDNode(MDNode *&N) {
3460 if (Lex.getKind() == lltok::MetadataVar)
3461 return ParseSpecializedMDNode(N);
3463 return ParseToken(lltok::exclaim, "expected '!' here") ||
3467 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3469 if (Lex.getKind() == lltok::lbrace)
3470 return ParseMDTuple(N);
3473 return ParseMDNodeID(N);
3478 /// Structure to represent an optional metadata field.
3479 template <class FieldTy> struct MDFieldImpl {
3480 typedef MDFieldImpl ImplTy;
3484 void assign(FieldTy Val) {
3486 this->Val = std::move(Val);
3489 explicit MDFieldImpl(FieldTy Default)
3490 : Val(std::move(Default)), Seen(false) {}
3493 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3496 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3497 : ImplTy(Default), Max(Max) {}
3500 struct LineField : public MDUnsignedField {
3501 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3504 struct ColumnField : public MDUnsignedField {
3505 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3508 struct DwarfTagField : public MDUnsignedField {
3509 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3510 DwarfTagField(dwarf::Tag DefaultTag)
3511 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3514 struct DwarfMacinfoTypeField : public MDUnsignedField {
3515 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3516 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3517 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3520 struct DwarfAttEncodingField : public MDUnsignedField {
3521 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3524 struct DwarfVirtualityField : public MDUnsignedField {
3525 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3528 struct DwarfLangField : public MDUnsignedField {
3529 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3532 struct DwarfCCField : public MDUnsignedField {
3533 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3536 struct EmissionKindField : public MDUnsignedField {
3537 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3540 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3541 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3544 struct MDSignedField : public MDFieldImpl<int64_t> {
3548 MDSignedField(int64_t Default = 0)
3549 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3550 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3551 : ImplTy(Default), Min(Min), Max(Max) {}
3554 struct MDBoolField : public MDFieldImpl<bool> {
3555 MDBoolField(bool Default = false) : ImplTy(Default) {}
3558 struct MDField : public MDFieldImpl<Metadata *> {
3561 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3564 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3565 MDConstant() : ImplTy(nullptr) {}
3568 struct MDStringField : public MDFieldImpl<MDString *> {
3570 MDStringField(bool AllowEmpty = true)
3571 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3574 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3575 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3578 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3579 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3580 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3583 } // end anonymous namespace
3588 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3589 MDUnsignedField &Result) {
3590 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3591 return TokError("expected unsigned integer");
3593 auto &U = Lex.getAPSIntVal();
3594 if (U.ugt(Result.Max))
3595 return TokError("value for '" + Name + "' too large, limit is " +
3597 Result.assign(U.getZExtValue());
3598 assert(Result.Val <= Result.Max && "Expected value in range");
3604 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3605 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3608 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3609 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3613 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3614 if (Lex.getKind() == lltok::APSInt)
3615 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3617 if (Lex.getKind() != lltok::DwarfTag)
3618 return TokError("expected DWARF tag");
3620 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3621 if (Tag == dwarf::DW_TAG_invalid)
3622 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3623 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3631 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3632 DwarfMacinfoTypeField &Result) {
3633 if (Lex.getKind() == lltok::APSInt)
3634 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3636 if (Lex.getKind() != lltok::DwarfMacinfo)
3637 return TokError("expected DWARF macinfo type");
3639 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3640 if (Macinfo == dwarf::DW_MACINFO_invalid)
3642 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3643 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3645 Result.assign(Macinfo);
3651 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3652 DwarfVirtualityField &Result) {
3653 if (Lex.getKind() == lltok::APSInt)
3654 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3656 if (Lex.getKind() != lltok::DwarfVirtuality)
3657 return TokError("expected DWARF virtuality code");
3659 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3660 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3661 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3662 Lex.getStrVal() + "'");
3663 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3664 Result.assign(Virtuality);
3670 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3671 if (Lex.getKind() == lltok::APSInt)
3672 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3674 if (Lex.getKind() != lltok::DwarfLang)
3675 return TokError("expected DWARF language");
3677 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3679 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3681 assert(Lang <= Result.Max && "Expected valid DWARF language");
3682 Result.assign(Lang);
3688 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3689 if (Lex.getKind() == lltok::APSInt)
3690 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3692 if (Lex.getKind() != lltok::DwarfCC)
3693 return TokError("expected DWARF calling convention");
3695 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3697 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3699 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3706 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3707 if (Lex.getKind() == lltok::APSInt)
3708 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3710 if (Lex.getKind() != lltok::EmissionKind)
3711 return TokError("expected emission kind");
3713 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3715 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3717 assert(*Kind <= Result.Max && "Expected valid emission kind");
3718 Result.assign(*Kind);
3724 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3725 DwarfAttEncodingField &Result) {
3726 if (Lex.getKind() == lltok::APSInt)
3727 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3729 if (Lex.getKind() != lltok::DwarfAttEncoding)
3730 return TokError("expected DWARF type attribute encoding");
3732 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3734 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3735 Lex.getStrVal() + "'");
3736 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3737 Result.assign(Encoding);
3744 /// ::= DIFlagVector
3745 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3747 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3749 // Parser for a single flag.
3750 auto parseFlag = [&](DINode::DIFlags &Val) {
3751 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3752 uint32_t TempVal = static_cast<uint32_t>(Val);
3753 bool Res = ParseUInt32(TempVal);
3754 Val = static_cast<DINode::DIFlags>(TempVal);
3758 if (Lex.getKind() != lltok::DIFlag)
3759 return TokError("expected debug info flag");
3761 Val = DINode::getFlag(Lex.getStrVal());
3763 return TokError(Twine("invalid debug info flag flag '") +
3764 Lex.getStrVal() + "'");
3769 // Parse the flags and combine them together.
3770 DINode::DIFlags Combined = DINode::FlagZero;
3772 DINode::DIFlags Val;
3776 } while (EatIfPresent(lltok::bar));
3778 Result.assign(Combined);
3783 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3784 MDSignedField &Result) {
3785 if (Lex.getKind() != lltok::APSInt)
3786 return TokError("expected signed integer");
3788 auto &S = Lex.getAPSIntVal();
3790 return TokError("value for '" + Name + "' too small, limit is " +
3793 return TokError("value for '" + Name + "' too large, limit is " +
3795 Result.assign(S.getExtValue());
3796 assert(Result.Val >= Result.Min && "Expected value in range");
3797 assert(Result.Val <= Result.Max && "Expected value in range");
3803 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3804 switch (Lex.getKind()) {
3806 return TokError("expected 'true' or 'false'");
3807 case lltok::kw_true:
3808 Result.assign(true);
3810 case lltok::kw_false:
3811 Result.assign(false);
3819 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3820 if (Lex.getKind() == lltok::kw_null) {
3821 if (!Result.AllowNull)
3822 return TokError("'" + Name + "' cannot be null");
3824 Result.assign(nullptr);
3829 if (ParseMetadata(MD, nullptr))
3837 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3838 LocTy ValueLoc = Lex.getLoc();
3840 if (ParseStringConstant(S))
3843 if (!Result.AllowEmpty && S.empty())
3844 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3846 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3851 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3852 SmallVector<Metadata *, 4> MDs;
3853 if (ParseMDNodeVector(MDs))
3856 Result.assign(std::move(MDs));
3861 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3862 ChecksumKindField &Result) {
3863 if (Lex.getKind() != lltok::ChecksumKind)
3865 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3867 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3869 Result.assign(CSKind);
3874 } // end namespace llvm
3876 template <class ParserTy>
3877 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3879 if (Lex.getKind() != lltok::LabelStr)
3880 return TokError("expected field label here");
3884 } while (EatIfPresent(lltok::comma));
3889 template <class ParserTy>
3890 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3891 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3894 if (ParseToken(lltok::lparen, "expected '(' here"))
3896 if (Lex.getKind() != lltok::rparen)
3897 if (ParseMDFieldsImplBody(parseField))
3900 ClosingLoc = Lex.getLoc();
3901 return ParseToken(lltok::rparen, "expected ')' here");
3904 template <class FieldTy>
3905 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3907 return TokError("field '" + Name + "' cannot be specified more than once");
3909 LocTy Loc = Lex.getLoc();
3911 return ParseMDField(Loc, Name, Result);
3914 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3915 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3917 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3918 if (Lex.getStrVal() == #CLASS) \
3919 return Parse##CLASS(N, IsDistinct);
3920 #include "llvm/IR/Metadata.def"
3922 return TokError("expected metadata type");
3925 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3926 #define NOP_FIELD(NAME, TYPE, INIT)
3927 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3929 return Error(ClosingLoc, "missing required field '" #NAME "'");
3930 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3931 if (Lex.getStrVal() == #NAME) \
3932 return ParseMDField(#NAME, NAME);
3933 #define PARSE_MD_FIELDS() \
3934 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3937 if (ParseMDFieldsImpl([&]() -> bool { \
3938 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3939 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3942 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3944 #define GET_OR_DISTINCT(CLASS, ARGS) \
3945 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3947 /// ParseDILocationFields:
3948 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3949 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3950 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3951 OPTIONAL(line, LineField, ); \
3952 OPTIONAL(column, ColumnField, ); \
3953 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3954 OPTIONAL(inlinedAt, MDField, );
3956 #undef VISIT_MD_FIELDS
3958 Result = GET_OR_DISTINCT(
3959 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3963 /// ParseGenericDINode:
3964 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3965 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3966 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3967 REQUIRED(tag, DwarfTagField, ); \
3968 OPTIONAL(header, MDStringField, ); \
3969 OPTIONAL(operands, MDFieldList, );
3971 #undef VISIT_MD_FIELDS
3973 Result = GET_OR_DISTINCT(GenericDINode,
3974 (Context, tag.Val, header.Val, operands.Val));
3978 /// ParseDISubrange:
3979 /// ::= !DISubrange(count: 30, lowerBound: 2)
3980 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3981 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3982 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3983 OPTIONAL(lowerBound, MDSignedField, );
3985 #undef VISIT_MD_FIELDS
3987 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3991 /// ParseDIEnumerator:
3992 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3993 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3994 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3995 REQUIRED(name, MDStringField, ); \
3996 REQUIRED(value, MDSignedField, );
3998 #undef VISIT_MD_FIELDS
4000 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
4004 /// ParseDIBasicType:
4005 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
4006 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4007 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4008 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4009 OPTIONAL(name, MDStringField, ); \
4010 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4011 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4012 OPTIONAL(encoding, DwarfAttEncodingField, );
4014 #undef VISIT_MD_FIELDS
4016 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4017 align.Val, encoding.Val));
4021 /// ParseDIDerivedType:
4022 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4023 /// line: 7, scope: !1, baseType: !2, size: 32,
4024 /// align: 32, offset: 0, flags: 0, extraData: !3,
4025 /// dwarfAddressSpace: 3)
4026 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4027 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4028 REQUIRED(tag, DwarfTagField, ); \
4029 OPTIONAL(name, MDStringField, ); \
4030 OPTIONAL(file, MDField, ); \
4031 OPTIONAL(line, LineField, ); \
4032 OPTIONAL(scope, MDField, ); \
4033 REQUIRED(baseType, MDField, ); \
4034 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4035 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4036 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4037 OPTIONAL(flags, DIFlagField, ); \
4038 OPTIONAL(extraData, MDField, ); \
4039 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4041 #undef VISIT_MD_FIELDS
4043 Optional<unsigned> DWARFAddressSpace;
4044 if (dwarfAddressSpace.Val != UINT32_MAX)
4045 DWARFAddressSpace = dwarfAddressSpace.Val;
4047 Result = GET_OR_DISTINCT(DIDerivedType,
4048 (Context, tag.Val, name.Val, file.Val, line.Val,
4049 scope.Val, baseType.Val, size.Val, align.Val,
4050 offset.Val, DWARFAddressSpace, flags.Val,
4055 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4056 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4057 REQUIRED(tag, DwarfTagField, ); \
4058 OPTIONAL(name, MDStringField, ); \
4059 OPTIONAL(file, MDField, ); \
4060 OPTIONAL(line, LineField, ); \
4061 OPTIONAL(scope, MDField, ); \
4062 OPTIONAL(baseType, MDField, ); \
4063 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4064 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4065 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4066 OPTIONAL(flags, DIFlagField, ); \
4067 OPTIONAL(elements, MDField, ); \
4068 OPTIONAL(runtimeLang, DwarfLangField, ); \
4069 OPTIONAL(vtableHolder, MDField, ); \
4070 OPTIONAL(templateParams, MDField, ); \
4071 OPTIONAL(identifier, MDStringField, );
4073 #undef VISIT_MD_FIELDS
4075 // If this has an identifier try to build an ODR type.
4077 if (auto *CT = DICompositeType::buildODRType(
4078 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4079 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4080 elements.Val, runtimeLang.Val, vtableHolder.Val,
4081 templateParams.Val)) {
4086 // Create a new node, and save it in the context if it belongs in the type
4088 Result = GET_OR_DISTINCT(
4090 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4091 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4092 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4096 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4097 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4098 OPTIONAL(flags, DIFlagField, ); \
4099 OPTIONAL(cc, DwarfCCField, ); \
4100 REQUIRED(types, MDField, );
4102 #undef VISIT_MD_FIELDS
4104 Result = GET_OR_DISTINCT(DISubroutineType,
4105 (Context, flags.Val, cc.Val, types.Val));
4109 /// ParseDIFileType:
4110 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4111 /// checksumkind: CSK_MD5,
4112 /// checksum: "000102030405060708090a0b0c0d0e0f")
4113 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4114 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4115 REQUIRED(filename, MDStringField, ); \
4116 REQUIRED(directory, MDStringField, ); \
4117 OPTIONAL(checksumkind, ChecksumKindField, ); \
4118 OPTIONAL(checksum, MDStringField, );
4120 #undef VISIT_MD_FIELDS
4122 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4123 checksumkind.Val, checksum.Val));
4127 /// ParseDICompileUnit:
4128 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4129 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4130 /// splitDebugFilename: "abc.debug",
4131 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4132 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4133 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4135 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4137 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4138 REQUIRED(language, DwarfLangField, ); \
4139 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4140 OPTIONAL(producer, MDStringField, ); \
4141 OPTIONAL(isOptimized, MDBoolField, ); \
4142 OPTIONAL(flags, MDStringField, ); \
4143 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4144 OPTIONAL(splitDebugFilename, MDStringField, ); \
4145 OPTIONAL(emissionKind, EmissionKindField, ); \
4146 OPTIONAL(enums, MDField, ); \
4147 OPTIONAL(retainedTypes, MDField, ); \
4148 OPTIONAL(globals, MDField, ); \
4149 OPTIONAL(imports, MDField, ); \
4150 OPTIONAL(macros, MDField, ); \
4151 OPTIONAL(dwoId, MDUnsignedField, ); \
4152 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4153 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4154 OPTIONAL(gnuPubnames, MDBoolField, = false);
4156 #undef VISIT_MD_FIELDS
4158 Result = DICompileUnit::getDistinct(
4159 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4160 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4161 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4162 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
4166 /// ParseDISubprogram:
4167 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4168 /// file: !1, line: 7, type: !2, isLocal: false,
4169 /// isDefinition: true, scopeLine: 8, containingType: !3,
4170 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4171 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4172 /// isOptimized: false, templateParams: !4, declaration: !5,
4173 /// variables: !6, thrownTypes: !7)
4174 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4175 auto Loc = Lex.getLoc();
4176 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4177 OPTIONAL(scope, MDField, ); \
4178 OPTIONAL(name, MDStringField, ); \
4179 OPTIONAL(linkageName, MDStringField, ); \
4180 OPTIONAL(file, MDField, ); \
4181 OPTIONAL(line, LineField, ); \
4182 OPTIONAL(type, MDField, ); \
4183 OPTIONAL(isLocal, MDBoolField, ); \
4184 OPTIONAL(isDefinition, MDBoolField, (true)); \
4185 OPTIONAL(scopeLine, LineField, ); \
4186 OPTIONAL(containingType, MDField, ); \
4187 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4188 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4189 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4190 OPTIONAL(flags, DIFlagField, ); \
4191 OPTIONAL(isOptimized, MDBoolField, ); \
4192 OPTIONAL(unit, MDField, ); \
4193 OPTIONAL(templateParams, MDField, ); \
4194 OPTIONAL(declaration, MDField, ); \
4195 OPTIONAL(variables, MDField, ); \
4196 OPTIONAL(thrownTypes, MDField, );
4198 #undef VISIT_MD_FIELDS
4200 if (isDefinition.Val && !IsDistinct)
4203 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4205 Result = GET_OR_DISTINCT(
4207 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4208 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4209 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4210 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4211 declaration.Val, variables.Val, thrownTypes.Val));
4215 /// ParseDILexicalBlock:
4216 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4217 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4218 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4219 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4220 OPTIONAL(file, MDField, ); \
4221 OPTIONAL(line, LineField, ); \
4222 OPTIONAL(column, ColumnField, );
4224 #undef VISIT_MD_FIELDS
4226 Result = GET_OR_DISTINCT(
4227 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4231 /// ParseDILexicalBlockFile:
4232 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4233 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4234 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4235 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4236 OPTIONAL(file, MDField, ); \
4237 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4239 #undef VISIT_MD_FIELDS
4241 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4242 (Context, scope.Val, file.Val, discriminator.Val));
4246 /// ParseDINamespace:
4247 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4248 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4249 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4250 REQUIRED(scope, MDField, ); \
4251 OPTIONAL(name, MDStringField, ); \
4252 OPTIONAL(exportSymbols, MDBoolField, );
4254 #undef VISIT_MD_FIELDS
4256 Result = GET_OR_DISTINCT(DINamespace,
4257 (Context, scope.Val, name.Val, exportSymbols.Val));
4262 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4263 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4264 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4265 REQUIRED(type, DwarfMacinfoTypeField, ); \
4266 OPTIONAL(line, LineField, ); \
4267 REQUIRED(name, MDStringField, ); \
4268 OPTIONAL(value, MDStringField, );
4270 #undef VISIT_MD_FIELDS
4272 Result = GET_OR_DISTINCT(DIMacro,
4273 (Context, type.Val, line.Val, name.Val, value.Val));
4277 /// ParseDIMacroFile:
4278 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4279 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4280 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4281 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4282 OPTIONAL(line, LineField, ); \
4283 REQUIRED(file, MDField, ); \
4284 OPTIONAL(nodes, MDField, );
4286 #undef VISIT_MD_FIELDS
4288 Result = GET_OR_DISTINCT(DIMacroFile,
4289 (Context, type.Val, line.Val, file.Val, nodes.Val));
4294 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4295 /// includePath: "/usr/include", isysroot: "/")
4296 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4297 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4298 REQUIRED(scope, MDField, ); \
4299 REQUIRED(name, MDStringField, ); \
4300 OPTIONAL(configMacros, MDStringField, ); \
4301 OPTIONAL(includePath, MDStringField, ); \
4302 OPTIONAL(isysroot, MDStringField, );
4304 #undef VISIT_MD_FIELDS
4306 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4307 configMacros.Val, includePath.Val, isysroot.Val));
4311 /// ParseDITemplateTypeParameter:
4312 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4313 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4314 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4315 OPTIONAL(name, MDStringField, ); \
4316 REQUIRED(type, MDField, );
4318 #undef VISIT_MD_FIELDS
4321 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4325 /// ParseDITemplateValueParameter:
4326 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4327 /// name: "V", type: !1, value: i32 7)
4328 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4329 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4330 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4331 OPTIONAL(name, MDStringField, ); \
4332 OPTIONAL(type, MDField, ); \
4333 REQUIRED(value, MDField, );
4335 #undef VISIT_MD_FIELDS
4337 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4338 (Context, tag.Val, name.Val, type.Val, value.Val));
4342 /// ParseDIGlobalVariable:
4343 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4344 /// file: !1, line: 7, type: !2, isLocal: false,
4345 /// isDefinition: true, declaration: !3, align: 8)
4346 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4347 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4348 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4349 OPTIONAL(scope, MDField, ); \
4350 OPTIONAL(linkageName, MDStringField, ); \
4351 OPTIONAL(file, MDField, ); \
4352 OPTIONAL(line, LineField, ); \
4353 OPTIONAL(type, MDField, ); \
4354 OPTIONAL(isLocal, MDBoolField, ); \
4355 OPTIONAL(isDefinition, MDBoolField, (true)); \
4356 OPTIONAL(declaration, MDField, ); \
4357 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4359 #undef VISIT_MD_FIELDS
4361 Result = GET_OR_DISTINCT(DIGlobalVariable,
4362 (Context, scope.Val, name.Val, linkageName.Val,
4363 file.Val, line.Val, type.Val, isLocal.Val,
4364 isDefinition.Val, declaration.Val, align.Val));
4368 /// ParseDILocalVariable:
4369 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4370 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4372 /// ::= !DILocalVariable(scope: !0, name: "foo",
4373 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4375 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4376 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4377 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4378 OPTIONAL(name, MDStringField, ); \
4379 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4380 OPTIONAL(file, MDField, ); \
4381 OPTIONAL(line, LineField, ); \
4382 OPTIONAL(type, MDField, ); \
4383 OPTIONAL(flags, DIFlagField, ); \
4384 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4386 #undef VISIT_MD_FIELDS
4388 Result = GET_OR_DISTINCT(DILocalVariable,
4389 (Context, scope.Val, name.Val, file.Val, line.Val,
4390 type.Val, arg.Val, flags.Val, align.Val));
4394 /// ParseDIExpression:
4395 /// ::= !DIExpression(0, 7, -1)
4396 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4397 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4400 if (ParseToken(lltok::lparen, "expected '(' here"))
4403 SmallVector<uint64_t, 8> Elements;
4404 if (Lex.getKind() != lltok::rparen)
4406 if (Lex.getKind() == lltok::DwarfOp) {
4407 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4409 Elements.push_back(Op);
4412 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4415 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4416 return TokError("expected unsigned integer");
4418 auto &U = Lex.getAPSIntVal();
4419 if (U.ugt(UINT64_MAX))
4420 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4421 Elements.push_back(U.getZExtValue());
4423 } while (EatIfPresent(lltok::comma));
4425 if (ParseToken(lltok::rparen, "expected ')' here"))
4428 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4432 /// ParseDIGlobalVariableExpression:
4433 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4434 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4436 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4437 REQUIRED(var, MDField, ); \
4438 REQUIRED(expr, MDField, );
4440 #undef VISIT_MD_FIELDS
4443 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4447 /// ParseDIObjCProperty:
4448 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4449 /// getter: "getFoo", attributes: 7, type: !2)
4450 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4451 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4452 OPTIONAL(name, MDStringField, ); \
4453 OPTIONAL(file, MDField, ); \
4454 OPTIONAL(line, LineField, ); \
4455 OPTIONAL(setter, MDStringField, ); \
4456 OPTIONAL(getter, MDStringField, ); \
4457 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4458 OPTIONAL(type, MDField, );
4460 #undef VISIT_MD_FIELDS
4462 Result = GET_OR_DISTINCT(DIObjCProperty,
4463 (Context, name.Val, file.Val, line.Val, setter.Val,
4464 getter.Val, attributes.Val, type.Val));
4468 /// ParseDIImportedEntity:
4469 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4470 /// line: 7, name: "foo")
4471 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4472 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4473 REQUIRED(tag, DwarfTagField, ); \
4474 REQUIRED(scope, MDField, ); \
4475 OPTIONAL(entity, MDField, ); \
4476 OPTIONAL(file, MDField, ); \
4477 OPTIONAL(line, LineField, ); \
4478 OPTIONAL(name, MDStringField, );
4480 #undef VISIT_MD_FIELDS
4482 Result = GET_OR_DISTINCT(
4484 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
4488 #undef PARSE_MD_FIELD
4490 #undef REQUIRE_FIELD
4491 #undef DECLARE_FIELD
4493 /// ParseMetadataAsValue
4494 /// ::= metadata i32 %local
4495 /// ::= metadata i32 @global
4496 /// ::= metadata i32 7
4498 /// ::= metadata !{...}
4499 /// ::= metadata !"string"
4500 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4501 // Note: the type 'metadata' has already been parsed.
4503 if (ParseMetadata(MD, &PFS))
4506 V = MetadataAsValue::get(Context, MD);
4510 /// ParseValueAsMetadata
4514 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4515 PerFunctionState *PFS) {
4518 if (ParseType(Ty, TypeMsg, Loc))
4520 if (Ty->isMetadataTy())
4521 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4524 if (ParseValue(Ty, V, PFS))
4527 MD = ValueAsMetadata::get(V);
4538 /// ::= !DILocation(...)
4539 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4540 if (Lex.getKind() == lltok::MetadataVar) {
4542 if (ParseSpecializedMDNode(N))
4550 if (Lex.getKind() != lltok::exclaim)
4551 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4554 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4558 // ::= '!' STRINGCONSTANT
4559 if (Lex.getKind() == lltok::StringConstant) {
4561 if (ParseMDString(S))
4571 if (ParseMDNodeTail(N))
4577 //===----------------------------------------------------------------------===//
4578 // Function Parsing.
4579 //===----------------------------------------------------------------------===//
4581 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4582 PerFunctionState *PFS) {
4583 if (Ty->isFunctionTy())
4584 return Error(ID.Loc, "functions are not values, refer to them as pointers");
4587 case ValID::t_LocalID:
4588 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4589 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4590 return V == nullptr;
4591 case ValID::t_LocalName:
4592 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4593 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4594 return V == nullptr;
4595 case ValID::t_InlineAsm: {
4596 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4597 return Error(ID.Loc, "invalid type for inline asm constraint string");
4598 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4599 (ID.UIntVal >> 1) & 1,
4600 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4603 case ValID::t_GlobalName:
4604 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4605 return V == nullptr;
4606 case ValID::t_GlobalID:
4607 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4608 return V == nullptr;
4609 case ValID::t_APSInt:
4610 if (!Ty->isIntegerTy())
4611 return Error(ID.Loc, "integer constant must have integer type");
4612 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4613 V = ConstantInt::get(Context, ID.APSIntVal);
4615 case ValID::t_APFloat:
4616 if (!Ty->isFloatingPointTy() ||
4617 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4618 return Error(ID.Loc, "floating point constant invalid for type");
4620 // The lexer has no type info, so builds all half, float, and double FP
4621 // constants as double. Fix this here. Long double does not need this.
4622 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
4625 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
4627 else if (Ty->isFloatTy())
4628 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
4631 V = ConstantFP::get(Context, ID.APFloatVal);
4633 if (V->getType() != Ty)
4634 return Error(ID.Loc, "floating point constant does not have type '" +
4635 getTypeString(Ty) + "'");
4639 if (!Ty->isPointerTy())
4640 return Error(ID.Loc, "null must be a pointer type");
4641 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4643 case ValID::t_Undef:
4644 // FIXME: LabelTy should not be a first-class type.
4645 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4646 return Error(ID.Loc, "invalid type for undef constant");
4647 V = UndefValue::get(Ty);
4649 case ValID::t_EmptyArray:
4650 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4651 return Error(ID.Loc, "invalid empty array initializer");
4652 V = UndefValue::get(Ty);
4655 // FIXME: LabelTy should not be a first-class type.
4656 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4657 return Error(ID.Loc, "invalid type for null constant");
4658 V = Constant::getNullValue(Ty);
4661 if (!Ty->isTokenTy())
4662 return Error(ID.Loc, "invalid type for none constant");
4663 V = Constant::getNullValue(Ty);
4665 case ValID::t_Constant:
4666 if (ID.ConstantVal->getType() != Ty)
4667 return Error(ID.Loc, "constant expression type mismatch");
4671 case ValID::t_ConstantStruct:
4672 case ValID::t_PackedConstantStruct:
4673 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4674 if (ST->getNumElements() != ID.UIntVal)
4675 return Error(ID.Loc,
4676 "initializer with struct type has wrong # elements");
4677 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4678 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4680 // Verify that the elements are compatible with the structtype.
4681 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4682 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4683 return Error(ID.Loc, "element " + Twine(i) +
4684 " of struct initializer doesn't match struct element type");
4686 V = ConstantStruct::get(
4687 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4689 return Error(ID.Loc, "constant expression type mismatch");
4692 llvm_unreachable("Invalid ValID");
4695 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4698 auto Loc = Lex.getLoc();
4699 if (ParseValID(ID, /*PFS=*/nullptr))
4702 case ValID::t_APSInt:
4703 case ValID::t_APFloat:
4704 case ValID::t_Undef:
4705 case ValID::t_Constant:
4706 case ValID::t_ConstantStruct:
4707 case ValID::t_PackedConstantStruct: {
4709 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4711 assert(isa<Constant>(V) && "Expected a constant value");
4712 C = cast<Constant>(V);
4716 C = Constant::getNullValue(Ty);
4719 return Error(Loc, "expected a constant value");
4723 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4726 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4729 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4731 return ParseType(Ty) ||
4732 ParseValue(Ty, V, PFS);
4735 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4736 PerFunctionState &PFS) {
4739 if (ParseTypeAndValue(V, PFS)) return true;
4740 if (!isa<BasicBlock>(V))
4741 return Error(Loc, "expected a basic block");
4742 BB = cast<BasicBlock>(V);
4747 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
4748 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
4749 /// '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
4750 /// OptionalPrefix OptionalPrologue OptPersonalityFn
4751 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4752 // Parse the linkage.
4753 LocTy LinkageLoc = Lex.getLoc();
4755 unsigned Visibility;
4756 unsigned DLLStorageClass;
4758 AttrBuilder RetAttrs;
4761 Type *RetType = nullptr;
4762 LocTy RetTypeLoc = Lex.getLoc();
4763 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
4765 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4766 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4769 // Verify that the linkage is ok.
4770 switch ((GlobalValue::LinkageTypes)Linkage) {
4771 case GlobalValue::ExternalLinkage:
4772 break; // always ok.
4773 case GlobalValue::ExternalWeakLinkage:
4775 return Error(LinkageLoc, "invalid linkage for function definition");
4777 case GlobalValue::PrivateLinkage:
4778 case GlobalValue::InternalLinkage:
4779 case GlobalValue::AvailableExternallyLinkage:
4780 case GlobalValue::LinkOnceAnyLinkage:
4781 case GlobalValue::LinkOnceODRLinkage:
4782 case GlobalValue::WeakAnyLinkage:
4783 case GlobalValue::WeakODRLinkage:
4785 return Error(LinkageLoc, "invalid linkage for function declaration");
4787 case GlobalValue::AppendingLinkage:
4788 case GlobalValue::CommonLinkage:
4789 return Error(LinkageLoc, "invalid function linkage type");
4792 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4793 return Error(LinkageLoc,
4794 "symbol with local linkage must have default visibility");
4796 if (!FunctionType::isValidReturnType(RetType))
4797 return Error(RetTypeLoc, "invalid function return type");
4799 LocTy NameLoc = Lex.getLoc();
4801 std::string FunctionName;
4802 if (Lex.getKind() == lltok::GlobalVar) {
4803 FunctionName = Lex.getStrVal();
4804 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4805 unsigned NameID = Lex.getUIntVal();
4807 if (NameID != NumberedVals.size())
4808 return TokError("function expected to be numbered '%" +
4809 Twine(NumberedVals.size()) + "'");
4811 return TokError("expected function name");
4816 if (Lex.getKind() != lltok::lparen)
4817 return TokError("expected '(' in function argument list");
4819 SmallVector<ArgInfo, 8> ArgList;
4821 AttrBuilder FuncAttrs;
4822 std::vector<unsigned> FwdRefAttrGrps;
4824 std::string Section;
4827 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4828 Constant *Prefix = nullptr;
4829 Constant *Prologue = nullptr;
4830 Constant *PersonalityFn = nullptr;
4833 if (ParseArgumentList(ArgList, isVarArg) ||
4834 ParseOptionalUnnamedAddr(UnnamedAddr) ||
4835 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4837 (EatIfPresent(lltok::kw_section) &&
4838 ParseStringConstant(Section)) ||
4839 parseOptionalComdat(FunctionName, C) ||
4840 ParseOptionalAlignment(Alignment) ||
4841 (EatIfPresent(lltok::kw_gc) &&
4842 ParseStringConstant(GC)) ||
4843 (EatIfPresent(lltok::kw_prefix) &&
4844 ParseGlobalTypeAndValue(Prefix)) ||
4845 (EatIfPresent(lltok::kw_prologue) &&
4846 ParseGlobalTypeAndValue(Prologue)) ||
4847 (EatIfPresent(lltok::kw_personality) &&
4848 ParseGlobalTypeAndValue(PersonalityFn)))
4851 if (FuncAttrs.contains(Attribute::Builtin))
4852 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4854 // If the alignment was parsed as an attribute, move to the alignment field.
4855 if (FuncAttrs.hasAlignmentAttr()) {
4856 Alignment = FuncAttrs.getAlignment();
4857 FuncAttrs.removeAttribute(Attribute::Alignment);
4860 // Okay, if we got here, the function is syntactically valid. Convert types
4861 // and do semantic checks.
4862 std::vector<Type*> ParamTypeList;
4863 SmallVector<AttributeSet, 8> Attrs;
4865 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4866 ParamTypeList.push_back(ArgList[i].Ty);
4867 Attrs.push_back(ArgList[i].Attrs);
4871 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4872 AttributeSet::get(Context, RetAttrs), Attrs);
4874 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4875 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4878 FunctionType::get(RetType, ParamTypeList, isVarArg);
4879 PointerType *PFT = PointerType::getUnqual(FT);
4882 if (!FunctionName.empty()) {
4883 // If this was a definition of a forward reference, remove the definition
4884 // from the forward reference table and fill in the forward ref.
4885 auto FRVI = ForwardRefVals.find(FunctionName);
4886 if (FRVI != ForwardRefVals.end()) {
4887 Fn = M->getFunction(FunctionName);
4889 return Error(FRVI->second.second, "invalid forward reference to "
4890 "function as global value!");
4891 if (Fn->getType() != PFT)
4892 return Error(FRVI->second.second, "invalid forward reference to "
4893 "function '" + FunctionName + "' with wrong type!");
4895 ForwardRefVals.erase(FRVI);
4896 } else if ((Fn = M->getFunction(FunctionName))) {
4897 // Reject redefinitions.
4898 return Error(NameLoc, "invalid redefinition of function '" +
4899 FunctionName + "'");
4900 } else if (M->getNamedValue(FunctionName)) {
4901 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4905 // If this is a definition of a forward referenced function, make sure the
4907 auto I = ForwardRefValIDs.find(NumberedVals.size());
4908 if (I != ForwardRefValIDs.end()) {
4909 Fn = cast<Function>(I->second.first);
4910 if (Fn->getType() != PFT)
4911 return Error(NameLoc, "type of definition and forward reference of '@" +
4912 Twine(NumberedVals.size()) + "' disagree");
4913 ForwardRefValIDs.erase(I);
4918 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4919 else // Move the forward-reference to the correct spot in the module.
4920 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4922 if (FunctionName.empty())
4923 NumberedVals.push_back(Fn);
4925 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4926 Fn->setDSOLocal(DSOLocal);
4927 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4928 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4929 Fn->setCallingConv(CC);
4930 Fn->setAttributes(PAL);
4931 Fn->setUnnamedAddr(UnnamedAddr);
4932 Fn->setAlignment(Alignment);
4933 Fn->setSection(Section);
4935 Fn->setPersonalityFn(PersonalityFn);
4936 if (!GC.empty()) Fn->setGC(GC);
4937 Fn->setPrefixData(Prefix);
4938 Fn->setPrologueData(Prologue);
4939 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4941 // Add all of the arguments we parsed to the function.
4942 Function::arg_iterator ArgIt = Fn->arg_begin();
4943 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4944 // If the argument has a name, insert it into the argument symbol table.
4945 if (ArgList[i].Name.empty()) continue;
4947 // Set the name, if it conflicted, it will be auto-renamed.
4948 ArgIt->setName(ArgList[i].Name);
4950 if (ArgIt->getName() != ArgList[i].Name)
4951 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4952 ArgList[i].Name + "'");
4958 // Check the declaration has no block address forward references.
4960 if (FunctionName.empty()) {
4961 ID.Kind = ValID::t_GlobalID;
4962 ID.UIntVal = NumberedVals.size() - 1;
4964 ID.Kind = ValID::t_GlobalName;
4965 ID.StrVal = FunctionName;
4967 auto Blocks = ForwardRefBlockAddresses.find(ID);
4968 if (Blocks != ForwardRefBlockAddresses.end())
4969 return Error(Blocks->first.Loc,
4970 "cannot take blockaddress inside a declaration");
4974 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4976 if (FunctionNumber == -1) {
4977 ID.Kind = ValID::t_GlobalName;
4978 ID.StrVal = F.getName();
4980 ID.Kind = ValID::t_GlobalID;
4981 ID.UIntVal = FunctionNumber;
4984 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4985 if (Blocks == P.ForwardRefBlockAddresses.end())
4988 for (const auto &I : Blocks->second) {
4989 const ValID &BBID = I.first;
4990 GlobalValue *GV = I.second;
4992 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4993 "Expected local id or name");
4995 if (BBID.Kind == ValID::t_LocalName)
4996 BB = GetBB(BBID.StrVal, BBID.Loc);
4998 BB = GetBB(BBID.UIntVal, BBID.Loc);
5000 return P.Error(BBID.Loc, "referenced value is not a basic block");
5002 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5003 GV->eraseFromParent();
5006 P.ForwardRefBlockAddresses.erase(Blocks);
5010 /// ParseFunctionBody
5011 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5012 bool LLParser::ParseFunctionBody(Function &Fn) {
5013 if (Lex.getKind() != lltok::lbrace)
5014 return TokError("expected '{' in function body");
5015 Lex.Lex(); // eat the {.
5017 int FunctionNumber = -1;
5018 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5020 PerFunctionState PFS(*this, Fn, FunctionNumber);
5022 // Resolve block addresses and allow basic blocks to be forward-declared
5023 // within this function.
5024 if (PFS.resolveForwardRefBlockAddresses())
5026 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5028 // We need at least one basic block.
5029 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5030 return TokError("function body requires at least one basic block");
5032 while (Lex.getKind() != lltok::rbrace &&
5033 Lex.getKind() != lltok::kw_uselistorder)
5034 if (ParseBasicBlock(PFS)) return true;
5036 while (Lex.getKind() != lltok::rbrace)
5037 if (ParseUseListOrder(&PFS))
5043 // Verify function is ok.
5044 return PFS.FinishFunction();
5048 /// ::= LabelStr? Instruction*
5049 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5050 // If this basic block starts out with a name, remember it.
5052 LocTy NameLoc = Lex.getLoc();
5053 if (Lex.getKind() == lltok::LabelStr) {
5054 Name = Lex.getStrVal();
5058 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
5060 return Error(NameLoc,
5061 "unable to create block named '" + Name + "'");
5063 std::string NameStr;
5065 // Parse the instructions in this block until we get a terminator.
5068 // This instruction may have three possibilities for a name: a) none
5069 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5070 LocTy NameLoc = Lex.getLoc();
5074 if (Lex.getKind() == lltok::LocalVarID) {
5075 NameID = Lex.getUIntVal();
5077 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5079 } else if (Lex.getKind() == lltok::LocalVar) {
5080 NameStr = Lex.getStrVal();
5082 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5086 switch (ParseInstruction(Inst, BB, PFS)) {
5087 default: llvm_unreachable("Unknown ParseInstruction result!");
5088 case InstError: return true;
5090 BB->getInstList().push_back(Inst);
5092 // With a normal result, we check to see if the instruction is followed by
5093 // a comma and metadata.
5094 if (EatIfPresent(lltok::comma))
5095 if (ParseInstructionMetadata(*Inst))
5098 case InstExtraComma:
5099 BB->getInstList().push_back(Inst);
5101 // If the instruction parser ate an extra comma at the end of it, it
5102 // *must* be followed by metadata.
5103 if (ParseInstructionMetadata(*Inst))
5108 // Set the name on the instruction.
5109 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5110 } while (!isa<TerminatorInst>(Inst));
5115 //===----------------------------------------------------------------------===//
5116 // Instruction Parsing.
5117 //===----------------------------------------------------------------------===//
5119 /// ParseInstruction - Parse one of the many different instructions.
5121 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5122 PerFunctionState &PFS) {
5123 lltok::Kind Token = Lex.getKind();
5124 if (Token == lltok::Eof)
5125 return TokError("found end of file when expecting more instructions");
5126 LocTy Loc = Lex.getLoc();
5127 unsigned KeywordVal = Lex.getUIntVal();
5128 Lex.Lex(); // Eat the keyword.
5131 default: return Error(Loc, "expected instruction opcode");
5132 // Terminator Instructions.
5133 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5134 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5135 case lltok::kw_br: return ParseBr(Inst, PFS);
5136 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5137 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5138 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5139 case lltok::kw_resume: return ParseResume(Inst, PFS);
5140 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5141 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5142 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5143 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5144 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5145 // Binary Operators.
5149 case lltok::kw_shl: {
5150 bool NUW = EatIfPresent(lltok::kw_nuw);
5151 bool NSW = EatIfPresent(lltok::kw_nsw);
5152 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5154 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5156 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5157 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5160 case lltok::kw_fadd:
5161 case lltok::kw_fsub:
5162 case lltok::kw_fmul:
5163 case lltok::kw_fdiv:
5164 case lltok::kw_frem: {
5165 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5166 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5170 Inst->setFastMathFlags(FMF);
5174 case lltok::kw_sdiv:
5175 case lltok::kw_udiv:
5176 case lltok::kw_lshr:
5177 case lltok::kw_ashr: {
5178 bool Exact = EatIfPresent(lltok::kw_exact);
5180 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5181 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5185 case lltok::kw_urem:
5186 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5189 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5190 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5191 case lltok::kw_fcmp: {
5192 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5193 int Res = ParseCompare(Inst, PFS, KeywordVal);
5197 Inst->setFastMathFlags(FMF);
5202 case lltok::kw_trunc:
5203 case lltok::kw_zext:
5204 case lltok::kw_sext:
5205 case lltok::kw_fptrunc:
5206 case lltok::kw_fpext:
5207 case lltok::kw_bitcast:
5208 case lltok::kw_addrspacecast:
5209 case lltok::kw_uitofp:
5210 case lltok::kw_sitofp:
5211 case lltok::kw_fptoui:
5212 case lltok::kw_fptosi:
5213 case lltok::kw_inttoptr:
5214 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5216 case lltok::kw_select: return ParseSelect(Inst, PFS);
5217 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5218 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5219 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5220 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5221 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5222 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5224 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5225 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5226 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5227 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5229 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5230 case lltok::kw_load: return ParseLoad(Inst, PFS);
5231 case lltok::kw_store: return ParseStore(Inst, PFS);
5232 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5233 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5234 case lltok::kw_fence: return ParseFence(Inst, PFS);
5235 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5236 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5237 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5241 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5242 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5243 if (Opc == Instruction::FCmp) {
5244 switch (Lex.getKind()) {
5245 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5246 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5247 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5248 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5249 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5250 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5251 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5252 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5253 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5254 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5255 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5256 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5257 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5258 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5259 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5260 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5261 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5264 switch (Lex.getKind()) {
5265 default: return TokError("expected icmp predicate (e.g. 'eq')");
5266 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5267 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5268 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5269 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5270 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5271 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5272 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5273 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5274 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5275 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5282 //===----------------------------------------------------------------------===//
5283 // Terminator Instructions.
5284 //===----------------------------------------------------------------------===//
5286 /// ParseRet - Parse a return instruction.
5287 /// ::= 'ret' void (',' !dbg, !1)*
5288 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5289 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5290 PerFunctionState &PFS) {
5291 SMLoc TypeLoc = Lex.getLoc();
5293 if (ParseType(Ty, true /*void allowed*/)) return true;
5295 Type *ResType = PFS.getFunction().getReturnType();
5297 if (Ty->isVoidTy()) {
5298 if (!ResType->isVoidTy())
5299 return Error(TypeLoc, "value doesn't match function result type '" +
5300 getTypeString(ResType) + "'");
5302 Inst = ReturnInst::Create(Context);
5307 if (ParseValue(Ty, RV, PFS)) return true;
5309 if (ResType != RV->getType())
5310 return Error(TypeLoc, "value doesn't match function result type '" +
5311 getTypeString(ResType) + "'");
5313 Inst = ReturnInst::Create(Context, RV);
5318 /// ::= 'br' TypeAndValue
5319 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5320 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5323 BasicBlock *Op1, *Op2;
5324 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5326 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5327 Inst = BranchInst::Create(BB);
5331 if (Op0->getType() != Type::getInt1Ty(Context))
5332 return Error(Loc, "branch condition must have 'i1' type");
5334 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5335 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5336 ParseToken(lltok::comma, "expected ',' after true destination") ||
5337 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5340 Inst = BranchInst::Create(Op1, Op2, Op0);
5346 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5348 /// ::= (TypeAndValue ',' TypeAndValue)*
5349 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5350 LocTy CondLoc, BBLoc;
5352 BasicBlock *DefaultBB;
5353 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5354 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5355 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5356 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5359 if (!Cond->getType()->isIntegerTy())
5360 return Error(CondLoc, "switch condition must have integer type");
5362 // Parse the jump table pairs.
5363 SmallPtrSet<Value*, 32> SeenCases;
5364 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5365 while (Lex.getKind() != lltok::rsquare) {
5369 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5370 ParseToken(lltok::comma, "expected ',' after case value") ||
5371 ParseTypeAndBasicBlock(DestBB, PFS))
5374 if (!SeenCases.insert(Constant).second)
5375 return Error(CondLoc, "duplicate case value in switch");
5376 if (!isa<ConstantInt>(Constant))
5377 return Error(CondLoc, "case value is not a constant integer");
5379 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5382 Lex.Lex(); // Eat the ']'.
5384 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5385 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5386 SI->addCase(Table[i].first, Table[i].second);
5393 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5394 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5397 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5398 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5399 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5402 if (!Address->getType()->isPointerTy())
5403 return Error(AddrLoc, "indirectbr address must have pointer type");
5405 // Parse the destination list.
5406 SmallVector<BasicBlock*, 16> DestList;
5408 if (Lex.getKind() != lltok::rsquare) {
5410 if (ParseTypeAndBasicBlock(DestBB, PFS))
5412 DestList.push_back(DestBB);
5414 while (EatIfPresent(lltok::comma)) {
5415 if (ParseTypeAndBasicBlock(DestBB, PFS))
5417 DestList.push_back(DestBB);
5421 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5424 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5425 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5426 IBI->addDestination(DestList[i]);
5432 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5433 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5434 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5435 LocTy CallLoc = Lex.getLoc();
5436 AttrBuilder RetAttrs, FnAttrs;
5437 std::vector<unsigned> FwdRefAttrGrps;
5440 Type *RetType = nullptr;
5443 SmallVector<ParamInfo, 16> ArgList;
5444 SmallVector<OperandBundleDef, 2> BundleList;
5446 BasicBlock *NormalBB, *UnwindBB;
5447 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5448 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5449 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5450 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5452 ParseOptionalOperandBundles(BundleList, PFS) ||
5453 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5454 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5455 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5456 ParseTypeAndBasicBlock(UnwindBB, PFS))
5459 // If RetType is a non-function pointer type, then this is the short syntax
5460 // for the call, which means that RetType is just the return type. Infer the
5461 // rest of the function argument types from the arguments that are present.
5462 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5464 // Pull out the types of all of the arguments...
5465 std::vector<Type*> ParamTypes;
5466 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5467 ParamTypes.push_back(ArgList[i].V->getType());
5469 if (!FunctionType::isValidReturnType(RetType))
5470 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5472 Ty = FunctionType::get(RetType, ParamTypes, false);
5477 // Look up the callee.
5479 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5482 // Set up the Attribute for the function.
5483 SmallVector<Value *, 8> Args;
5484 SmallVector<AttributeSet, 8> ArgAttrs;
5486 // Loop through FunctionType's arguments and ensure they are specified
5487 // correctly. Also, gather any parameter attributes.
5488 FunctionType::param_iterator I = Ty->param_begin();
5489 FunctionType::param_iterator E = Ty->param_end();
5490 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5491 Type *ExpectedTy = nullptr;
5494 } else if (!Ty->isVarArg()) {
5495 return Error(ArgList[i].Loc, "too many arguments specified");
5498 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5499 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5500 getTypeString(ExpectedTy) + "'");
5501 Args.push_back(ArgList[i].V);
5502 ArgAttrs.push_back(ArgList[i].Attrs);
5506 return Error(CallLoc, "not enough parameters specified for call");
5508 if (FnAttrs.hasAlignmentAttr())
5509 return Error(CallLoc, "invoke instructions may not have an alignment");
5511 // Finish off the Attribute and check them
5513 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5514 AttributeSet::get(Context, RetAttrs), ArgAttrs);
5517 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5518 II->setCallingConv(CC);
5519 II->setAttributes(PAL);
5520 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5526 /// ::= 'resume' TypeAndValue
5527 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5528 Value *Exn; LocTy ExnLoc;
5529 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5532 ResumeInst *RI = ResumeInst::Create(Exn);
5537 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5538 PerFunctionState &PFS) {
5539 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5542 while (Lex.getKind() != lltok::rsquare) {
5543 // If this isn't the first argument, we need a comma.
5544 if (!Args.empty() &&
5545 ParseToken(lltok::comma, "expected ',' in argument list"))
5548 // Parse the argument.
5550 Type *ArgTy = nullptr;
5551 if (ParseType(ArgTy, ArgLoc))
5555 if (ArgTy->isMetadataTy()) {
5556 if (ParseMetadataAsValue(V, PFS))
5559 if (ParseValue(ArgTy, V, PFS))
5565 Lex.Lex(); // Lex the ']'.
5570 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5571 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5572 Value *CleanupPad = nullptr;
5574 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5577 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5580 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5583 BasicBlock *UnwindBB = nullptr;
5584 if (Lex.getKind() == lltok::kw_to) {
5586 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5589 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5594 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5599 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
5600 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5601 Value *CatchPad = nullptr;
5603 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5606 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5610 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5611 ParseTypeAndBasicBlock(BB, PFS))
5614 Inst = CatchReturnInst::Create(CatchPad, BB);
5618 /// ParseCatchSwitch
5619 /// ::= 'catchswitch' within Parent
5620 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5623 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5626 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5627 Lex.getKind() != lltok::LocalVarID)
5628 return TokError("expected scope value for catchswitch");
5630 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5633 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5636 SmallVector<BasicBlock *, 32> Table;
5639 if (ParseTypeAndBasicBlock(DestBB, PFS))
5641 Table.push_back(DestBB);
5642 } while (EatIfPresent(lltok::comma));
5644 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5647 if (ParseToken(lltok::kw_unwind,
5648 "expected 'unwind' after catchswitch scope"))
5651 BasicBlock *UnwindBB = nullptr;
5652 if (EatIfPresent(lltok::kw_to)) {
5653 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5656 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5661 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5662 for (BasicBlock *DestBB : Table)
5663 CatchSwitch->addHandler(DestBB);
5669 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5670 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5671 Value *CatchSwitch = nullptr;
5673 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5676 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5677 return TokError("expected scope value for catchpad");
5679 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5682 SmallVector<Value *, 8> Args;
5683 if (ParseExceptionArgs(Args, PFS))
5686 Inst = CatchPadInst::Create(CatchSwitch, Args);
5691 /// ::= 'cleanuppad' within Parent ParamList
5692 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5693 Value *ParentPad = nullptr;
5695 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5698 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5699 Lex.getKind() != lltok::LocalVarID)
5700 return TokError("expected scope value for cleanuppad");
5702 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5705 SmallVector<Value *, 8> Args;
5706 if (ParseExceptionArgs(Args, PFS))
5709 Inst = CleanupPadInst::Create(ParentPad, Args);
5713 //===----------------------------------------------------------------------===//
5714 // Binary Operators.
5715 //===----------------------------------------------------------------------===//
5718 /// ::= ArithmeticOps TypeAndValue ',' Value
5720 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5721 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5722 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5723 unsigned Opc, unsigned OperandType) {
5724 LocTy Loc; Value *LHS, *RHS;
5725 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5726 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5727 ParseValue(LHS->getType(), RHS, PFS))
5731 switch (OperandType) {
5732 default: llvm_unreachable("Unknown operand type!");
5733 case 0: // int or FP.
5734 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5735 LHS->getType()->isFPOrFPVectorTy();
5737 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5738 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5742 return Error(Loc, "invalid operand type for instruction");
5744 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5749 /// ::= ArithmeticOps TypeAndValue ',' Value {
5750 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5752 LocTy Loc; Value *LHS, *RHS;
5753 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5754 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5755 ParseValue(LHS->getType(), RHS, PFS))
5758 if (!LHS->getType()->isIntOrIntVectorTy())
5759 return Error(Loc,"instruction requires integer or integer vector operands");
5761 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5766 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5767 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5768 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5770 // Parse the integer/fp comparison predicate.
5774 if (ParseCmpPredicate(Pred, Opc) ||
5775 ParseTypeAndValue(LHS, Loc, PFS) ||
5776 ParseToken(lltok::comma, "expected ',' after compare value") ||
5777 ParseValue(LHS->getType(), RHS, PFS))
5780 if (Opc == Instruction::FCmp) {
5781 if (!LHS->getType()->isFPOrFPVectorTy())
5782 return Error(Loc, "fcmp requires floating point operands");
5783 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5785 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5786 if (!LHS->getType()->isIntOrIntVectorTy() &&
5787 !LHS->getType()->isPtrOrPtrVectorTy())
5788 return Error(Loc, "icmp requires integer operands");
5789 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5794 //===----------------------------------------------------------------------===//
5795 // Other Instructions.
5796 //===----------------------------------------------------------------------===//
5800 /// ::= CastOpc TypeAndValue 'to' Type
5801 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5805 Type *DestTy = nullptr;
5806 if (ParseTypeAndValue(Op, Loc, PFS) ||
5807 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5811 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5812 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5813 return Error(Loc, "invalid cast opcode for cast from '" +
5814 getTypeString(Op->getType()) + "' to '" +
5815 getTypeString(DestTy) + "'");
5817 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5822 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5823 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5825 Value *Op0, *Op1, *Op2;
5826 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5827 ParseToken(lltok::comma, "expected ',' after select condition") ||
5828 ParseTypeAndValue(Op1, PFS) ||
5829 ParseToken(lltok::comma, "expected ',' after select value") ||
5830 ParseTypeAndValue(Op2, PFS))
5833 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5834 return Error(Loc, Reason);
5836 Inst = SelectInst::Create(Op0, Op1, Op2);
5841 /// ::= 'va_arg' TypeAndValue ',' Type
5842 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5844 Type *EltTy = nullptr;
5846 if (ParseTypeAndValue(Op, PFS) ||
5847 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5848 ParseType(EltTy, TypeLoc))
5851 if (!EltTy->isFirstClassType())
5852 return Error(TypeLoc, "va_arg requires operand with first class type");
5854 Inst = new VAArgInst(Op, EltTy);
5858 /// ParseExtractElement
5859 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5860 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5863 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5864 ParseToken(lltok::comma, "expected ',' after extract value") ||
5865 ParseTypeAndValue(Op1, PFS))
5868 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5869 return Error(Loc, "invalid extractelement operands");
5871 Inst = ExtractElementInst::Create(Op0, Op1);
5875 /// ParseInsertElement
5876 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5877 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5879 Value *Op0, *Op1, *Op2;
5880 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5881 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5882 ParseTypeAndValue(Op1, PFS) ||
5883 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5884 ParseTypeAndValue(Op2, PFS))
5887 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5888 return Error(Loc, "invalid insertelement operands");
5890 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5894 /// ParseShuffleVector
5895 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5896 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5898 Value *Op0, *Op1, *Op2;
5899 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5900 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5901 ParseTypeAndValue(Op1, PFS) ||
5902 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5903 ParseTypeAndValue(Op2, PFS))
5906 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5907 return Error(Loc, "invalid shufflevector operands");
5909 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5914 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5915 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5916 Type *Ty = nullptr; LocTy TypeLoc;
5919 if (ParseType(Ty, TypeLoc) ||
5920 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5921 ParseValue(Ty, Op0, PFS) ||
5922 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5923 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5924 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5927 bool AteExtraComma = false;
5928 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5931 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5933 if (!EatIfPresent(lltok::comma))
5936 if (Lex.getKind() == lltok::MetadataVar) {
5937 AteExtraComma = true;
5941 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5942 ParseValue(Ty, Op0, PFS) ||
5943 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5944 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5945 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5949 if (!Ty->isFirstClassType())
5950 return Error(TypeLoc, "phi node must have first class type");
5952 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5953 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5954 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5956 return AteExtraComma ? InstExtraComma : InstNormal;
5960 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5962 /// ::= 'catch' TypeAndValue
5964 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5965 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5966 Type *Ty = nullptr; LocTy TyLoc;
5968 if (ParseType(Ty, TyLoc))
5971 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5972 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5974 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5975 LandingPadInst::ClauseType CT;
5976 if (EatIfPresent(lltok::kw_catch))
5977 CT = LandingPadInst::Catch;
5978 else if (EatIfPresent(lltok::kw_filter))
5979 CT = LandingPadInst::Filter;
5981 return TokError("expected 'catch' or 'filter' clause type");
5985 if (ParseTypeAndValue(V, VLoc, PFS))
5988 // A 'catch' type expects a non-array constant. A filter clause expects an
5990 if (CT == LandingPadInst::Catch) {
5991 if (isa<ArrayType>(V->getType()))
5992 Error(VLoc, "'catch' clause has an invalid type");
5994 if (!isa<ArrayType>(V->getType()))
5995 Error(VLoc, "'filter' clause has an invalid type");
5998 Constant *CV = dyn_cast<Constant>(V);
6000 return Error(VLoc, "clause argument must be a constant");
6004 Inst = LP.release();
6009 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6010 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6011 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6012 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6013 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6014 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6015 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6016 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6017 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
6018 CallInst::TailCallKind TCK) {
6019 AttrBuilder RetAttrs, FnAttrs;
6020 std::vector<unsigned> FwdRefAttrGrps;
6023 Type *RetType = nullptr;
6026 SmallVector<ParamInfo, 16> ArgList;
6027 SmallVector<OperandBundleDef, 2> BundleList;
6028 LocTy CallLoc = Lex.getLoc();
6030 if (TCK != CallInst::TCK_None &&
6031 ParseToken(lltok::kw_call,
6032 "expected 'tail call', 'musttail call', or 'notail call'"))
6035 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6037 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6038 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6039 ParseValID(CalleeID) ||
6040 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6041 PFS.getFunction().isVarArg()) ||
6042 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6043 ParseOptionalOperandBundles(BundleList, PFS))
6046 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6047 return Error(CallLoc, "fast-math-flags specified for call without "
6048 "floating-point scalar or vector return type");
6050 // If RetType is a non-function pointer type, then this is the short syntax
6051 // for the call, which means that RetType is just the return type. Infer the
6052 // rest of the function argument types from the arguments that are present.
6053 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6055 // Pull out the types of all of the arguments...
6056 std::vector<Type*> ParamTypes;
6057 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6058 ParamTypes.push_back(ArgList[i].V->getType());
6060 if (!FunctionType::isValidReturnType(RetType))
6061 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6063 Ty = FunctionType::get(RetType, ParamTypes, false);
6068 // Look up the callee.
6070 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6073 // Set up the Attribute for the function.
6074 SmallVector<AttributeSet, 8> Attrs;
6076 SmallVector<Value*, 8> Args;
6078 // Loop through FunctionType's arguments and ensure they are specified
6079 // correctly. Also, gather any parameter attributes.
6080 FunctionType::param_iterator I = Ty->param_begin();
6081 FunctionType::param_iterator E = Ty->param_end();
6082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6083 Type *ExpectedTy = nullptr;
6086 } else if (!Ty->isVarArg()) {
6087 return Error(ArgList[i].Loc, "too many arguments specified");
6090 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6091 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6092 getTypeString(ExpectedTy) + "'");
6093 Args.push_back(ArgList[i].V);
6094 Attrs.push_back(ArgList[i].Attrs);
6098 return Error(CallLoc, "not enough parameters specified for call");
6100 if (FnAttrs.hasAlignmentAttr())
6101 return Error(CallLoc, "call instructions may not have an alignment");
6103 // Finish off the Attribute and check them
6105 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6106 AttributeSet::get(Context, RetAttrs), Attrs);
6108 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6109 CI->setTailCallKind(TCK);
6110 CI->setCallingConv(CC);
6112 CI->setFastMathFlags(FMF);
6113 CI->setAttributes(PAL);
6114 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6119 //===----------------------------------------------------------------------===//
6120 // Memory Instructions.
6121 //===----------------------------------------------------------------------===//
6124 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6125 /// (',' 'align' i32)? (',', 'addrspace(n))?
6126 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6127 Value *Size = nullptr;
6128 LocTy SizeLoc, TyLoc, ASLoc;
6129 unsigned Alignment = 0;
6130 unsigned AddrSpace = 0;
6133 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6134 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6136 if (ParseType(Ty, TyLoc)) return true;
6138 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6139 return Error(TyLoc, "invalid type for alloca");
6141 bool AteExtraComma = false;
6142 if (EatIfPresent(lltok::comma)) {
6143 if (Lex.getKind() == lltok::kw_align) {
6144 if (ParseOptionalAlignment(Alignment))
6146 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6148 } else if (Lex.getKind() == lltok::kw_addrspace) {
6149 ASLoc = Lex.getLoc();
6150 if (ParseOptionalAddrSpace(AddrSpace))
6152 } else if (Lex.getKind() == lltok::MetadataVar) {
6153 AteExtraComma = true;
6155 if (ParseTypeAndValue(Size, SizeLoc, PFS))
6157 if (EatIfPresent(lltok::comma)) {
6158 if (Lex.getKind() == lltok::kw_align) {
6159 if (ParseOptionalAlignment(Alignment))
6161 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6163 } else if (Lex.getKind() == lltok::kw_addrspace) {
6164 ASLoc = Lex.getLoc();
6165 if (ParseOptionalAddrSpace(AddrSpace))
6167 } else if (Lex.getKind() == lltok::MetadataVar) {
6168 AteExtraComma = true;
6174 if (Size && !Size->getType()->isIntegerTy())
6175 return Error(SizeLoc, "element count must have integer type");
6177 const DataLayout &DL = M->getDataLayout();
6178 unsigned AS = DL.getAllocaAddrSpace();
6179 if (AS != AddrSpace) {
6180 // TODO: In the future it should be possible to specify addrspace per-alloca.
6181 return Error(ASLoc, "address space must match datalayout");
6184 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
6185 AI->setUsedWithInAlloca(IsInAlloca);
6186 AI->setSwiftError(IsSwiftError);
6188 return AteExtraComma ? InstExtraComma : InstNormal;
6192 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6193 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6194 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6195 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6196 Value *Val; LocTy Loc;
6197 unsigned Alignment = 0;
6198 bool AteExtraComma = false;
6199 bool isAtomic = false;
6200 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6201 SyncScope::ID SSID = SyncScope::System;
6203 if (Lex.getKind() == lltok::kw_atomic) {
6208 bool isVolatile = false;
6209 if (Lex.getKind() == lltok::kw_volatile) {
6215 LocTy ExplicitTypeLoc = Lex.getLoc();
6216 if (ParseType(Ty) ||
6217 ParseToken(lltok::comma, "expected comma after load's type") ||
6218 ParseTypeAndValue(Val, Loc, PFS) ||
6219 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6220 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6223 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6224 return Error(Loc, "load operand must be a pointer to a first class type");
6225 if (isAtomic && !Alignment)
6226 return Error(Loc, "atomic load must have explicit non-zero alignment");
6227 if (Ordering == AtomicOrdering::Release ||
6228 Ordering == AtomicOrdering::AcquireRelease)
6229 return Error(Loc, "atomic load cannot use Release ordering");
6231 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6232 return Error(ExplicitTypeLoc,
6233 "explicit pointee type doesn't match operand's pointee type");
6235 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6236 return AteExtraComma ? InstExtraComma : InstNormal;
6241 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6242 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6243 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6244 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6245 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6246 unsigned Alignment = 0;
6247 bool AteExtraComma = false;
6248 bool isAtomic = false;
6249 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6250 SyncScope::ID SSID = SyncScope::System;
6252 if (Lex.getKind() == lltok::kw_atomic) {
6257 bool isVolatile = false;
6258 if (Lex.getKind() == lltok::kw_volatile) {
6263 if (ParseTypeAndValue(Val, Loc, PFS) ||
6264 ParseToken(lltok::comma, "expected ',' after store operand") ||
6265 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6266 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6267 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6270 if (!Ptr->getType()->isPointerTy())
6271 return Error(PtrLoc, "store operand must be a pointer");
6272 if (!Val->getType()->isFirstClassType())
6273 return Error(Loc, "store operand must be a first class value");
6274 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6275 return Error(Loc, "stored value and pointer type do not match");
6276 if (isAtomic && !Alignment)
6277 return Error(Loc, "atomic store must have explicit non-zero alignment");
6278 if (Ordering == AtomicOrdering::Acquire ||
6279 Ordering == AtomicOrdering::AcquireRelease)
6280 return Error(Loc, "atomic store cannot use Acquire ordering");
6282 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
6283 return AteExtraComma ? InstExtraComma : InstNormal;
6287 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6288 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6289 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6290 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6291 bool AteExtraComma = false;
6292 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6293 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6294 SyncScope::ID SSID = SyncScope::System;
6295 bool isVolatile = false;
6296 bool isWeak = false;
6298 if (EatIfPresent(lltok::kw_weak))
6301 if (EatIfPresent(lltok::kw_volatile))
6304 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6305 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6306 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6307 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6308 ParseTypeAndValue(New, NewLoc, PFS) ||
6309 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
6310 ParseOrdering(FailureOrdering))
6313 if (SuccessOrdering == AtomicOrdering::Unordered ||
6314 FailureOrdering == AtomicOrdering::Unordered)
6315 return TokError("cmpxchg cannot be unordered");
6316 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6317 return TokError("cmpxchg failure argument shall be no stronger than the "
6318 "success argument");
6319 if (FailureOrdering == AtomicOrdering::Release ||
6320 FailureOrdering == AtomicOrdering::AcquireRelease)
6322 "cmpxchg failure ordering cannot include release semantics");
6323 if (!Ptr->getType()->isPointerTy())
6324 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6325 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6326 return Error(CmpLoc, "compare value and pointer type do not match");
6327 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6328 return Error(NewLoc, "new value and pointer type do not match");
6329 if (!New->getType()->isFirstClassType())
6330 return Error(NewLoc, "cmpxchg operand must be a first class value");
6331 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6332 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
6333 CXI->setVolatile(isVolatile);
6334 CXI->setWeak(isWeak);
6336 return AteExtraComma ? InstExtraComma : InstNormal;
6340 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6341 /// 'singlethread'? AtomicOrdering
6342 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6343 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6344 bool AteExtraComma = false;
6345 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6346 SyncScope::ID SSID = SyncScope::System;
6347 bool isVolatile = false;
6348 AtomicRMWInst::BinOp Operation;
6350 if (EatIfPresent(lltok::kw_volatile))
6353 switch (Lex.getKind()) {
6354 default: return TokError("expected binary operation in atomicrmw");
6355 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6356 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6357 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6358 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6359 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6360 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6361 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6362 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6363 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6364 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6365 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6367 Lex.Lex(); // Eat the operation.
6369 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6370 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6371 ParseTypeAndValue(Val, ValLoc, PFS) ||
6372 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6375 if (Ordering == AtomicOrdering::Unordered)
6376 return TokError("atomicrmw cannot be unordered");
6377 if (!Ptr->getType()->isPointerTy())
6378 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6379 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6380 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6381 if (!Val->getType()->isIntegerTy())
6382 return Error(ValLoc, "atomicrmw operand must be an integer");
6383 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6384 if (Size < 8 || (Size & (Size - 1)))
6385 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6388 AtomicRMWInst *RMWI =
6389 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
6390 RMWI->setVolatile(isVolatile);
6392 return AteExtraComma ? InstExtraComma : InstNormal;
6396 /// ::= 'fence' 'singlethread'? AtomicOrdering
6397 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6398 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6399 SyncScope::ID SSID = SyncScope::System;
6400 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6403 if (Ordering == AtomicOrdering::Unordered)
6404 return TokError("fence cannot be unordered");
6405 if (Ordering == AtomicOrdering::Monotonic)
6406 return TokError("fence cannot be monotonic");
6408 Inst = new FenceInst(Context, Ordering, SSID);
6412 /// ParseGetElementPtr
6413 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6414 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6415 Value *Ptr = nullptr;
6416 Value *Val = nullptr;
6419 bool InBounds = EatIfPresent(lltok::kw_inbounds);
6422 LocTy ExplicitTypeLoc = Lex.getLoc();
6423 if (ParseType(Ty) ||
6424 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6425 ParseTypeAndValue(Ptr, Loc, PFS))
6428 Type *BaseType = Ptr->getType();
6429 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6430 if (!BasePointerType)
6431 return Error(Loc, "base of getelementptr must be a pointer");
6433 if (Ty != BasePointerType->getElementType())
6434 return Error(ExplicitTypeLoc,
6435 "explicit pointee type doesn't match operand's pointee type");
6437 SmallVector<Value*, 16> Indices;
6438 bool AteExtraComma = false;
6439 // GEP returns a vector of pointers if at least one of parameters is a vector.
6440 // All vector parameters should have the same vector width.
6441 unsigned GEPWidth = BaseType->isVectorTy() ?
6442 BaseType->getVectorNumElements() : 0;
6444 while (EatIfPresent(lltok::comma)) {
6445 if (Lex.getKind() == lltok::MetadataVar) {
6446 AteExtraComma = true;
6449 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6450 if (!Val->getType()->isIntOrIntVectorTy())
6451 return Error(EltLoc, "getelementptr index must be an integer");
6453 if (Val->getType()->isVectorTy()) {
6454 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6455 if (GEPWidth && GEPWidth != ValNumEl)
6456 return Error(EltLoc,
6457 "getelementptr vector index has a wrong number of elements");
6458 GEPWidth = ValNumEl;
6460 Indices.push_back(Val);
6463 SmallPtrSet<Type*, 4> Visited;
6464 if (!Indices.empty() && !Ty->isSized(&Visited))
6465 return Error(Loc, "base element of getelementptr must be sized");
6467 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6468 return Error(Loc, "invalid getelementptr indices");
6469 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6471 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6472 return AteExtraComma ? InstExtraComma : InstNormal;
6475 /// ParseExtractValue
6476 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6477 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6478 Value *Val; LocTy Loc;
6479 SmallVector<unsigned, 4> Indices;
6481 if (ParseTypeAndValue(Val, Loc, PFS) ||
6482 ParseIndexList(Indices, AteExtraComma))
6485 if (!Val->getType()->isAggregateType())
6486 return Error(Loc, "extractvalue operand must be aggregate type");
6488 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6489 return Error(Loc, "invalid indices for extractvalue");
6490 Inst = ExtractValueInst::Create(Val, Indices);
6491 return AteExtraComma ? InstExtraComma : InstNormal;
6494 /// ParseInsertValue
6495 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6496 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6497 Value *Val0, *Val1; LocTy Loc0, Loc1;
6498 SmallVector<unsigned, 4> Indices;
6500 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6501 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6502 ParseTypeAndValue(Val1, Loc1, PFS) ||
6503 ParseIndexList(Indices, AteExtraComma))
6506 if (!Val0->getType()->isAggregateType())
6507 return Error(Loc0, "insertvalue operand must be aggregate type");
6509 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6511 return Error(Loc0, "invalid indices for insertvalue");
6512 if (IndexedType != Val1->getType())
6513 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6514 getTypeString(Val1->getType()) + "' instead of '" +
6515 getTypeString(IndexedType) + "'");
6516 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6517 return AteExtraComma ? InstExtraComma : InstNormal;
6520 //===----------------------------------------------------------------------===//
6521 // Embedded metadata.
6522 //===----------------------------------------------------------------------===//
6524 /// ParseMDNodeVector
6525 /// ::= { Element (',' Element)* }
6527 /// ::= 'null' | TypeAndValue
6528 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6529 if (ParseToken(lltok::lbrace, "expected '{' here"))
6532 // Check for an empty list.
6533 if (EatIfPresent(lltok::rbrace))
6537 // Null is a special case since it is typeless.
6538 if (EatIfPresent(lltok::kw_null)) {
6539 Elts.push_back(nullptr);
6544 if (ParseMetadata(MD, nullptr))
6547 } while (EatIfPresent(lltok::comma));
6549 return ParseToken(lltok::rbrace, "expected end of metadata node");
6552 //===----------------------------------------------------------------------===//
6553 // Use-list order directives.
6554 //===----------------------------------------------------------------------===//
6555 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6558 return Error(Loc, "value has no uses");
6560 unsigned NumUses = 0;
6561 SmallDenseMap<const Use *, unsigned, 16> Order;
6562 for (const Use &U : V->uses()) {
6563 if (++NumUses > Indexes.size())
6565 Order[&U] = Indexes[NumUses - 1];
6568 return Error(Loc, "value only has one use");
6569 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6570 return Error(Loc, "wrong number of indexes, expected " +
6571 Twine(std::distance(V->use_begin(), V->use_end())));
6573 V->sortUseList([&](const Use &L, const Use &R) {
6574 return Order.lookup(&L) < Order.lookup(&R);
6579 /// ParseUseListOrderIndexes
6580 /// ::= '{' uint32 (',' uint32)+ '}'
6581 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6582 SMLoc Loc = Lex.getLoc();
6583 if (ParseToken(lltok::lbrace, "expected '{' here"))
6585 if (Lex.getKind() == lltok::rbrace)
6586 return Lex.Error("expected non-empty list of uselistorder indexes");
6588 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6589 // indexes should be distinct numbers in the range [0, size-1], and should
6591 unsigned Offset = 0;
6593 bool IsOrdered = true;
6594 assert(Indexes.empty() && "Expected empty order vector");
6597 if (ParseUInt32(Index))
6600 // Update consistency checks.
6601 Offset += Index - Indexes.size();
6602 Max = std::max(Max, Index);
6603 IsOrdered &= Index == Indexes.size();
6605 Indexes.push_back(Index);
6606 } while (EatIfPresent(lltok::comma));
6608 if (ParseToken(lltok::rbrace, "expected '}' here"))
6611 if (Indexes.size() < 2)
6612 return Error(Loc, "expected >= 2 uselistorder indexes");
6613 if (Offset != 0 || Max >= Indexes.size())
6614 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6616 return Error(Loc, "expected uselistorder indexes to change the order");
6621 /// ParseUseListOrder
6622 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6623 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6624 SMLoc Loc = Lex.getLoc();
6625 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6629 SmallVector<unsigned, 16> Indexes;
6630 if (ParseTypeAndValue(V, PFS) ||
6631 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6632 ParseUseListOrderIndexes(Indexes))
6635 return sortUseListOrder(V, Indexes, Loc);
6638 /// ParseUseListOrderBB
6639 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6640 bool LLParser::ParseUseListOrderBB() {
6641 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6642 SMLoc Loc = Lex.getLoc();
6646 SmallVector<unsigned, 16> Indexes;
6647 if (ParseValID(Fn) ||
6648 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6649 ParseValID(Label) ||
6650 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6651 ParseUseListOrderIndexes(Indexes))
6654 // Check the function.
6656 if (Fn.Kind == ValID::t_GlobalName)
6657 GV = M->getNamedValue(Fn.StrVal);
6658 else if (Fn.Kind == ValID::t_GlobalID)
6659 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6661 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6663 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6664 auto *F = dyn_cast<Function>(GV);
6666 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6667 if (F->isDeclaration())
6668 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6670 // Check the basic block.
6671 if (Label.Kind == ValID::t_LocalID)
6672 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6673 if (Label.Kind != ValID::t_LocalName)
6674 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6675 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
6677 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6678 if (!isa<BasicBlock>(V))
6679 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6681 return sortUseListOrder(V, Indexes, Loc);