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/SmallPtrSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/Dwarf.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);
166 llvm_unreachable("invalid object with forward attribute group reference");
170 // If there are entries in ForwardRefBlockAddresses at this point, the
171 // function was never defined.
172 if (!ForwardRefBlockAddresses.empty())
173 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
174 "expected function name in blockaddress");
176 for (const auto &NT : NumberedTypes)
177 if (NT.second.second.isValid())
178 return Error(NT.second.second,
179 "use of undefined type '%" + Twine(NT.first) + "'");
181 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
182 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
183 if (I->second.second.isValid())
184 return Error(I->second.second,
185 "use of undefined type named '" + I->getKey() + "'");
187 if (!ForwardRefComdats.empty())
188 return Error(ForwardRefComdats.begin()->second,
189 "use of undefined comdat '$" +
190 ForwardRefComdats.begin()->first + "'");
192 if (!ForwardRefVals.empty())
193 return Error(ForwardRefVals.begin()->second.second,
194 "use of undefined value '@" + ForwardRefVals.begin()->first +
197 if (!ForwardRefValIDs.empty())
198 return Error(ForwardRefValIDs.begin()->second.second,
199 "use of undefined value '@" +
200 Twine(ForwardRefValIDs.begin()->first) + "'");
202 if (!ForwardRefMDNodes.empty())
203 return Error(ForwardRefMDNodes.begin()->second.second,
204 "use of undefined metadata '!" +
205 Twine(ForwardRefMDNodes.begin()->first) + "'");
207 // Resolve metadata cycles.
208 for (auto &N : NumberedMetadata) {
209 if (N.second && !N.second->isResolved())
210 N.second->resolveCycles();
213 for (auto *Inst : InstsWithTBAATag) {
214 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
215 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
216 auto *UpgradedMD = UpgradeTBAANode(*MD);
217 if (MD != UpgradedMD)
218 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
221 // Look for intrinsic functions and CallInst that need to be upgraded
222 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
223 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
225 // Some types could be renamed during loading if several modules are
226 // loaded in the same LLVMContext (LTO scenario). In this case we should
227 // remangle intrinsics names as well.
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
229 Function *F = &*FI++;
230 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
231 F->replaceAllUsesWith(Remangled.getValue());
232 F->eraseFromParent();
236 UpgradeDebugInfo(*M);
238 UpgradeModuleFlags(*M);
242 // Initialize the slot mapping.
243 // Because by this point we've parsed and validated everything, we can "steal"
244 // the mapping from LLParser as it doesn't need it anymore.
245 Slots->GlobalValues = std::move(NumberedVals);
246 Slots->MetadataNodes = std::move(NumberedMetadata);
247 for (const auto &I : NamedTypes)
248 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
249 for (const auto &I : NumberedTypes)
250 Slots->Types.insert(std::make_pair(I.first, I.second.first));
255 //===----------------------------------------------------------------------===//
256 // Top-Level Entities
257 //===----------------------------------------------------------------------===//
259 bool LLParser::ParseTopLevelEntities() {
261 switch (Lex.getKind()) {
262 default: return TokError("expected top-level entity");
263 case lltok::Eof: return false;
264 case lltok::kw_declare: if (ParseDeclare()) return true; break;
265 case lltok::kw_define: if (ParseDefine()) return true; break;
266 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
267 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
268 case lltok::kw_source_filename:
269 if (ParseSourceFileName())
272 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
273 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
274 case lltok::LocalVar: if (ParseNamedType()) return true; break;
275 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
276 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
277 case lltok::ComdatVar: if (parseComdat()) return true; break;
278 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
279 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
280 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
281 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
282 case lltok::kw_uselistorder_bb:
283 if (ParseUseListOrderBB())
291 /// ::= 'module' 'asm' STRINGCONSTANT
292 bool LLParser::ParseModuleAsm() {
293 assert(Lex.getKind() == lltok::kw_module);
297 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
298 ParseStringConstant(AsmStr)) return true;
300 M->appendModuleInlineAsm(AsmStr);
305 /// ::= 'target' 'triple' '=' STRINGCONSTANT
306 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
307 bool LLParser::ParseTargetDefinition() {
308 assert(Lex.getKind() == lltok::kw_target);
311 default: return TokError("unknown target property");
312 case lltok::kw_triple:
314 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
315 ParseStringConstant(Str))
317 M->setTargetTriple(Str);
319 case lltok::kw_datalayout:
321 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
322 ParseStringConstant(Str))
324 M->setDataLayout(Str);
330 /// ::= 'source_filename' '=' STRINGCONSTANT
331 bool LLParser::ParseSourceFileName() {
332 assert(Lex.getKind() == lltok::kw_source_filename);
335 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
336 ParseStringConstant(Str))
338 M->setSourceFileName(Str);
343 /// ::= 'deplibs' '=' '[' ']'
344 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
345 /// FIXME: Remove in 4.0. Currently parse, but ignore.
346 bool LLParser::ParseDepLibs() {
347 assert(Lex.getKind() == lltok::kw_deplibs);
349 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
350 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
353 if (EatIfPresent(lltok::rsquare))
358 if (ParseStringConstant(Str)) return true;
359 } while (EatIfPresent(lltok::comma));
361 return ParseToken(lltok::rsquare, "expected ']' at end of list");
364 /// ParseUnnamedType:
365 /// ::= LocalVarID '=' 'type' type
366 bool LLParser::ParseUnnamedType() {
367 LocTy TypeLoc = Lex.getLoc();
368 unsigned TypeID = Lex.getUIntVal();
369 Lex.Lex(); // eat LocalVarID;
371 if (ParseToken(lltok::equal, "expected '=' after name") ||
372 ParseToken(lltok::kw_type, "expected 'type' after '='"))
375 Type *Result = nullptr;
376 if (ParseStructDefinition(TypeLoc, "",
377 NumberedTypes[TypeID], Result)) return true;
379 if (!isa<StructType>(Result)) {
380 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
382 return Error(TypeLoc, "non-struct types may not be recursive");
383 Entry.first = Result;
384 Entry.second = SMLoc();
391 /// ::= LocalVar '=' 'type' type
392 bool LLParser::ParseNamedType() {
393 std::string Name = Lex.getStrVal();
394 LocTy NameLoc = Lex.getLoc();
395 Lex.Lex(); // eat LocalVar.
397 if (ParseToken(lltok::equal, "expected '=' after name") ||
398 ParseToken(lltok::kw_type, "expected 'type' after name"))
401 Type *Result = nullptr;
402 if (ParseStructDefinition(NameLoc, Name,
403 NamedTypes[Name], Result)) return true;
405 if (!isa<StructType>(Result)) {
406 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
408 return Error(NameLoc, "non-struct types may not be recursive");
409 Entry.first = Result;
410 Entry.second = SMLoc();
417 /// ::= 'declare' FunctionHeader
418 bool LLParser::ParseDeclare() {
419 assert(Lex.getKind() == lltok::kw_declare);
422 std::vector<std::pair<unsigned, MDNode *>> MDs;
423 while (Lex.getKind() == lltok::MetadataVar) {
426 if (ParseMetadataAttachment(MDK, N))
428 MDs.push_back({MDK, N});
432 if (ParseFunctionHeader(F, false))
435 F->addMetadata(MD.first, *MD.second);
440 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
441 bool LLParser::ParseDefine() {
442 assert(Lex.getKind() == lltok::kw_define);
446 return ParseFunctionHeader(F, true) ||
447 ParseOptionalFunctionMetadata(*F) ||
448 ParseFunctionBody(*F);
454 bool LLParser::ParseGlobalType(bool &IsConstant) {
455 if (Lex.getKind() == lltok::kw_constant)
457 else if (Lex.getKind() == lltok::kw_global)
461 return TokError("expected 'global' or 'constant'");
467 bool LLParser::ParseOptionalUnnamedAddr(
468 GlobalVariable::UnnamedAddr &UnnamedAddr) {
469 if (EatIfPresent(lltok::kw_unnamed_addr))
470 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
471 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
472 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
474 UnnamedAddr = GlobalValue::UnnamedAddr::None;
478 /// ParseUnnamedGlobal:
479 /// OptionalVisibility (ALIAS | IFUNC) ...
480 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
481 /// ... -> global variable
482 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
483 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
484 /// ... -> global variable
485 bool LLParser::ParseUnnamedGlobal() {
486 unsigned VarID = NumberedVals.size();
488 LocTy NameLoc = Lex.getLoc();
490 // Handle the GlobalID form.
491 if (Lex.getKind() == lltok::GlobalID) {
492 if (Lex.getUIntVal() != VarID)
493 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
495 Lex.Lex(); // eat GlobalID;
497 if (ParseToken(lltok::equal, "expected '=' after name"))
502 unsigned Linkage, Visibility, DLLStorageClass;
503 GlobalVariable::ThreadLocalMode TLM;
504 GlobalVariable::UnnamedAddr UnnamedAddr;
505 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
506 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
509 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
510 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
511 DLLStorageClass, TLM, UnnamedAddr);
513 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
514 DLLStorageClass, TLM, UnnamedAddr);
517 /// ParseNamedGlobal:
518 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
519 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
520 /// ... -> global variable
521 bool LLParser::ParseNamedGlobal() {
522 assert(Lex.getKind() == lltok::GlobalVar);
523 LocTy NameLoc = Lex.getLoc();
524 std::string Name = Lex.getStrVal();
528 unsigned Linkage, Visibility, DLLStorageClass;
529 GlobalVariable::ThreadLocalMode TLM;
530 GlobalVariable::UnnamedAddr UnnamedAddr;
531 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
532 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
533 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
536 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
537 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
538 DLLStorageClass, TLM, UnnamedAddr);
540 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
541 DLLStorageClass, TLM, UnnamedAddr);
544 bool LLParser::parseComdat() {
545 assert(Lex.getKind() == lltok::ComdatVar);
546 std::string Name = Lex.getStrVal();
547 LocTy NameLoc = Lex.getLoc();
550 if (ParseToken(lltok::equal, "expected '=' here"))
553 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
554 return TokError("expected comdat type");
556 Comdat::SelectionKind SK;
557 switch (Lex.getKind()) {
559 return TokError("unknown selection kind");
563 case lltok::kw_exactmatch:
564 SK = Comdat::ExactMatch;
566 case lltok::kw_largest:
567 SK = Comdat::Largest;
569 case lltok::kw_noduplicates:
570 SK = Comdat::NoDuplicates;
572 case lltok::kw_samesize:
573 SK = Comdat::SameSize;
578 // See if the comdat was forward referenced, if so, use the comdat.
579 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
580 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
581 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
582 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
585 if (I != ComdatSymTab.end())
588 C = M->getOrInsertComdat(Name);
589 C->setSelectionKind(SK);
595 // ::= '!' STRINGCONSTANT
596 bool LLParser::ParseMDString(MDString *&Result) {
598 if (ParseStringConstant(Str)) return true;
599 Result = MDString::get(Context, Str);
604 // ::= '!' MDNodeNumber
605 bool LLParser::ParseMDNodeID(MDNode *&Result) {
606 // !{ ..., !42, ... }
607 LocTy IDLoc = Lex.getLoc();
609 if (ParseUInt32(MID))
612 // If not a forward reference, just return it now.
613 if (NumberedMetadata.count(MID)) {
614 Result = NumberedMetadata[MID];
618 // Otherwise, create MDNode forward reference.
619 auto &FwdRef = ForwardRefMDNodes[MID];
620 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
622 Result = FwdRef.first.get();
623 NumberedMetadata[MID].reset(Result);
627 /// ParseNamedMetadata:
628 /// !foo = !{ !1, !2 }
629 bool LLParser::ParseNamedMetadata() {
630 assert(Lex.getKind() == lltok::MetadataVar);
631 std::string Name = Lex.getStrVal();
634 if (ParseToken(lltok::equal, "expected '=' here") ||
635 ParseToken(lltok::exclaim, "Expected '!' here") ||
636 ParseToken(lltok::lbrace, "Expected '{' here"))
639 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
640 if (Lex.getKind() != lltok::rbrace)
642 if (ParseToken(lltok::exclaim, "Expected '!' here"))
646 if (ParseMDNodeID(N)) return true;
648 } while (EatIfPresent(lltok::comma));
650 return ParseToken(lltok::rbrace, "expected end of metadata node");
653 /// ParseStandaloneMetadata:
655 bool LLParser::ParseStandaloneMetadata() {
656 assert(Lex.getKind() == lltok::exclaim);
658 unsigned MetadataID = 0;
661 if (ParseUInt32(MetadataID) ||
662 ParseToken(lltok::equal, "expected '=' here"))
665 // Detect common error, from old metadata syntax.
666 if (Lex.getKind() == lltok::Type)
667 return TokError("unexpected type in metadata definition");
669 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
670 if (Lex.getKind() == lltok::MetadataVar) {
671 if (ParseSpecializedMDNode(Init, IsDistinct))
673 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
674 ParseMDTuple(Init, IsDistinct))
677 // See if this was forward referenced, if so, handle it.
678 auto FI = ForwardRefMDNodes.find(MetadataID);
679 if (FI != ForwardRefMDNodes.end()) {
680 FI->second.first->replaceAllUsesWith(Init);
681 ForwardRefMDNodes.erase(FI);
683 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
685 if (NumberedMetadata.count(MetadataID))
686 return TokError("Metadata id is already used");
687 NumberedMetadata[MetadataID].reset(Init);
693 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
694 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
695 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
698 /// parseIndirectSymbol:
699 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
700 /// OptionalDLLStorageClass OptionalThreadLocal
701 /// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
706 /// Everything through OptionalUnnamedAddr has already been parsed.
708 bool LLParser::parseIndirectSymbol(
709 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
710 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
711 GlobalVariable::UnnamedAddr UnnamedAddr) {
713 if (Lex.getKind() == lltok::kw_alias)
715 else if (Lex.getKind() == lltok::kw_ifunc)
718 llvm_unreachable("Not an alias or ifunc!");
721 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
723 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
724 return Error(NameLoc, "invalid linkage type for alias");
726 if (!isValidVisibilityForLinkage(Visibility, L))
727 return Error(NameLoc,
728 "symbol with local linkage must have default visibility");
731 LocTy ExplicitTypeLoc = Lex.getLoc();
733 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
737 LocTy AliaseeLoc = Lex.getLoc();
738 if (Lex.getKind() != lltok::kw_bitcast &&
739 Lex.getKind() != lltok::kw_getelementptr &&
740 Lex.getKind() != lltok::kw_addrspacecast &&
741 Lex.getKind() != lltok::kw_inttoptr) {
742 if (ParseGlobalTypeAndValue(Aliasee))
745 // The bitcast dest type is not present, it is implied by the dest type.
749 if (ID.Kind != ValID::t_Constant)
750 return Error(AliaseeLoc, "invalid aliasee");
751 Aliasee = ID.ConstantVal;
754 Type *AliaseeType = Aliasee->getType();
755 auto *PTy = dyn_cast<PointerType>(AliaseeType);
757 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
758 unsigned AddrSpace = PTy->getAddressSpace();
760 if (IsAlias && Ty != PTy->getElementType())
763 "explicit pointee type doesn't match operand's pointee type");
765 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
768 "explicit pointee type should be a function type");
770 GlobalValue *GVal = nullptr;
772 // See if the alias was forward referenced, if so, prepare to replace the
773 // forward reference.
775 GVal = M->getNamedValue(Name);
777 if (!ForwardRefVals.erase(Name))
778 return Error(NameLoc, "redefinition of global '@" + Name + "'");
781 auto I = ForwardRefValIDs.find(NumberedVals.size());
782 if (I != ForwardRefValIDs.end()) {
783 GVal = I->second.first;
784 ForwardRefValIDs.erase(I);
788 // Okay, create the alias but do not insert it into the module yet.
789 std::unique_ptr<GlobalIndirectSymbol> GA;
791 GA.reset(GlobalAlias::create(Ty, AddrSpace,
792 (GlobalValue::LinkageTypes)Linkage, Name,
793 Aliasee, /*Parent*/ nullptr));
795 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
796 (GlobalValue::LinkageTypes)Linkage, Name,
797 Aliasee, /*Parent*/ nullptr));
798 GA->setThreadLocalMode(TLM);
799 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
800 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
801 GA->setUnnamedAddr(UnnamedAddr);
804 NumberedVals.push_back(GA.get());
807 // Verify that types agree.
808 if (GVal->getType() != GA->getType())
811 "forward reference and definition of alias have different types");
813 // If they agree, just RAUW the old value with the alias and remove the
815 GVal->replaceAllUsesWith(GA.get());
816 GVal->eraseFromParent();
819 // Insert into the module, we know its name won't collide now.
821 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
823 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
824 assert(GA->getName() == Name && "Should not be a name conflict!");
826 // The module owns this now
833 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
834 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
835 /// OptionalExternallyInitialized GlobalType Type Const
836 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
837 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
838 /// OptionalExternallyInitialized GlobalType Type Const
840 /// Everything up to and including OptionalUnnamedAddr has been parsed
843 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
844 unsigned Linkage, bool HasLinkage,
845 unsigned Visibility, unsigned DLLStorageClass,
846 GlobalVariable::ThreadLocalMode TLM,
847 GlobalVariable::UnnamedAddr UnnamedAddr) {
848 if (!isValidVisibilityForLinkage(Visibility, Linkage))
849 return Error(NameLoc,
850 "symbol with local linkage must have default visibility");
853 bool IsConstant, IsExternallyInitialized;
854 LocTy IsExternallyInitializedLoc;
858 if (ParseOptionalAddrSpace(AddrSpace) ||
859 ParseOptionalToken(lltok::kw_externally_initialized,
860 IsExternallyInitialized,
861 &IsExternallyInitializedLoc) ||
862 ParseGlobalType(IsConstant) ||
863 ParseType(Ty, TyLoc))
866 // If the linkage is specified and is external, then no initializer is
868 Constant *Init = nullptr;
870 !GlobalValue::isValidDeclarationLinkage(
871 (GlobalValue::LinkageTypes)Linkage)) {
872 if (ParseGlobalValue(Ty, Init))
876 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
877 return Error(TyLoc, "invalid type for global variable");
879 GlobalValue *GVal = nullptr;
881 // See if the global was forward referenced, if so, use the global.
883 GVal = M->getNamedValue(Name);
885 if (!ForwardRefVals.erase(Name))
886 return Error(NameLoc, "redefinition of global '@" + Name + "'");
889 auto I = ForwardRefValIDs.find(NumberedVals.size());
890 if (I != ForwardRefValIDs.end()) {
891 GVal = I->second.first;
892 ForwardRefValIDs.erase(I);
898 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
899 Name, nullptr, GlobalVariable::NotThreadLocal,
902 if (GVal->getValueType() != Ty)
904 "forward reference and definition of global have different types");
906 GV = cast<GlobalVariable>(GVal);
908 // Move the forward-reference to the correct spot in the module.
909 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
913 NumberedVals.push_back(GV);
915 // Set the parsed properties on the global.
917 GV->setInitializer(Init);
918 GV->setConstant(IsConstant);
919 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
920 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
921 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
922 GV->setExternallyInitialized(IsExternallyInitialized);
923 GV->setThreadLocalMode(TLM);
924 GV->setUnnamedAddr(UnnamedAddr);
926 // Parse attributes on the global.
927 while (Lex.getKind() == lltok::comma) {
930 if (Lex.getKind() == lltok::kw_section) {
932 GV->setSection(Lex.getStrVal());
933 if (ParseToken(lltok::StringConstant, "expected global section string"))
935 } else if (Lex.getKind() == lltok::kw_align) {
937 if (ParseOptionalAlignment(Alignment)) return true;
938 GV->setAlignment(Alignment);
939 } else if (Lex.getKind() == lltok::MetadataVar) {
940 if (ParseGlobalObjectMetadataAttachment(*GV))
944 if (parseOptionalComdat(Name, C))
949 return TokError("unknown global variable property!");
956 /// ParseUnnamedAttrGrp
957 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
958 bool LLParser::ParseUnnamedAttrGrp() {
959 assert(Lex.getKind() == lltok::kw_attributes);
960 LocTy AttrGrpLoc = Lex.getLoc();
963 if (Lex.getKind() != lltok::AttrGrpID)
964 return TokError("expected attribute group id");
966 unsigned VarID = Lex.getUIntVal();
967 std::vector<unsigned> unused;
971 if (ParseToken(lltok::equal, "expected '=' here") ||
972 ParseToken(lltok::lbrace, "expected '{' here") ||
973 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
975 ParseToken(lltok::rbrace, "expected end of attribute group"))
978 if (!NumberedAttrBuilders[VarID].hasAttributes())
979 return Error(AttrGrpLoc, "attribute group has no attributes");
984 /// ParseFnAttributeValuePairs
985 /// ::= <attr> | <attr> '=' <value>
986 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
987 std::vector<unsigned> &FwdRefAttrGrps,
988 bool inAttrGrp, LocTy &BuiltinLoc) {
989 bool HaveError = false;
994 lltok::Kind Token = Lex.getKind();
995 if (Token == lltok::kw_builtin)
996 BuiltinLoc = Lex.getLoc();
999 if (!inAttrGrp) return HaveError;
1000 return Error(Lex.getLoc(), "unterminated attribute group");
1005 case lltok::AttrGrpID: {
1006 // Allow a function to reference an attribute group:
1008 // define void @foo() #1 { ... }
1012 "cannot have an attribute group reference in an attribute group");
1014 unsigned AttrGrpNum = Lex.getUIntVal();
1015 if (inAttrGrp) break;
1017 // Save the reference to the attribute group. We'll fill it in later.
1018 FwdRefAttrGrps.push_back(AttrGrpNum);
1021 // Target-dependent attributes:
1022 case lltok::StringConstant: {
1023 if (ParseStringAttribute(B))
1028 // Target-independent attributes:
1029 case lltok::kw_align: {
1030 // As a hack, we allow function alignment to be initially parsed as an
1031 // attribute on a function declaration/definition or added to an attribute
1032 // group and later moved to the alignment field.
1036 if (ParseToken(lltok::equal, "expected '=' here") ||
1037 ParseUInt32(Alignment))
1040 if (ParseOptionalAlignment(Alignment))
1043 B.addAlignmentAttr(Alignment);
1046 case lltok::kw_alignstack: {
1050 if (ParseToken(lltok::equal, "expected '=' here") ||
1051 ParseUInt32(Alignment))
1054 if (ParseOptionalStackAlignment(Alignment))
1057 B.addStackAlignmentAttr(Alignment);
1060 case lltok::kw_allocsize: {
1061 unsigned ElemSizeArg;
1062 Optional<unsigned> NumElemsArg;
1063 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1064 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1066 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1069 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1070 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1071 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1072 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1073 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1074 case lltok::kw_inaccessiblememonly:
1075 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1076 case lltok::kw_inaccessiblemem_or_argmemonly:
1077 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1078 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1079 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1080 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1081 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1082 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1083 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1084 case lltok::kw_noimplicitfloat:
1085 B.addAttribute(Attribute::NoImplicitFloat); break;
1086 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1087 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1088 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1089 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1090 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1091 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1092 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1093 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1094 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1095 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1096 case lltok::kw_returns_twice:
1097 B.addAttribute(Attribute::ReturnsTwice); break;
1098 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1099 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1100 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1101 case lltok::kw_sspstrong:
1102 B.addAttribute(Attribute::StackProtectStrong); break;
1103 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1104 case lltok::kw_sanitize_address:
1105 B.addAttribute(Attribute::SanitizeAddress); break;
1106 case lltok::kw_sanitize_thread:
1107 B.addAttribute(Attribute::SanitizeThread); break;
1108 case lltok::kw_sanitize_memory:
1109 B.addAttribute(Attribute::SanitizeMemory); break;
1110 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1111 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1114 case lltok::kw_inreg:
1115 case lltok::kw_signext:
1116 case lltok::kw_zeroext:
1119 "invalid use of attribute on a function");
1121 case lltok::kw_byval:
1122 case lltok::kw_dereferenceable:
1123 case lltok::kw_dereferenceable_or_null:
1124 case lltok::kw_inalloca:
1125 case lltok::kw_nest:
1126 case lltok::kw_noalias:
1127 case lltok::kw_nocapture:
1128 case lltok::kw_nonnull:
1129 case lltok::kw_returned:
1130 case lltok::kw_sret:
1131 case lltok::kw_swifterror:
1132 case lltok::kw_swiftself:
1135 "invalid use of parameter-only attribute on a function");
1143 //===----------------------------------------------------------------------===//
1144 // GlobalValue Reference/Resolution Routines.
1145 //===----------------------------------------------------------------------===//
1147 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1148 const std::string &Name) {
1149 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1150 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1152 return new GlobalVariable(*M, PTy->getElementType(), false,
1153 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1154 nullptr, GlobalVariable::NotThreadLocal,
1155 PTy->getAddressSpace());
1158 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1159 /// forward reference record if needed. This can return null if the value
1160 /// exists but does not have the right type.
1161 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1163 PointerType *PTy = dyn_cast<PointerType>(Ty);
1165 Error(Loc, "global variable reference must have pointer type");
1169 // Look this name up in the normal function symbol table.
1171 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1173 // If this is a forward reference for the value, see if we already created a
1174 // forward ref record.
1176 auto I = ForwardRefVals.find(Name);
1177 if (I != ForwardRefVals.end())
1178 Val = I->second.first;
1181 // If we have the value in the symbol table or fwd-ref table, return it.
1183 if (Val->getType() == Ty) return Val;
1184 Error(Loc, "'@" + Name + "' defined with type '" +
1185 getTypeString(Val->getType()) + "'");
1189 // Otherwise, create a new forward reference for this value and remember it.
1190 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1191 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1195 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1196 PointerType *PTy = dyn_cast<PointerType>(Ty);
1198 Error(Loc, "global variable reference must have pointer type");
1202 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1204 // If this is a forward reference for the value, see if we already created a
1205 // forward ref record.
1207 auto I = ForwardRefValIDs.find(ID);
1208 if (I != ForwardRefValIDs.end())
1209 Val = I->second.first;
1212 // If we have the value in the symbol table or fwd-ref table, return it.
1214 if (Val->getType() == Ty) return Val;
1215 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1216 getTypeString(Val->getType()) + "'");
1220 // Otherwise, create a new forward reference for this value and remember it.
1221 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1222 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1226 //===----------------------------------------------------------------------===//
1227 // Comdat Reference/Resolution Routines.
1228 //===----------------------------------------------------------------------===//
1230 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1231 // Look this name up in the comdat symbol table.
1232 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1233 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1234 if (I != ComdatSymTab.end())
1237 // Otherwise, create a new forward reference for this value and remember it.
1238 Comdat *C = M->getOrInsertComdat(Name);
1239 ForwardRefComdats[Name] = Loc;
1243 //===----------------------------------------------------------------------===//
1245 //===----------------------------------------------------------------------===//
1247 /// ParseToken - If the current token has the specified kind, eat it and return
1248 /// success. Otherwise, emit the specified error and return failure.
1249 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1250 if (Lex.getKind() != T)
1251 return TokError(ErrMsg);
1256 /// ParseStringConstant
1257 /// ::= StringConstant
1258 bool LLParser::ParseStringConstant(std::string &Result) {
1259 if (Lex.getKind() != lltok::StringConstant)
1260 return TokError("expected string constant");
1261 Result = Lex.getStrVal();
1268 bool LLParser::ParseUInt32(uint32_t &Val) {
1269 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1270 return TokError("expected integer");
1271 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1272 if (Val64 != unsigned(Val64))
1273 return TokError("expected 32-bit integer (too large)");
1281 bool LLParser::ParseUInt64(uint64_t &Val) {
1282 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1283 return TokError("expected integer");
1284 Val = Lex.getAPSIntVal().getLimitedValue();
1290 /// := 'localdynamic'
1291 /// := 'initialexec'
1293 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1294 switch (Lex.getKind()) {
1296 return TokError("expected localdynamic, initialexec or localexec");
1297 case lltok::kw_localdynamic:
1298 TLM = GlobalVariable::LocalDynamicTLSModel;
1300 case lltok::kw_initialexec:
1301 TLM = GlobalVariable::InitialExecTLSModel;
1303 case lltok::kw_localexec:
1304 TLM = GlobalVariable::LocalExecTLSModel;
1312 /// ParseOptionalThreadLocal
1314 /// := 'thread_local'
1315 /// := 'thread_local' '(' tlsmodel ')'
1316 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1317 TLM = GlobalVariable::NotThreadLocal;
1318 if (!EatIfPresent(lltok::kw_thread_local))
1321 TLM = GlobalVariable::GeneralDynamicTLSModel;
1322 if (Lex.getKind() == lltok::lparen) {
1324 return ParseTLSModel(TLM) ||
1325 ParseToken(lltok::rparen, "expected ')' after thread local model");
1330 /// ParseOptionalAddrSpace
1332 /// := 'addrspace' '(' uint32 ')'
1333 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1335 if (!EatIfPresent(lltok::kw_addrspace))
1337 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1338 ParseUInt32(AddrSpace) ||
1339 ParseToken(lltok::rparen, "expected ')' in address space");
1342 /// ParseStringAttribute
1343 /// := StringConstant
1344 /// := StringConstant '=' StringConstant
1345 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1346 std::string Attr = Lex.getStrVal();
1349 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1351 B.addAttribute(Attr, Val);
1355 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1356 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1357 bool HaveError = false;
1362 lltok::Kind Token = Lex.getKind();
1364 default: // End of attributes.
1366 case lltok::StringConstant: {
1367 if (ParseStringAttribute(B))
1371 case lltok::kw_align: {
1373 if (ParseOptionalAlignment(Alignment))
1375 B.addAlignmentAttr(Alignment);
1378 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1379 case lltok::kw_dereferenceable: {
1381 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1383 B.addDereferenceableAttr(Bytes);
1386 case lltok::kw_dereferenceable_or_null: {
1388 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1390 B.addDereferenceableOrNullAttr(Bytes);
1393 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1394 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1395 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1396 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1397 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1398 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1399 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1400 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1401 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1402 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1403 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1404 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1405 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1406 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1407 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1409 case lltok::kw_alignstack:
1410 case lltok::kw_alwaysinline:
1411 case lltok::kw_argmemonly:
1412 case lltok::kw_builtin:
1413 case lltok::kw_inlinehint:
1414 case lltok::kw_jumptable:
1415 case lltok::kw_minsize:
1416 case lltok::kw_naked:
1417 case lltok::kw_nobuiltin:
1418 case lltok::kw_noduplicate:
1419 case lltok::kw_noimplicitfloat:
1420 case lltok::kw_noinline:
1421 case lltok::kw_nonlazybind:
1422 case lltok::kw_noredzone:
1423 case lltok::kw_noreturn:
1424 case lltok::kw_nounwind:
1425 case lltok::kw_optnone:
1426 case lltok::kw_optsize:
1427 case lltok::kw_returns_twice:
1428 case lltok::kw_sanitize_address:
1429 case lltok::kw_sanitize_memory:
1430 case lltok::kw_sanitize_thread:
1432 case lltok::kw_sspreq:
1433 case lltok::kw_sspstrong:
1434 case lltok::kw_safestack:
1435 case lltok::kw_uwtable:
1436 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1444 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1445 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1446 bool HaveError = false;
1451 lltok::Kind Token = Lex.getKind();
1453 default: // End of attributes.
1455 case lltok::StringConstant: {
1456 if (ParseStringAttribute(B))
1460 case lltok::kw_dereferenceable: {
1462 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1464 B.addDereferenceableAttr(Bytes);
1467 case lltok::kw_dereferenceable_or_null: {
1469 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1471 B.addDereferenceableOrNullAttr(Bytes);
1474 case lltok::kw_align: {
1476 if (ParseOptionalAlignment(Alignment))
1478 B.addAlignmentAttr(Alignment);
1481 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1482 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1483 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1484 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1485 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1488 case lltok::kw_byval:
1489 case lltok::kw_inalloca:
1490 case lltok::kw_nest:
1491 case lltok::kw_nocapture:
1492 case lltok::kw_returned:
1493 case lltok::kw_sret:
1494 case lltok::kw_swifterror:
1495 case lltok::kw_swiftself:
1496 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1499 case lltok::kw_alignstack:
1500 case lltok::kw_alwaysinline:
1501 case lltok::kw_argmemonly:
1502 case lltok::kw_builtin:
1503 case lltok::kw_cold:
1504 case lltok::kw_inlinehint:
1505 case lltok::kw_jumptable:
1506 case lltok::kw_minsize:
1507 case lltok::kw_naked:
1508 case lltok::kw_nobuiltin:
1509 case lltok::kw_noduplicate:
1510 case lltok::kw_noimplicitfloat:
1511 case lltok::kw_noinline:
1512 case lltok::kw_nonlazybind:
1513 case lltok::kw_noredzone:
1514 case lltok::kw_noreturn:
1515 case lltok::kw_nounwind:
1516 case lltok::kw_optnone:
1517 case lltok::kw_optsize:
1518 case lltok::kw_returns_twice:
1519 case lltok::kw_sanitize_address:
1520 case lltok::kw_sanitize_memory:
1521 case lltok::kw_sanitize_thread:
1523 case lltok::kw_sspreq:
1524 case lltok::kw_sspstrong:
1525 case lltok::kw_safestack:
1526 case lltok::kw_uwtable:
1527 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1530 case lltok::kw_readnone:
1531 case lltok::kw_readonly:
1532 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1539 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1544 return GlobalValue::ExternalLinkage;
1545 case lltok::kw_private:
1546 return GlobalValue::PrivateLinkage;
1547 case lltok::kw_internal:
1548 return GlobalValue::InternalLinkage;
1549 case lltok::kw_weak:
1550 return GlobalValue::WeakAnyLinkage;
1551 case lltok::kw_weak_odr:
1552 return GlobalValue::WeakODRLinkage;
1553 case lltok::kw_linkonce:
1554 return GlobalValue::LinkOnceAnyLinkage;
1555 case lltok::kw_linkonce_odr:
1556 return GlobalValue::LinkOnceODRLinkage;
1557 case lltok::kw_available_externally:
1558 return GlobalValue::AvailableExternallyLinkage;
1559 case lltok::kw_appending:
1560 return GlobalValue::AppendingLinkage;
1561 case lltok::kw_common:
1562 return GlobalValue::CommonLinkage;
1563 case lltok::kw_extern_weak:
1564 return GlobalValue::ExternalWeakLinkage;
1565 case lltok::kw_external:
1566 return GlobalValue::ExternalLinkage;
1570 /// ParseOptionalLinkage
1577 /// ::= 'linkonce_odr'
1578 /// ::= 'available_externally'
1581 /// ::= 'extern_weak'
1583 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1584 unsigned &Visibility,
1585 unsigned &DLLStorageClass) {
1586 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1589 ParseOptionalVisibility(Visibility);
1590 ParseOptionalDLLStorageClass(DLLStorageClass);
1594 /// ParseOptionalVisibility
1600 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1601 switch (Lex.getKind()) {
1603 Res = GlobalValue::DefaultVisibility;
1605 case lltok::kw_default:
1606 Res = GlobalValue::DefaultVisibility;
1608 case lltok::kw_hidden:
1609 Res = GlobalValue::HiddenVisibility;
1611 case lltok::kw_protected:
1612 Res = GlobalValue::ProtectedVisibility;
1618 /// ParseOptionalDLLStorageClass
1623 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1624 switch (Lex.getKind()) {
1626 Res = GlobalValue::DefaultStorageClass;
1628 case lltok::kw_dllimport:
1629 Res = GlobalValue::DLLImportStorageClass;
1631 case lltok::kw_dllexport:
1632 Res = GlobalValue::DLLExportStorageClass;
1638 /// ParseOptionalCallingConv
1642 /// ::= 'intel_ocl_bicc'
1644 /// ::= 'x86_stdcallcc'
1645 /// ::= 'x86_fastcallcc'
1646 /// ::= 'x86_thiscallcc'
1647 /// ::= 'x86_vectorcallcc'
1648 /// ::= 'arm_apcscc'
1649 /// ::= 'arm_aapcscc'
1650 /// ::= 'arm_aapcs_vfpcc'
1651 /// ::= 'msp430_intrcc'
1652 /// ::= 'avr_intrcc'
1653 /// ::= 'avr_signalcc'
1654 /// ::= 'ptx_kernel'
1655 /// ::= 'ptx_device'
1657 /// ::= 'spir_kernel'
1658 /// ::= 'x86_64_sysvcc'
1659 /// ::= 'x86_64_win64cc'
1660 /// ::= 'webkit_jscc'
1662 /// ::= 'preserve_mostcc'
1663 /// ::= 'preserve_allcc'
1666 /// ::= 'x86_intrcc'
1669 /// ::= 'cxx_fast_tlscc'
1675 /// ::= 'amdgpu_kernel'
1678 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1679 switch (Lex.getKind()) {
1680 default: CC = CallingConv::C; return false;
1681 case lltok::kw_ccc: CC = CallingConv::C; break;
1682 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1683 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1684 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1685 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1686 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1687 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1688 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1689 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1690 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1691 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1692 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1693 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1694 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1695 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1696 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1697 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1698 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1699 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1700 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1701 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1702 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1703 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1704 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1705 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1706 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1707 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1708 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1709 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1710 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1711 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1712 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1713 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1714 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1715 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1716 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1717 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1718 case lltok::kw_cc: {
1720 return ParseUInt32(CC);
1728 /// ParseMetadataAttachment
1730 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1731 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1733 std::string Name = Lex.getStrVal();
1734 Kind = M->getMDKindID(Name);
1737 return ParseMDNode(MD);
1740 /// ParseInstructionMetadata
1741 /// ::= !dbg !42 (',' !dbg !57)*
1742 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1744 if (Lex.getKind() != lltok::MetadataVar)
1745 return TokError("expected metadata after comma");
1749 if (ParseMetadataAttachment(MDK, N))
1752 Inst.setMetadata(MDK, N);
1753 if (MDK == LLVMContext::MD_tbaa)
1754 InstsWithTBAATag.push_back(&Inst);
1756 // If this is the end of the list, we're done.
1757 } while (EatIfPresent(lltok::comma));
1761 /// ParseGlobalObjectMetadataAttachment
1763 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1766 if (ParseMetadataAttachment(MDK, N))
1769 GO.addMetadata(MDK, *N);
1773 /// ParseOptionalFunctionMetadata
1775 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1776 while (Lex.getKind() == lltok::MetadataVar)
1777 if (ParseGlobalObjectMetadataAttachment(F))
1782 /// ParseOptionalAlignment
1785 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1787 if (!EatIfPresent(lltok::kw_align))
1789 LocTy AlignLoc = Lex.getLoc();
1790 if (ParseUInt32(Alignment)) return true;
1791 if (!isPowerOf2_32(Alignment))
1792 return Error(AlignLoc, "alignment is not a power of two");
1793 if (Alignment > Value::MaximumAlignment)
1794 return Error(AlignLoc, "huge alignments are not supported yet");
1798 /// ParseOptionalDerefAttrBytes
1800 /// ::= AttrKind '(' 4 ')'
1802 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1803 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1805 assert((AttrKind == lltok::kw_dereferenceable ||
1806 AttrKind == lltok::kw_dereferenceable_or_null) &&
1810 if (!EatIfPresent(AttrKind))
1812 LocTy ParenLoc = Lex.getLoc();
1813 if (!EatIfPresent(lltok::lparen))
1814 return Error(ParenLoc, "expected '('");
1815 LocTy DerefLoc = Lex.getLoc();
1816 if (ParseUInt64(Bytes)) return true;
1817 ParenLoc = Lex.getLoc();
1818 if (!EatIfPresent(lltok::rparen))
1819 return Error(ParenLoc, "expected ')'");
1821 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1825 /// ParseOptionalCommaAlign
1829 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1831 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1832 bool &AteExtraComma) {
1833 AteExtraComma = false;
1834 while (EatIfPresent(lltok::comma)) {
1835 // Metadata at the end is an early exit.
1836 if (Lex.getKind() == lltok::MetadataVar) {
1837 AteExtraComma = true;
1841 if (Lex.getKind() != lltok::kw_align)
1842 return Error(Lex.getLoc(), "expected metadata or 'align'");
1844 if (ParseOptionalAlignment(Alignment)) return true;
1850 /// ParseOptionalCommaAddrSpace
1852 /// ::= ',' addrspace(1)
1854 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1856 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1858 bool &AteExtraComma) {
1859 AteExtraComma = false;
1860 while (EatIfPresent(lltok::comma)) {
1861 // Metadata at the end is an early exit.
1862 if (Lex.getKind() == lltok::MetadataVar) {
1863 AteExtraComma = true;
1868 if (Lex.getKind() != lltok::kw_addrspace)
1869 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1871 if (ParseOptionalAddrSpace(AddrSpace))
1878 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1879 Optional<unsigned> &HowManyArg) {
1882 auto StartParen = Lex.getLoc();
1883 if (!EatIfPresent(lltok::lparen))
1884 return Error(StartParen, "expected '('");
1886 if (ParseUInt32(BaseSizeArg))
1889 if (EatIfPresent(lltok::comma)) {
1890 auto HowManyAt = Lex.getLoc();
1892 if (ParseUInt32(HowMany))
1894 if (HowMany == BaseSizeArg)
1895 return Error(HowManyAt,
1896 "'allocsize' indices can't refer to the same parameter");
1897 HowManyArg = HowMany;
1901 auto EndParen = Lex.getLoc();
1902 if (!EatIfPresent(lltok::rparen))
1903 return Error(EndParen, "expected ')'");
1907 /// ParseScopeAndOrdering
1908 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1911 /// This sets Scope and Ordering to the parsed values.
1912 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1913 AtomicOrdering &Ordering) {
1917 Scope = CrossThread;
1918 if (EatIfPresent(lltok::kw_singlethread))
1919 Scope = SingleThread;
1921 return ParseOrdering(Ordering);
1925 /// ::= AtomicOrdering
1927 /// This sets Ordering to the parsed value.
1928 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1929 switch (Lex.getKind()) {
1930 default: return TokError("Expected ordering on atomic instruction");
1931 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1932 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1933 // Not specified yet:
1934 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1935 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1936 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1937 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1938 case lltok::kw_seq_cst:
1939 Ordering = AtomicOrdering::SequentiallyConsistent;
1946 /// ParseOptionalStackAlignment
1948 /// ::= 'alignstack' '(' 4 ')'
1949 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1951 if (!EatIfPresent(lltok::kw_alignstack))
1953 LocTy ParenLoc = Lex.getLoc();
1954 if (!EatIfPresent(lltok::lparen))
1955 return Error(ParenLoc, "expected '('");
1956 LocTy AlignLoc = Lex.getLoc();
1957 if (ParseUInt32(Alignment)) return true;
1958 ParenLoc = Lex.getLoc();
1959 if (!EatIfPresent(lltok::rparen))
1960 return Error(ParenLoc, "expected ')'");
1961 if (!isPowerOf2_32(Alignment))
1962 return Error(AlignLoc, "stack alignment is not a power of two");
1966 /// ParseIndexList - This parses the index list for an insert/extractvalue
1967 /// instruction. This sets AteExtraComma in the case where we eat an extra
1968 /// comma at the end of the line and find that it is followed by metadata.
1969 /// Clients that don't allow metadata can call the version of this function that
1970 /// only takes one argument.
1973 /// ::= (',' uint32)+
1975 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1976 bool &AteExtraComma) {
1977 AteExtraComma = false;
1979 if (Lex.getKind() != lltok::comma)
1980 return TokError("expected ',' as start of index list");
1982 while (EatIfPresent(lltok::comma)) {
1983 if (Lex.getKind() == lltok::MetadataVar) {
1984 if (Indices.empty()) return TokError("expected index");
1985 AteExtraComma = true;
1989 if (ParseUInt32(Idx)) return true;
1990 Indices.push_back(Idx);
1996 //===----------------------------------------------------------------------===//
1998 //===----------------------------------------------------------------------===//
2000 /// ParseType - Parse a type.
2001 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2002 SMLoc TypeLoc = Lex.getLoc();
2003 switch (Lex.getKind()) {
2005 return TokError(Msg);
2007 // Type ::= 'float' | 'void' (etc)
2008 Result = Lex.getTyVal();
2012 // Type ::= StructType
2013 if (ParseAnonStructType(Result, false))
2016 case lltok::lsquare:
2017 // Type ::= '[' ... ']'
2018 Lex.Lex(); // eat the lsquare.
2019 if (ParseArrayVectorType(Result, false))
2022 case lltok::less: // Either vector or packed struct.
2023 // Type ::= '<' ... '>'
2025 if (Lex.getKind() == lltok::lbrace) {
2026 if (ParseAnonStructType(Result, true) ||
2027 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2029 } else if (ParseArrayVectorType(Result, true))
2032 case lltok::LocalVar: {
2034 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2036 // If the type hasn't been defined yet, create a forward definition and
2037 // remember where that forward def'n was seen (in case it never is defined).
2039 Entry.first = StructType::create(Context, Lex.getStrVal());
2040 Entry.second = Lex.getLoc();
2042 Result = Entry.first;
2047 case lltok::LocalVarID: {
2049 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2051 // If the type hasn't been defined yet, create a forward definition and
2052 // remember where that forward def'n was seen (in case it never is defined).
2054 Entry.first = StructType::create(Context);
2055 Entry.second = Lex.getLoc();
2057 Result = Entry.first;
2063 // Parse the type suffixes.
2065 switch (Lex.getKind()) {
2068 if (!AllowVoid && Result->isVoidTy())
2069 return Error(TypeLoc, "void type only allowed for function results");
2072 // Type ::= Type '*'
2074 if (Result->isLabelTy())
2075 return TokError("basic block pointers are invalid");
2076 if (Result->isVoidTy())
2077 return TokError("pointers to void are invalid - use i8* instead");
2078 if (!PointerType::isValidElementType(Result))
2079 return TokError("pointer to this type is invalid");
2080 Result = PointerType::getUnqual(Result);
2084 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2085 case lltok::kw_addrspace: {
2086 if (Result->isLabelTy())
2087 return TokError("basic block pointers are invalid");
2088 if (Result->isVoidTy())
2089 return TokError("pointers to void are invalid; use i8* instead");
2090 if (!PointerType::isValidElementType(Result))
2091 return TokError("pointer to this type is invalid");
2093 if (ParseOptionalAddrSpace(AddrSpace) ||
2094 ParseToken(lltok::star, "expected '*' in address space"))
2097 Result = PointerType::get(Result, AddrSpace);
2101 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2103 if (ParseFunctionType(Result))
2110 /// ParseParameterList
2112 /// ::= '(' Arg (',' Arg)* ')'
2114 /// ::= Type OptionalAttributes Value OptionalAttributes
2115 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2116 PerFunctionState &PFS, bool IsMustTailCall,
2117 bool InVarArgsFunc) {
2118 if (ParseToken(lltok::lparen, "expected '(' in call"))
2121 while (Lex.getKind() != lltok::rparen) {
2122 // If this isn't the first argument, we need a comma.
2123 if (!ArgList.empty() &&
2124 ParseToken(lltok::comma, "expected ',' in argument list"))
2127 // Parse an ellipsis if this is a musttail call in a variadic function.
2128 if (Lex.getKind() == lltok::dotdotdot) {
2129 const char *Msg = "unexpected ellipsis in argument list for ";
2130 if (!IsMustTailCall)
2131 return TokError(Twine(Msg) + "non-musttail call");
2133 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2134 Lex.Lex(); // Lex the '...', it is purely for readability.
2135 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2138 // Parse the argument.
2140 Type *ArgTy = nullptr;
2141 AttrBuilder ArgAttrs;
2143 if (ParseType(ArgTy, ArgLoc))
2146 if (ArgTy->isMetadataTy()) {
2147 if (ParseMetadataAsValue(V, PFS))
2150 // Otherwise, handle normal operands.
2151 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2154 ArgList.push_back(ParamInfo(
2155 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2158 if (IsMustTailCall && InVarArgsFunc)
2159 return TokError("expected '...' at end of argument list for musttail call "
2160 "in varargs function");
2162 Lex.Lex(); // Lex the ')'.
2166 /// ParseOptionalOperandBundles
2168 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2171 /// ::= bundle-tag '(' ')'
2172 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2174 /// bundle-tag ::= String Constant
2175 bool LLParser::ParseOptionalOperandBundles(
2176 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2177 LocTy BeginLoc = Lex.getLoc();
2178 if (!EatIfPresent(lltok::lsquare))
2181 while (Lex.getKind() != lltok::rsquare) {
2182 // If this isn't the first operand bundle, we need a comma.
2183 if (!BundleList.empty() &&
2184 ParseToken(lltok::comma, "expected ',' in input list"))
2188 if (ParseStringConstant(Tag))
2191 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2194 std::vector<Value *> Inputs;
2195 while (Lex.getKind() != lltok::rparen) {
2196 // If this isn't the first input, we need a comma.
2197 if (!Inputs.empty() &&
2198 ParseToken(lltok::comma, "expected ',' in input list"))
2202 Value *Input = nullptr;
2203 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2205 Inputs.push_back(Input);
2208 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2210 Lex.Lex(); // Lex the ')'.
2213 if (BundleList.empty())
2214 return Error(BeginLoc, "operand bundle set must not be empty");
2216 Lex.Lex(); // Lex the ']'.
2220 /// ParseArgumentList - Parse the argument list for a function type or function
2222 /// ::= '(' ArgTypeListI ')'
2226 /// ::= ArgTypeList ',' '...'
2227 /// ::= ArgType (',' ArgType)*
2229 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2232 assert(Lex.getKind() == lltok::lparen);
2233 Lex.Lex(); // eat the (.
2235 if (Lex.getKind() == lltok::rparen) {
2237 } else if (Lex.getKind() == lltok::dotdotdot) {
2241 LocTy TypeLoc = Lex.getLoc();
2242 Type *ArgTy = nullptr;
2246 if (ParseType(ArgTy) ||
2247 ParseOptionalParamAttrs(Attrs)) return true;
2249 if (ArgTy->isVoidTy())
2250 return Error(TypeLoc, "argument can not have void type");
2252 if (Lex.getKind() == lltok::LocalVar) {
2253 Name = Lex.getStrVal();
2257 if (!FunctionType::isValidArgumentType(ArgTy))
2258 return Error(TypeLoc, "invalid type for function argument");
2260 ArgList.emplace_back(TypeLoc, ArgTy,
2261 AttributeSet::get(ArgTy->getContext(), Attrs),
2264 while (EatIfPresent(lltok::comma)) {
2265 // Handle ... at end of arg list.
2266 if (EatIfPresent(lltok::dotdotdot)) {
2271 // Otherwise must be an argument type.
2272 TypeLoc = Lex.getLoc();
2273 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2275 if (ArgTy->isVoidTy())
2276 return Error(TypeLoc, "argument can not have void type");
2278 if (Lex.getKind() == lltok::LocalVar) {
2279 Name = Lex.getStrVal();
2285 if (!ArgTy->isFirstClassType())
2286 return Error(TypeLoc, "invalid type for function argument");
2288 ArgList.emplace_back(TypeLoc, ArgTy,
2289 AttributeSet::get(ArgTy->getContext(), Attrs),
2294 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2297 /// ParseFunctionType
2298 /// ::= Type ArgumentList OptionalAttrs
2299 bool LLParser::ParseFunctionType(Type *&Result) {
2300 assert(Lex.getKind() == lltok::lparen);
2302 if (!FunctionType::isValidReturnType(Result))
2303 return TokError("invalid function return type");
2305 SmallVector<ArgInfo, 8> ArgList;
2307 if (ParseArgumentList(ArgList, isVarArg))
2310 // Reject names on the arguments lists.
2311 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2312 if (!ArgList[i].Name.empty())
2313 return Error(ArgList[i].Loc, "argument name invalid in function type");
2314 if (ArgList[i].Attrs.hasAttributes())
2315 return Error(ArgList[i].Loc,
2316 "argument attributes invalid in function type");
2319 SmallVector<Type*, 16> ArgListTy;
2320 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2321 ArgListTy.push_back(ArgList[i].Ty);
2323 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2327 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2329 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2330 SmallVector<Type*, 8> Elts;
2331 if (ParseStructBody(Elts)) return true;
2333 Result = StructType::get(Context, Elts, Packed);
2337 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2338 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2339 std::pair<Type*, LocTy> &Entry,
2341 // If the type was already defined, diagnose the redefinition.
2342 if (Entry.first && !Entry.second.isValid())
2343 return Error(TypeLoc, "redefinition of type");
2345 // If we have opaque, just return without filling in the definition for the
2346 // struct. This counts as a definition as far as the .ll file goes.
2347 if (EatIfPresent(lltok::kw_opaque)) {
2348 // This type is being defined, so clear the location to indicate this.
2349 Entry.second = SMLoc();
2351 // If this type number has never been uttered, create it.
2353 Entry.first = StructType::create(Context, Name);
2354 ResultTy = Entry.first;
2358 // If the type starts with '<', then it is either a packed struct or a vector.
2359 bool isPacked = EatIfPresent(lltok::less);
2361 // If we don't have a struct, then we have a random type alias, which we
2362 // accept for compatibility with old files. These types are not allowed to be
2363 // forward referenced and not allowed to be recursive.
2364 if (Lex.getKind() != lltok::lbrace) {
2366 return Error(TypeLoc, "forward references to non-struct type");
2370 return ParseArrayVectorType(ResultTy, true);
2371 return ParseType(ResultTy);
2374 // This type is being defined, so clear the location to indicate this.
2375 Entry.second = SMLoc();
2377 // If this type number has never been uttered, create it.
2379 Entry.first = StructType::create(Context, Name);
2381 StructType *STy = cast<StructType>(Entry.first);
2383 SmallVector<Type*, 8> Body;
2384 if (ParseStructBody(Body) ||
2385 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2388 STy->setBody(Body, isPacked);
2393 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2396 /// ::= '{' Type (',' Type)* '}'
2397 /// ::= '<' '{' '}' '>'
2398 /// ::= '<' '{' Type (',' Type)* '}' '>'
2399 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2400 assert(Lex.getKind() == lltok::lbrace);
2401 Lex.Lex(); // Consume the '{'
2403 // Handle the empty struct.
2404 if (EatIfPresent(lltok::rbrace))
2407 LocTy EltTyLoc = Lex.getLoc();
2409 if (ParseType(Ty)) return true;
2412 if (!StructType::isValidElementType(Ty))
2413 return Error(EltTyLoc, "invalid element type for struct");
2415 while (EatIfPresent(lltok::comma)) {
2416 EltTyLoc = Lex.getLoc();
2417 if (ParseType(Ty)) return true;
2419 if (!StructType::isValidElementType(Ty))
2420 return Error(EltTyLoc, "invalid element type for struct");
2425 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2428 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2429 /// token has already been consumed.
2431 /// ::= '[' APSINTVAL 'x' Types ']'
2432 /// ::= '<' APSINTVAL 'x' Types '>'
2433 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2434 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2435 Lex.getAPSIntVal().getBitWidth() > 64)
2436 return TokError("expected number in address space");
2438 LocTy SizeLoc = Lex.getLoc();
2439 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2442 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2445 LocTy TypeLoc = Lex.getLoc();
2446 Type *EltTy = nullptr;
2447 if (ParseType(EltTy)) return true;
2449 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2450 "expected end of sequential type"))
2455 return Error(SizeLoc, "zero element vector is illegal");
2456 if ((unsigned)Size != Size)
2457 return Error(SizeLoc, "size too large for vector");
2458 if (!VectorType::isValidElementType(EltTy))
2459 return Error(TypeLoc, "invalid vector element type");
2460 Result = VectorType::get(EltTy, unsigned(Size));
2462 if (!ArrayType::isValidElementType(EltTy))
2463 return Error(TypeLoc, "invalid array element type");
2464 Result = ArrayType::get(EltTy, Size);
2469 //===----------------------------------------------------------------------===//
2470 // Function Semantic Analysis.
2471 //===----------------------------------------------------------------------===//
2473 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2475 : P(p), F(f), FunctionNumber(functionNumber) {
2477 // Insert unnamed arguments into the NumberedVals list.
2478 for (Argument &A : F.args())
2480 NumberedVals.push_back(&A);
2483 LLParser::PerFunctionState::~PerFunctionState() {
2484 // If there were any forward referenced non-basicblock values, delete them.
2486 for (const auto &P : ForwardRefVals) {
2487 if (isa<BasicBlock>(P.second.first))
2489 P.second.first->replaceAllUsesWith(
2490 UndefValue::get(P.second.first->getType()));
2491 delete P.second.first;
2494 for (const auto &P : ForwardRefValIDs) {
2495 if (isa<BasicBlock>(P.second.first))
2497 P.second.first->replaceAllUsesWith(
2498 UndefValue::get(P.second.first->getType()));
2499 delete P.second.first;
2503 bool LLParser::PerFunctionState::FinishFunction() {
2504 if (!ForwardRefVals.empty())
2505 return P.Error(ForwardRefVals.begin()->second.second,
2506 "use of undefined value '%" + ForwardRefVals.begin()->first +
2508 if (!ForwardRefValIDs.empty())
2509 return P.Error(ForwardRefValIDs.begin()->second.second,
2510 "use of undefined value '%" +
2511 Twine(ForwardRefValIDs.begin()->first) + "'");
2515 /// GetVal - Get a value with the specified name or ID, creating a
2516 /// forward reference record if needed. This can return null if the value
2517 /// exists but does not have the right type.
2518 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2520 // Look this name up in the normal function symbol table.
2521 Value *Val = F.getValueSymbolTable()->lookup(Name);
2523 // If this is a forward reference for the value, see if we already created a
2524 // forward ref record.
2526 auto I = ForwardRefVals.find(Name);
2527 if (I != ForwardRefVals.end())
2528 Val = I->second.first;
2531 // If we have the value in the symbol table or fwd-ref table, return it.
2533 if (Val->getType() == Ty) return Val;
2534 if (Ty->isLabelTy())
2535 P.Error(Loc, "'%" + Name + "' is not a basic block");
2537 P.Error(Loc, "'%" + Name + "' defined with type '" +
2538 getTypeString(Val->getType()) + "'");
2542 // Don't make placeholders with invalid type.
2543 if (!Ty->isFirstClassType()) {
2544 P.Error(Loc, "invalid use of a non-first-class type");
2548 // Otherwise, create a new forward reference for this value and remember it.
2550 if (Ty->isLabelTy()) {
2551 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2553 FwdVal = new Argument(Ty, Name);
2556 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2560 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2561 // Look this name up in the normal function symbol table.
2562 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2564 // If this is a forward reference for the value, see if we already created a
2565 // forward ref record.
2567 auto I = ForwardRefValIDs.find(ID);
2568 if (I != ForwardRefValIDs.end())
2569 Val = I->second.first;
2572 // If we have the value in the symbol table or fwd-ref table, return it.
2574 if (Val->getType() == Ty) return Val;
2575 if (Ty->isLabelTy())
2576 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2578 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2579 getTypeString(Val->getType()) + "'");
2583 if (!Ty->isFirstClassType()) {
2584 P.Error(Loc, "invalid use of a non-first-class type");
2588 // Otherwise, create a new forward reference for this value and remember it.
2590 if (Ty->isLabelTy()) {
2591 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2593 FwdVal = new Argument(Ty);
2596 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2600 /// SetInstName - After an instruction is parsed and inserted into its
2601 /// basic block, this installs its name.
2602 bool LLParser::PerFunctionState::SetInstName(int NameID,
2603 const std::string &NameStr,
2604 LocTy NameLoc, Instruction *Inst) {
2605 // If this instruction has void type, it cannot have a name or ID specified.
2606 if (Inst->getType()->isVoidTy()) {
2607 if (NameID != -1 || !NameStr.empty())
2608 return P.Error(NameLoc, "instructions returning void cannot have a name");
2612 // If this was a numbered instruction, verify that the instruction is the
2613 // expected value and resolve any forward references.
2614 if (NameStr.empty()) {
2615 // If neither a name nor an ID was specified, just use the next ID.
2617 NameID = NumberedVals.size();
2619 if (unsigned(NameID) != NumberedVals.size())
2620 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2621 Twine(NumberedVals.size()) + "'");
2623 auto FI = ForwardRefValIDs.find(NameID);
2624 if (FI != ForwardRefValIDs.end()) {
2625 Value *Sentinel = FI->second.first;
2626 if (Sentinel->getType() != Inst->getType())
2627 return P.Error(NameLoc, "instruction forward referenced with type '" +
2628 getTypeString(FI->second.first->getType()) + "'");
2630 Sentinel->replaceAllUsesWith(Inst);
2632 ForwardRefValIDs.erase(FI);
2635 NumberedVals.push_back(Inst);
2639 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2640 auto FI = ForwardRefVals.find(NameStr);
2641 if (FI != ForwardRefVals.end()) {
2642 Value *Sentinel = FI->second.first;
2643 if (Sentinel->getType() != Inst->getType())
2644 return P.Error(NameLoc, "instruction forward referenced with type '" +
2645 getTypeString(FI->second.first->getType()) + "'");
2647 Sentinel->replaceAllUsesWith(Inst);
2649 ForwardRefVals.erase(FI);
2652 // Set the name on the instruction.
2653 Inst->setName(NameStr);
2655 if (Inst->getName() != NameStr)
2656 return P.Error(NameLoc, "multiple definition of local value named '" +
2661 /// GetBB - Get a basic block with the specified name or ID, creating a
2662 /// forward reference record if needed.
2663 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2665 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2666 Type::getLabelTy(F.getContext()), Loc));
2669 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2670 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2671 Type::getLabelTy(F.getContext()), Loc));
2674 /// DefineBB - Define the specified basic block, which is either named or
2675 /// unnamed. If there is an error, this returns null otherwise it returns
2676 /// the block being defined.
2677 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2681 BB = GetBB(NumberedVals.size(), Loc);
2683 BB = GetBB(Name, Loc);
2684 if (!BB) return nullptr; // Already diagnosed error.
2686 // Move the block to the end of the function. Forward ref'd blocks are
2687 // inserted wherever they happen to be referenced.
2688 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2690 // Remove the block from forward ref sets.
2692 ForwardRefValIDs.erase(NumberedVals.size());
2693 NumberedVals.push_back(BB);
2695 // BB forward references are already in the function symbol table.
2696 ForwardRefVals.erase(Name);
2702 //===----------------------------------------------------------------------===//
2704 //===----------------------------------------------------------------------===//
2706 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2707 /// type implied. For example, if we parse "4" we don't know what integer type
2708 /// it has. The value will later be combined with its type and checked for
2709 /// sanity. PFS is used to convert function-local operands of metadata (since
2710 /// metadata operands are not just parsed here but also converted to values).
2711 /// PFS can be null when we are not parsing metadata values inside a function.
2712 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2713 ID.Loc = Lex.getLoc();
2714 switch (Lex.getKind()) {
2715 default: return TokError("expected value token");
2716 case lltok::GlobalID: // @42
2717 ID.UIntVal = Lex.getUIntVal();
2718 ID.Kind = ValID::t_GlobalID;
2720 case lltok::GlobalVar: // @foo
2721 ID.StrVal = Lex.getStrVal();
2722 ID.Kind = ValID::t_GlobalName;
2724 case lltok::LocalVarID: // %42
2725 ID.UIntVal = Lex.getUIntVal();
2726 ID.Kind = ValID::t_LocalID;
2728 case lltok::LocalVar: // %foo
2729 ID.StrVal = Lex.getStrVal();
2730 ID.Kind = ValID::t_LocalName;
2733 ID.APSIntVal = Lex.getAPSIntVal();
2734 ID.Kind = ValID::t_APSInt;
2736 case lltok::APFloat:
2737 ID.APFloatVal = Lex.getAPFloatVal();
2738 ID.Kind = ValID::t_APFloat;
2740 case lltok::kw_true:
2741 ID.ConstantVal = ConstantInt::getTrue(Context);
2742 ID.Kind = ValID::t_Constant;
2744 case lltok::kw_false:
2745 ID.ConstantVal = ConstantInt::getFalse(Context);
2746 ID.Kind = ValID::t_Constant;
2748 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2749 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2750 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2751 case lltok::kw_none: ID.Kind = ValID::t_None; break;
2753 case lltok::lbrace: {
2754 // ValID ::= '{' ConstVector '}'
2756 SmallVector<Constant*, 16> Elts;
2757 if (ParseGlobalValueVector(Elts) ||
2758 ParseToken(lltok::rbrace, "expected end of struct constant"))
2761 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2762 ID.UIntVal = Elts.size();
2763 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2764 Elts.size() * sizeof(Elts[0]));
2765 ID.Kind = ValID::t_ConstantStruct;
2769 // ValID ::= '<' ConstVector '>' --> Vector.
2770 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2772 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2774 SmallVector<Constant*, 16> Elts;
2775 LocTy FirstEltLoc = Lex.getLoc();
2776 if (ParseGlobalValueVector(Elts) ||
2778 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2779 ParseToken(lltok::greater, "expected end of constant"))
2782 if (isPackedStruct) {
2783 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2784 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2785 Elts.size() * sizeof(Elts[0]));
2786 ID.UIntVal = Elts.size();
2787 ID.Kind = ValID::t_PackedConstantStruct;
2792 return Error(ID.Loc, "constant vector must not be empty");
2794 if (!Elts[0]->getType()->isIntegerTy() &&
2795 !Elts[0]->getType()->isFloatingPointTy() &&
2796 !Elts[0]->getType()->isPointerTy())
2797 return Error(FirstEltLoc,
2798 "vector elements must have integer, pointer or floating point type");
2800 // Verify that all the vector elements have the same type.
2801 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2802 if (Elts[i]->getType() != Elts[0]->getType())
2803 return Error(FirstEltLoc,
2804 "vector element #" + Twine(i) +
2805 " is not of type '" + getTypeString(Elts[0]->getType()));
2807 ID.ConstantVal = ConstantVector::get(Elts);
2808 ID.Kind = ValID::t_Constant;
2811 case lltok::lsquare: { // Array Constant
2813 SmallVector<Constant*, 16> Elts;
2814 LocTy FirstEltLoc = Lex.getLoc();
2815 if (ParseGlobalValueVector(Elts) ||
2816 ParseToken(lltok::rsquare, "expected end of array constant"))
2819 // Handle empty element.
2821 // Use undef instead of an array because it's inconvenient to determine
2822 // the element type at this point, there being no elements to examine.
2823 ID.Kind = ValID::t_EmptyArray;
2827 if (!Elts[0]->getType()->isFirstClassType())
2828 return Error(FirstEltLoc, "invalid array element type: " +
2829 getTypeString(Elts[0]->getType()));
2831 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2833 // Verify all elements are correct type!
2834 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2835 if (Elts[i]->getType() != Elts[0]->getType())
2836 return Error(FirstEltLoc,
2837 "array element #" + Twine(i) +
2838 " is not of type '" + getTypeString(Elts[0]->getType()));
2841 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2842 ID.Kind = ValID::t_Constant;
2845 case lltok::kw_c: // c "foo"
2847 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2849 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2850 ID.Kind = ValID::t_Constant;
2853 case lltok::kw_asm: {
2854 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2856 bool HasSideEffect, AlignStack, AsmDialect;
2858 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2859 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2860 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2861 ParseStringConstant(ID.StrVal) ||
2862 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2863 ParseToken(lltok::StringConstant, "expected constraint string"))
2865 ID.StrVal2 = Lex.getStrVal();
2866 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2867 (unsigned(AsmDialect)<<2);
2868 ID.Kind = ValID::t_InlineAsm;
2872 case lltok::kw_blockaddress: {
2873 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2878 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2880 ParseToken(lltok::comma, "expected comma in block address expression")||
2881 ParseValID(Label) ||
2882 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2885 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2886 return Error(Fn.Loc, "expected function name in blockaddress");
2887 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2888 return Error(Label.Loc, "expected basic block name in blockaddress");
2890 // Try to find the function (but skip it if it's forward-referenced).
2891 GlobalValue *GV = nullptr;
2892 if (Fn.Kind == ValID::t_GlobalID) {
2893 if (Fn.UIntVal < NumberedVals.size())
2894 GV = NumberedVals[Fn.UIntVal];
2895 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2896 GV = M->getNamedValue(Fn.StrVal);
2898 Function *F = nullptr;
2900 // Confirm that it's actually a function with a definition.
2901 if (!isa<Function>(GV))
2902 return Error(Fn.Loc, "expected function name in blockaddress");
2903 F = cast<Function>(GV);
2904 if (F->isDeclaration())
2905 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2909 // Make a global variable as a placeholder for this reference.
2910 GlobalValue *&FwdRef =
2911 ForwardRefBlockAddresses.insert(std::make_pair(
2913 std::map<ValID, GlobalValue *>()))
2914 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2917 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2918 GlobalValue::InternalLinkage, nullptr, "");
2919 ID.ConstantVal = FwdRef;
2920 ID.Kind = ValID::t_Constant;
2924 // We found the function; now find the basic block. Don't use PFS, since we
2925 // might be inside a constant expression.
2927 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2928 if (Label.Kind == ValID::t_LocalID)
2929 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2931 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2933 return Error(Label.Loc, "referenced value is not a basic block");
2935 if (Label.Kind == ValID::t_LocalID)
2936 return Error(Label.Loc, "cannot take address of numeric label after "
2937 "the function is defined");
2938 BB = dyn_cast_or_null<BasicBlock>(
2939 F->getValueSymbolTable()->lookup(Label.StrVal));
2941 return Error(Label.Loc, "referenced value is not a basic block");
2944 ID.ConstantVal = BlockAddress::get(F, BB);
2945 ID.Kind = ValID::t_Constant;
2949 case lltok::kw_trunc:
2950 case lltok::kw_zext:
2951 case lltok::kw_sext:
2952 case lltok::kw_fptrunc:
2953 case lltok::kw_fpext:
2954 case lltok::kw_bitcast:
2955 case lltok::kw_addrspacecast:
2956 case lltok::kw_uitofp:
2957 case lltok::kw_sitofp:
2958 case lltok::kw_fptoui:
2959 case lltok::kw_fptosi:
2960 case lltok::kw_inttoptr:
2961 case lltok::kw_ptrtoint: {
2962 unsigned Opc = Lex.getUIntVal();
2963 Type *DestTy = nullptr;
2966 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2967 ParseGlobalTypeAndValue(SrcVal) ||
2968 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2969 ParseType(DestTy) ||
2970 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2972 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2973 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2974 getTypeString(SrcVal->getType()) + "' to '" +
2975 getTypeString(DestTy) + "'");
2976 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2978 ID.Kind = ValID::t_Constant;
2981 case lltok::kw_extractvalue: {
2984 SmallVector<unsigned, 4> Indices;
2985 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2986 ParseGlobalTypeAndValue(Val) ||
2987 ParseIndexList(Indices) ||
2988 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2991 if (!Val->getType()->isAggregateType())
2992 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2993 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2994 return Error(ID.Loc, "invalid indices for extractvalue");
2995 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2996 ID.Kind = ValID::t_Constant;
2999 case lltok::kw_insertvalue: {
3001 Constant *Val0, *Val1;
3002 SmallVector<unsigned, 4> Indices;
3003 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3004 ParseGlobalTypeAndValue(Val0) ||
3005 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3006 ParseGlobalTypeAndValue(Val1) ||
3007 ParseIndexList(Indices) ||
3008 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3010 if (!Val0->getType()->isAggregateType())
3011 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3013 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3015 return Error(ID.Loc, "invalid indices for insertvalue");
3016 if (IndexedType != Val1->getType())
3017 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3018 getTypeString(Val1->getType()) +
3019 "' instead of '" + getTypeString(IndexedType) +
3021 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3022 ID.Kind = ValID::t_Constant;
3025 case lltok::kw_icmp:
3026 case lltok::kw_fcmp: {
3027 unsigned PredVal, Opc = Lex.getUIntVal();
3028 Constant *Val0, *Val1;
3030 if (ParseCmpPredicate(PredVal, Opc) ||
3031 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3032 ParseGlobalTypeAndValue(Val0) ||
3033 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3034 ParseGlobalTypeAndValue(Val1) ||
3035 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3038 if (Val0->getType() != Val1->getType())
3039 return Error(ID.Loc, "compare operands must have the same type");
3041 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3043 if (Opc == Instruction::FCmp) {
3044 if (!Val0->getType()->isFPOrFPVectorTy())
3045 return Error(ID.Loc, "fcmp requires floating point operands");
3046 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3048 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3049 if (!Val0->getType()->isIntOrIntVectorTy() &&
3050 !Val0->getType()->getScalarType()->isPointerTy())
3051 return Error(ID.Loc, "icmp requires pointer or integer operands");
3052 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3054 ID.Kind = ValID::t_Constant;
3058 // Binary Operators.
3060 case lltok::kw_fadd:
3062 case lltok::kw_fsub:
3064 case lltok::kw_fmul:
3065 case lltok::kw_udiv:
3066 case lltok::kw_sdiv:
3067 case lltok::kw_fdiv:
3068 case lltok::kw_urem:
3069 case lltok::kw_srem:
3070 case lltok::kw_frem:
3072 case lltok::kw_lshr:
3073 case lltok::kw_ashr: {
3077 unsigned Opc = Lex.getUIntVal();
3078 Constant *Val0, *Val1;
3080 LocTy ModifierLoc = Lex.getLoc();
3081 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3082 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3083 if (EatIfPresent(lltok::kw_nuw))
3085 if (EatIfPresent(lltok::kw_nsw)) {
3087 if (EatIfPresent(lltok::kw_nuw))
3090 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3091 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3092 if (EatIfPresent(lltok::kw_exact))
3095 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3096 ParseGlobalTypeAndValue(Val0) ||
3097 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3098 ParseGlobalTypeAndValue(Val1) ||
3099 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3101 if (Val0->getType() != Val1->getType())
3102 return Error(ID.Loc, "operands of constexpr must have same type");
3103 if (!Val0->getType()->isIntOrIntVectorTy()) {
3105 return Error(ModifierLoc, "nuw only applies to integer operations");
3107 return Error(ModifierLoc, "nsw only applies to integer operations");
3109 // Check that the type is valid for the operator.
3111 case Instruction::Add:
3112 case Instruction::Sub:
3113 case Instruction::Mul:
3114 case Instruction::UDiv:
3115 case Instruction::SDiv:
3116 case Instruction::URem:
3117 case Instruction::SRem:
3118 case Instruction::Shl:
3119 case Instruction::AShr:
3120 case Instruction::LShr:
3121 if (!Val0->getType()->isIntOrIntVectorTy())
3122 return Error(ID.Loc, "constexpr requires integer operands");
3124 case Instruction::FAdd:
3125 case Instruction::FSub:
3126 case Instruction::FMul:
3127 case Instruction::FDiv:
3128 case Instruction::FRem:
3129 if (!Val0->getType()->isFPOrFPVectorTy())
3130 return Error(ID.Loc, "constexpr requires fp operands");
3132 default: llvm_unreachable("Unknown binary operator!");
3135 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3136 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3137 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3138 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3140 ID.Kind = ValID::t_Constant;
3144 // Logical Operations
3147 case lltok::kw_xor: {
3148 unsigned Opc = Lex.getUIntVal();
3149 Constant *Val0, *Val1;
3151 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3152 ParseGlobalTypeAndValue(Val0) ||
3153 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3154 ParseGlobalTypeAndValue(Val1) ||
3155 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3157 if (Val0->getType() != Val1->getType())
3158 return Error(ID.Loc, "operands of constexpr must have same type");
3159 if (!Val0->getType()->isIntOrIntVectorTy())
3160 return Error(ID.Loc,
3161 "constexpr requires integer or integer vector operands");
3162 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3163 ID.Kind = ValID::t_Constant;
3167 case lltok::kw_getelementptr:
3168 case lltok::kw_shufflevector:
3169 case lltok::kw_insertelement:
3170 case lltok::kw_extractelement:
3171 case lltok::kw_select: {
3172 unsigned Opc = Lex.getUIntVal();
3173 SmallVector<Constant*, 16> Elts;
3174 bool InBounds = false;
3178 if (Opc == Instruction::GetElementPtr)
3179 InBounds = EatIfPresent(lltok::kw_inbounds);
3181 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3184 LocTy ExplicitTypeLoc = Lex.getLoc();
3185 if (Opc == Instruction::GetElementPtr) {
3186 if (ParseType(Ty) ||
3187 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3191 Optional<unsigned> InRangeOp;
3192 if (ParseGlobalValueVector(
3193 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3194 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3197 if (Opc == Instruction::GetElementPtr) {
3198 if (Elts.size() == 0 ||
3199 !Elts[0]->getType()->getScalarType()->isPointerTy())
3200 return Error(ID.Loc, "base of getelementptr must be a pointer");
3202 Type *BaseType = Elts[0]->getType();
3203 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3204 if (Ty != BasePointerType->getElementType())
3207 "explicit pointee type doesn't match operand's pointee type");
3210 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3212 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3213 for (Constant *Val : Indices) {
3214 Type *ValTy = Val->getType();
3215 if (!ValTy->getScalarType()->isIntegerTy())
3216 return Error(ID.Loc, "getelementptr index must be an integer");
3217 if (ValTy->isVectorTy()) {
3218 unsigned ValNumEl = ValTy->getVectorNumElements();
3219 if (GEPWidth && (ValNumEl != GEPWidth))
3222 "getelementptr vector index has a wrong number of elements");
3223 // GEPWidth may have been unknown because the base is a scalar,
3224 // but it is known now.
3225 GEPWidth = ValNumEl;
3229 SmallPtrSet<Type*, 4> Visited;
3230 if (!Indices.empty() && !Ty->isSized(&Visited))
3231 return Error(ID.Loc, "base element of getelementptr must be sized");
3233 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3234 return Error(ID.Loc, "invalid getelementptr indices");
3237 if (*InRangeOp == 0)
3238 return Error(ID.Loc,
3239 "inrange keyword may not appear on pointer operand");
3243 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3244 InBounds, InRangeOp);
3245 } else if (Opc == Instruction::Select) {
3246 if (Elts.size() != 3)
3247 return Error(ID.Loc, "expected three operands to select");
3248 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3250 return Error(ID.Loc, Reason);
3251 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3252 } else if (Opc == Instruction::ShuffleVector) {
3253 if (Elts.size() != 3)
3254 return Error(ID.Loc, "expected three operands to shufflevector");
3255 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3256 return Error(ID.Loc, "invalid operands to shufflevector");
3258 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3259 } else if (Opc == Instruction::ExtractElement) {
3260 if (Elts.size() != 2)
3261 return Error(ID.Loc, "expected two operands to extractelement");
3262 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3263 return Error(ID.Loc, "invalid extractelement operands");
3264 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3266 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3267 if (Elts.size() != 3)
3268 return Error(ID.Loc, "expected three operands to insertelement");
3269 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3270 return Error(ID.Loc, "invalid insertelement operands");
3272 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3275 ID.Kind = ValID::t_Constant;
3284 /// ParseGlobalValue - Parse a global value with the specified type.
3285 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3289 bool Parsed = ParseValID(ID) ||
3290 ConvertValIDToValue(Ty, ID, V, nullptr);
3291 if (V && !(C = dyn_cast<Constant>(V)))
3292 return Error(ID.Loc, "global values must be constants");
3296 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3298 return ParseType(Ty) ||
3299 ParseGlobalValue(Ty, V);
3302 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3305 LocTy KwLoc = Lex.getLoc();
3306 if (!EatIfPresent(lltok::kw_comdat))
3309 if (EatIfPresent(lltok::lparen)) {
3310 if (Lex.getKind() != lltok::ComdatVar)
3311 return TokError("expected comdat variable");
3312 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3314 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3317 if (GlobalName.empty())
3318 return TokError("comdat cannot be unnamed");
3319 C = getComdat(GlobalName, KwLoc);
3325 /// ParseGlobalValueVector
3327 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3328 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3329 Optional<unsigned> *InRangeOp) {
3331 if (Lex.getKind() == lltok::rbrace ||
3332 Lex.getKind() == lltok::rsquare ||
3333 Lex.getKind() == lltok::greater ||
3334 Lex.getKind() == lltok::rparen)
3338 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3339 *InRangeOp = Elts.size();
3342 if (ParseGlobalTypeAndValue(C)) return true;
3344 } while (EatIfPresent(lltok::comma));
3349 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3350 SmallVector<Metadata *, 16> Elts;
3351 if (ParseMDNodeVector(Elts))
3354 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3361 /// ::= !DILocation(...)
3362 bool LLParser::ParseMDNode(MDNode *&N) {
3363 if (Lex.getKind() == lltok::MetadataVar)
3364 return ParseSpecializedMDNode(N);
3366 return ParseToken(lltok::exclaim, "expected '!' here") ||
3370 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3372 if (Lex.getKind() == lltok::lbrace)
3373 return ParseMDTuple(N);
3376 return ParseMDNodeID(N);
3381 /// Structure to represent an optional metadata field.
3382 template <class FieldTy> struct MDFieldImpl {
3383 typedef MDFieldImpl ImplTy;
3387 void assign(FieldTy Val) {
3389 this->Val = std::move(Val);
3392 explicit MDFieldImpl(FieldTy Default)
3393 : Val(std::move(Default)), Seen(false) {}
3396 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3399 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3400 : ImplTy(Default), Max(Max) {}
3403 struct LineField : public MDUnsignedField {
3404 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3407 struct ColumnField : public MDUnsignedField {
3408 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3411 struct DwarfTagField : public MDUnsignedField {
3412 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3413 DwarfTagField(dwarf::Tag DefaultTag)
3414 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3417 struct DwarfMacinfoTypeField : public MDUnsignedField {
3418 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3419 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3420 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3423 struct DwarfAttEncodingField : public MDUnsignedField {
3424 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3427 struct DwarfVirtualityField : public MDUnsignedField {
3428 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3431 struct DwarfLangField : public MDUnsignedField {
3432 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3435 struct DwarfCCField : public MDUnsignedField {
3436 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3439 struct EmissionKindField : public MDUnsignedField {
3440 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3443 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3444 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3447 struct MDSignedField : public MDFieldImpl<int64_t> {
3451 MDSignedField(int64_t Default = 0)
3452 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3453 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3454 : ImplTy(Default), Min(Min), Max(Max) {}
3457 struct MDBoolField : public MDFieldImpl<bool> {
3458 MDBoolField(bool Default = false) : ImplTy(Default) {}
3461 struct MDField : public MDFieldImpl<Metadata *> {
3464 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3467 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3468 MDConstant() : ImplTy(nullptr) {}
3471 struct MDStringField : public MDFieldImpl<MDString *> {
3473 MDStringField(bool AllowEmpty = true)
3474 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3477 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3478 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3481 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3482 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3483 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3486 } // end anonymous namespace
3491 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3492 MDUnsignedField &Result) {
3493 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3494 return TokError("expected unsigned integer");
3496 auto &U = Lex.getAPSIntVal();
3497 if (U.ugt(Result.Max))
3498 return TokError("value for '" + Name + "' too large, limit is " +
3500 Result.assign(U.getZExtValue());
3501 assert(Result.Val <= Result.Max && "Expected value in range");
3507 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3508 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3511 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3512 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3516 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3517 if (Lex.getKind() == lltok::APSInt)
3518 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3520 if (Lex.getKind() != lltok::DwarfTag)
3521 return TokError("expected DWARF tag");
3523 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3524 if (Tag == dwarf::DW_TAG_invalid)
3525 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3526 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3534 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3535 DwarfMacinfoTypeField &Result) {
3536 if (Lex.getKind() == lltok::APSInt)
3537 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3539 if (Lex.getKind() != lltok::DwarfMacinfo)
3540 return TokError("expected DWARF macinfo type");
3542 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3543 if (Macinfo == dwarf::DW_MACINFO_invalid)
3545 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3546 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3548 Result.assign(Macinfo);
3554 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3555 DwarfVirtualityField &Result) {
3556 if (Lex.getKind() == lltok::APSInt)
3557 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3559 if (Lex.getKind() != lltok::DwarfVirtuality)
3560 return TokError("expected DWARF virtuality code");
3562 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3563 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3564 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3565 Lex.getStrVal() + "'");
3566 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3567 Result.assign(Virtuality);
3573 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3574 if (Lex.getKind() == lltok::APSInt)
3575 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3577 if (Lex.getKind() != lltok::DwarfLang)
3578 return TokError("expected DWARF language");
3580 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3582 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3584 assert(Lang <= Result.Max && "Expected valid DWARF language");
3585 Result.assign(Lang);
3591 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3592 if (Lex.getKind() == lltok::APSInt)
3593 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3595 if (Lex.getKind() != lltok::DwarfCC)
3596 return TokError("expected DWARF calling convention");
3598 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3600 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3602 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3609 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3610 if (Lex.getKind() == lltok::APSInt)
3611 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3613 if (Lex.getKind() != lltok::EmissionKind)
3614 return TokError("expected emission kind");
3616 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3618 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3620 assert(*Kind <= Result.Max && "Expected valid emission kind");
3621 Result.assign(*Kind);
3627 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3628 DwarfAttEncodingField &Result) {
3629 if (Lex.getKind() == lltok::APSInt)
3630 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3632 if (Lex.getKind() != lltok::DwarfAttEncoding)
3633 return TokError("expected DWARF type attribute encoding");
3635 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3637 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3638 Lex.getStrVal() + "'");
3639 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3640 Result.assign(Encoding);
3647 /// ::= DIFlagVector
3648 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3650 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3652 // Parser for a single flag.
3653 auto parseFlag = [&](DINode::DIFlags &Val) {
3654 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3655 uint32_t TempVal = static_cast<uint32_t>(Val);
3656 bool Res = ParseUInt32(TempVal);
3657 Val = static_cast<DINode::DIFlags>(TempVal);
3661 if (Lex.getKind() != lltok::DIFlag)
3662 return TokError("expected debug info flag");
3664 Val = DINode::getFlag(Lex.getStrVal());
3666 return TokError(Twine("invalid debug info flag flag '") +
3667 Lex.getStrVal() + "'");
3672 // Parse the flags and combine them together.
3673 DINode::DIFlags Combined = DINode::FlagZero;
3675 DINode::DIFlags Val;
3679 } while (EatIfPresent(lltok::bar));
3681 Result.assign(Combined);
3686 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3687 MDSignedField &Result) {
3688 if (Lex.getKind() != lltok::APSInt)
3689 return TokError("expected signed integer");
3691 auto &S = Lex.getAPSIntVal();
3693 return TokError("value for '" + Name + "' too small, limit is " +
3696 return TokError("value for '" + Name + "' too large, limit is " +
3698 Result.assign(S.getExtValue());
3699 assert(Result.Val >= Result.Min && "Expected value in range");
3700 assert(Result.Val <= Result.Max && "Expected value in range");
3706 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3707 switch (Lex.getKind()) {
3709 return TokError("expected 'true' or 'false'");
3710 case lltok::kw_true:
3711 Result.assign(true);
3713 case lltok::kw_false:
3714 Result.assign(false);
3722 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3723 if (Lex.getKind() == lltok::kw_null) {
3724 if (!Result.AllowNull)
3725 return TokError("'" + Name + "' cannot be null");
3727 Result.assign(nullptr);
3732 if (ParseMetadata(MD, nullptr))
3740 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3741 LocTy ValueLoc = Lex.getLoc();
3743 if (ParseStringConstant(S))
3746 if (!Result.AllowEmpty && S.empty())
3747 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3749 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3754 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3755 SmallVector<Metadata *, 4> MDs;
3756 if (ParseMDNodeVector(MDs))
3759 Result.assign(std::move(MDs));
3764 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3765 ChecksumKindField &Result) {
3766 if (Lex.getKind() != lltok::ChecksumKind)
3768 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3770 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3772 Result.assign(CSKind);
3777 } // end namespace llvm
3779 template <class ParserTy>
3780 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3782 if (Lex.getKind() != lltok::LabelStr)
3783 return TokError("expected field label here");
3787 } while (EatIfPresent(lltok::comma));
3792 template <class ParserTy>
3793 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3794 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3797 if (ParseToken(lltok::lparen, "expected '(' here"))
3799 if (Lex.getKind() != lltok::rparen)
3800 if (ParseMDFieldsImplBody(parseField))
3803 ClosingLoc = Lex.getLoc();
3804 return ParseToken(lltok::rparen, "expected ')' here");
3807 template <class FieldTy>
3808 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3810 return TokError("field '" + Name + "' cannot be specified more than once");
3812 LocTy Loc = Lex.getLoc();
3814 return ParseMDField(Loc, Name, Result);
3817 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3818 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3820 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3821 if (Lex.getStrVal() == #CLASS) \
3822 return Parse##CLASS(N, IsDistinct);
3823 #include "llvm/IR/Metadata.def"
3825 return TokError("expected metadata type");
3828 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3829 #define NOP_FIELD(NAME, TYPE, INIT)
3830 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3832 return Error(ClosingLoc, "missing required field '" #NAME "'");
3833 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3834 if (Lex.getStrVal() == #NAME) \
3835 return ParseMDField(#NAME, NAME);
3836 #define PARSE_MD_FIELDS() \
3837 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3840 if (ParseMDFieldsImpl([&]() -> bool { \
3841 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3842 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3845 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3847 #define GET_OR_DISTINCT(CLASS, ARGS) \
3848 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3850 /// ParseDILocationFields:
3851 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3852 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3853 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3854 OPTIONAL(line, LineField, ); \
3855 OPTIONAL(column, ColumnField, ); \
3856 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3857 OPTIONAL(inlinedAt, MDField, );
3859 #undef VISIT_MD_FIELDS
3861 Result = GET_OR_DISTINCT(
3862 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3866 /// ParseGenericDINode:
3867 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3868 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3869 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3870 REQUIRED(tag, DwarfTagField, ); \
3871 OPTIONAL(header, MDStringField, ); \
3872 OPTIONAL(operands, MDFieldList, );
3874 #undef VISIT_MD_FIELDS
3876 Result = GET_OR_DISTINCT(GenericDINode,
3877 (Context, tag.Val, header.Val, operands.Val));
3881 /// ParseDISubrange:
3882 /// ::= !DISubrange(count: 30, lowerBound: 2)
3883 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3884 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3885 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3886 OPTIONAL(lowerBound, MDSignedField, );
3888 #undef VISIT_MD_FIELDS
3890 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3894 /// ParseDIEnumerator:
3895 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3896 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3897 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3898 REQUIRED(name, MDStringField, ); \
3899 REQUIRED(value, MDSignedField, );
3901 #undef VISIT_MD_FIELDS
3903 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3907 /// ParseDIBasicType:
3908 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3909 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3910 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3911 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3912 OPTIONAL(name, MDStringField, ); \
3913 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3914 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3915 OPTIONAL(encoding, DwarfAttEncodingField, );
3917 #undef VISIT_MD_FIELDS
3919 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3920 align.Val, encoding.Val));
3924 /// ParseDIDerivedType:
3925 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3926 /// line: 7, scope: !1, baseType: !2, size: 32,
3927 /// align: 32, offset: 0, flags: 0, extraData: !3,
3928 /// dwarfAddressSpace: 3)
3929 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3930 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3931 REQUIRED(tag, DwarfTagField, ); \
3932 OPTIONAL(name, MDStringField, ); \
3933 OPTIONAL(file, MDField, ); \
3934 OPTIONAL(line, LineField, ); \
3935 OPTIONAL(scope, MDField, ); \
3936 REQUIRED(baseType, MDField, ); \
3937 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3938 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3939 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3940 OPTIONAL(flags, DIFlagField, ); \
3941 OPTIONAL(extraData, MDField, ); \
3942 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
3944 #undef VISIT_MD_FIELDS
3946 Optional<unsigned> DWARFAddressSpace;
3947 if (dwarfAddressSpace.Val != UINT32_MAX)
3948 DWARFAddressSpace = dwarfAddressSpace.Val;
3950 Result = GET_OR_DISTINCT(DIDerivedType,
3951 (Context, tag.Val, name.Val, file.Val, line.Val,
3952 scope.Val, baseType.Val, size.Val, align.Val,
3953 offset.Val, DWARFAddressSpace, flags.Val,
3958 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3959 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3960 REQUIRED(tag, DwarfTagField, ); \
3961 OPTIONAL(name, MDStringField, ); \
3962 OPTIONAL(file, MDField, ); \
3963 OPTIONAL(line, LineField, ); \
3964 OPTIONAL(scope, MDField, ); \
3965 OPTIONAL(baseType, MDField, ); \
3966 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3967 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3968 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3969 OPTIONAL(flags, DIFlagField, ); \
3970 OPTIONAL(elements, MDField, ); \
3971 OPTIONAL(runtimeLang, DwarfLangField, ); \
3972 OPTIONAL(vtableHolder, MDField, ); \
3973 OPTIONAL(templateParams, MDField, ); \
3974 OPTIONAL(identifier, MDStringField, );
3976 #undef VISIT_MD_FIELDS
3978 // If this has an identifier try to build an ODR type.
3980 if (auto *CT = DICompositeType::buildODRType(
3981 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3982 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3983 elements.Val, runtimeLang.Val, vtableHolder.Val,
3984 templateParams.Val)) {
3989 // Create a new node, and save it in the context if it belongs in the type
3991 Result = GET_OR_DISTINCT(
3993 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3994 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3995 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3999 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4000 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4001 OPTIONAL(flags, DIFlagField, ); \
4002 OPTIONAL(cc, DwarfCCField, ); \
4003 REQUIRED(types, MDField, );
4005 #undef VISIT_MD_FIELDS
4007 Result = GET_OR_DISTINCT(DISubroutineType,
4008 (Context, flags.Val, cc.Val, types.Val));
4012 /// ParseDIFileType:
4013 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4014 /// checksumkind: CSK_MD5,
4015 /// checksum: "000102030405060708090a0b0c0d0e0f")
4016 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4017 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4018 REQUIRED(filename, MDStringField, ); \
4019 REQUIRED(directory, MDStringField, ); \
4020 OPTIONAL(checksumkind, ChecksumKindField, ); \
4021 OPTIONAL(checksum, MDStringField, );
4023 #undef VISIT_MD_FIELDS
4025 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4026 checksumkind.Val, checksum.Val));
4030 /// ParseDICompileUnit:
4031 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4032 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4033 /// splitDebugFilename: "abc.debug",
4034 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4035 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4036 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4038 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4040 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4041 REQUIRED(language, DwarfLangField, ); \
4042 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4043 OPTIONAL(producer, MDStringField, ); \
4044 OPTIONAL(isOptimized, MDBoolField, ); \
4045 OPTIONAL(flags, MDStringField, ); \
4046 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4047 OPTIONAL(splitDebugFilename, MDStringField, ); \
4048 OPTIONAL(emissionKind, EmissionKindField, ); \
4049 OPTIONAL(enums, MDField, ); \
4050 OPTIONAL(retainedTypes, MDField, ); \
4051 OPTIONAL(globals, MDField, ); \
4052 OPTIONAL(imports, MDField, ); \
4053 OPTIONAL(macros, MDField, ); \
4054 OPTIONAL(dwoId, MDUnsignedField, ); \
4055 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4056 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
4058 #undef VISIT_MD_FIELDS
4060 Result = DICompileUnit::getDistinct(
4061 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4062 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4063 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4064 splitDebugInlining.Val, debugInfoForProfiling.Val);
4068 /// ParseDISubprogram:
4069 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4070 /// file: !1, line: 7, type: !2, isLocal: false,
4071 /// isDefinition: true, scopeLine: 8, containingType: !3,
4072 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4073 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4074 /// isOptimized: false, templateParams: !4, declaration: !5,
4075 /// variables: !6, thrownTypes: !7)
4076 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4077 auto Loc = Lex.getLoc();
4078 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4079 OPTIONAL(scope, MDField, ); \
4080 OPTIONAL(name, MDStringField, ); \
4081 OPTIONAL(linkageName, MDStringField, ); \
4082 OPTIONAL(file, MDField, ); \
4083 OPTIONAL(line, LineField, ); \
4084 OPTIONAL(type, MDField, ); \
4085 OPTIONAL(isLocal, MDBoolField, ); \
4086 OPTIONAL(isDefinition, MDBoolField, (true)); \
4087 OPTIONAL(scopeLine, LineField, ); \
4088 OPTIONAL(containingType, MDField, ); \
4089 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4090 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4091 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4092 OPTIONAL(flags, DIFlagField, ); \
4093 OPTIONAL(isOptimized, MDBoolField, ); \
4094 OPTIONAL(unit, MDField, ); \
4095 OPTIONAL(templateParams, MDField, ); \
4096 OPTIONAL(declaration, MDField, ); \
4097 OPTIONAL(variables, MDField, ); \
4098 OPTIONAL(thrownTypes, MDField, );
4100 #undef VISIT_MD_FIELDS
4102 if (isDefinition.Val && !IsDistinct)
4105 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4107 Result = GET_OR_DISTINCT(
4109 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4110 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4111 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4112 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4113 declaration.Val, variables.Val, thrownTypes.Val));
4117 /// ParseDILexicalBlock:
4118 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4119 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4120 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4121 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4122 OPTIONAL(file, MDField, ); \
4123 OPTIONAL(line, LineField, ); \
4124 OPTIONAL(column, ColumnField, );
4126 #undef VISIT_MD_FIELDS
4128 Result = GET_OR_DISTINCT(
4129 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4133 /// ParseDILexicalBlockFile:
4134 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4135 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4136 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4137 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4138 OPTIONAL(file, MDField, ); \
4139 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4141 #undef VISIT_MD_FIELDS
4143 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4144 (Context, scope.Val, file.Val, discriminator.Val));
4148 /// ParseDINamespace:
4149 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4150 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4151 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4152 REQUIRED(scope, MDField, ); \
4153 OPTIONAL(name, MDStringField, ); \
4154 OPTIONAL(exportSymbols, MDBoolField, );
4156 #undef VISIT_MD_FIELDS
4158 Result = GET_OR_DISTINCT(DINamespace,
4159 (Context, scope.Val, name.Val, exportSymbols.Val));
4164 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4165 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4166 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4167 REQUIRED(type, DwarfMacinfoTypeField, ); \
4168 OPTIONAL(line, LineField, ); \
4169 REQUIRED(name, MDStringField, ); \
4170 OPTIONAL(value, MDStringField, );
4172 #undef VISIT_MD_FIELDS
4174 Result = GET_OR_DISTINCT(DIMacro,
4175 (Context, type.Val, line.Val, name.Val, value.Val));
4179 /// ParseDIMacroFile:
4180 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4181 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4182 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4183 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4184 OPTIONAL(line, LineField, ); \
4185 REQUIRED(file, MDField, ); \
4186 OPTIONAL(nodes, MDField, );
4188 #undef VISIT_MD_FIELDS
4190 Result = GET_OR_DISTINCT(DIMacroFile,
4191 (Context, type.Val, line.Val, file.Val, nodes.Val));
4196 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4197 /// includePath: "/usr/include", isysroot: "/")
4198 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4199 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4200 REQUIRED(scope, MDField, ); \
4201 REQUIRED(name, MDStringField, ); \
4202 OPTIONAL(configMacros, MDStringField, ); \
4203 OPTIONAL(includePath, MDStringField, ); \
4204 OPTIONAL(isysroot, MDStringField, );
4206 #undef VISIT_MD_FIELDS
4208 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4209 configMacros.Val, includePath.Val, isysroot.Val));
4213 /// ParseDITemplateTypeParameter:
4214 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4215 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4216 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4217 OPTIONAL(name, MDStringField, ); \
4218 REQUIRED(type, MDField, );
4220 #undef VISIT_MD_FIELDS
4223 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4227 /// ParseDITemplateValueParameter:
4228 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4229 /// name: "V", type: !1, value: i32 7)
4230 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4231 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4232 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4233 OPTIONAL(name, MDStringField, ); \
4234 OPTIONAL(type, MDField, ); \
4235 REQUIRED(value, MDField, );
4237 #undef VISIT_MD_FIELDS
4239 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4240 (Context, tag.Val, name.Val, type.Val, value.Val));
4244 /// ParseDIGlobalVariable:
4245 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4246 /// file: !1, line: 7, type: !2, isLocal: false,
4247 /// isDefinition: true, declaration: !3, align: 8)
4248 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4249 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4250 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4251 OPTIONAL(scope, MDField, ); \
4252 OPTIONAL(linkageName, MDStringField, ); \
4253 OPTIONAL(file, MDField, ); \
4254 OPTIONAL(line, LineField, ); \
4255 OPTIONAL(type, MDField, ); \
4256 OPTIONAL(isLocal, MDBoolField, ); \
4257 OPTIONAL(isDefinition, MDBoolField, (true)); \
4258 OPTIONAL(declaration, MDField, ); \
4259 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4261 #undef VISIT_MD_FIELDS
4263 Result = GET_OR_DISTINCT(DIGlobalVariable,
4264 (Context, scope.Val, name.Val, linkageName.Val,
4265 file.Val, line.Val, type.Val, isLocal.Val,
4266 isDefinition.Val, declaration.Val, align.Val));
4270 /// ParseDILocalVariable:
4271 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4272 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4274 /// ::= !DILocalVariable(scope: !0, name: "foo",
4275 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4277 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4278 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4279 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4280 OPTIONAL(name, MDStringField, ); \
4281 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4282 OPTIONAL(file, MDField, ); \
4283 OPTIONAL(line, LineField, ); \
4284 OPTIONAL(type, MDField, ); \
4285 OPTIONAL(flags, DIFlagField, ); \
4286 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4288 #undef VISIT_MD_FIELDS
4290 Result = GET_OR_DISTINCT(DILocalVariable,
4291 (Context, scope.Val, name.Val, file.Val, line.Val,
4292 type.Val, arg.Val, flags.Val, align.Val));
4296 /// ParseDIExpression:
4297 /// ::= !DIExpression(0, 7, -1)
4298 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4299 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4302 if (ParseToken(lltok::lparen, "expected '(' here"))
4305 SmallVector<uint64_t, 8> Elements;
4306 if (Lex.getKind() != lltok::rparen)
4308 if (Lex.getKind() == lltok::DwarfOp) {
4309 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4311 Elements.push_back(Op);
4314 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4317 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4318 return TokError("expected unsigned integer");
4320 auto &U = Lex.getAPSIntVal();
4321 if (U.ugt(UINT64_MAX))
4322 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4323 Elements.push_back(U.getZExtValue());
4325 } while (EatIfPresent(lltok::comma));
4327 if (ParseToken(lltok::rparen, "expected ')' here"))
4330 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4334 /// ParseDIGlobalVariableExpression:
4335 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4336 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4338 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4339 REQUIRED(var, MDField, ); \
4340 OPTIONAL(expr, MDField, );
4342 #undef VISIT_MD_FIELDS
4345 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4349 /// ParseDIObjCProperty:
4350 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4351 /// getter: "getFoo", attributes: 7, type: !2)
4352 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4353 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4354 OPTIONAL(name, MDStringField, ); \
4355 OPTIONAL(file, MDField, ); \
4356 OPTIONAL(line, LineField, ); \
4357 OPTIONAL(setter, MDStringField, ); \
4358 OPTIONAL(getter, MDStringField, ); \
4359 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4360 OPTIONAL(type, MDField, );
4362 #undef VISIT_MD_FIELDS
4364 Result = GET_OR_DISTINCT(DIObjCProperty,
4365 (Context, name.Val, file.Val, line.Val, setter.Val,
4366 getter.Val, attributes.Val, type.Val));
4370 /// ParseDIImportedEntity:
4371 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4372 /// line: 7, name: "foo")
4373 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4374 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4375 REQUIRED(tag, DwarfTagField, ); \
4376 REQUIRED(scope, MDField, ); \
4377 OPTIONAL(entity, MDField, ); \
4378 OPTIONAL(line, LineField, ); \
4379 OPTIONAL(name, MDStringField, );
4381 #undef VISIT_MD_FIELDS
4383 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4384 entity.Val, line.Val, name.Val));
4388 #undef PARSE_MD_FIELD
4390 #undef REQUIRE_FIELD
4391 #undef DECLARE_FIELD
4393 /// ParseMetadataAsValue
4394 /// ::= metadata i32 %local
4395 /// ::= metadata i32 @global
4396 /// ::= metadata i32 7
4398 /// ::= metadata !{...}
4399 /// ::= metadata !"string"
4400 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4401 // Note: the type 'metadata' has already been parsed.
4403 if (ParseMetadata(MD, &PFS))
4406 V = MetadataAsValue::get(Context, MD);
4410 /// ParseValueAsMetadata
4414 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4415 PerFunctionState *PFS) {
4418 if (ParseType(Ty, TypeMsg, Loc))
4420 if (Ty->isMetadataTy())
4421 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4424 if (ParseValue(Ty, V, PFS))
4427 MD = ValueAsMetadata::get(V);
4438 /// ::= !DILocation(...)
4439 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4440 if (Lex.getKind() == lltok::MetadataVar) {
4442 if (ParseSpecializedMDNode(N))
4450 if (Lex.getKind() != lltok::exclaim)
4451 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4454 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4458 // ::= '!' STRINGCONSTANT
4459 if (Lex.getKind() == lltok::StringConstant) {
4461 if (ParseMDString(S))
4471 if (ParseMDNodeTail(N))
4477 //===----------------------------------------------------------------------===//
4478 // Function Parsing.
4479 //===----------------------------------------------------------------------===//
4481 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4482 PerFunctionState *PFS) {
4483 if (Ty->isFunctionTy())
4484 return Error(ID.Loc, "functions are not values, refer to them as pointers");
4487 case ValID::t_LocalID:
4488 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4489 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4490 return V == nullptr;
4491 case ValID::t_LocalName:
4492 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4493 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4494 return V == nullptr;
4495 case ValID::t_InlineAsm: {
4496 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4497 return Error(ID.Loc, "invalid type for inline asm constraint string");
4498 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4499 (ID.UIntVal >> 1) & 1,
4500 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4503 case ValID::t_GlobalName:
4504 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4505 return V == nullptr;
4506 case ValID::t_GlobalID:
4507 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4508 return V == nullptr;
4509 case ValID::t_APSInt:
4510 if (!Ty->isIntegerTy())
4511 return Error(ID.Loc, "integer constant must have integer type");
4512 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4513 V = ConstantInt::get(Context, ID.APSIntVal);
4515 case ValID::t_APFloat:
4516 if (!Ty->isFloatingPointTy() ||
4517 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4518 return Error(ID.Loc, "floating point constant invalid for type");
4520 // The lexer has no type info, so builds all half, float, and double FP
4521 // constants as double. Fix this here. Long double does not need this.
4522 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
4525 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
4527 else if (Ty->isFloatTy())
4528 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
4531 V = ConstantFP::get(Context, ID.APFloatVal);
4533 if (V->getType() != Ty)
4534 return Error(ID.Loc, "floating point constant does not have type '" +
4535 getTypeString(Ty) + "'");
4539 if (!Ty->isPointerTy())
4540 return Error(ID.Loc, "null must be a pointer type");
4541 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4543 case ValID::t_Undef:
4544 // FIXME: LabelTy should not be a first-class type.
4545 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4546 return Error(ID.Loc, "invalid type for undef constant");
4547 V = UndefValue::get(Ty);
4549 case ValID::t_EmptyArray:
4550 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4551 return Error(ID.Loc, "invalid empty array initializer");
4552 V = UndefValue::get(Ty);
4555 // FIXME: LabelTy should not be a first-class type.
4556 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4557 return Error(ID.Loc, "invalid type for null constant");
4558 V = Constant::getNullValue(Ty);
4561 if (!Ty->isTokenTy())
4562 return Error(ID.Loc, "invalid type for none constant");
4563 V = Constant::getNullValue(Ty);
4565 case ValID::t_Constant:
4566 if (ID.ConstantVal->getType() != Ty)
4567 return Error(ID.Loc, "constant expression type mismatch");
4571 case ValID::t_ConstantStruct:
4572 case ValID::t_PackedConstantStruct:
4573 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4574 if (ST->getNumElements() != ID.UIntVal)
4575 return Error(ID.Loc,
4576 "initializer with struct type has wrong # elements");
4577 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4578 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4580 // Verify that the elements are compatible with the structtype.
4581 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4582 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4583 return Error(ID.Loc, "element " + Twine(i) +
4584 " of struct initializer doesn't match struct element type");
4586 V = ConstantStruct::get(
4587 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4589 return Error(ID.Loc, "constant expression type mismatch");
4592 llvm_unreachable("Invalid ValID");
4595 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4598 auto Loc = Lex.getLoc();
4599 if (ParseValID(ID, /*PFS=*/nullptr))
4602 case ValID::t_APSInt:
4603 case ValID::t_APFloat:
4604 case ValID::t_Undef:
4605 case ValID::t_Constant:
4606 case ValID::t_ConstantStruct:
4607 case ValID::t_PackedConstantStruct: {
4609 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4611 assert(isa<Constant>(V) && "Expected a constant value");
4612 C = cast<Constant>(V);
4616 C = Constant::getNullValue(Ty);
4619 return Error(Loc, "expected a constant value");
4623 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4626 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4629 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4631 return ParseType(Ty) ||
4632 ParseValue(Ty, V, PFS);
4635 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4636 PerFunctionState &PFS) {
4639 if (ParseTypeAndValue(V, PFS)) return true;
4640 if (!isa<BasicBlock>(V))
4641 return Error(Loc, "expected a basic block");
4642 BB = cast<BasicBlock>(V);
4647 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4648 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4649 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4650 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4651 // Parse the linkage.
4652 LocTy LinkageLoc = Lex.getLoc();
4655 unsigned Visibility;
4656 unsigned DLLStorageClass;
4657 AttrBuilder RetAttrs;
4660 Type *RetType = nullptr;
4661 LocTy RetTypeLoc = Lex.getLoc();
4662 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4663 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4664 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4667 // Verify that the linkage is ok.
4668 switch ((GlobalValue::LinkageTypes)Linkage) {
4669 case GlobalValue::ExternalLinkage:
4670 break; // always ok.
4671 case GlobalValue::ExternalWeakLinkage:
4673 return Error(LinkageLoc, "invalid linkage for function definition");
4675 case GlobalValue::PrivateLinkage:
4676 case GlobalValue::InternalLinkage:
4677 case GlobalValue::AvailableExternallyLinkage:
4678 case GlobalValue::LinkOnceAnyLinkage:
4679 case GlobalValue::LinkOnceODRLinkage:
4680 case GlobalValue::WeakAnyLinkage:
4681 case GlobalValue::WeakODRLinkage:
4683 return Error(LinkageLoc, "invalid linkage for function declaration");
4685 case GlobalValue::AppendingLinkage:
4686 case GlobalValue::CommonLinkage:
4687 return Error(LinkageLoc, "invalid function linkage type");
4690 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4691 return Error(LinkageLoc,
4692 "symbol with local linkage must have default visibility");
4694 if (!FunctionType::isValidReturnType(RetType))
4695 return Error(RetTypeLoc, "invalid function return type");
4697 LocTy NameLoc = Lex.getLoc();
4699 std::string FunctionName;
4700 if (Lex.getKind() == lltok::GlobalVar) {
4701 FunctionName = Lex.getStrVal();
4702 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4703 unsigned NameID = Lex.getUIntVal();
4705 if (NameID != NumberedVals.size())
4706 return TokError("function expected to be numbered '%" +
4707 Twine(NumberedVals.size()) + "'");
4709 return TokError("expected function name");
4714 if (Lex.getKind() != lltok::lparen)
4715 return TokError("expected '(' in function argument list");
4717 SmallVector<ArgInfo, 8> ArgList;
4719 AttrBuilder FuncAttrs;
4720 std::vector<unsigned> FwdRefAttrGrps;
4722 std::string Section;
4725 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4726 LocTy UnnamedAddrLoc;
4727 Constant *Prefix = nullptr;
4728 Constant *Prologue = nullptr;
4729 Constant *PersonalityFn = nullptr;
4732 if (ParseArgumentList(ArgList, isVarArg) ||
4733 ParseOptionalUnnamedAddr(UnnamedAddr) ||
4734 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4736 (EatIfPresent(lltok::kw_section) &&
4737 ParseStringConstant(Section)) ||
4738 parseOptionalComdat(FunctionName, C) ||
4739 ParseOptionalAlignment(Alignment) ||
4740 (EatIfPresent(lltok::kw_gc) &&
4741 ParseStringConstant(GC)) ||
4742 (EatIfPresent(lltok::kw_prefix) &&
4743 ParseGlobalTypeAndValue(Prefix)) ||
4744 (EatIfPresent(lltok::kw_prologue) &&
4745 ParseGlobalTypeAndValue(Prologue)) ||
4746 (EatIfPresent(lltok::kw_personality) &&
4747 ParseGlobalTypeAndValue(PersonalityFn)))
4750 if (FuncAttrs.contains(Attribute::Builtin))
4751 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4753 // If the alignment was parsed as an attribute, move to the alignment field.
4754 if (FuncAttrs.hasAlignmentAttr()) {
4755 Alignment = FuncAttrs.getAlignment();
4756 FuncAttrs.removeAttribute(Attribute::Alignment);
4759 // Okay, if we got here, the function is syntactically valid. Convert types
4760 // and do semantic checks.
4761 std::vector<Type*> ParamTypeList;
4762 SmallVector<AttributeSet, 8> Attrs;
4764 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4765 ParamTypeList.push_back(ArgList[i].Ty);
4766 Attrs.push_back(ArgList[i].Attrs);
4770 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4771 AttributeSet::get(Context, RetAttrs), Attrs);
4773 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4774 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4777 FunctionType::get(RetType, ParamTypeList, isVarArg);
4778 PointerType *PFT = PointerType::getUnqual(FT);
4781 if (!FunctionName.empty()) {
4782 // If this was a definition of a forward reference, remove the definition
4783 // from the forward reference table and fill in the forward ref.
4784 auto FRVI = ForwardRefVals.find(FunctionName);
4785 if (FRVI != ForwardRefVals.end()) {
4786 Fn = M->getFunction(FunctionName);
4788 return Error(FRVI->second.second, "invalid forward reference to "
4789 "function as global value!");
4790 if (Fn->getType() != PFT)
4791 return Error(FRVI->second.second, "invalid forward reference to "
4792 "function '" + FunctionName + "' with wrong type!");
4794 ForwardRefVals.erase(FRVI);
4795 } else if ((Fn = M->getFunction(FunctionName))) {
4796 // Reject redefinitions.
4797 return Error(NameLoc, "invalid redefinition of function '" +
4798 FunctionName + "'");
4799 } else if (M->getNamedValue(FunctionName)) {
4800 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4804 // If this is a definition of a forward referenced function, make sure the
4806 auto I = ForwardRefValIDs.find(NumberedVals.size());
4807 if (I != ForwardRefValIDs.end()) {
4808 Fn = cast<Function>(I->second.first);
4809 if (Fn->getType() != PFT)
4810 return Error(NameLoc, "type of definition and forward reference of '@" +
4811 Twine(NumberedVals.size()) + "' disagree");
4812 ForwardRefValIDs.erase(I);
4817 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4818 else // Move the forward-reference to the correct spot in the module.
4819 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4821 if (FunctionName.empty())
4822 NumberedVals.push_back(Fn);
4824 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4825 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4826 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4827 Fn->setCallingConv(CC);
4828 Fn->setAttributes(PAL);
4829 Fn->setUnnamedAddr(UnnamedAddr);
4830 Fn->setAlignment(Alignment);
4831 Fn->setSection(Section);
4833 Fn->setPersonalityFn(PersonalityFn);
4834 if (!GC.empty()) Fn->setGC(GC);
4835 Fn->setPrefixData(Prefix);
4836 Fn->setPrologueData(Prologue);
4837 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4839 // Add all of the arguments we parsed to the function.
4840 Function::arg_iterator ArgIt = Fn->arg_begin();
4841 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4842 // If the argument has a name, insert it into the argument symbol table.
4843 if (ArgList[i].Name.empty()) continue;
4845 // Set the name, if it conflicted, it will be auto-renamed.
4846 ArgIt->setName(ArgList[i].Name);
4848 if (ArgIt->getName() != ArgList[i].Name)
4849 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4850 ArgList[i].Name + "'");
4856 // Check the declaration has no block address forward references.
4858 if (FunctionName.empty()) {
4859 ID.Kind = ValID::t_GlobalID;
4860 ID.UIntVal = NumberedVals.size() - 1;
4862 ID.Kind = ValID::t_GlobalName;
4863 ID.StrVal = FunctionName;
4865 auto Blocks = ForwardRefBlockAddresses.find(ID);
4866 if (Blocks != ForwardRefBlockAddresses.end())
4867 return Error(Blocks->first.Loc,
4868 "cannot take blockaddress inside a declaration");
4872 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4874 if (FunctionNumber == -1) {
4875 ID.Kind = ValID::t_GlobalName;
4876 ID.StrVal = F.getName();
4878 ID.Kind = ValID::t_GlobalID;
4879 ID.UIntVal = FunctionNumber;
4882 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4883 if (Blocks == P.ForwardRefBlockAddresses.end())
4886 for (const auto &I : Blocks->second) {
4887 const ValID &BBID = I.first;
4888 GlobalValue *GV = I.second;
4890 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4891 "Expected local id or name");
4893 if (BBID.Kind == ValID::t_LocalName)
4894 BB = GetBB(BBID.StrVal, BBID.Loc);
4896 BB = GetBB(BBID.UIntVal, BBID.Loc);
4898 return P.Error(BBID.Loc, "referenced value is not a basic block");
4900 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4901 GV->eraseFromParent();
4904 P.ForwardRefBlockAddresses.erase(Blocks);
4908 /// ParseFunctionBody
4909 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4910 bool LLParser::ParseFunctionBody(Function &Fn) {
4911 if (Lex.getKind() != lltok::lbrace)
4912 return TokError("expected '{' in function body");
4913 Lex.Lex(); // eat the {.
4915 int FunctionNumber = -1;
4916 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4918 PerFunctionState PFS(*this, Fn, FunctionNumber);
4920 // Resolve block addresses and allow basic blocks to be forward-declared
4921 // within this function.
4922 if (PFS.resolveForwardRefBlockAddresses())
4924 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4926 // We need at least one basic block.
4927 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4928 return TokError("function body requires at least one basic block");
4930 while (Lex.getKind() != lltok::rbrace &&
4931 Lex.getKind() != lltok::kw_uselistorder)
4932 if (ParseBasicBlock(PFS)) return true;
4934 while (Lex.getKind() != lltok::rbrace)
4935 if (ParseUseListOrder(&PFS))
4941 // Verify function is ok.
4942 return PFS.FinishFunction();
4946 /// ::= LabelStr? Instruction*
4947 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4948 // If this basic block starts out with a name, remember it.
4950 LocTy NameLoc = Lex.getLoc();
4951 if (Lex.getKind() == lltok::LabelStr) {
4952 Name = Lex.getStrVal();
4956 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4958 return Error(NameLoc,
4959 "unable to create block named '" + Name + "'");
4961 std::string NameStr;
4963 // Parse the instructions in this block until we get a terminator.
4966 // This instruction may have three possibilities for a name: a) none
4967 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4968 LocTy NameLoc = Lex.getLoc();
4972 if (Lex.getKind() == lltok::LocalVarID) {
4973 NameID = Lex.getUIntVal();
4975 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4977 } else if (Lex.getKind() == lltok::LocalVar) {
4978 NameStr = Lex.getStrVal();
4980 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4984 switch (ParseInstruction(Inst, BB, PFS)) {
4985 default: llvm_unreachable("Unknown ParseInstruction result!");
4986 case InstError: return true;
4988 BB->getInstList().push_back(Inst);
4990 // With a normal result, we check to see if the instruction is followed by
4991 // a comma and metadata.
4992 if (EatIfPresent(lltok::comma))
4993 if (ParseInstructionMetadata(*Inst))
4996 case InstExtraComma:
4997 BB->getInstList().push_back(Inst);
4999 // If the instruction parser ate an extra comma at the end of it, it
5000 // *must* be followed by metadata.
5001 if (ParseInstructionMetadata(*Inst))
5006 // Set the name on the instruction.
5007 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5008 } while (!isa<TerminatorInst>(Inst));
5013 //===----------------------------------------------------------------------===//
5014 // Instruction Parsing.
5015 //===----------------------------------------------------------------------===//
5017 /// ParseInstruction - Parse one of the many different instructions.
5019 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5020 PerFunctionState &PFS) {
5021 lltok::Kind Token = Lex.getKind();
5022 if (Token == lltok::Eof)
5023 return TokError("found end of file when expecting more instructions");
5024 LocTy Loc = Lex.getLoc();
5025 unsigned KeywordVal = Lex.getUIntVal();
5026 Lex.Lex(); // Eat the keyword.
5029 default: return Error(Loc, "expected instruction opcode");
5030 // Terminator Instructions.
5031 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5032 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5033 case lltok::kw_br: return ParseBr(Inst, PFS);
5034 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5035 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5036 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5037 case lltok::kw_resume: return ParseResume(Inst, PFS);
5038 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5039 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5040 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5041 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5042 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5043 // Binary Operators.
5047 case lltok::kw_shl: {
5048 bool NUW = EatIfPresent(lltok::kw_nuw);
5049 bool NSW = EatIfPresent(lltok::kw_nsw);
5050 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5052 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5054 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5055 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5058 case lltok::kw_fadd:
5059 case lltok::kw_fsub:
5060 case lltok::kw_fmul:
5061 case lltok::kw_fdiv:
5062 case lltok::kw_frem: {
5063 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5064 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5068 Inst->setFastMathFlags(FMF);
5072 case lltok::kw_sdiv:
5073 case lltok::kw_udiv:
5074 case lltok::kw_lshr:
5075 case lltok::kw_ashr: {
5076 bool Exact = EatIfPresent(lltok::kw_exact);
5078 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5079 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5083 case lltok::kw_urem:
5084 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5087 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5088 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5089 case lltok::kw_fcmp: {
5090 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5091 int Res = ParseCompare(Inst, PFS, KeywordVal);
5095 Inst->setFastMathFlags(FMF);
5100 case lltok::kw_trunc:
5101 case lltok::kw_zext:
5102 case lltok::kw_sext:
5103 case lltok::kw_fptrunc:
5104 case lltok::kw_fpext:
5105 case lltok::kw_bitcast:
5106 case lltok::kw_addrspacecast:
5107 case lltok::kw_uitofp:
5108 case lltok::kw_sitofp:
5109 case lltok::kw_fptoui:
5110 case lltok::kw_fptosi:
5111 case lltok::kw_inttoptr:
5112 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5114 case lltok::kw_select: return ParseSelect(Inst, PFS);
5115 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5116 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5117 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5118 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5119 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5120 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5122 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5123 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5124 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5125 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5127 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5128 case lltok::kw_load: return ParseLoad(Inst, PFS);
5129 case lltok::kw_store: return ParseStore(Inst, PFS);
5130 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5131 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5132 case lltok::kw_fence: return ParseFence(Inst, PFS);
5133 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5134 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5135 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5139 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5140 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5141 if (Opc == Instruction::FCmp) {
5142 switch (Lex.getKind()) {
5143 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5144 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5145 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5146 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5147 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5148 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5149 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5150 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5151 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5152 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5153 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5154 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5155 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5156 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5157 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5158 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5159 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5162 switch (Lex.getKind()) {
5163 default: return TokError("expected icmp predicate (e.g. 'eq')");
5164 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5165 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5166 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5167 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5168 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5169 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5170 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5171 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5172 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5173 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5180 //===----------------------------------------------------------------------===//
5181 // Terminator Instructions.
5182 //===----------------------------------------------------------------------===//
5184 /// ParseRet - Parse a return instruction.
5185 /// ::= 'ret' void (',' !dbg, !1)*
5186 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5187 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5188 PerFunctionState &PFS) {
5189 SMLoc TypeLoc = Lex.getLoc();
5191 if (ParseType(Ty, true /*void allowed*/)) return true;
5193 Type *ResType = PFS.getFunction().getReturnType();
5195 if (Ty->isVoidTy()) {
5196 if (!ResType->isVoidTy())
5197 return Error(TypeLoc, "value doesn't match function result type '" +
5198 getTypeString(ResType) + "'");
5200 Inst = ReturnInst::Create(Context);
5205 if (ParseValue(Ty, RV, PFS)) return true;
5207 if (ResType != RV->getType())
5208 return Error(TypeLoc, "value doesn't match function result type '" +
5209 getTypeString(ResType) + "'");
5211 Inst = ReturnInst::Create(Context, RV);
5216 /// ::= 'br' TypeAndValue
5217 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5218 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5221 BasicBlock *Op1, *Op2;
5222 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5224 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5225 Inst = BranchInst::Create(BB);
5229 if (Op0->getType() != Type::getInt1Ty(Context))
5230 return Error(Loc, "branch condition must have 'i1' type");
5232 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5233 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5234 ParseToken(lltok::comma, "expected ',' after true destination") ||
5235 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5238 Inst = BranchInst::Create(Op1, Op2, Op0);
5244 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5246 /// ::= (TypeAndValue ',' TypeAndValue)*
5247 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5248 LocTy CondLoc, BBLoc;
5250 BasicBlock *DefaultBB;
5251 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5252 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5253 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5254 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5257 if (!Cond->getType()->isIntegerTy())
5258 return Error(CondLoc, "switch condition must have integer type");
5260 // Parse the jump table pairs.
5261 SmallPtrSet<Value*, 32> SeenCases;
5262 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5263 while (Lex.getKind() != lltok::rsquare) {
5267 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5268 ParseToken(lltok::comma, "expected ',' after case value") ||
5269 ParseTypeAndBasicBlock(DestBB, PFS))
5272 if (!SeenCases.insert(Constant).second)
5273 return Error(CondLoc, "duplicate case value in switch");
5274 if (!isa<ConstantInt>(Constant))
5275 return Error(CondLoc, "case value is not a constant integer");
5277 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5280 Lex.Lex(); // Eat the ']'.
5282 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5283 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5284 SI->addCase(Table[i].first, Table[i].second);
5291 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5292 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5295 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5296 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5297 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5300 if (!Address->getType()->isPointerTy())
5301 return Error(AddrLoc, "indirectbr address must have pointer type");
5303 // Parse the destination list.
5304 SmallVector<BasicBlock*, 16> DestList;
5306 if (Lex.getKind() != lltok::rsquare) {
5308 if (ParseTypeAndBasicBlock(DestBB, PFS))
5310 DestList.push_back(DestBB);
5312 while (EatIfPresent(lltok::comma)) {
5313 if (ParseTypeAndBasicBlock(DestBB, PFS))
5315 DestList.push_back(DestBB);
5319 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5322 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5323 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5324 IBI->addDestination(DestList[i]);
5330 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5331 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5332 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5333 LocTy CallLoc = Lex.getLoc();
5334 AttrBuilder RetAttrs, FnAttrs;
5335 std::vector<unsigned> FwdRefAttrGrps;
5338 Type *RetType = nullptr;
5341 SmallVector<ParamInfo, 16> ArgList;
5342 SmallVector<OperandBundleDef, 2> BundleList;
5344 BasicBlock *NormalBB, *UnwindBB;
5345 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5346 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5347 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5348 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5350 ParseOptionalOperandBundles(BundleList, PFS) ||
5351 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5352 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5353 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5354 ParseTypeAndBasicBlock(UnwindBB, PFS))
5357 // If RetType is a non-function pointer type, then this is the short syntax
5358 // for the call, which means that RetType is just the return type. Infer the
5359 // rest of the function argument types from the arguments that are present.
5360 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5362 // Pull out the types of all of the arguments...
5363 std::vector<Type*> ParamTypes;
5364 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5365 ParamTypes.push_back(ArgList[i].V->getType());
5367 if (!FunctionType::isValidReturnType(RetType))
5368 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5370 Ty = FunctionType::get(RetType, ParamTypes, false);
5375 // Look up the callee.
5377 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5380 // Set up the Attribute for the function.
5381 SmallVector<Value *, 8> Args;
5382 SmallVector<AttributeSet, 8> ArgAttrs;
5384 // Loop through FunctionType's arguments and ensure they are specified
5385 // correctly. Also, gather any parameter attributes.
5386 FunctionType::param_iterator I = Ty->param_begin();
5387 FunctionType::param_iterator E = Ty->param_end();
5388 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5389 Type *ExpectedTy = nullptr;
5392 } else if (!Ty->isVarArg()) {
5393 return Error(ArgList[i].Loc, "too many arguments specified");
5396 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5397 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5398 getTypeString(ExpectedTy) + "'");
5399 Args.push_back(ArgList[i].V);
5400 ArgAttrs.push_back(ArgList[i].Attrs);
5404 return Error(CallLoc, "not enough parameters specified for call");
5406 if (FnAttrs.hasAlignmentAttr())
5407 return Error(CallLoc, "invoke instructions may not have an alignment");
5409 // Finish off the Attribute and check them
5411 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5412 AttributeSet::get(Context, RetAttrs), ArgAttrs);
5415 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5416 II->setCallingConv(CC);
5417 II->setAttributes(PAL);
5418 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5424 /// ::= 'resume' TypeAndValue
5425 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5426 Value *Exn; LocTy ExnLoc;
5427 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5430 ResumeInst *RI = ResumeInst::Create(Exn);
5435 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5436 PerFunctionState &PFS) {
5437 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5440 while (Lex.getKind() != lltok::rsquare) {
5441 // If this isn't the first argument, we need a comma.
5442 if (!Args.empty() &&
5443 ParseToken(lltok::comma, "expected ',' in argument list"))
5446 // Parse the argument.
5448 Type *ArgTy = nullptr;
5449 if (ParseType(ArgTy, ArgLoc))
5453 if (ArgTy->isMetadataTy()) {
5454 if (ParseMetadataAsValue(V, PFS))
5457 if (ParseValue(ArgTy, V, PFS))
5463 Lex.Lex(); // Lex the ']'.
5468 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5469 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5470 Value *CleanupPad = nullptr;
5472 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5475 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5478 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5481 BasicBlock *UnwindBB = nullptr;
5482 if (Lex.getKind() == lltok::kw_to) {
5484 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5487 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5492 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5497 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
5498 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5499 Value *CatchPad = nullptr;
5501 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5504 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5508 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5509 ParseTypeAndBasicBlock(BB, PFS))
5512 Inst = CatchReturnInst::Create(CatchPad, BB);
5516 /// ParseCatchSwitch
5517 /// ::= 'catchswitch' within Parent
5518 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5522 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5525 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5526 Lex.getKind() != lltok::LocalVarID)
5527 return TokError("expected scope value for catchswitch");
5529 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5532 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5535 SmallVector<BasicBlock *, 32> Table;
5538 if (ParseTypeAndBasicBlock(DestBB, PFS))
5540 Table.push_back(DestBB);
5541 } while (EatIfPresent(lltok::comma));
5543 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5546 if (ParseToken(lltok::kw_unwind,
5547 "expected 'unwind' after catchswitch scope"))
5550 BasicBlock *UnwindBB = nullptr;
5551 if (EatIfPresent(lltok::kw_to)) {
5552 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5555 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5560 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5561 for (BasicBlock *DestBB : Table)
5562 CatchSwitch->addHandler(DestBB);
5568 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5569 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5570 Value *CatchSwitch = nullptr;
5572 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5575 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5576 return TokError("expected scope value for catchpad");
5578 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5581 SmallVector<Value *, 8> Args;
5582 if (ParseExceptionArgs(Args, PFS))
5585 Inst = CatchPadInst::Create(CatchSwitch, Args);
5590 /// ::= 'cleanuppad' within Parent ParamList
5591 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5592 Value *ParentPad = nullptr;
5594 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5597 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5598 Lex.getKind() != lltok::LocalVarID)
5599 return TokError("expected scope value for cleanuppad");
5601 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5604 SmallVector<Value *, 8> Args;
5605 if (ParseExceptionArgs(Args, PFS))
5608 Inst = CleanupPadInst::Create(ParentPad, Args);
5612 //===----------------------------------------------------------------------===//
5613 // Binary Operators.
5614 //===----------------------------------------------------------------------===//
5617 /// ::= ArithmeticOps TypeAndValue ',' Value
5619 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5620 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5621 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5622 unsigned Opc, unsigned OperandType) {
5623 LocTy Loc; Value *LHS, *RHS;
5624 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5625 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5626 ParseValue(LHS->getType(), RHS, PFS))
5630 switch (OperandType) {
5631 default: llvm_unreachable("Unknown operand type!");
5632 case 0: // int or FP.
5633 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5634 LHS->getType()->isFPOrFPVectorTy();
5636 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5637 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5641 return Error(Loc, "invalid operand type for instruction");
5643 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5648 /// ::= ArithmeticOps TypeAndValue ',' Value {
5649 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5651 LocTy Loc; Value *LHS, *RHS;
5652 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5653 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5654 ParseValue(LHS->getType(), RHS, PFS))
5657 if (!LHS->getType()->isIntOrIntVectorTy())
5658 return Error(Loc,"instruction requires integer or integer vector operands");
5660 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5665 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5666 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5667 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5669 // Parse the integer/fp comparison predicate.
5673 if (ParseCmpPredicate(Pred, Opc) ||
5674 ParseTypeAndValue(LHS, Loc, PFS) ||
5675 ParseToken(lltok::comma, "expected ',' after compare value") ||
5676 ParseValue(LHS->getType(), RHS, PFS))
5679 if (Opc == Instruction::FCmp) {
5680 if (!LHS->getType()->isFPOrFPVectorTy())
5681 return Error(Loc, "fcmp requires floating point operands");
5682 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5684 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5685 if (!LHS->getType()->isIntOrIntVectorTy() &&
5686 !LHS->getType()->getScalarType()->isPointerTy())
5687 return Error(Loc, "icmp requires integer operands");
5688 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5693 //===----------------------------------------------------------------------===//
5694 // Other Instructions.
5695 //===----------------------------------------------------------------------===//
5699 /// ::= CastOpc TypeAndValue 'to' Type
5700 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5704 Type *DestTy = nullptr;
5705 if (ParseTypeAndValue(Op, Loc, PFS) ||
5706 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5710 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5711 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5712 return Error(Loc, "invalid cast opcode for cast from '" +
5713 getTypeString(Op->getType()) + "' to '" +
5714 getTypeString(DestTy) + "'");
5716 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5721 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5722 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5724 Value *Op0, *Op1, *Op2;
5725 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5726 ParseToken(lltok::comma, "expected ',' after select condition") ||
5727 ParseTypeAndValue(Op1, PFS) ||
5728 ParseToken(lltok::comma, "expected ',' after select value") ||
5729 ParseTypeAndValue(Op2, PFS))
5732 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5733 return Error(Loc, Reason);
5735 Inst = SelectInst::Create(Op0, Op1, Op2);
5740 /// ::= 'va_arg' TypeAndValue ',' Type
5741 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5743 Type *EltTy = nullptr;
5745 if (ParseTypeAndValue(Op, PFS) ||
5746 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5747 ParseType(EltTy, TypeLoc))
5750 if (!EltTy->isFirstClassType())
5751 return Error(TypeLoc, "va_arg requires operand with first class type");
5753 Inst = new VAArgInst(Op, EltTy);
5757 /// ParseExtractElement
5758 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5759 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5762 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5763 ParseToken(lltok::comma, "expected ',' after extract value") ||
5764 ParseTypeAndValue(Op1, PFS))
5767 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5768 return Error(Loc, "invalid extractelement operands");
5770 Inst = ExtractElementInst::Create(Op0, Op1);
5774 /// ParseInsertElement
5775 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5776 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5778 Value *Op0, *Op1, *Op2;
5779 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5780 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5781 ParseTypeAndValue(Op1, PFS) ||
5782 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5783 ParseTypeAndValue(Op2, PFS))
5786 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5787 return Error(Loc, "invalid insertelement operands");
5789 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5793 /// ParseShuffleVector
5794 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5795 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5797 Value *Op0, *Op1, *Op2;
5798 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5799 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5800 ParseTypeAndValue(Op1, PFS) ||
5801 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5802 ParseTypeAndValue(Op2, PFS))
5805 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5806 return Error(Loc, "invalid shufflevector operands");
5808 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5813 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5814 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5815 Type *Ty = nullptr; LocTy TypeLoc;
5818 if (ParseType(Ty, TypeLoc) ||
5819 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5820 ParseValue(Ty, Op0, PFS) ||
5821 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5822 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5823 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5826 bool AteExtraComma = false;
5827 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5830 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5832 if (!EatIfPresent(lltok::comma))
5835 if (Lex.getKind() == lltok::MetadataVar) {
5836 AteExtraComma = true;
5840 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5841 ParseValue(Ty, Op0, PFS) ||
5842 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5843 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5844 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5848 if (!Ty->isFirstClassType())
5849 return Error(TypeLoc, "phi node must have first class type");
5851 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5852 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5853 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5855 return AteExtraComma ? InstExtraComma : InstNormal;
5859 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5861 /// ::= 'catch' TypeAndValue
5863 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5864 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5865 Type *Ty = nullptr; LocTy TyLoc;
5867 if (ParseType(Ty, TyLoc))
5870 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5871 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5873 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5874 LandingPadInst::ClauseType CT;
5875 if (EatIfPresent(lltok::kw_catch))
5876 CT = LandingPadInst::Catch;
5877 else if (EatIfPresent(lltok::kw_filter))
5878 CT = LandingPadInst::Filter;
5880 return TokError("expected 'catch' or 'filter' clause type");
5884 if (ParseTypeAndValue(V, VLoc, PFS))
5887 // A 'catch' type expects a non-array constant. A filter clause expects an
5889 if (CT == LandingPadInst::Catch) {
5890 if (isa<ArrayType>(V->getType()))
5891 Error(VLoc, "'catch' clause has an invalid type");
5893 if (!isa<ArrayType>(V->getType()))
5894 Error(VLoc, "'filter' clause has an invalid type");
5897 Constant *CV = dyn_cast<Constant>(V);
5899 return Error(VLoc, "clause argument must be a constant");
5903 Inst = LP.release();
5908 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5909 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5910 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5911 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5912 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5913 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5914 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5915 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5916 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5917 CallInst::TailCallKind TCK) {
5918 AttrBuilder RetAttrs, FnAttrs;
5919 std::vector<unsigned> FwdRefAttrGrps;
5922 Type *RetType = nullptr;
5925 SmallVector<ParamInfo, 16> ArgList;
5926 SmallVector<OperandBundleDef, 2> BundleList;
5927 LocTy CallLoc = Lex.getLoc();
5929 if (TCK != CallInst::TCK_None &&
5930 ParseToken(lltok::kw_call,
5931 "expected 'tail call', 'musttail call', or 'notail call'"))
5934 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5936 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5937 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5938 ParseValID(CalleeID) ||
5939 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5940 PFS.getFunction().isVarArg()) ||
5941 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5942 ParseOptionalOperandBundles(BundleList, PFS))
5945 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5946 return Error(CallLoc, "fast-math-flags specified for call without "
5947 "floating-point scalar or vector return type");
5949 // If RetType is a non-function pointer type, then this is the short syntax
5950 // for the call, which means that RetType is just the return type. Infer the
5951 // rest of the function argument types from the arguments that are present.
5952 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5954 // Pull out the types of all of the arguments...
5955 std::vector<Type*> ParamTypes;
5956 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5957 ParamTypes.push_back(ArgList[i].V->getType());
5959 if (!FunctionType::isValidReturnType(RetType))
5960 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5962 Ty = FunctionType::get(RetType, ParamTypes, false);
5967 // Look up the callee.
5969 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5972 // Set up the Attribute for the function.
5973 SmallVector<AttributeSet, 8> Attrs;
5975 SmallVector<Value*, 8> Args;
5977 // Loop through FunctionType's arguments and ensure they are specified
5978 // correctly. Also, gather any parameter attributes.
5979 FunctionType::param_iterator I = Ty->param_begin();
5980 FunctionType::param_iterator E = Ty->param_end();
5981 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5982 Type *ExpectedTy = nullptr;
5985 } else if (!Ty->isVarArg()) {
5986 return Error(ArgList[i].Loc, "too many arguments specified");
5989 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5990 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5991 getTypeString(ExpectedTy) + "'");
5992 Args.push_back(ArgList[i].V);
5993 Attrs.push_back(ArgList[i].Attrs);
5997 return Error(CallLoc, "not enough parameters specified for call");
5999 if (FnAttrs.hasAlignmentAttr())
6000 return Error(CallLoc, "call instructions may not have an alignment");
6002 // Finish off the Attribute and check them
6004 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6005 AttributeSet::get(Context, RetAttrs), Attrs);
6007 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6008 CI->setTailCallKind(TCK);
6009 CI->setCallingConv(CC);
6011 CI->setFastMathFlags(FMF);
6012 CI->setAttributes(PAL);
6013 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6018 //===----------------------------------------------------------------------===//
6019 // Memory Instructions.
6020 //===----------------------------------------------------------------------===//
6023 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6024 /// (',' 'align' i32)?
6025 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6026 Value *Size = nullptr;
6027 LocTy SizeLoc, TyLoc, ASLoc;
6028 unsigned Alignment = 0;
6029 unsigned AddrSpace = 0;
6032 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6033 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6035 if (ParseType(Ty, TyLoc)) return true;
6037 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6038 return Error(TyLoc, "invalid type for alloca");
6040 bool AteExtraComma = false;
6041 if (EatIfPresent(lltok::comma)) {
6042 if (Lex.getKind() == lltok::kw_align) {
6043 if (ParseOptionalAlignment(Alignment))
6045 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6047 } else if (Lex.getKind() == lltok::kw_addrspace) {
6048 ASLoc = Lex.getLoc();
6049 if (ParseOptionalAddrSpace(AddrSpace))
6051 } else if (Lex.getKind() == lltok::MetadataVar) {
6052 AteExtraComma = true;
6054 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6055 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6057 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
6062 if (Size && !Size->getType()->isIntegerTy())
6063 return Error(SizeLoc, "element count must have integer type");
6065 const DataLayout &DL = M->getDataLayout();
6066 unsigned AS = DL.getAllocaAddrSpace();
6067 if (AS != AddrSpace) {
6068 // TODO: In the future it should be possible to specify addrspace per-alloca.
6069 return Error(ASLoc, "address space must match datalayout");
6072 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
6073 AI->setUsedWithInAlloca(IsInAlloca);
6074 AI->setSwiftError(IsSwiftError);
6076 return AteExtraComma ? InstExtraComma : InstNormal;
6080 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6081 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6082 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6083 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6084 Value *Val; LocTy Loc;
6085 unsigned Alignment = 0;
6086 bool AteExtraComma = false;
6087 bool isAtomic = false;
6088 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6089 SynchronizationScope Scope = CrossThread;
6091 if (Lex.getKind() == lltok::kw_atomic) {
6096 bool isVolatile = false;
6097 if (Lex.getKind() == lltok::kw_volatile) {
6103 LocTy ExplicitTypeLoc = Lex.getLoc();
6104 if (ParseType(Ty) ||
6105 ParseToken(lltok::comma, "expected comma after load's type") ||
6106 ParseTypeAndValue(Val, Loc, PFS) ||
6107 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6108 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6111 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6112 return Error(Loc, "load operand must be a pointer to a first class type");
6113 if (isAtomic && !Alignment)
6114 return Error(Loc, "atomic load must have explicit non-zero alignment");
6115 if (Ordering == AtomicOrdering::Release ||
6116 Ordering == AtomicOrdering::AcquireRelease)
6117 return Error(Loc, "atomic load cannot use Release ordering");
6119 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6120 return Error(ExplicitTypeLoc,
6121 "explicit pointee type doesn't match operand's pointee type");
6123 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
6124 return AteExtraComma ? InstExtraComma : InstNormal;
6129 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6130 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6131 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6132 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6133 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6134 unsigned Alignment = 0;
6135 bool AteExtraComma = false;
6136 bool isAtomic = false;
6137 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6138 SynchronizationScope Scope = CrossThread;
6140 if (Lex.getKind() == lltok::kw_atomic) {
6145 bool isVolatile = false;
6146 if (Lex.getKind() == lltok::kw_volatile) {
6151 if (ParseTypeAndValue(Val, Loc, PFS) ||
6152 ParseToken(lltok::comma, "expected ',' after store operand") ||
6153 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6154 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6155 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6158 if (!Ptr->getType()->isPointerTy())
6159 return Error(PtrLoc, "store operand must be a pointer");
6160 if (!Val->getType()->isFirstClassType())
6161 return Error(Loc, "store operand must be a first class value");
6162 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6163 return Error(Loc, "stored value and pointer type do not match");
6164 if (isAtomic && !Alignment)
6165 return Error(Loc, "atomic store must have explicit non-zero alignment");
6166 if (Ordering == AtomicOrdering::Acquire ||
6167 Ordering == AtomicOrdering::AcquireRelease)
6168 return Error(Loc, "atomic store cannot use Acquire ordering");
6170 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
6171 return AteExtraComma ? InstExtraComma : InstNormal;
6175 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6176 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6177 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6178 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6179 bool AteExtraComma = false;
6180 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6181 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6182 SynchronizationScope Scope = CrossThread;
6183 bool isVolatile = false;
6184 bool isWeak = false;
6186 if (EatIfPresent(lltok::kw_weak))
6189 if (EatIfPresent(lltok::kw_volatile))
6192 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6193 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6194 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6195 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6196 ParseTypeAndValue(New, NewLoc, PFS) ||
6197 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6198 ParseOrdering(FailureOrdering))
6201 if (SuccessOrdering == AtomicOrdering::Unordered ||
6202 FailureOrdering == AtomicOrdering::Unordered)
6203 return TokError("cmpxchg cannot be unordered");
6204 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6205 return TokError("cmpxchg failure argument shall be no stronger than the "
6206 "success argument");
6207 if (FailureOrdering == AtomicOrdering::Release ||
6208 FailureOrdering == AtomicOrdering::AcquireRelease)
6210 "cmpxchg failure ordering cannot include release semantics");
6211 if (!Ptr->getType()->isPointerTy())
6212 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6213 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6214 return Error(CmpLoc, "compare value and pointer type do not match");
6215 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6216 return Error(NewLoc, "new value and pointer type do not match");
6217 if (!New->getType()->isFirstClassType())
6218 return Error(NewLoc, "cmpxchg operand must be a first class value");
6219 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6220 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
6221 CXI->setVolatile(isVolatile);
6222 CXI->setWeak(isWeak);
6224 return AteExtraComma ? InstExtraComma : InstNormal;
6228 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6229 /// 'singlethread'? AtomicOrdering
6230 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6231 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6232 bool AteExtraComma = false;
6233 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6234 SynchronizationScope Scope = CrossThread;
6235 bool isVolatile = false;
6236 AtomicRMWInst::BinOp Operation;
6238 if (EatIfPresent(lltok::kw_volatile))
6241 switch (Lex.getKind()) {
6242 default: return TokError("expected binary operation in atomicrmw");
6243 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6244 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6245 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6246 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6247 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6248 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6249 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6250 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6251 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6252 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6253 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6255 Lex.Lex(); // Eat the operation.
6257 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6258 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6259 ParseTypeAndValue(Val, ValLoc, PFS) ||
6260 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6263 if (Ordering == AtomicOrdering::Unordered)
6264 return TokError("atomicrmw cannot be unordered");
6265 if (!Ptr->getType()->isPointerTy())
6266 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6267 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6268 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6269 if (!Val->getType()->isIntegerTy())
6270 return Error(ValLoc, "atomicrmw operand must be an integer");
6271 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6272 if (Size < 8 || (Size & (Size - 1)))
6273 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6276 AtomicRMWInst *RMWI =
6277 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6278 RMWI->setVolatile(isVolatile);
6280 return AteExtraComma ? InstExtraComma : InstNormal;
6284 /// ::= 'fence' 'singlethread'? AtomicOrdering
6285 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6286 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6287 SynchronizationScope Scope = CrossThread;
6288 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6291 if (Ordering == AtomicOrdering::Unordered)
6292 return TokError("fence cannot be unordered");
6293 if (Ordering == AtomicOrdering::Monotonic)
6294 return TokError("fence cannot be monotonic");
6296 Inst = new FenceInst(Context, Ordering, Scope);
6300 /// ParseGetElementPtr
6301 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6302 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6303 Value *Ptr = nullptr;
6304 Value *Val = nullptr;
6307 bool InBounds = EatIfPresent(lltok::kw_inbounds);
6310 LocTy ExplicitTypeLoc = Lex.getLoc();
6311 if (ParseType(Ty) ||
6312 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6313 ParseTypeAndValue(Ptr, Loc, PFS))
6316 Type *BaseType = Ptr->getType();
6317 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6318 if (!BasePointerType)
6319 return Error(Loc, "base of getelementptr must be a pointer");
6321 if (Ty != BasePointerType->getElementType())
6322 return Error(ExplicitTypeLoc,
6323 "explicit pointee type doesn't match operand's pointee type");
6325 SmallVector<Value*, 16> Indices;
6326 bool AteExtraComma = false;
6327 // GEP returns a vector of pointers if at least one of parameters is a vector.
6328 // All vector parameters should have the same vector width.
6329 unsigned GEPWidth = BaseType->isVectorTy() ?
6330 BaseType->getVectorNumElements() : 0;
6332 while (EatIfPresent(lltok::comma)) {
6333 if (Lex.getKind() == lltok::MetadataVar) {
6334 AteExtraComma = true;
6337 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6338 if (!Val->getType()->getScalarType()->isIntegerTy())
6339 return Error(EltLoc, "getelementptr index must be an integer");
6341 if (Val->getType()->isVectorTy()) {
6342 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6343 if (GEPWidth && GEPWidth != ValNumEl)
6344 return Error(EltLoc,
6345 "getelementptr vector index has a wrong number of elements");
6346 GEPWidth = ValNumEl;
6348 Indices.push_back(Val);
6351 SmallPtrSet<Type*, 4> Visited;
6352 if (!Indices.empty() && !Ty->isSized(&Visited))
6353 return Error(Loc, "base element of getelementptr must be sized");
6355 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6356 return Error(Loc, "invalid getelementptr indices");
6357 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6359 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6360 return AteExtraComma ? InstExtraComma : InstNormal;
6363 /// ParseExtractValue
6364 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6365 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6366 Value *Val; LocTy Loc;
6367 SmallVector<unsigned, 4> Indices;
6369 if (ParseTypeAndValue(Val, Loc, PFS) ||
6370 ParseIndexList(Indices, AteExtraComma))
6373 if (!Val->getType()->isAggregateType())
6374 return Error(Loc, "extractvalue operand must be aggregate type");
6376 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6377 return Error(Loc, "invalid indices for extractvalue");
6378 Inst = ExtractValueInst::Create(Val, Indices);
6379 return AteExtraComma ? InstExtraComma : InstNormal;
6382 /// ParseInsertValue
6383 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6384 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6385 Value *Val0, *Val1; LocTy Loc0, Loc1;
6386 SmallVector<unsigned, 4> Indices;
6388 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6389 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6390 ParseTypeAndValue(Val1, Loc1, PFS) ||
6391 ParseIndexList(Indices, AteExtraComma))
6394 if (!Val0->getType()->isAggregateType())
6395 return Error(Loc0, "insertvalue operand must be aggregate type");
6397 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6399 return Error(Loc0, "invalid indices for insertvalue");
6400 if (IndexedType != Val1->getType())
6401 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6402 getTypeString(Val1->getType()) + "' instead of '" +
6403 getTypeString(IndexedType) + "'");
6404 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6405 return AteExtraComma ? InstExtraComma : InstNormal;
6408 //===----------------------------------------------------------------------===//
6409 // Embedded metadata.
6410 //===----------------------------------------------------------------------===//
6412 /// ParseMDNodeVector
6413 /// ::= { Element (',' Element)* }
6415 /// ::= 'null' | TypeAndValue
6416 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6417 if (ParseToken(lltok::lbrace, "expected '{' here"))
6420 // Check for an empty list.
6421 if (EatIfPresent(lltok::rbrace))
6425 // Null is a special case since it is typeless.
6426 if (EatIfPresent(lltok::kw_null)) {
6427 Elts.push_back(nullptr);
6432 if (ParseMetadata(MD, nullptr))
6435 } while (EatIfPresent(lltok::comma));
6437 return ParseToken(lltok::rbrace, "expected end of metadata node");
6440 //===----------------------------------------------------------------------===//
6441 // Use-list order directives.
6442 //===----------------------------------------------------------------------===//
6443 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6446 return Error(Loc, "value has no uses");
6448 unsigned NumUses = 0;
6449 SmallDenseMap<const Use *, unsigned, 16> Order;
6450 for (const Use &U : V->uses()) {
6451 if (++NumUses > Indexes.size())
6453 Order[&U] = Indexes[NumUses - 1];
6456 return Error(Loc, "value only has one use");
6457 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6458 return Error(Loc, "wrong number of indexes, expected " +
6459 Twine(std::distance(V->use_begin(), V->use_end())));
6461 V->sortUseList([&](const Use &L, const Use &R) {
6462 return Order.lookup(&L) < Order.lookup(&R);
6467 /// ParseUseListOrderIndexes
6468 /// ::= '{' uint32 (',' uint32)+ '}'
6469 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6470 SMLoc Loc = Lex.getLoc();
6471 if (ParseToken(lltok::lbrace, "expected '{' here"))
6473 if (Lex.getKind() == lltok::rbrace)
6474 return Lex.Error("expected non-empty list of uselistorder indexes");
6476 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6477 // indexes should be distinct numbers in the range [0, size-1], and should
6479 unsigned Offset = 0;
6481 bool IsOrdered = true;
6482 assert(Indexes.empty() && "Expected empty order vector");
6485 if (ParseUInt32(Index))
6488 // Update consistency checks.
6489 Offset += Index - Indexes.size();
6490 Max = std::max(Max, Index);
6491 IsOrdered &= Index == Indexes.size();
6493 Indexes.push_back(Index);
6494 } while (EatIfPresent(lltok::comma));
6496 if (ParseToken(lltok::rbrace, "expected '}' here"))
6499 if (Indexes.size() < 2)
6500 return Error(Loc, "expected >= 2 uselistorder indexes");
6501 if (Offset != 0 || Max >= Indexes.size())
6502 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6504 return Error(Loc, "expected uselistorder indexes to change the order");
6509 /// ParseUseListOrder
6510 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6511 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6512 SMLoc Loc = Lex.getLoc();
6513 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6517 SmallVector<unsigned, 16> Indexes;
6518 if (ParseTypeAndValue(V, PFS) ||
6519 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6520 ParseUseListOrderIndexes(Indexes))
6523 return sortUseListOrder(V, Indexes, Loc);
6526 /// ParseUseListOrderBB
6527 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6528 bool LLParser::ParseUseListOrderBB() {
6529 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6530 SMLoc Loc = Lex.getLoc();
6534 SmallVector<unsigned, 16> Indexes;
6535 if (ParseValID(Fn) ||
6536 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6537 ParseValID(Label) ||
6538 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6539 ParseUseListOrderIndexes(Indexes))
6542 // Check the function.
6544 if (Fn.Kind == ValID::t_GlobalName)
6545 GV = M->getNamedValue(Fn.StrVal);
6546 else if (Fn.Kind == ValID::t_GlobalID)
6547 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6549 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6551 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6552 auto *F = dyn_cast<Function>(GV);
6554 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6555 if (F->isDeclaration())
6556 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6558 // Check the basic block.
6559 if (Label.Kind == ValID::t_LocalID)
6560 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6561 if (Label.Kind != ValID::t_LocalName)
6562 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6563 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
6565 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6566 if (!isa<BasicBlock>(V))
6567 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6569 return sortUseListOrder(V, Indexes, Loc);