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/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/AsmParser/SlotMapping.h"
18 #include "llvm/IR/AutoUpgrade.h"
19 #include "llvm/IR/CallingConv.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueSymbolTable.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/SaveAndRestore.h"
33 #include "llvm/Support/raw_ostream.h"
36 static std::string getTypeString(Type *T) {
38 raw_string_ostream Tmp(Result);
43 /// Run: module ::= toplevelentity*
44 bool LLParser::Run() {
48 return ParseTopLevelEntities() ||
49 ValidateEndOfModule();
52 bool LLParser::parseStandaloneConstantValue(Constant *&C,
53 const SlotMapping *Slots) {
54 restoreParsingState(Slots);
58 if (ParseType(Ty) || parseConstantValue(Ty, C))
60 if (Lex.getKind() != lltok::Eof)
61 return Error(Lex.getLoc(), "expected end of string");
65 void LLParser::restoreParsingState(const SlotMapping *Slots) {
68 NumberedVals = Slots->GlobalValues;
69 NumberedMetadata = Slots->MetadataNodes;
70 for (const auto &I : Slots->NamedTypes)
72 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
73 for (const auto &I : Slots->Types)
75 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
78 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
80 bool LLParser::ValidateEndOfModule() {
81 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
82 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
84 // Handle any function attribute group forward references.
85 for (std::map<Value*, std::vector<unsigned> >::iterator
86 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
89 std::vector<unsigned> &Vec = I->second;
92 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
94 B.merge(NumberedAttrBuilders[*VI]);
96 if (Function *Fn = dyn_cast<Function>(V)) {
97 AttributeSet AS = Fn->getAttributes();
98 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
99 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
100 AS.getFnAttributes());
104 // If the alignment was parsed as an attribute, move to the alignment
106 if (FnAttrs.hasAlignmentAttr()) {
107 Fn->setAlignment(FnAttrs.getAlignment());
108 FnAttrs.removeAttribute(Attribute::Alignment);
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 Fn->setAttributes(AS);
116 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
117 AttributeSet AS = CI->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
126 CI->setAttributes(AS);
127 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
128 AttributeSet AS = II->getAttributes();
129 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
130 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
131 AS.getFnAttributes());
133 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
134 AttributeSet::get(Context,
135 AttributeSet::FunctionIndex,
137 II->setAttributes(AS);
139 llvm_unreachable("invalid object with forward attribute group reference");
143 // If there are entries in ForwardRefBlockAddresses at this point, the
144 // function was never defined.
145 if (!ForwardRefBlockAddresses.empty())
146 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
147 "expected function name in blockaddress");
149 for (const auto &NT : NumberedTypes)
150 if (NT.second.second.isValid())
151 return Error(NT.second.second,
152 "use of undefined type '%" + Twine(NT.first) + "'");
154 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
155 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
156 if (I->second.second.isValid())
157 return Error(I->second.second,
158 "use of undefined type named '" + I->getKey() + "'");
160 if (!ForwardRefComdats.empty())
161 return Error(ForwardRefComdats.begin()->second,
162 "use of undefined comdat '$" +
163 ForwardRefComdats.begin()->first + "'");
165 if (!ForwardRefVals.empty())
166 return Error(ForwardRefVals.begin()->second.second,
167 "use of undefined value '@" + ForwardRefVals.begin()->first +
170 if (!ForwardRefValIDs.empty())
171 return Error(ForwardRefValIDs.begin()->second.second,
172 "use of undefined value '@" +
173 Twine(ForwardRefValIDs.begin()->first) + "'");
175 if (!ForwardRefMDNodes.empty())
176 return Error(ForwardRefMDNodes.begin()->second.second,
177 "use of undefined metadata '!" +
178 Twine(ForwardRefMDNodes.begin()->first) + "'");
180 // Resolve metadata cycles.
181 for (auto &N : NumberedMetadata) {
182 if (N.second && !N.second->isResolved())
183 N.second->resolveCycles();
186 // Look for intrinsic functions and CallInst that need to be upgraded
187 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
188 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
190 UpgradeDebugInfo(*M);
194 // Initialize the slot mapping.
195 // Because by this point we've parsed and validated everything, we can "steal"
196 // the mapping from LLParser as it doesn't need it anymore.
197 Slots->GlobalValues = std::move(NumberedVals);
198 Slots->MetadataNodes = std::move(NumberedMetadata);
199 for (const auto &I : NamedTypes)
200 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
201 for (const auto &I : NumberedTypes)
202 Slots->Types.insert(std::make_pair(I.first, I.second.first));
207 //===----------------------------------------------------------------------===//
208 // Top-Level Entities
209 //===----------------------------------------------------------------------===//
211 bool LLParser::ParseTopLevelEntities() {
213 switch (Lex.getKind()) {
214 default: return TokError("expected top-level entity");
215 case lltok::Eof: return false;
216 case lltok::kw_declare: if (ParseDeclare()) return true; break;
217 case lltok::kw_define: if (ParseDefine()) return true; break;
218 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
219 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
220 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
221 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
222 case lltok::LocalVar: if (ParseNamedType()) return true; break;
223 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
224 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
225 case lltok::ComdatVar: if (parseComdat()) return true; break;
226 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
227 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
229 // The Global variable production with no name can have many different
230 // optional leading prefixes, the production is:
231 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
232 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
233 // ('constant'|'global') ...
234 case lltok::kw_private: // OptionalLinkage
235 case lltok::kw_internal: // OptionalLinkage
236 case lltok::kw_weak: // OptionalLinkage
237 case lltok::kw_weak_odr: // OptionalLinkage
238 case lltok::kw_linkonce: // OptionalLinkage
239 case lltok::kw_linkonce_odr: // OptionalLinkage
240 case lltok::kw_appending: // OptionalLinkage
241 case lltok::kw_common: // OptionalLinkage
242 case lltok::kw_extern_weak: // OptionalLinkage
243 case lltok::kw_external: // OptionalLinkage
244 case lltok::kw_default: // OptionalVisibility
245 case lltok::kw_hidden: // OptionalVisibility
246 case lltok::kw_protected: // OptionalVisibility
247 case lltok::kw_dllimport: // OptionalDLLStorageClass
248 case lltok::kw_dllexport: // OptionalDLLStorageClass
249 case lltok::kw_thread_local: // OptionalThreadLocal
250 case lltok::kw_addrspace: // OptionalAddrSpace
251 case lltok::kw_constant: // GlobalType
252 case lltok::kw_global: { // GlobalType
253 unsigned Linkage, Visibility, DLLStorageClass;
255 GlobalVariable::ThreadLocalMode TLM;
257 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
258 ParseOptionalVisibility(Visibility) ||
259 ParseOptionalDLLStorageClass(DLLStorageClass) ||
260 ParseOptionalThreadLocal(TLM) ||
261 parseOptionalUnnamedAddr(UnnamedAddr) ||
262 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
263 DLLStorageClass, TLM, UnnamedAddr))
268 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
269 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
270 case lltok::kw_uselistorder_bb:
271 if (ParseUseListOrderBB()) return true; break;
278 /// ::= 'module' 'asm' STRINGCONSTANT
279 bool LLParser::ParseModuleAsm() {
280 assert(Lex.getKind() == lltok::kw_module);
284 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
285 ParseStringConstant(AsmStr)) return true;
287 M->appendModuleInlineAsm(AsmStr);
292 /// ::= 'target' 'triple' '=' STRINGCONSTANT
293 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
294 bool LLParser::ParseTargetDefinition() {
295 assert(Lex.getKind() == lltok::kw_target);
298 default: return TokError("unknown target property");
299 case lltok::kw_triple:
301 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
302 ParseStringConstant(Str))
304 M->setTargetTriple(Str);
306 case lltok::kw_datalayout:
308 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
309 ParseStringConstant(Str))
311 M->setDataLayout(Str);
317 /// ::= 'deplibs' '=' '[' ']'
318 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
319 /// FIXME: Remove in 4.0. Currently parse, but ignore.
320 bool LLParser::ParseDepLibs() {
321 assert(Lex.getKind() == lltok::kw_deplibs);
323 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
324 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
327 if (EatIfPresent(lltok::rsquare))
332 if (ParseStringConstant(Str)) return true;
333 } while (EatIfPresent(lltok::comma));
335 return ParseToken(lltok::rsquare, "expected ']' at end of list");
338 /// ParseUnnamedType:
339 /// ::= LocalVarID '=' 'type' type
340 bool LLParser::ParseUnnamedType() {
341 LocTy TypeLoc = Lex.getLoc();
342 unsigned TypeID = Lex.getUIntVal();
343 Lex.Lex(); // eat LocalVarID;
345 if (ParseToken(lltok::equal, "expected '=' after name") ||
346 ParseToken(lltok::kw_type, "expected 'type' after '='"))
349 Type *Result = nullptr;
350 if (ParseStructDefinition(TypeLoc, "",
351 NumberedTypes[TypeID], Result)) return true;
353 if (!isa<StructType>(Result)) {
354 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
356 return Error(TypeLoc, "non-struct types may not be recursive");
357 Entry.first = Result;
358 Entry.second = SMLoc();
366 /// ::= LocalVar '=' 'type' type
367 bool LLParser::ParseNamedType() {
368 std::string Name = Lex.getStrVal();
369 LocTy NameLoc = Lex.getLoc();
370 Lex.Lex(); // eat LocalVar.
372 if (ParseToken(lltok::equal, "expected '=' after name") ||
373 ParseToken(lltok::kw_type, "expected 'type' after name"))
376 Type *Result = nullptr;
377 if (ParseStructDefinition(NameLoc, Name,
378 NamedTypes[Name], Result)) return true;
380 if (!isa<StructType>(Result)) {
381 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
383 return Error(NameLoc, "non-struct types may not be recursive");
384 Entry.first = Result;
385 Entry.second = SMLoc();
393 /// ::= 'declare' FunctionHeader
394 bool LLParser::ParseDeclare() {
395 assert(Lex.getKind() == lltok::kw_declare);
399 return ParseFunctionHeader(F, false);
403 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
404 bool LLParser::ParseDefine() {
405 assert(Lex.getKind() == lltok::kw_define);
409 return ParseFunctionHeader(F, true) ||
410 ParseOptionalFunctionMetadata(*F) ||
411 ParseFunctionBody(*F);
417 bool LLParser::ParseGlobalType(bool &IsConstant) {
418 if (Lex.getKind() == lltok::kw_constant)
420 else if (Lex.getKind() == lltok::kw_global)
424 return TokError("expected 'global' or 'constant'");
430 /// ParseUnnamedGlobal:
431 /// OptionalVisibility ALIAS ...
432 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433 /// ... -> global variable
434 /// GlobalID '=' OptionalVisibility ALIAS ...
435 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
436 /// ... -> global variable
437 bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
440 LocTy NameLoc = Lex.getLoc();
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
447 Lex.Lex(); // eat GlobalID;
449 if (ParseToken(lltok::equal, "expected '=' after name"))
454 unsigned Linkage, Visibility, DLLStorageClass;
455 GlobalVariable::ThreadLocalMode TLM;
457 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
458 ParseOptionalVisibility(Visibility) ||
459 ParseOptionalDLLStorageClass(DLLStorageClass) ||
460 ParseOptionalThreadLocal(TLM) ||
461 parseOptionalUnnamedAddr(UnnamedAddr))
464 if (Lex.getKind() != lltok::kw_alias)
465 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
466 DLLStorageClass, TLM, UnnamedAddr);
467 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
471 /// ParseNamedGlobal:
472 /// GlobalVar '=' OptionalVisibility ALIAS ...
473 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
474 /// ... -> global variable
475 bool LLParser::ParseNamedGlobal() {
476 assert(Lex.getKind() == lltok::GlobalVar);
477 LocTy NameLoc = Lex.getLoc();
478 std::string Name = Lex.getStrVal();
482 unsigned Linkage, Visibility, DLLStorageClass;
483 GlobalVariable::ThreadLocalMode TLM;
485 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
486 ParseOptionalLinkage(Linkage, HasLinkage) ||
487 ParseOptionalVisibility(Visibility) ||
488 ParseOptionalDLLStorageClass(DLLStorageClass) ||
489 ParseOptionalThreadLocal(TLM) ||
490 parseOptionalUnnamedAddr(UnnamedAddr))
493 if (Lex.getKind() != lltok::kw_alias)
494 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
495 DLLStorageClass, TLM, UnnamedAddr);
497 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
501 bool LLParser::parseComdat() {
502 assert(Lex.getKind() == lltok::ComdatVar);
503 std::string Name = Lex.getStrVal();
504 LocTy NameLoc = Lex.getLoc();
507 if (ParseToken(lltok::equal, "expected '=' here"))
510 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
511 return TokError("expected comdat type");
513 Comdat::SelectionKind SK;
514 switch (Lex.getKind()) {
516 return TokError("unknown selection kind");
520 case lltok::kw_exactmatch:
521 SK = Comdat::ExactMatch;
523 case lltok::kw_largest:
524 SK = Comdat::Largest;
526 case lltok::kw_noduplicates:
527 SK = Comdat::NoDuplicates;
529 case lltok::kw_samesize:
530 SK = Comdat::SameSize;
535 // See if the comdat was forward referenced, if so, use the comdat.
536 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
537 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
538 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
539 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
542 if (I != ComdatSymTab.end())
545 C = M->getOrInsertComdat(Name);
546 C->setSelectionKind(SK);
552 // ::= '!' STRINGCONSTANT
553 bool LLParser::ParseMDString(MDString *&Result) {
555 if (ParseStringConstant(Str)) return true;
556 llvm::UpgradeMDStringConstant(Str);
557 Result = MDString::get(Context, Str);
562 // ::= '!' MDNodeNumber
563 bool LLParser::ParseMDNodeID(MDNode *&Result) {
564 // !{ ..., !42, ... }
566 if (ParseUInt32(MID))
569 // If not a forward reference, just return it now.
570 if (NumberedMetadata.count(MID)) {
571 Result = NumberedMetadata[MID];
575 // Otherwise, create MDNode forward reference.
576 auto &FwdRef = ForwardRefMDNodes[MID];
577 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
579 Result = FwdRef.first.get();
580 NumberedMetadata[MID].reset(Result);
584 /// ParseNamedMetadata:
585 /// !foo = !{ !1, !2 }
586 bool LLParser::ParseNamedMetadata() {
587 assert(Lex.getKind() == lltok::MetadataVar);
588 std::string Name = Lex.getStrVal();
591 if (ParseToken(lltok::equal, "expected '=' here") ||
592 ParseToken(lltok::exclaim, "Expected '!' here") ||
593 ParseToken(lltok::lbrace, "Expected '{' here"))
596 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
597 if (Lex.getKind() != lltok::rbrace)
599 if (ParseToken(lltok::exclaim, "Expected '!' here"))
603 if (ParseMDNodeID(N)) return true;
605 } while (EatIfPresent(lltok::comma));
607 return ParseToken(lltok::rbrace, "expected end of metadata node");
610 /// ParseStandaloneMetadata:
612 bool LLParser::ParseStandaloneMetadata() {
613 assert(Lex.getKind() == lltok::exclaim);
615 unsigned MetadataID = 0;
618 if (ParseUInt32(MetadataID) ||
619 ParseToken(lltok::equal, "expected '=' here"))
622 // Detect common error, from old metadata syntax.
623 if (Lex.getKind() == lltok::Type)
624 return TokError("unexpected type in metadata definition");
626 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
627 if (Lex.getKind() == lltok::MetadataVar) {
628 if (ParseSpecializedMDNode(Init, IsDistinct))
630 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
631 ParseMDTuple(Init, IsDistinct))
634 // See if this was forward referenced, if so, handle it.
635 auto FI = ForwardRefMDNodes.find(MetadataID);
636 if (FI != ForwardRefMDNodes.end()) {
637 FI->second.first->replaceAllUsesWith(Init);
638 ForwardRefMDNodes.erase(FI);
640 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
642 if (NumberedMetadata.count(MetadataID))
643 return TokError("Metadata id is already used");
644 NumberedMetadata[MetadataID].reset(Init);
650 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
651 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
652 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
656 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
657 /// OptionalDLLStorageClass OptionalThreadLocal
658 /// OptionalUnnamedAddr 'alias' Aliasee
663 /// Everything through OptionalUnnamedAddr has already been parsed.
665 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
666 unsigned Visibility, unsigned DLLStorageClass,
667 GlobalVariable::ThreadLocalMode TLM,
669 assert(Lex.getKind() == lltok::kw_alias);
672 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
674 if(!GlobalAlias::isValidLinkage(Linkage))
675 return Error(NameLoc, "invalid linkage type for alias");
677 if (!isValidVisibilityForLinkage(Visibility, L))
678 return Error(NameLoc,
679 "symbol with local linkage must have default visibility");
682 LocTy ExplicitTypeLoc = Lex.getLoc();
684 ParseToken(lltok::comma, "expected comma after alias's type"))
688 LocTy AliaseeLoc = Lex.getLoc();
689 if (Lex.getKind() != lltok::kw_bitcast &&
690 Lex.getKind() != lltok::kw_getelementptr &&
691 Lex.getKind() != lltok::kw_addrspacecast &&
692 Lex.getKind() != lltok::kw_inttoptr) {
693 if (ParseGlobalTypeAndValue(Aliasee))
696 // The bitcast dest type is not present, it is implied by the dest type.
700 if (ID.Kind != ValID::t_Constant)
701 return Error(AliaseeLoc, "invalid aliasee");
702 Aliasee = ID.ConstantVal;
705 Type *AliaseeType = Aliasee->getType();
706 auto *PTy = dyn_cast<PointerType>(AliaseeType);
708 return Error(AliaseeLoc, "An alias must have pointer type");
710 if (Ty != PTy->getElementType())
713 "explicit pointee type doesn't match operand's pointee type");
715 // Okay, create the alias but do not insert it into the module yet.
716 std::unique_ptr<GlobalAlias> GA(
717 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
718 Aliasee, /*Parent*/ nullptr));
719 GA->setThreadLocalMode(TLM);
720 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
721 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
722 GA->setUnnamedAddr(UnnamedAddr);
725 NumberedVals.push_back(GA.get());
727 // See if this value already exists in the symbol table. If so, it is either
728 // a redefinition or a definition of a forward reference.
729 if (GlobalValue *Val = M->getNamedValue(Name)) {
730 // See if this was a redefinition. If so, there is no entry in
732 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
733 I = ForwardRefVals.find(Name);
734 if (I == ForwardRefVals.end())
735 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
737 // Otherwise, this was a definition of forward ref. Verify that types
739 if (Val->getType() != GA->getType())
740 return Error(NameLoc,
741 "forward reference and definition of alias have different types");
743 // If they agree, just RAUW the old value with the alias and remove the
745 Val->replaceAllUsesWith(GA.get());
746 Val->eraseFromParent();
747 ForwardRefVals.erase(I);
750 // Insert into the module, we know its name won't collide now.
751 M->getAliasList().push_back(GA.get());
752 assert(GA->getName() == Name && "Should not be a name conflict!");
754 // The module owns this now
761 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
762 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
763 /// OptionalExternallyInitialized GlobalType Type Const
764 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
765 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
766 /// OptionalExternallyInitialized GlobalType Type Const
768 /// Everything up to and including OptionalUnnamedAddr has been parsed
771 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
772 unsigned Linkage, bool HasLinkage,
773 unsigned Visibility, unsigned DLLStorageClass,
774 GlobalVariable::ThreadLocalMode TLM,
776 if (!isValidVisibilityForLinkage(Visibility, Linkage))
777 return Error(NameLoc,
778 "symbol with local linkage must have default visibility");
781 bool IsConstant, IsExternallyInitialized;
782 LocTy IsExternallyInitializedLoc;
786 if (ParseOptionalAddrSpace(AddrSpace) ||
787 ParseOptionalToken(lltok::kw_externally_initialized,
788 IsExternallyInitialized,
789 &IsExternallyInitializedLoc) ||
790 ParseGlobalType(IsConstant) ||
791 ParseType(Ty, TyLoc))
794 // If the linkage is specified and is external, then no initializer is
796 Constant *Init = nullptr;
797 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
798 Linkage != GlobalValue::ExternalLinkage)) {
799 if (ParseGlobalValue(Ty, Init))
803 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
804 return Error(TyLoc, "invalid type for global variable");
806 GlobalValue *GVal = nullptr;
808 // See if the global was forward referenced, if so, use the global.
810 GVal = M->getNamedValue(Name);
812 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
813 return Error(NameLoc, "redefinition of global '@" + Name + "'");
816 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
817 I = ForwardRefValIDs.find(NumberedVals.size());
818 if (I != ForwardRefValIDs.end()) {
819 GVal = I->second.first;
820 ForwardRefValIDs.erase(I);
826 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
827 Name, nullptr, GlobalVariable::NotThreadLocal,
830 if (GVal->getValueType() != Ty)
832 "forward reference and definition of global have different types");
834 GV = cast<GlobalVariable>(GVal);
836 // Move the forward-reference to the correct spot in the module.
837 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
841 NumberedVals.push_back(GV);
843 // Set the parsed properties on the global.
845 GV->setInitializer(Init);
846 GV->setConstant(IsConstant);
847 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
848 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
849 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
850 GV->setExternallyInitialized(IsExternallyInitialized);
851 GV->setThreadLocalMode(TLM);
852 GV->setUnnamedAddr(UnnamedAddr);
854 // Parse attributes on the global.
855 while (Lex.getKind() == lltok::comma) {
858 if (Lex.getKind() == lltok::kw_section) {
860 GV->setSection(Lex.getStrVal());
861 if (ParseToken(lltok::StringConstant, "expected global section string"))
863 } else if (Lex.getKind() == lltok::kw_align) {
865 if (ParseOptionalAlignment(Alignment)) return true;
866 GV->setAlignment(Alignment);
869 if (parseOptionalComdat(Name, C))
874 return TokError("unknown global variable property!");
881 /// ParseUnnamedAttrGrp
882 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
883 bool LLParser::ParseUnnamedAttrGrp() {
884 assert(Lex.getKind() == lltok::kw_attributes);
885 LocTy AttrGrpLoc = Lex.getLoc();
888 if (Lex.getKind() != lltok::AttrGrpID)
889 return TokError("expected attribute group id");
891 unsigned VarID = Lex.getUIntVal();
892 std::vector<unsigned> unused;
896 if (ParseToken(lltok::equal, "expected '=' here") ||
897 ParseToken(lltok::lbrace, "expected '{' here") ||
898 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
900 ParseToken(lltok::rbrace, "expected end of attribute group"))
903 if (!NumberedAttrBuilders[VarID].hasAttributes())
904 return Error(AttrGrpLoc, "attribute group has no attributes");
909 /// ParseFnAttributeValuePairs
910 /// ::= <attr> | <attr> '=' <value>
911 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
912 std::vector<unsigned> &FwdRefAttrGrps,
913 bool inAttrGrp, LocTy &BuiltinLoc) {
914 bool HaveError = false;
919 lltok::Kind Token = Lex.getKind();
920 if (Token == lltok::kw_builtin)
921 BuiltinLoc = Lex.getLoc();
924 if (!inAttrGrp) return HaveError;
925 return Error(Lex.getLoc(), "unterminated attribute group");
930 case lltok::AttrGrpID: {
931 // Allow a function to reference an attribute group:
933 // define void @foo() #1 { ... }
937 "cannot have an attribute group reference in an attribute group");
939 unsigned AttrGrpNum = Lex.getUIntVal();
940 if (inAttrGrp) break;
942 // Save the reference to the attribute group. We'll fill it in later.
943 FwdRefAttrGrps.push_back(AttrGrpNum);
946 // Target-dependent attributes:
947 case lltok::StringConstant: {
948 if (ParseStringAttribute(B))
953 // Target-independent attributes:
954 case lltok::kw_align: {
955 // As a hack, we allow function alignment to be initially parsed as an
956 // attribute on a function declaration/definition or added to an attribute
957 // group and later moved to the alignment field.
961 if (ParseToken(lltok::equal, "expected '=' here") ||
962 ParseUInt32(Alignment))
965 if (ParseOptionalAlignment(Alignment))
968 B.addAlignmentAttr(Alignment);
971 case lltok::kw_alignstack: {
975 if (ParseToken(lltok::equal, "expected '=' here") ||
976 ParseUInt32(Alignment))
979 if (ParseOptionalStackAlignment(Alignment))
982 B.addStackAlignmentAttr(Alignment);
985 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
986 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
987 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
988 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
989 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
990 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
991 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
992 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
993 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
994 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
995 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
996 case lltok::kw_noimplicitfloat:
997 B.addAttribute(Attribute::NoImplicitFloat); break;
998 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
999 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1000 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1001 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1002 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1003 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1004 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1005 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1006 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1007 case lltok::kw_returns_twice:
1008 B.addAttribute(Attribute::ReturnsTwice); break;
1009 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1010 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1011 case lltok::kw_sspstrong:
1012 B.addAttribute(Attribute::StackProtectStrong); break;
1013 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1014 case lltok::kw_sanitize_address:
1015 B.addAttribute(Attribute::SanitizeAddress); break;
1016 case lltok::kw_sanitize_thread:
1017 B.addAttribute(Attribute::SanitizeThread); break;
1018 case lltok::kw_sanitize_memory:
1019 B.addAttribute(Attribute::SanitizeMemory); break;
1020 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1023 case lltok::kw_inreg:
1024 case lltok::kw_signext:
1025 case lltok::kw_zeroext:
1028 "invalid use of attribute on a function");
1030 case lltok::kw_byval:
1031 case lltok::kw_dereferenceable:
1032 case lltok::kw_dereferenceable_or_null:
1033 case lltok::kw_inalloca:
1034 case lltok::kw_nest:
1035 case lltok::kw_noalias:
1036 case lltok::kw_nocapture:
1037 case lltok::kw_nonnull:
1038 case lltok::kw_returned:
1039 case lltok::kw_sret:
1042 "invalid use of parameter-only attribute on a function");
1050 //===----------------------------------------------------------------------===//
1051 // GlobalValue Reference/Resolution Routines.
1052 //===----------------------------------------------------------------------===//
1054 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1055 const std::string &Name) {
1056 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1057 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1059 return new GlobalVariable(*M, PTy->getElementType(), false,
1060 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1061 nullptr, GlobalVariable::NotThreadLocal,
1062 PTy->getAddressSpace());
1065 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1066 /// forward reference record if needed. This can return null if the value
1067 /// exists but does not have the right type.
1068 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1070 PointerType *PTy = dyn_cast<PointerType>(Ty);
1072 Error(Loc, "global variable reference must have pointer type");
1076 // Look this name up in the normal function symbol table.
1078 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1080 // If this is a forward reference for the value, see if we already created a
1081 // forward ref record.
1083 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1084 I = ForwardRefVals.find(Name);
1085 if (I != ForwardRefVals.end())
1086 Val = I->second.first;
1089 // If we have the value in the symbol table or fwd-ref table, return it.
1091 if (Val->getType() == Ty) return Val;
1092 Error(Loc, "'@" + Name + "' defined with type '" +
1093 getTypeString(Val->getType()) + "'");
1097 // Otherwise, create a new forward reference for this value and remember it.
1098 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1099 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1103 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1104 PointerType *PTy = dyn_cast<PointerType>(Ty);
1106 Error(Loc, "global variable reference must have pointer type");
1110 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1112 // If this is a forward reference for the value, see if we already created a
1113 // forward ref record.
1115 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1116 I = ForwardRefValIDs.find(ID);
1117 if (I != ForwardRefValIDs.end())
1118 Val = I->second.first;
1121 // If we have the value in the symbol table or fwd-ref table, return it.
1123 if (Val->getType() == Ty) return Val;
1124 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1125 getTypeString(Val->getType()) + "'");
1129 // Otherwise, create a new forward reference for this value and remember it.
1130 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1131 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1136 //===----------------------------------------------------------------------===//
1137 // Comdat Reference/Resolution Routines.
1138 //===----------------------------------------------------------------------===//
1140 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1141 // Look this name up in the comdat symbol table.
1142 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1143 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1144 if (I != ComdatSymTab.end())
1147 // Otherwise, create a new forward reference for this value and remember it.
1148 Comdat *C = M->getOrInsertComdat(Name);
1149 ForwardRefComdats[Name] = Loc;
1154 //===----------------------------------------------------------------------===//
1156 //===----------------------------------------------------------------------===//
1158 /// ParseToken - If the current token has the specified kind, eat it and return
1159 /// success. Otherwise, emit the specified error and return failure.
1160 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1161 if (Lex.getKind() != T)
1162 return TokError(ErrMsg);
1167 /// ParseStringConstant
1168 /// ::= StringConstant
1169 bool LLParser::ParseStringConstant(std::string &Result) {
1170 if (Lex.getKind() != lltok::StringConstant)
1171 return TokError("expected string constant");
1172 Result = Lex.getStrVal();
1179 bool LLParser::ParseUInt32(unsigned &Val) {
1180 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1181 return TokError("expected integer");
1182 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1183 if (Val64 != unsigned(Val64))
1184 return TokError("expected 32-bit integer (too large)");
1192 bool LLParser::ParseUInt64(uint64_t &Val) {
1193 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1194 return TokError("expected integer");
1195 Val = Lex.getAPSIntVal().getLimitedValue();
1201 /// := 'localdynamic'
1202 /// := 'initialexec'
1204 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1205 switch (Lex.getKind()) {
1207 return TokError("expected localdynamic, initialexec or localexec");
1208 case lltok::kw_localdynamic:
1209 TLM = GlobalVariable::LocalDynamicTLSModel;
1211 case lltok::kw_initialexec:
1212 TLM = GlobalVariable::InitialExecTLSModel;
1214 case lltok::kw_localexec:
1215 TLM = GlobalVariable::LocalExecTLSModel;
1223 /// ParseOptionalThreadLocal
1225 /// := 'thread_local'
1226 /// := 'thread_local' '(' tlsmodel ')'
1227 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1228 TLM = GlobalVariable::NotThreadLocal;
1229 if (!EatIfPresent(lltok::kw_thread_local))
1232 TLM = GlobalVariable::GeneralDynamicTLSModel;
1233 if (Lex.getKind() == lltok::lparen) {
1235 return ParseTLSModel(TLM) ||
1236 ParseToken(lltok::rparen, "expected ')' after thread local model");
1241 /// ParseOptionalAddrSpace
1243 /// := 'addrspace' '(' uint32 ')'
1244 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1246 if (!EatIfPresent(lltok::kw_addrspace))
1248 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1249 ParseUInt32(AddrSpace) ||
1250 ParseToken(lltok::rparen, "expected ')' in address space");
1253 /// ParseStringAttribute
1254 /// := StringConstant
1255 /// := StringConstant '=' StringConstant
1256 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1257 std::string Attr = Lex.getStrVal();
1260 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1262 B.addAttribute(Attr, Val);
1266 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1267 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1268 bool HaveError = false;
1273 lltok::Kind Token = Lex.getKind();
1275 default: // End of attributes.
1277 case lltok::StringConstant: {
1278 if (ParseStringAttribute(B))
1282 case lltok::kw_align: {
1284 if (ParseOptionalAlignment(Alignment))
1286 B.addAlignmentAttr(Alignment);
1289 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1290 case lltok::kw_dereferenceable: {
1292 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1294 B.addDereferenceableAttr(Bytes);
1297 case lltok::kw_dereferenceable_or_null: {
1299 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1301 B.addDereferenceableOrNullAttr(Bytes);
1304 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1305 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1306 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1307 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1308 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1309 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1310 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1311 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1312 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1313 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1314 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1315 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1317 case lltok::kw_alignstack:
1318 case lltok::kw_alwaysinline:
1319 case lltok::kw_argmemonly:
1320 case lltok::kw_builtin:
1321 case lltok::kw_inlinehint:
1322 case lltok::kw_jumptable:
1323 case lltok::kw_minsize:
1324 case lltok::kw_naked:
1325 case lltok::kw_nobuiltin:
1326 case lltok::kw_noduplicate:
1327 case lltok::kw_noimplicitfloat:
1328 case lltok::kw_noinline:
1329 case lltok::kw_nonlazybind:
1330 case lltok::kw_noredzone:
1331 case lltok::kw_noreturn:
1332 case lltok::kw_nounwind:
1333 case lltok::kw_optnone:
1334 case lltok::kw_optsize:
1335 case lltok::kw_returns_twice:
1336 case lltok::kw_sanitize_address:
1337 case lltok::kw_sanitize_memory:
1338 case lltok::kw_sanitize_thread:
1340 case lltok::kw_sspreq:
1341 case lltok::kw_sspstrong:
1342 case lltok::kw_safestack:
1343 case lltok::kw_uwtable:
1344 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1352 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1353 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1354 bool HaveError = false;
1359 lltok::Kind Token = Lex.getKind();
1361 default: // End of attributes.
1363 case lltok::StringConstant: {
1364 if (ParseStringAttribute(B))
1368 case lltok::kw_dereferenceable: {
1370 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1372 B.addDereferenceableAttr(Bytes);
1375 case lltok::kw_dereferenceable_or_null: {
1377 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1379 B.addDereferenceableOrNullAttr(Bytes);
1382 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1383 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1384 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1385 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1386 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1389 case lltok::kw_align:
1390 case lltok::kw_byval:
1391 case lltok::kw_inalloca:
1392 case lltok::kw_nest:
1393 case lltok::kw_nocapture:
1394 case lltok::kw_returned:
1395 case lltok::kw_sret:
1396 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1399 case lltok::kw_alignstack:
1400 case lltok::kw_alwaysinline:
1401 case lltok::kw_argmemonly:
1402 case lltok::kw_builtin:
1403 case lltok::kw_cold:
1404 case lltok::kw_inlinehint:
1405 case lltok::kw_jumptable:
1406 case lltok::kw_minsize:
1407 case lltok::kw_naked:
1408 case lltok::kw_nobuiltin:
1409 case lltok::kw_noduplicate:
1410 case lltok::kw_noimplicitfloat:
1411 case lltok::kw_noinline:
1412 case lltok::kw_nonlazybind:
1413 case lltok::kw_noredzone:
1414 case lltok::kw_noreturn:
1415 case lltok::kw_nounwind:
1416 case lltok::kw_optnone:
1417 case lltok::kw_optsize:
1418 case lltok::kw_returns_twice:
1419 case lltok::kw_sanitize_address:
1420 case lltok::kw_sanitize_memory:
1421 case lltok::kw_sanitize_thread:
1423 case lltok::kw_sspreq:
1424 case lltok::kw_sspstrong:
1425 case lltok::kw_safestack:
1426 case lltok::kw_uwtable:
1427 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1430 case lltok::kw_readnone:
1431 case lltok::kw_readonly:
1432 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1439 /// ParseOptionalLinkage
1446 /// ::= 'linkonce_odr'
1447 /// ::= 'available_externally'
1450 /// ::= 'extern_weak'
1452 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1454 switch (Lex.getKind()) {
1455 default: Res=GlobalValue::ExternalLinkage; return false;
1456 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1457 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1458 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1459 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1460 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1461 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1462 case lltok::kw_available_externally:
1463 Res = GlobalValue::AvailableExternallyLinkage;
1465 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1466 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1467 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1468 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1475 /// ParseOptionalVisibility
1481 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1482 switch (Lex.getKind()) {
1483 default: Res = GlobalValue::DefaultVisibility; return false;
1484 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1485 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1486 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1492 /// ParseOptionalDLLStorageClass
1497 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1498 switch (Lex.getKind()) {
1499 default: Res = GlobalValue::DefaultStorageClass; return false;
1500 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1501 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1507 /// ParseOptionalCallingConv
1511 /// ::= 'intel_ocl_bicc'
1513 /// ::= 'x86_stdcallcc'
1514 /// ::= 'x86_fastcallcc'
1515 /// ::= 'x86_thiscallcc'
1516 /// ::= 'x86_vectorcallcc'
1517 /// ::= 'arm_apcscc'
1518 /// ::= 'arm_aapcscc'
1519 /// ::= 'arm_aapcs_vfpcc'
1520 /// ::= 'msp430_intrcc'
1521 /// ::= 'ptx_kernel'
1522 /// ::= 'ptx_device'
1524 /// ::= 'spir_kernel'
1525 /// ::= 'x86_64_sysvcc'
1526 /// ::= 'x86_64_win64cc'
1527 /// ::= 'webkit_jscc'
1529 /// ::= 'preserve_mostcc'
1530 /// ::= 'preserve_allcc'
1534 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1535 switch (Lex.getKind()) {
1536 default: CC = CallingConv::C; return false;
1537 case lltok::kw_ccc: CC = CallingConv::C; break;
1538 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1539 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1540 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1541 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1542 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1543 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1544 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1545 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1546 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1547 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1548 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1549 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1550 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1551 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1552 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1553 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1554 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1555 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1556 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1557 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1558 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1559 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1560 case lltok::kw_cc: {
1562 return ParseUInt32(CC);
1570 /// ParseMetadataAttachment
1572 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1573 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1575 std::string Name = Lex.getStrVal();
1576 Kind = M->getMDKindID(Name);
1579 return ParseMDNode(MD);
1582 /// ParseInstructionMetadata
1583 /// ::= !dbg !42 (',' !dbg !57)*
1584 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1586 if (Lex.getKind() != lltok::MetadataVar)
1587 return TokError("expected metadata after comma");
1591 if (ParseMetadataAttachment(MDK, N))
1594 Inst.setMetadata(MDK, N);
1595 if (MDK == LLVMContext::MD_tbaa)
1596 InstsWithTBAATag.push_back(&Inst);
1598 // If this is the end of the list, we're done.
1599 } while (EatIfPresent(lltok::comma));
1603 /// ParseOptionalFunctionMetadata
1605 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1606 while (Lex.getKind() == lltok::MetadataVar) {
1609 if (ParseMetadataAttachment(MDK, N))
1612 F.setMetadata(MDK, N);
1617 /// ParseOptionalAlignment
1620 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1622 if (!EatIfPresent(lltok::kw_align))
1624 LocTy AlignLoc = Lex.getLoc();
1625 if (ParseUInt32(Alignment)) return true;
1626 if (!isPowerOf2_32(Alignment))
1627 return Error(AlignLoc, "alignment is not a power of two");
1628 if (Alignment > Value::MaximumAlignment)
1629 return Error(AlignLoc, "huge alignments are not supported yet");
1633 /// ParseOptionalDerefAttrBytes
1635 /// ::= AttrKind '(' 4 ')'
1637 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1638 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1640 assert((AttrKind == lltok::kw_dereferenceable ||
1641 AttrKind == lltok::kw_dereferenceable_or_null) &&
1645 if (!EatIfPresent(AttrKind))
1647 LocTy ParenLoc = Lex.getLoc();
1648 if (!EatIfPresent(lltok::lparen))
1649 return Error(ParenLoc, "expected '('");
1650 LocTy DerefLoc = Lex.getLoc();
1651 if (ParseUInt64(Bytes)) return true;
1652 ParenLoc = Lex.getLoc();
1653 if (!EatIfPresent(lltok::rparen))
1654 return Error(ParenLoc, "expected ')'");
1656 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1660 /// ParseOptionalCommaAlign
1664 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1666 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1667 bool &AteExtraComma) {
1668 AteExtraComma = false;
1669 while (EatIfPresent(lltok::comma)) {
1670 // Metadata at the end is an early exit.
1671 if (Lex.getKind() == lltok::MetadataVar) {
1672 AteExtraComma = true;
1676 if (Lex.getKind() != lltok::kw_align)
1677 return Error(Lex.getLoc(), "expected metadata or 'align'");
1679 if (ParseOptionalAlignment(Alignment)) return true;
1685 /// ParseScopeAndOrdering
1686 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1689 /// This sets Scope and Ordering to the parsed values.
1690 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1691 AtomicOrdering &Ordering) {
1695 Scope = CrossThread;
1696 if (EatIfPresent(lltok::kw_singlethread))
1697 Scope = SingleThread;
1699 return ParseOrdering(Ordering);
1703 /// ::= AtomicOrdering
1705 /// This sets Ordering to the parsed value.
1706 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1707 switch (Lex.getKind()) {
1708 default: return TokError("Expected ordering on atomic instruction");
1709 case lltok::kw_unordered: Ordering = Unordered; break;
1710 case lltok::kw_monotonic: Ordering = Monotonic; break;
1711 case lltok::kw_acquire: Ordering = Acquire; break;
1712 case lltok::kw_release: Ordering = Release; break;
1713 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1714 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1720 /// ParseOptionalStackAlignment
1722 /// ::= 'alignstack' '(' 4 ')'
1723 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1725 if (!EatIfPresent(lltok::kw_alignstack))
1727 LocTy ParenLoc = Lex.getLoc();
1728 if (!EatIfPresent(lltok::lparen))
1729 return Error(ParenLoc, "expected '('");
1730 LocTy AlignLoc = Lex.getLoc();
1731 if (ParseUInt32(Alignment)) return true;
1732 ParenLoc = Lex.getLoc();
1733 if (!EatIfPresent(lltok::rparen))
1734 return Error(ParenLoc, "expected ')'");
1735 if (!isPowerOf2_32(Alignment))
1736 return Error(AlignLoc, "stack alignment is not a power of two");
1740 /// ParseIndexList - This parses the index list for an insert/extractvalue
1741 /// instruction. This sets AteExtraComma in the case where we eat an extra
1742 /// comma at the end of the line and find that it is followed by metadata.
1743 /// Clients that don't allow metadata can call the version of this function that
1744 /// only takes one argument.
1747 /// ::= (',' uint32)+
1749 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1750 bool &AteExtraComma) {
1751 AteExtraComma = false;
1753 if (Lex.getKind() != lltok::comma)
1754 return TokError("expected ',' as start of index list");
1756 while (EatIfPresent(lltok::comma)) {
1757 if (Lex.getKind() == lltok::MetadataVar) {
1758 if (Indices.empty()) return TokError("expected index");
1759 AteExtraComma = true;
1763 if (ParseUInt32(Idx)) return true;
1764 Indices.push_back(Idx);
1770 //===----------------------------------------------------------------------===//
1772 //===----------------------------------------------------------------------===//
1774 /// ParseType - Parse a type.
1775 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1776 SMLoc TypeLoc = Lex.getLoc();
1777 switch (Lex.getKind()) {
1779 return TokError(Msg);
1781 // Type ::= 'float' | 'void' (etc)
1782 Result = Lex.getTyVal();
1786 // Type ::= StructType
1787 if (ParseAnonStructType(Result, false))
1790 case lltok::lsquare:
1791 // Type ::= '[' ... ']'
1792 Lex.Lex(); // eat the lsquare.
1793 if (ParseArrayVectorType(Result, false))
1796 case lltok::less: // Either vector or packed struct.
1797 // Type ::= '<' ... '>'
1799 if (Lex.getKind() == lltok::lbrace) {
1800 if (ParseAnonStructType(Result, true) ||
1801 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1803 } else if (ParseArrayVectorType(Result, true))
1806 case lltok::LocalVar: {
1808 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1810 // If the type hasn't been defined yet, create a forward definition and
1811 // remember where that forward def'n was seen (in case it never is defined).
1813 Entry.first = StructType::create(Context, Lex.getStrVal());
1814 Entry.second = Lex.getLoc();
1816 Result = Entry.first;
1821 case lltok::LocalVarID: {
1823 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1825 // If the type hasn't been defined yet, create a forward definition and
1826 // remember where that forward def'n was seen (in case it never is defined).
1828 Entry.first = StructType::create(Context);
1829 Entry.second = Lex.getLoc();
1831 Result = Entry.first;
1837 // Parse the type suffixes.
1839 switch (Lex.getKind()) {
1842 if (!AllowVoid && Result->isVoidTy())
1843 return Error(TypeLoc, "void type only allowed for function results");
1846 // Type ::= Type '*'
1848 if (Result->isLabelTy())
1849 return TokError("basic block pointers are invalid");
1850 if (Result->isVoidTy())
1851 return TokError("pointers to void are invalid - use i8* instead");
1852 if (!PointerType::isValidElementType(Result))
1853 return TokError("pointer to this type is invalid");
1854 Result = PointerType::getUnqual(Result);
1858 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1859 case lltok::kw_addrspace: {
1860 if (Result->isLabelTy())
1861 return TokError("basic block pointers are invalid");
1862 if (Result->isVoidTy())
1863 return TokError("pointers to void are invalid; use i8* instead");
1864 if (!PointerType::isValidElementType(Result))
1865 return TokError("pointer to this type is invalid");
1867 if (ParseOptionalAddrSpace(AddrSpace) ||
1868 ParseToken(lltok::star, "expected '*' in address space"))
1871 Result = PointerType::get(Result, AddrSpace);
1875 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1877 if (ParseFunctionType(Result))
1884 /// ParseParameterList
1886 /// ::= '(' Arg (',' Arg)* ')'
1888 /// ::= Type OptionalAttributes Value OptionalAttributes
1889 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1890 PerFunctionState &PFS, bool IsMustTailCall,
1891 bool InVarArgsFunc) {
1892 if (ParseToken(lltok::lparen, "expected '(' in call"))
1895 unsigned AttrIndex = 1;
1896 while (Lex.getKind() != lltok::rparen) {
1897 // If this isn't the first argument, we need a comma.
1898 if (!ArgList.empty() &&
1899 ParseToken(lltok::comma, "expected ',' in argument list"))
1902 // Parse an ellipsis if this is a musttail call in a variadic function.
1903 if (Lex.getKind() == lltok::dotdotdot) {
1904 const char *Msg = "unexpected ellipsis in argument list for ";
1905 if (!IsMustTailCall)
1906 return TokError(Twine(Msg) + "non-musttail call");
1908 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1909 Lex.Lex(); // Lex the '...', it is purely for readability.
1910 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1913 // Parse the argument.
1915 Type *ArgTy = nullptr;
1916 AttrBuilder ArgAttrs;
1918 if (ParseType(ArgTy, ArgLoc))
1921 if (ArgTy->isMetadataTy()) {
1922 if (ParseMetadataAsValue(V, PFS))
1925 // Otherwise, handle normal operands.
1926 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1929 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1934 if (IsMustTailCall && InVarArgsFunc)
1935 return TokError("expected '...' at end of argument list for musttail call "
1936 "in varargs function");
1938 Lex.Lex(); // Lex the ')'.
1944 /// ParseArgumentList - Parse the argument list for a function type or function
1946 /// ::= '(' ArgTypeListI ')'
1950 /// ::= ArgTypeList ',' '...'
1951 /// ::= ArgType (',' ArgType)*
1953 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1956 assert(Lex.getKind() == lltok::lparen);
1957 Lex.Lex(); // eat the (.
1959 if (Lex.getKind() == lltok::rparen) {
1961 } else if (Lex.getKind() == lltok::dotdotdot) {
1965 LocTy TypeLoc = Lex.getLoc();
1966 Type *ArgTy = nullptr;
1970 if (ParseType(ArgTy) ||
1971 ParseOptionalParamAttrs(Attrs)) return true;
1973 if (ArgTy->isVoidTy())
1974 return Error(TypeLoc, "argument can not have void type");
1976 if (Lex.getKind() == lltok::LocalVar) {
1977 Name = Lex.getStrVal();
1981 if (!FunctionType::isValidArgumentType(ArgTy))
1982 return Error(TypeLoc, "invalid type for function argument");
1984 unsigned AttrIndex = 1;
1985 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1986 AttrIndex++, Attrs),
1989 while (EatIfPresent(lltok::comma)) {
1990 // Handle ... at end of arg list.
1991 if (EatIfPresent(lltok::dotdotdot)) {
1996 // Otherwise must be an argument type.
1997 TypeLoc = Lex.getLoc();
1998 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2000 if (ArgTy->isVoidTy())
2001 return Error(TypeLoc, "argument can not have void type");
2003 if (Lex.getKind() == lltok::LocalVar) {
2004 Name = Lex.getStrVal();
2010 if (!ArgTy->isFirstClassType())
2011 return Error(TypeLoc, "invalid type for function argument");
2013 ArgList.emplace_back(
2015 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2020 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2023 /// ParseFunctionType
2024 /// ::= Type ArgumentList OptionalAttrs
2025 bool LLParser::ParseFunctionType(Type *&Result) {
2026 assert(Lex.getKind() == lltok::lparen);
2028 if (!FunctionType::isValidReturnType(Result))
2029 return TokError("invalid function return type");
2031 SmallVector<ArgInfo, 8> ArgList;
2033 if (ParseArgumentList(ArgList, isVarArg))
2036 // Reject names on the arguments lists.
2037 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2038 if (!ArgList[i].Name.empty())
2039 return Error(ArgList[i].Loc, "argument name invalid in function type");
2040 if (ArgList[i].Attrs.hasAttributes(i + 1))
2041 return Error(ArgList[i].Loc,
2042 "argument attributes invalid in function type");
2045 SmallVector<Type*, 16> ArgListTy;
2046 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2047 ArgListTy.push_back(ArgList[i].Ty);
2049 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2053 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2055 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2056 SmallVector<Type*, 8> Elts;
2057 if (ParseStructBody(Elts)) return true;
2059 Result = StructType::get(Context, Elts, Packed);
2063 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2064 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2065 std::pair<Type*, LocTy> &Entry,
2067 // If the type was already defined, diagnose the redefinition.
2068 if (Entry.first && !Entry.second.isValid())
2069 return Error(TypeLoc, "redefinition of type");
2071 // If we have opaque, just return without filling in the definition for the
2072 // struct. This counts as a definition as far as the .ll file goes.
2073 if (EatIfPresent(lltok::kw_opaque)) {
2074 // This type is being defined, so clear the location to indicate this.
2075 Entry.second = SMLoc();
2077 // If this type number has never been uttered, create it.
2079 Entry.first = StructType::create(Context, Name);
2080 ResultTy = Entry.first;
2084 // If the type starts with '<', then it is either a packed struct or a vector.
2085 bool isPacked = EatIfPresent(lltok::less);
2087 // If we don't have a struct, then we have a random type alias, which we
2088 // accept for compatibility with old files. These types are not allowed to be
2089 // forward referenced and not allowed to be recursive.
2090 if (Lex.getKind() != lltok::lbrace) {
2092 return Error(TypeLoc, "forward references to non-struct type");
2096 return ParseArrayVectorType(ResultTy, true);
2097 return ParseType(ResultTy);
2100 // This type is being defined, so clear the location to indicate this.
2101 Entry.second = SMLoc();
2103 // If this type number has never been uttered, create it.
2105 Entry.first = StructType::create(Context, Name);
2107 StructType *STy = cast<StructType>(Entry.first);
2109 SmallVector<Type*, 8> Body;
2110 if (ParseStructBody(Body) ||
2111 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2114 STy->setBody(Body, isPacked);
2120 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2123 /// ::= '{' Type (',' Type)* '}'
2124 /// ::= '<' '{' '}' '>'
2125 /// ::= '<' '{' Type (',' Type)* '}' '>'
2126 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2127 assert(Lex.getKind() == lltok::lbrace);
2128 Lex.Lex(); // Consume the '{'
2130 // Handle the empty struct.
2131 if (EatIfPresent(lltok::rbrace))
2134 LocTy EltTyLoc = Lex.getLoc();
2136 if (ParseType(Ty)) return true;
2139 if (!StructType::isValidElementType(Ty))
2140 return Error(EltTyLoc, "invalid element type for struct");
2142 while (EatIfPresent(lltok::comma)) {
2143 EltTyLoc = Lex.getLoc();
2144 if (ParseType(Ty)) return true;
2146 if (!StructType::isValidElementType(Ty))
2147 return Error(EltTyLoc, "invalid element type for struct");
2152 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2155 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2156 /// token has already been consumed.
2158 /// ::= '[' APSINTVAL 'x' Types ']'
2159 /// ::= '<' APSINTVAL 'x' Types '>'
2160 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2161 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2162 Lex.getAPSIntVal().getBitWidth() > 64)
2163 return TokError("expected number in address space");
2165 LocTy SizeLoc = Lex.getLoc();
2166 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2169 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2172 LocTy TypeLoc = Lex.getLoc();
2173 Type *EltTy = nullptr;
2174 if (ParseType(EltTy)) return true;
2176 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2177 "expected end of sequential type"))
2182 return Error(SizeLoc, "zero element vector is illegal");
2183 if ((unsigned)Size != Size)
2184 return Error(SizeLoc, "size too large for vector");
2185 if (!VectorType::isValidElementType(EltTy))
2186 return Error(TypeLoc, "invalid vector element type");
2187 Result = VectorType::get(EltTy, unsigned(Size));
2189 if (!ArrayType::isValidElementType(EltTy))
2190 return Error(TypeLoc, "invalid array element type");
2191 Result = ArrayType::get(EltTy, Size);
2196 //===----------------------------------------------------------------------===//
2197 // Function Semantic Analysis.
2198 //===----------------------------------------------------------------------===//
2200 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2202 : P(p), F(f), FunctionNumber(functionNumber) {
2204 // Insert unnamed arguments into the NumberedVals list.
2205 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2208 NumberedVals.push_back(AI);
2211 LLParser::PerFunctionState::~PerFunctionState() {
2212 // If there were any forward referenced non-basicblock values, delete them.
2213 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2214 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2215 if (!isa<BasicBlock>(I->second.first)) {
2216 I->second.first->replaceAllUsesWith(
2217 UndefValue::get(I->second.first->getType()));
2218 delete I->second.first;
2219 I->second.first = nullptr;
2222 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2223 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2224 if (!isa<BasicBlock>(I->second.first)) {
2225 I->second.first->replaceAllUsesWith(
2226 UndefValue::get(I->second.first->getType()));
2227 delete I->second.first;
2228 I->second.first = nullptr;
2232 bool LLParser::PerFunctionState::FinishFunction() {
2233 if (!ForwardRefVals.empty())
2234 return P.Error(ForwardRefVals.begin()->second.second,
2235 "use of undefined value '%" + ForwardRefVals.begin()->first +
2237 if (!ForwardRefValIDs.empty())
2238 return P.Error(ForwardRefValIDs.begin()->second.second,
2239 "use of undefined value '%" +
2240 Twine(ForwardRefValIDs.begin()->first) + "'");
2245 /// GetVal - Get a value with the specified name or ID, creating a
2246 /// forward reference record if needed. This can return null if the value
2247 /// exists but does not have the right type.
2248 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2249 LocTy Loc, OperatorConstraint OC) {
2250 // Look this name up in the normal function symbol table.
2251 Value *Val = F.getValueSymbolTable().lookup(Name);
2253 // If this is a forward reference for the value, see if we already created a
2254 // forward ref record.
2256 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2257 I = ForwardRefVals.find(Name);
2258 if (I != ForwardRefVals.end())
2259 Val = I->second.first;
2262 // If we have the value in the symbol table or fwd-ref table, return it.
2264 // Check operator constraints.
2270 if (!isa<CatchPadInst>(Val)) {
2271 P.Error(Loc, "'%" + Name + "' is not a catchpad");
2276 if (!isa<CleanupPadInst>(Val)) {
2277 P.Error(Loc, "'%" + Name + "' is not a cleanuppad");
2282 if (Val->getType() == Ty) return Val;
2283 if (Ty->isLabelTy())
2284 P.Error(Loc, "'%" + Name + "' is not a basic block");
2286 P.Error(Loc, "'%" + Name + "' defined with type '" +
2287 getTypeString(Val->getType()) + "'");
2291 // Don't make placeholders with invalid type.
2292 if (!Ty->isFirstClassType()) {
2293 P.Error(Loc, "invalid use of a non-first-class type");
2297 // Otherwise, create a new forward reference for this value and remember it.
2299 if (Ty->isLabelTy()) {
2301 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2303 FwdVal = new Argument(Ty, Name);
2307 FwdVal = CatchPadInst::Create(&F.getEntryBlock(), &F.getEntryBlock(), {},
2311 FwdVal = CleanupPadInst::Create(F.getContext(), {}, Name);
2314 llvm_unreachable("unexpected constraint");
2318 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2322 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2323 OperatorConstraint OC) {
2324 // Look this name up in the normal function symbol table.
2325 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2327 // If this is a forward reference for the value, see if we already created a
2328 // forward ref record.
2330 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2331 I = ForwardRefValIDs.find(ID);
2332 if (I != ForwardRefValIDs.end())
2333 Val = I->second.first;
2336 // If we have the value in the symbol table or fwd-ref table, return it.
2338 // Check operator constraint.
2344 if (!isa<CatchPadInst>(Val)) {
2345 P.Error(Loc, "'%" + Twine(ID) + "' is not a catchpad");
2350 if (!isa<CleanupPadInst>(Val)) {
2351 P.Error(Loc, "'%" + Twine(ID) + "' is not a cleanuppad");
2356 if (Val->getType() == Ty) return Val;
2357 if (Ty->isLabelTy())
2358 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2360 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2361 getTypeString(Val->getType()) + "'");
2365 if (!Ty->isFirstClassType()) {
2366 P.Error(Loc, "invalid use of a non-first-class type");
2370 // Otherwise, create a new forward reference for this value and remember it.
2372 if (Ty->isLabelTy()) {
2374 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2376 FwdVal = new Argument(Ty);
2380 FwdVal = CatchPadInst::Create(&F.getEntryBlock(), &F.getEntryBlock(), {});
2383 FwdVal = CleanupPadInst::Create(F.getContext(), {});
2386 llvm_unreachable("unexpected constraint");
2390 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2394 /// SetInstName - After an instruction is parsed and inserted into its
2395 /// basic block, this installs its name.
2396 bool LLParser::PerFunctionState::SetInstName(int NameID,
2397 const std::string &NameStr,
2398 LocTy NameLoc, Instruction *Inst) {
2399 // If this instruction has void type, it cannot have a name or ID specified.
2400 if (Inst->getType()->isVoidTy()) {
2401 if (NameID != -1 || !NameStr.empty())
2402 return P.Error(NameLoc, "instructions returning void cannot have a name");
2406 // If this was a numbered instruction, verify that the instruction is the
2407 // expected value and resolve any forward references.
2408 if (NameStr.empty()) {
2409 // If neither a name nor an ID was specified, just use the next ID.
2411 NameID = NumberedVals.size();
2413 if (unsigned(NameID) != NumberedVals.size())
2414 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2415 Twine(NumberedVals.size()) + "'");
2417 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2418 ForwardRefValIDs.find(NameID);
2419 if (FI != ForwardRefValIDs.end()) {
2420 Value *Sentinel = FI->second.first;
2421 if (Sentinel->getType() != Inst->getType())
2422 return P.Error(NameLoc, "instruction forward referenced with type '" +
2423 getTypeString(FI->second.first->getType()) + "'");
2424 // Check operator constraints. We only put cleanuppads or catchpads in
2425 // the forward value map if the value is constrained to match.
2426 if (isa<CatchPadInst>(Sentinel)) {
2427 if (!isa<CatchPadInst>(Inst))
2428 return P.Error(FI->second.second,
2429 "'%" + Twine(NameID) + "' is not a catchpad");
2430 } else if (isa<CleanupPadInst>(Sentinel)) {
2431 if (!isa<CleanupPadInst>(Inst))
2432 return P.Error(FI->second.second,
2433 "'%" + Twine(NameID) + "' is not a cleanuppad");
2436 Sentinel->replaceAllUsesWith(Inst);
2438 ForwardRefValIDs.erase(FI);
2441 NumberedVals.push_back(Inst);
2445 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2446 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2447 FI = ForwardRefVals.find(NameStr);
2448 if (FI != ForwardRefVals.end()) {
2449 Value *Sentinel = FI->second.first;
2450 if (Sentinel->getType() != Inst->getType())
2451 return P.Error(NameLoc, "instruction forward referenced with type '" +
2452 getTypeString(FI->second.first->getType()) + "'");
2453 // Check operator constraints. We only put cleanuppads or catchpads in
2454 // the forward value map if the value is constrained to match.
2455 if (isa<CatchPadInst>(Sentinel)) {
2456 if (!isa<CatchPadInst>(Inst))
2457 return P.Error(FI->second.second,
2458 "'%" + NameStr + "' is not a catchpad");
2459 } else if (isa<CleanupPadInst>(Sentinel)) {
2460 if (!isa<CleanupPadInst>(Inst))
2461 return P.Error(FI->second.second,
2462 "'%" + NameStr + "' is not a cleanuppad");
2465 Sentinel->replaceAllUsesWith(Inst);
2467 ForwardRefVals.erase(FI);
2470 // Set the name on the instruction.
2471 Inst->setName(NameStr);
2473 if (Inst->getName() != NameStr)
2474 return P.Error(NameLoc, "multiple definition of local value named '" +
2479 /// GetBB - Get a basic block with the specified name or ID, creating a
2480 /// forward reference record if needed.
2481 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2483 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2484 Type::getLabelTy(F.getContext()), Loc));
2487 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2488 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2489 Type::getLabelTy(F.getContext()), Loc));
2492 /// DefineBB - Define the specified basic block, which is either named or
2493 /// unnamed. If there is an error, this returns null otherwise it returns
2494 /// the block being defined.
2495 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2499 BB = GetBB(NumberedVals.size(), Loc);
2501 BB = GetBB(Name, Loc);
2502 if (!BB) return nullptr; // Already diagnosed error.
2504 // Move the block to the end of the function. Forward ref'd blocks are
2505 // inserted wherever they happen to be referenced.
2506 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2508 // Remove the block from forward ref sets.
2510 ForwardRefValIDs.erase(NumberedVals.size());
2511 NumberedVals.push_back(BB);
2513 // BB forward references are already in the function symbol table.
2514 ForwardRefVals.erase(Name);
2520 //===----------------------------------------------------------------------===//
2522 //===----------------------------------------------------------------------===//
2524 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2525 /// type implied. For example, if we parse "4" we don't know what integer type
2526 /// it has. The value will later be combined with its type and checked for
2527 /// sanity. PFS is used to convert function-local operands of metadata (since
2528 /// metadata operands are not just parsed here but also converted to values).
2529 /// PFS can be null when we are not parsing metadata values inside a function.
2530 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2531 ID.Loc = Lex.getLoc();
2532 switch (Lex.getKind()) {
2533 default: return TokError("expected value token");
2534 case lltok::GlobalID: // @42
2535 ID.UIntVal = Lex.getUIntVal();
2536 ID.Kind = ValID::t_GlobalID;
2538 case lltok::GlobalVar: // @foo
2539 ID.StrVal = Lex.getStrVal();
2540 ID.Kind = ValID::t_GlobalName;
2542 case lltok::LocalVarID: // %42
2543 ID.UIntVal = Lex.getUIntVal();
2544 ID.Kind = ValID::t_LocalID;
2546 case lltok::LocalVar: // %foo
2547 ID.StrVal = Lex.getStrVal();
2548 ID.Kind = ValID::t_LocalName;
2551 ID.APSIntVal = Lex.getAPSIntVal();
2552 ID.Kind = ValID::t_APSInt;
2554 case lltok::APFloat:
2555 ID.APFloatVal = Lex.getAPFloatVal();
2556 ID.Kind = ValID::t_APFloat;
2558 case lltok::kw_true:
2559 ID.ConstantVal = ConstantInt::getTrue(Context);
2560 ID.Kind = ValID::t_Constant;
2562 case lltok::kw_false:
2563 ID.ConstantVal = ConstantInt::getFalse(Context);
2564 ID.Kind = ValID::t_Constant;
2566 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2567 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2568 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2570 case lltok::lbrace: {
2571 // ValID ::= '{' ConstVector '}'
2573 SmallVector<Constant*, 16> Elts;
2574 if (ParseGlobalValueVector(Elts) ||
2575 ParseToken(lltok::rbrace, "expected end of struct constant"))
2578 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2579 ID.UIntVal = Elts.size();
2580 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2581 Elts.size() * sizeof(Elts[0]));
2582 ID.Kind = ValID::t_ConstantStruct;
2586 // ValID ::= '<' ConstVector '>' --> Vector.
2587 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2589 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2591 SmallVector<Constant*, 16> Elts;
2592 LocTy FirstEltLoc = Lex.getLoc();
2593 if (ParseGlobalValueVector(Elts) ||
2595 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2596 ParseToken(lltok::greater, "expected end of constant"))
2599 if (isPackedStruct) {
2600 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2601 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2602 Elts.size() * sizeof(Elts[0]));
2603 ID.UIntVal = Elts.size();
2604 ID.Kind = ValID::t_PackedConstantStruct;
2609 return Error(ID.Loc, "constant vector must not be empty");
2611 if (!Elts[0]->getType()->isIntegerTy() &&
2612 !Elts[0]->getType()->isFloatingPointTy() &&
2613 !Elts[0]->getType()->isPointerTy())
2614 return Error(FirstEltLoc,
2615 "vector elements must have integer, pointer or floating point type");
2617 // Verify that all the vector elements have the same type.
2618 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2619 if (Elts[i]->getType() != Elts[0]->getType())
2620 return Error(FirstEltLoc,
2621 "vector element #" + Twine(i) +
2622 " is not of type '" + getTypeString(Elts[0]->getType()));
2624 ID.ConstantVal = ConstantVector::get(Elts);
2625 ID.Kind = ValID::t_Constant;
2628 case lltok::lsquare: { // Array Constant
2630 SmallVector<Constant*, 16> Elts;
2631 LocTy FirstEltLoc = Lex.getLoc();
2632 if (ParseGlobalValueVector(Elts) ||
2633 ParseToken(lltok::rsquare, "expected end of array constant"))
2636 // Handle empty element.
2638 // Use undef instead of an array because it's inconvenient to determine
2639 // the element type at this point, there being no elements to examine.
2640 ID.Kind = ValID::t_EmptyArray;
2644 if (!Elts[0]->getType()->isFirstClassType())
2645 return Error(FirstEltLoc, "invalid array element type: " +
2646 getTypeString(Elts[0]->getType()));
2648 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2650 // Verify all elements are correct type!
2651 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2652 if (Elts[i]->getType() != Elts[0]->getType())
2653 return Error(FirstEltLoc,
2654 "array element #" + Twine(i) +
2655 " is not of type '" + getTypeString(Elts[0]->getType()));
2658 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2659 ID.Kind = ValID::t_Constant;
2662 case lltok::kw_c: // c "foo"
2664 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2666 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2667 ID.Kind = ValID::t_Constant;
2670 case lltok::kw_asm: {
2671 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2673 bool HasSideEffect, AlignStack, AsmDialect;
2675 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2676 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2677 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2678 ParseStringConstant(ID.StrVal) ||
2679 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2680 ParseToken(lltok::StringConstant, "expected constraint string"))
2682 ID.StrVal2 = Lex.getStrVal();
2683 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2684 (unsigned(AsmDialect)<<2);
2685 ID.Kind = ValID::t_InlineAsm;
2689 case lltok::kw_blockaddress: {
2690 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2695 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2697 ParseToken(lltok::comma, "expected comma in block address expression")||
2698 ParseValID(Label) ||
2699 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2702 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2703 return Error(Fn.Loc, "expected function name in blockaddress");
2704 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2705 return Error(Label.Loc, "expected basic block name in blockaddress");
2707 // Try to find the function (but skip it if it's forward-referenced).
2708 GlobalValue *GV = nullptr;
2709 if (Fn.Kind == ValID::t_GlobalID) {
2710 if (Fn.UIntVal < NumberedVals.size())
2711 GV = NumberedVals[Fn.UIntVal];
2712 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2713 GV = M->getNamedValue(Fn.StrVal);
2715 Function *F = nullptr;
2717 // Confirm that it's actually a function with a definition.
2718 if (!isa<Function>(GV))
2719 return Error(Fn.Loc, "expected function name in blockaddress");
2720 F = cast<Function>(GV);
2721 if (F->isDeclaration())
2722 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2726 // Make a global variable as a placeholder for this reference.
2727 GlobalValue *&FwdRef =
2728 ForwardRefBlockAddresses.insert(std::make_pair(
2730 std::map<ValID, GlobalValue *>()))
2731 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2734 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2735 GlobalValue::InternalLinkage, nullptr, "");
2736 ID.ConstantVal = FwdRef;
2737 ID.Kind = ValID::t_Constant;
2741 // We found the function; now find the basic block. Don't use PFS, since we
2742 // might be inside a constant expression.
2744 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2745 if (Label.Kind == ValID::t_LocalID)
2746 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2748 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2750 return Error(Label.Loc, "referenced value is not a basic block");
2752 if (Label.Kind == ValID::t_LocalID)
2753 return Error(Label.Loc, "cannot take address of numeric label after "
2754 "the function is defined");
2755 BB = dyn_cast_or_null<BasicBlock>(
2756 F->getValueSymbolTable().lookup(Label.StrVal));
2758 return Error(Label.Loc, "referenced value is not a basic block");
2761 ID.ConstantVal = BlockAddress::get(F, BB);
2762 ID.Kind = ValID::t_Constant;
2766 case lltok::kw_trunc:
2767 case lltok::kw_zext:
2768 case lltok::kw_sext:
2769 case lltok::kw_fptrunc:
2770 case lltok::kw_fpext:
2771 case lltok::kw_bitcast:
2772 case lltok::kw_addrspacecast:
2773 case lltok::kw_uitofp:
2774 case lltok::kw_sitofp:
2775 case lltok::kw_fptoui:
2776 case lltok::kw_fptosi:
2777 case lltok::kw_inttoptr:
2778 case lltok::kw_ptrtoint: {
2779 unsigned Opc = Lex.getUIntVal();
2780 Type *DestTy = nullptr;
2783 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2784 ParseGlobalTypeAndValue(SrcVal) ||
2785 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2786 ParseType(DestTy) ||
2787 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2789 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2790 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2791 getTypeString(SrcVal->getType()) + "' to '" +
2792 getTypeString(DestTy) + "'");
2793 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2795 ID.Kind = ValID::t_Constant;
2798 case lltok::kw_extractvalue: {
2801 SmallVector<unsigned, 4> Indices;
2802 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2803 ParseGlobalTypeAndValue(Val) ||
2804 ParseIndexList(Indices) ||
2805 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2808 if (!Val->getType()->isAggregateType())
2809 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2810 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2811 return Error(ID.Loc, "invalid indices for extractvalue");
2812 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2813 ID.Kind = ValID::t_Constant;
2816 case lltok::kw_insertvalue: {
2818 Constant *Val0, *Val1;
2819 SmallVector<unsigned, 4> Indices;
2820 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2821 ParseGlobalTypeAndValue(Val0) ||
2822 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2823 ParseGlobalTypeAndValue(Val1) ||
2824 ParseIndexList(Indices) ||
2825 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2827 if (!Val0->getType()->isAggregateType())
2828 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2830 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2832 return Error(ID.Loc, "invalid indices for insertvalue");
2833 if (IndexedType != Val1->getType())
2834 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2835 getTypeString(Val1->getType()) +
2836 "' instead of '" + getTypeString(IndexedType) +
2838 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2839 ID.Kind = ValID::t_Constant;
2842 case lltok::kw_icmp:
2843 case lltok::kw_fcmp: {
2844 unsigned PredVal, Opc = Lex.getUIntVal();
2845 Constant *Val0, *Val1;
2847 if (ParseCmpPredicate(PredVal, Opc) ||
2848 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2849 ParseGlobalTypeAndValue(Val0) ||
2850 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2851 ParseGlobalTypeAndValue(Val1) ||
2852 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2855 if (Val0->getType() != Val1->getType())
2856 return Error(ID.Loc, "compare operands must have the same type");
2858 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2860 if (Opc == Instruction::FCmp) {
2861 if (!Val0->getType()->isFPOrFPVectorTy())
2862 return Error(ID.Loc, "fcmp requires floating point operands");
2863 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2865 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2866 if (!Val0->getType()->isIntOrIntVectorTy() &&
2867 !Val0->getType()->getScalarType()->isPointerTy())
2868 return Error(ID.Loc, "icmp requires pointer or integer operands");
2869 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2871 ID.Kind = ValID::t_Constant;
2875 // Binary Operators.
2877 case lltok::kw_fadd:
2879 case lltok::kw_fsub:
2881 case lltok::kw_fmul:
2882 case lltok::kw_udiv:
2883 case lltok::kw_sdiv:
2884 case lltok::kw_fdiv:
2885 case lltok::kw_urem:
2886 case lltok::kw_srem:
2887 case lltok::kw_frem:
2889 case lltok::kw_lshr:
2890 case lltok::kw_ashr: {
2894 unsigned Opc = Lex.getUIntVal();
2895 Constant *Val0, *Val1;
2897 LocTy ModifierLoc = Lex.getLoc();
2898 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2899 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2900 if (EatIfPresent(lltok::kw_nuw))
2902 if (EatIfPresent(lltok::kw_nsw)) {
2904 if (EatIfPresent(lltok::kw_nuw))
2907 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2908 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2909 if (EatIfPresent(lltok::kw_exact))
2912 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2913 ParseGlobalTypeAndValue(Val0) ||
2914 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2915 ParseGlobalTypeAndValue(Val1) ||
2916 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2918 if (Val0->getType() != Val1->getType())
2919 return Error(ID.Loc, "operands of constexpr must have same type");
2920 if (!Val0->getType()->isIntOrIntVectorTy()) {
2922 return Error(ModifierLoc, "nuw only applies to integer operations");
2924 return Error(ModifierLoc, "nsw only applies to integer operations");
2926 // Check that the type is valid for the operator.
2928 case Instruction::Add:
2929 case Instruction::Sub:
2930 case Instruction::Mul:
2931 case Instruction::UDiv:
2932 case Instruction::SDiv:
2933 case Instruction::URem:
2934 case Instruction::SRem:
2935 case Instruction::Shl:
2936 case Instruction::AShr:
2937 case Instruction::LShr:
2938 if (!Val0->getType()->isIntOrIntVectorTy())
2939 return Error(ID.Loc, "constexpr requires integer operands");
2941 case Instruction::FAdd:
2942 case Instruction::FSub:
2943 case Instruction::FMul:
2944 case Instruction::FDiv:
2945 case Instruction::FRem:
2946 if (!Val0->getType()->isFPOrFPVectorTy())
2947 return Error(ID.Loc, "constexpr requires fp operands");
2949 default: llvm_unreachable("Unknown binary operator!");
2952 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2953 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2954 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2955 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2957 ID.Kind = ValID::t_Constant;
2961 // Logical Operations
2964 case lltok::kw_xor: {
2965 unsigned Opc = Lex.getUIntVal();
2966 Constant *Val0, *Val1;
2968 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2969 ParseGlobalTypeAndValue(Val0) ||
2970 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2971 ParseGlobalTypeAndValue(Val1) ||
2972 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2974 if (Val0->getType() != Val1->getType())
2975 return Error(ID.Loc, "operands of constexpr must have same type");
2976 if (!Val0->getType()->isIntOrIntVectorTy())
2977 return Error(ID.Loc,
2978 "constexpr requires integer or integer vector operands");
2979 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2980 ID.Kind = ValID::t_Constant;
2984 case lltok::kw_getelementptr:
2985 case lltok::kw_shufflevector:
2986 case lltok::kw_insertelement:
2987 case lltok::kw_extractelement:
2988 case lltok::kw_select: {
2989 unsigned Opc = Lex.getUIntVal();
2990 SmallVector<Constant*, 16> Elts;
2991 bool InBounds = false;
2995 if (Opc == Instruction::GetElementPtr)
2996 InBounds = EatIfPresent(lltok::kw_inbounds);
2998 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3001 LocTy ExplicitTypeLoc = Lex.getLoc();
3002 if (Opc == Instruction::GetElementPtr) {
3003 if (ParseType(Ty) ||
3004 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3008 if (ParseGlobalValueVector(Elts) ||
3009 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3012 if (Opc == Instruction::GetElementPtr) {
3013 if (Elts.size() == 0 ||
3014 !Elts[0]->getType()->getScalarType()->isPointerTy())
3015 return Error(ID.Loc, "base of getelementptr must be a pointer");
3017 Type *BaseType = Elts[0]->getType();
3018 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3019 if (Ty != BasePointerType->getElementType())
3022 "explicit pointee type doesn't match operand's pointee type");
3024 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3025 for (Constant *Val : Indices) {
3026 Type *ValTy = Val->getType();
3027 if (!ValTy->getScalarType()->isIntegerTy())
3028 return Error(ID.Loc, "getelementptr index must be an integer");
3029 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3030 return Error(ID.Loc, "getelementptr index type missmatch");
3031 if (ValTy->isVectorTy()) {
3032 unsigned ValNumEl = ValTy->getVectorNumElements();
3033 unsigned PtrNumEl = BaseType->getVectorNumElements();
3034 if (ValNumEl != PtrNumEl)
3037 "getelementptr vector index has a wrong number of elements");
3041 SmallPtrSet<Type*, 4> Visited;
3042 if (!Indices.empty() && !Ty->isSized(&Visited))
3043 return Error(ID.Loc, "base element of getelementptr must be sized");
3045 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3046 return Error(ID.Loc, "invalid getelementptr indices");
3048 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
3049 } else if (Opc == Instruction::Select) {
3050 if (Elts.size() != 3)
3051 return Error(ID.Loc, "expected three operands to select");
3052 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3054 return Error(ID.Loc, Reason);
3055 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3056 } else if (Opc == Instruction::ShuffleVector) {
3057 if (Elts.size() != 3)
3058 return Error(ID.Loc, "expected three operands to shufflevector");
3059 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3060 return Error(ID.Loc, "invalid operands to shufflevector");
3062 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3063 } else if (Opc == Instruction::ExtractElement) {
3064 if (Elts.size() != 2)
3065 return Error(ID.Loc, "expected two operands to extractelement");
3066 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3067 return Error(ID.Loc, "invalid extractelement operands");
3068 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3070 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3071 if (Elts.size() != 3)
3072 return Error(ID.Loc, "expected three operands to insertelement");
3073 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3074 return Error(ID.Loc, "invalid insertelement operands");
3076 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3079 ID.Kind = ValID::t_Constant;
3088 /// ParseGlobalValue - Parse a global value with the specified type.
3089 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3093 bool Parsed = ParseValID(ID) ||
3094 ConvertValIDToValue(Ty, ID, V, nullptr);
3095 if (V && !(C = dyn_cast<Constant>(V)))
3096 return Error(ID.Loc, "global values must be constants");
3100 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3102 return ParseType(Ty) ||
3103 ParseGlobalValue(Ty, V);
3106 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3109 LocTy KwLoc = Lex.getLoc();
3110 if (!EatIfPresent(lltok::kw_comdat))
3113 if (EatIfPresent(lltok::lparen)) {
3114 if (Lex.getKind() != lltok::ComdatVar)
3115 return TokError("expected comdat variable");
3116 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3118 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3121 if (GlobalName.empty())
3122 return TokError("comdat cannot be unnamed");
3123 C = getComdat(GlobalName, KwLoc);
3129 /// ParseGlobalValueVector
3131 /// ::= TypeAndValue (',' TypeAndValue)*
3132 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
3134 if (Lex.getKind() == lltok::rbrace ||
3135 Lex.getKind() == lltok::rsquare ||
3136 Lex.getKind() == lltok::greater ||
3137 Lex.getKind() == lltok::rparen)
3141 if (ParseGlobalTypeAndValue(C)) return true;
3144 while (EatIfPresent(lltok::comma)) {
3145 if (ParseGlobalTypeAndValue(C)) return true;
3152 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3153 SmallVector<Metadata *, 16> Elts;
3154 if (ParseMDNodeVector(Elts))
3157 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3164 /// ::= !DILocation(...)
3165 bool LLParser::ParseMDNode(MDNode *&N) {
3166 if (Lex.getKind() == lltok::MetadataVar)
3167 return ParseSpecializedMDNode(N);
3169 return ParseToken(lltok::exclaim, "expected '!' here") ||
3173 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3175 if (Lex.getKind() == lltok::lbrace)
3176 return ParseMDTuple(N);
3179 return ParseMDNodeID(N);
3184 /// Structure to represent an optional metadata field.
3185 template <class FieldTy> struct MDFieldImpl {
3186 typedef MDFieldImpl ImplTy;
3190 void assign(FieldTy Val) {
3192 this->Val = std::move(Val);
3195 explicit MDFieldImpl(FieldTy Default)
3196 : Val(std::move(Default)), Seen(false) {}
3199 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3202 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3203 : ImplTy(Default), Max(Max) {}
3205 struct LineField : public MDUnsignedField {
3206 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3208 struct ColumnField : public MDUnsignedField {
3209 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3211 struct DwarfTagField : public MDUnsignedField {
3212 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3213 DwarfTagField(dwarf::Tag DefaultTag)
3214 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3216 struct DwarfAttEncodingField : public MDUnsignedField {
3217 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3219 struct DwarfVirtualityField : public MDUnsignedField {
3220 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3222 struct DwarfLangField : public MDUnsignedField {
3223 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3226 struct DIFlagField : public MDUnsignedField {
3227 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3230 struct MDSignedField : public MDFieldImpl<int64_t> {
3234 MDSignedField(int64_t Default = 0)
3235 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3236 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3237 : ImplTy(Default), Min(Min), Max(Max) {}
3240 struct MDBoolField : public MDFieldImpl<bool> {
3241 MDBoolField(bool Default = false) : ImplTy(Default) {}
3243 struct MDField : public MDFieldImpl<Metadata *> {
3246 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3248 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3249 MDConstant() : ImplTy(nullptr) {}
3251 struct MDStringField : public MDFieldImpl<MDString *> {
3253 MDStringField(bool AllowEmpty = true)
3254 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3256 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3257 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3265 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3266 MDUnsignedField &Result) {
3267 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3268 return TokError("expected unsigned integer");
3270 auto &U = Lex.getAPSIntVal();
3271 if (U.ugt(Result.Max))
3272 return TokError("value for '" + Name + "' too large, limit is " +
3274 Result.assign(U.getZExtValue());
3275 assert(Result.Val <= Result.Max && "Expected value in range");
3281 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3282 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3285 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3286 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3290 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3291 if (Lex.getKind() == lltok::APSInt)
3292 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3294 if (Lex.getKind() != lltok::DwarfTag)
3295 return TokError("expected DWARF tag");
3297 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3298 if (Tag == dwarf::DW_TAG_invalid)
3299 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3300 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3308 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3309 DwarfVirtualityField &Result) {
3310 if (Lex.getKind() == lltok::APSInt)
3311 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3313 if (Lex.getKind() != lltok::DwarfVirtuality)
3314 return TokError("expected DWARF virtuality code");
3316 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3318 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3319 Lex.getStrVal() + "'");
3320 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3321 Result.assign(Virtuality);
3327 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3328 if (Lex.getKind() == lltok::APSInt)
3329 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3331 if (Lex.getKind() != lltok::DwarfLang)
3332 return TokError("expected DWARF language");
3334 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3336 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3338 assert(Lang <= Result.Max && "Expected valid DWARF language");
3339 Result.assign(Lang);
3345 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3346 DwarfAttEncodingField &Result) {
3347 if (Lex.getKind() == lltok::APSInt)
3348 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3350 if (Lex.getKind() != lltok::DwarfAttEncoding)
3351 return TokError("expected DWARF type attribute encoding");
3353 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3355 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3356 Lex.getStrVal() + "'");
3357 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3358 Result.assign(Encoding);
3365 /// ::= DIFlagVector
3366 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3368 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3369 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3371 // Parser for a single flag.
3372 auto parseFlag = [&](unsigned &Val) {
3373 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3374 return ParseUInt32(Val);
3376 if (Lex.getKind() != lltok::DIFlag)
3377 return TokError("expected debug info flag");
3379 Val = DINode::getFlag(Lex.getStrVal());
3381 return TokError(Twine("invalid debug info flag flag '") +
3382 Lex.getStrVal() + "'");
3387 // Parse the flags and combine them together.
3388 unsigned Combined = 0;
3394 } while (EatIfPresent(lltok::bar));
3396 Result.assign(Combined);
3401 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3402 MDSignedField &Result) {
3403 if (Lex.getKind() != lltok::APSInt)
3404 return TokError("expected signed integer");
3406 auto &S = Lex.getAPSIntVal();
3408 return TokError("value for '" + Name + "' too small, limit is " +
3411 return TokError("value for '" + Name + "' too large, limit is " +
3413 Result.assign(S.getExtValue());
3414 assert(Result.Val >= Result.Min && "Expected value in range");
3415 assert(Result.Val <= Result.Max && "Expected value in range");
3421 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3422 switch (Lex.getKind()) {
3424 return TokError("expected 'true' or 'false'");
3425 case lltok::kw_true:
3426 Result.assign(true);
3428 case lltok::kw_false:
3429 Result.assign(false);
3437 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3438 if (Lex.getKind() == lltok::kw_null) {
3439 if (!Result.AllowNull)
3440 return TokError("'" + Name + "' cannot be null");
3442 Result.assign(nullptr);
3447 if (ParseMetadata(MD, nullptr))
3455 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3457 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3460 Result.assign(cast<ConstantAsMetadata>(MD));
3465 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3466 LocTy ValueLoc = Lex.getLoc();
3468 if (ParseStringConstant(S))
3471 if (!Result.AllowEmpty && S.empty())
3472 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3474 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3479 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3480 SmallVector<Metadata *, 4> MDs;
3481 if (ParseMDNodeVector(MDs))
3484 Result.assign(std::move(MDs));
3488 } // end namespace llvm
3490 template <class ParserTy>
3491 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3493 if (Lex.getKind() != lltok::LabelStr)
3494 return TokError("expected field label here");
3498 } while (EatIfPresent(lltok::comma));
3503 template <class ParserTy>
3504 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3505 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3508 if (ParseToken(lltok::lparen, "expected '(' here"))
3510 if (Lex.getKind() != lltok::rparen)
3511 if (ParseMDFieldsImplBody(parseField))
3514 ClosingLoc = Lex.getLoc();
3515 return ParseToken(lltok::rparen, "expected ')' here");
3518 template <class FieldTy>
3519 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3521 return TokError("field '" + Name + "' cannot be specified more than once");
3523 LocTy Loc = Lex.getLoc();
3525 return ParseMDField(Loc, Name, Result);
3528 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3529 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3531 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3532 if (Lex.getStrVal() == #CLASS) \
3533 return Parse##CLASS(N, IsDistinct);
3534 #include "llvm/IR/Metadata.def"
3536 return TokError("expected metadata type");
3539 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3540 #define NOP_FIELD(NAME, TYPE, INIT)
3541 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3543 return Error(ClosingLoc, "missing required field '" #NAME "'");
3544 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3545 if (Lex.getStrVal() == #NAME) \
3546 return ParseMDField(#NAME, NAME);
3547 #define PARSE_MD_FIELDS() \
3548 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3551 if (ParseMDFieldsImpl([&]() -> bool { \
3552 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3553 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3556 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3558 #define GET_OR_DISTINCT(CLASS, ARGS) \
3559 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3561 /// ParseDILocationFields:
3562 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3563 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3564 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3565 OPTIONAL(line, LineField, ); \
3566 OPTIONAL(column, ColumnField, ); \
3567 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3568 OPTIONAL(inlinedAt, MDField, );
3570 #undef VISIT_MD_FIELDS
3572 Result = GET_OR_DISTINCT(
3573 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3577 /// ParseGenericDINode:
3578 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3579 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3580 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3581 REQUIRED(tag, DwarfTagField, ); \
3582 OPTIONAL(header, MDStringField, ); \
3583 OPTIONAL(operands, MDFieldList, );
3585 #undef VISIT_MD_FIELDS
3587 Result = GET_OR_DISTINCT(GenericDINode,
3588 (Context, tag.Val, header.Val, operands.Val));
3592 /// ParseDISubrange:
3593 /// ::= !DISubrange(count: 30, lowerBound: 2)
3594 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3595 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3596 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3597 OPTIONAL(lowerBound, MDSignedField, );
3599 #undef VISIT_MD_FIELDS
3601 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3605 /// ParseDIEnumerator:
3606 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3607 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3608 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3609 REQUIRED(name, MDStringField, ); \
3610 REQUIRED(value, MDSignedField, );
3612 #undef VISIT_MD_FIELDS
3614 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3618 /// ParseDIBasicType:
3619 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3620 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3621 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3622 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3623 OPTIONAL(name, MDStringField, ); \
3624 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3625 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3626 OPTIONAL(encoding, DwarfAttEncodingField, );
3628 #undef VISIT_MD_FIELDS
3630 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3631 align.Val, encoding.Val));
3635 /// ParseDIDerivedType:
3636 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3637 /// line: 7, scope: !1, baseType: !2, size: 32,
3638 /// align: 32, offset: 0, flags: 0, extraData: !3)
3639 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3640 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3641 REQUIRED(tag, DwarfTagField, ); \
3642 OPTIONAL(name, MDStringField, ); \
3643 OPTIONAL(file, MDField, ); \
3644 OPTIONAL(line, LineField, ); \
3645 OPTIONAL(scope, MDField, ); \
3646 REQUIRED(baseType, MDField, ); \
3647 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3648 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3649 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3650 OPTIONAL(flags, DIFlagField, ); \
3651 OPTIONAL(extraData, MDField, );
3653 #undef VISIT_MD_FIELDS
3655 Result = GET_OR_DISTINCT(DIDerivedType,
3656 (Context, tag.Val, name.Val, file.Val, line.Val,
3657 scope.Val, baseType.Val, size.Val, align.Val,
3658 offset.Val, flags.Val, extraData.Val));
3662 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3663 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3664 REQUIRED(tag, DwarfTagField, ); \
3665 OPTIONAL(name, MDStringField, ); \
3666 OPTIONAL(file, MDField, ); \
3667 OPTIONAL(line, LineField, ); \
3668 OPTIONAL(scope, MDField, ); \
3669 OPTIONAL(baseType, MDField, ); \
3670 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3671 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3672 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3673 OPTIONAL(flags, DIFlagField, ); \
3674 OPTIONAL(elements, MDField, ); \
3675 OPTIONAL(runtimeLang, DwarfLangField, ); \
3676 OPTIONAL(vtableHolder, MDField, ); \
3677 OPTIONAL(templateParams, MDField, ); \
3678 OPTIONAL(identifier, MDStringField, );
3680 #undef VISIT_MD_FIELDS
3682 Result = GET_OR_DISTINCT(
3684 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3685 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3686 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3690 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3691 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3692 OPTIONAL(flags, DIFlagField, ); \
3693 REQUIRED(types, MDField, );
3695 #undef VISIT_MD_FIELDS
3697 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3701 /// ParseDIFileType:
3702 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3703 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3704 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3705 REQUIRED(filename, MDStringField, ); \
3706 REQUIRED(directory, MDStringField, );
3708 #undef VISIT_MD_FIELDS
3710 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3714 /// ParseDICompileUnit:
3715 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3716 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3717 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3718 /// enums: !1, retainedTypes: !2, subprograms: !3,
3719 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3720 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3722 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3724 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3725 REQUIRED(language, DwarfLangField, ); \
3726 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3727 OPTIONAL(producer, MDStringField, ); \
3728 OPTIONAL(isOptimized, MDBoolField, ); \
3729 OPTIONAL(flags, MDStringField, ); \
3730 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3731 OPTIONAL(splitDebugFilename, MDStringField, ); \
3732 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3733 OPTIONAL(enums, MDField, ); \
3734 OPTIONAL(retainedTypes, MDField, ); \
3735 OPTIONAL(subprograms, MDField, ); \
3736 OPTIONAL(globals, MDField, ); \
3737 OPTIONAL(imports, MDField, ); \
3738 OPTIONAL(dwoId, MDUnsignedField, );
3740 #undef VISIT_MD_FIELDS
3742 Result = DICompileUnit::getDistinct(
3743 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3744 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
3745 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, dwoId.Val);
3749 /// ParseDISubprogram:
3750 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3751 /// file: !1, line: 7, type: !2, isLocal: false,
3752 /// isDefinition: true, scopeLine: 8, containingType: !3,
3753 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3754 /// virtualIndex: 10, flags: 11,
3755 /// isOptimized: false, function: void ()* @_Z3foov,
3756 /// templateParams: !4, declaration: !5, variables: !6)
3757 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3758 auto Loc = Lex.getLoc();
3759 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3760 OPTIONAL(scope, MDField, ); \
3761 OPTIONAL(name, MDStringField, ); \
3762 OPTIONAL(linkageName, MDStringField, ); \
3763 OPTIONAL(file, MDField, ); \
3764 OPTIONAL(line, LineField, ); \
3765 OPTIONAL(type, MDField, ); \
3766 OPTIONAL(isLocal, MDBoolField, ); \
3767 OPTIONAL(isDefinition, MDBoolField, (true)); \
3768 OPTIONAL(scopeLine, LineField, ); \
3769 OPTIONAL(containingType, MDField, ); \
3770 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3771 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3772 OPTIONAL(flags, DIFlagField, ); \
3773 OPTIONAL(isOptimized, MDBoolField, ); \
3774 OPTIONAL(function, MDConstant, ); \
3775 OPTIONAL(templateParams, MDField, ); \
3776 OPTIONAL(declaration, MDField, ); \
3777 OPTIONAL(variables, MDField, );
3779 #undef VISIT_MD_FIELDS
3781 if (isDefinition.Val && !IsDistinct)
3784 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3786 Result = GET_OR_DISTINCT(
3787 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3788 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3789 scopeLine.Val, containingType.Val, virtuality.Val,
3790 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3791 templateParams.Val, declaration.Val, variables.Val));
3795 /// ParseDILexicalBlock:
3796 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3797 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3798 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3799 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3800 OPTIONAL(file, MDField, ); \
3801 OPTIONAL(line, LineField, ); \
3802 OPTIONAL(column, ColumnField, );
3804 #undef VISIT_MD_FIELDS
3806 Result = GET_OR_DISTINCT(
3807 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3811 /// ParseDILexicalBlockFile:
3812 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3813 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3814 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3815 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3816 OPTIONAL(file, MDField, ); \
3817 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3819 #undef VISIT_MD_FIELDS
3821 Result = GET_OR_DISTINCT(DILexicalBlockFile,
3822 (Context, scope.Val, file.Val, discriminator.Val));
3826 /// ParseDINamespace:
3827 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3828 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3829 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3830 REQUIRED(scope, MDField, ); \
3831 OPTIONAL(file, MDField, ); \
3832 OPTIONAL(name, MDStringField, ); \
3833 OPTIONAL(line, LineField, );
3835 #undef VISIT_MD_FIELDS
3837 Result = GET_OR_DISTINCT(DINamespace,
3838 (Context, scope.Val, file.Val, name.Val, line.Val));
3843 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3844 /// includePath: "/usr/include", isysroot: "/")
3845 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3846 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3847 REQUIRED(scope, MDField, ); \
3848 REQUIRED(name, MDStringField, ); \
3849 OPTIONAL(configMacros, MDStringField, ); \
3850 OPTIONAL(includePath, MDStringField, ); \
3851 OPTIONAL(isysroot, MDStringField, );
3853 #undef VISIT_MD_FIELDS
3855 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3856 configMacros.Val, includePath.Val, isysroot.Val));
3860 /// ParseDITemplateTypeParameter:
3861 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3862 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3863 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3864 OPTIONAL(name, MDStringField, ); \
3865 REQUIRED(type, MDField, );
3867 #undef VISIT_MD_FIELDS
3870 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3874 /// ParseDITemplateValueParameter:
3875 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3876 /// name: "V", type: !1, value: i32 7)
3877 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3878 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3879 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3880 OPTIONAL(name, MDStringField, ); \
3881 OPTIONAL(type, MDField, ); \
3882 REQUIRED(value, MDField, );
3884 #undef VISIT_MD_FIELDS
3886 Result = GET_OR_DISTINCT(DITemplateValueParameter,
3887 (Context, tag.Val, name.Val, type.Val, value.Val));
3891 /// ParseDIGlobalVariable:
3892 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3893 /// file: !1, line: 7, type: !2, isLocal: false,
3894 /// isDefinition: true, variable: i32* @foo,
3895 /// declaration: !3)
3896 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3897 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3898 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3899 OPTIONAL(scope, MDField, ); \
3900 OPTIONAL(linkageName, MDStringField, ); \
3901 OPTIONAL(file, MDField, ); \
3902 OPTIONAL(line, LineField, ); \
3903 OPTIONAL(type, MDField, ); \
3904 OPTIONAL(isLocal, MDBoolField, ); \
3905 OPTIONAL(isDefinition, MDBoolField, (true)); \
3906 OPTIONAL(variable, MDConstant, ); \
3907 OPTIONAL(declaration, MDField, );
3909 #undef VISIT_MD_FIELDS
3911 Result = GET_OR_DISTINCT(DIGlobalVariable,
3912 (Context, scope.Val, name.Val, linkageName.Val,
3913 file.Val, line.Val, type.Val, isLocal.Val,
3914 isDefinition.Val, variable.Val, declaration.Val));
3918 /// ParseDILocalVariable:
3919 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3920 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3921 /// ::= !DILocalVariable(scope: !0, name: "foo",
3922 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3923 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3924 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3925 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3926 OPTIONAL(name, MDStringField, ); \
3927 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
3928 OPTIONAL(file, MDField, ); \
3929 OPTIONAL(line, LineField, ); \
3930 OPTIONAL(type, MDField, ); \
3931 OPTIONAL(flags, DIFlagField, );
3933 #undef VISIT_MD_FIELDS
3935 Result = GET_OR_DISTINCT(DILocalVariable,
3936 (Context, scope.Val, name.Val, file.Val, line.Val,
3937 type.Val, arg.Val, flags.Val));
3941 /// ParseDIExpression:
3942 /// ::= !DIExpression(0, 7, -1)
3943 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3944 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3947 if (ParseToken(lltok::lparen, "expected '(' here"))
3950 SmallVector<uint64_t, 8> Elements;
3951 if (Lex.getKind() != lltok::rparen)
3953 if (Lex.getKind() == lltok::DwarfOp) {
3954 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3956 Elements.push_back(Op);
3959 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3962 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3963 return TokError("expected unsigned integer");
3965 auto &U = Lex.getAPSIntVal();
3966 if (U.ugt(UINT64_MAX))
3967 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3968 Elements.push_back(U.getZExtValue());
3970 } while (EatIfPresent(lltok::comma));
3972 if (ParseToken(lltok::rparen, "expected ')' here"))
3975 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3979 /// ParseDIObjCProperty:
3980 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3981 /// getter: "getFoo", attributes: 7, type: !2)
3982 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3983 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3984 OPTIONAL(name, MDStringField, ); \
3985 OPTIONAL(file, MDField, ); \
3986 OPTIONAL(line, LineField, ); \
3987 OPTIONAL(setter, MDStringField, ); \
3988 OPTIONAL(getter, MDStringField, ); \
3989 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3990 OPTIONAL(type, MDField, );
3992 #undef VISIT_MD_FIELDS
3994 Result = GET_OR_DISTINCT(DIObjCProperty,
3995 (Context, name.Val, file.Val, line.Val, setter.Val,
3996 getter.Val, attributes.Val, type.Val));
4000 /// ParseDIImportedEntity:
4001 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4002 /// line: 7, name: "foo")
4003 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4004 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4005 REQUIRED(tag, DwarfTagField, ); \
4006 REQUIRED(scope, MDField, ); \
4007 OPTIONAL(entity, MDField, ); \
4008 OPTIONAL(line, LineField, ); \
4009 OPTIONAL(name, MDStringField, );
4011 #undef VISIT_MD_FIELDS
4013 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4014 entity.Val, line.Val, name.Val));
4018 #undef PARSE_MD_FIELD
4020 #undef REQUIRE_FIELD
4021 #undef DECLARE_FIELD
4023 /// ParseMetadataAsValue
4024 /// ::= metadata i32 %local
4025 /// ::= metadata i32 @global
4026 /// ::= metadata i32 7
4028 /// ::= metadata !{...}
4029 /// ::= metadata !"string"
4030 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4031 // Note: the type 'metadata' has already been parsed.
4033 if (ParseMetadata(MD, &PFS))
4036 V = MetadataAsValue::get(Context, MD);
4040 /// ParseValueAsMetadata
4044 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4045 PerFunctionState *PFS) {
4048 if (ParseType(Ty, TypeMsg, Loc))
4050 if (Ty->isMetadataTy())
4051 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4054 if (ParseValue(Ty, V, PFS))
4057 MD = ValueAsMetadata::get(V);
4068 /// ::= !DILocation(...)
4069 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4070 if (Lex.getKind() == lltok::MetadataVar) {
4072 if (ParseSpecializedMDNode(N))
4080 if (Lex.getKind() != lltok::exclaim)
4081 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4084 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4088 // ::= '!' STRINGCONSTANT
4089 if (Lex.getKind() == lltok::StringConstant) {
4091 if (ParseMDString(S))
4101 if (ParseMDNodeTail(N))
4108 //===----------------------------------------------------------------------===//
4109 // Function Parsing.
4110 //===----------------------------------------------------------------------===//
4112 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4113 PerFunctionState *PFS,
4114 OperatorConstraint OC) {
4115 if (Ty->isFunctionTy())
4116 return Error(ID.Loc, "functions are not values, refer to them as pointers");
4118 if (OC && ID.Kind != ValID::t_LocalID && ID.Kind != ValID::t_LocalName) {
4121 return Error(ID.Loc, "Catchpad value required in this position");
4123 return Error(ID.Loc, "Cleanuppad value required in this position");
4125 llvm_unreachable("Unexpected constraint kind");
4130 case ValID::t_LocalID:
4131 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4132 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, OC);
4133 return V == nullptr;
4134 case ValID::t_LocalName:
4135 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4136 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, OC);
4137 return V == nullptr;
4138 case ValID::t_InlineAsm: {
4139 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4140 return Error(ID.Loc, "invalid type for inline asm constraint string");
4141 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4142 (ID.UIntVal >> 1) & 1,
4143 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4146 case ValID::t_GlobalName:
4147 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4148 return V == nullptr;
4149 case ValID::t_GlobalID:
4150 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4151 return V == nullptr;
4152 case ValID::t_APSInt:
4153 if (!Ty->isIntegerTy())
4154 return Error(ID.Loc, "integer constant must have integer type");
4155 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4156 V = ConstantInt::get(Context, ID.APSIntVal);
4158 case ValID::t_APFloat:
4159 if (!Ty->isFloatingPointTy() ||
4160 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4161 return Error(ID.Loc, "floating point constant invalid for type");
4163 // The lexer has no type info, so builds all half, float, and double FP
4164 // constants as double. Fix this here. Long double does not need this.
4165 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4168 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4170 else if (Ty->isFloatTy())
4171 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4174 V = ConstantFP::get(Context, ID.APFloatVal);
4176 if (V->getType() != Ty)
4177 return Error(ID.Loc, "floating point constant does not have type '" +
4178 getTypeString(Ty) + "'");
4182 if (!Ty->isPointerTy())
4183 return Error(ID.Loc, "null must be a pointer type");
4184 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4186 case ValID::t_Undef:
4187 // FIXME: LabelTy should not be a first-class type.
4188 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4189 return Error(ID.Loc, "invalid type for undef constant");
4190 V = UndefValue::get(Ty);
4192 case ValID::t_EmptyArray:
4193 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4194 return Error(ID.Loc, "invalid empty array initializer");
4195 V = UndefValue::get(Ty);
4198 // FIXME: LabelTy should not be a first-class type.
4199 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4200 return Error(ID.Loc, "invalid type for null constant");
4201 V = Constant::getNullValue(Ty);
4203 case ValID::t_Constant:
4204 if (ID.ConstantVal->getType() != Ty)
4205 return Error(ID.Loc, "constant expression type mismatch");
4209 case ValID::t_ConstantStruct:
4210 case ValID::t_PackedConstantStruct:
4211 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4212 if (ST->getNumElements() != ID.UIntVal)
4213 return Error(ID.Loc,
4214 "initializer with struct type has wrong # elements");
4215 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4216 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4218 // Verify that the elements are compatible with the structtype.
4219 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4220 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4221 return Error(ID.Loc, "element " + Twine(i) +
4222 " of struct initializer doesn't match struct element type");
4224 V = ConstantStruct::get(
4225 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4227 return Error(ID.Loc, "constant expression type mismatch");
4230 llvm_unreachable("Invalid ValID");
4233 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4236 auto Loc = Lex.getLoc();
4237 if (ParseValID(ID, /*PFS=*/nullptr))
4240 case ValID::t_APSInt:
4241 case ValID::t_APFloat:
4242 case ValID::t_Undef:
4243 case ValID::t_Constant:
4244 case ValID::t_ConstantStruct:
4245 case ValID::t_PackedConstantStruct: {
4247 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4249 assert(isa<Constant>(V) && "Expected a constant value");
4250 C = cast<Constant>(V);
4254 return Error(Loc, "expected a constant value");
4258 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS,
4259 OperatorConstraint OC) {
4262 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS, OC);
4265 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4267 return ParseType(Ty) ||
4268 ParseValue(Ty, V, PFS);
4271 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4272 PerFunctionState &PFS) {
4275 if (ParseTypeAndValue(V, PFS)) return true;
4276 if (!isa<BasicBlock>(V))
4277 return Error(Loc, "expected a basic block");
4278 BB = cast<BasicBlock>(V);
4284 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4285 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4286 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4287 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4288 // Parse the linkage.
4289 LocTy LinkageLoc = Lex.getLoc();
4292 unsigned Visibility;
4293 unsigned DLLStorageClass;
4294 AttrBuilder RetAttrs;
4296 Type *RetType = nullptr;
4297 LocTy RetTypeLoc = Lex.getLoc();
4298 if (ParseOptionalLinkage(Linkage) ||
4299 ParseOptionalVisibility(Visibility) ||
4300 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4301 ParseOptionalCallingConv(CC) ||
4302 ParseOptionalReturnAttrs(RetAttrs) ||
4303 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4306 // Verify that the linkage is ok.
4307 switch ((GlobalValue::LinkageTypes)Linkage) {
4308 case GlobalValue::ExternalLinkage:
4309 break; // always ok.
4310 case GlobalValue::ExternalWeakLinkage:
4312 return Error(LinkageLoc, "invalid linkage for function definition");
4314 case GlobalValue::PrivateLinkage:
4315 case GlobalValue::InternalLinkage:
4316 case GlobalValue::AvailableExternallyLinkage:
4317 case GlobalValue::LinkOnceAnyLinkage:
4318 case GlobalValue::LinkOnceODRLinkage:
4319 case GlobalValue::WeakAnyLinkage:
4320 case GlobalValue::WeakODRLinkage:
4322 return Error(LinkageLoc, "invalid linkage for function declaration");
4324 case GlobalValue::AppendingLinkage:
4325 case GlobalValue::CommonLinkage:
4326 return Error(LinkageLoc, "invalid function linkage type");
4329 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4330 return Error(LinkageLoc,
4331 "symbol with local linkage must have default visibility");
4333 if (!FunctionType::isValidReturnType(RetType))
4334 return Error(RetTypeLoc, "invalid function return type");
4336 LocTy NameLoc = Lex.getLoc();
4338 std::string FunctionName;
4339 if (Lex.getKind() == lltok::GlobalVar) {
4340 FunctionName = Lex.getStrVal();
4341 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4342 unsigned NameID = Lex.getUIntVal();
4344 if (NameID != NumberedVals.size())
4345 return TokError("function expected to be numbered '%" +
4346 Twine(NumberedVals.size()) + "'");
4348 return TokError("expected function name");
4353 if (Lex.getKind() != lltok::lparen)
4354 return TokError("expected '(' in function argument list");
4356 SmallVector<ArgInfo, 8> ArgList;
4358 AttrBuilder FuncAttrs;
4359 std::vector<unsigned> FwdRefAttrGrps;
4361 std::string Section;
4365 LocTy UnnamedAddrLoc;
4366 Constant *Prefix = nullptr;
4367 Constant *Prologue = nullptr;
4368 Constant *PersonalityFn = nullptr;
4371 if (ParseArgumentList(ArgList, isVarArg) ||
4372 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4374 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4376 (EatIfPresent(lltok::kw_section) &&
4377 ParseStringConstant(Section)) ||
4378 parseOptionalComdat(FunctionName, C) ||
4379 ParseOptionalAlignment(Alignment) ||
4380 (EatIfPresent(lltok::kw_gc) &&
4381 ParseStringConstant(GC)) ||
4382 (EatIfPresent(lltok::kw_prefix) &&
4383 ParseGlobalTypeAndValue(Prefix)) ||
4384 (EatIfPresent(lltok::kw_prologue) &&
4385 ParseGlobalTypeAndValue(Prologue)) ||
4386 (EatIfPresent(lltok::kw_personality) &&
4387 ParseGlobalTypeAndValue(PersonalityFn)))
4390 if (FuncAttrs.contains(Attribute::Builtin))
4391 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4393 // If the alignment was parsed as an attribute, move to the alignment field.
4394 if (FuncAttrs.hasAlignmentAttr()) {
4395 Alignment = FuncAttrs.getAlignment();
4396 FuncAttrs.removeAttribute(Attribute::Alignment);
4399 // Okay, if we got here, the function is syntactically valid. Convert types
4400 // and do semantic checks.
4401 std::vector<Type*> ParamTypeList;
4402 SmallVector<AttributeSet, 8> Attrs;
4404 if (RetAttrs.hasAttributes())
4405 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4406 AttributeSet::ReturnIndex,
4409 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4410 ParamTypeList.push_back(ArgList[i].Ty);
4411 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4412 AttrBuilder B(ArgList[i].Attrs, i + 1);
4413 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4417 if (FuncAttrs.hasAttributes())
4418 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4419 AttributeSet::FunctionIndex,
4422 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4424 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4425 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4428 FunctionType::get(RetType, ParamTypeList, isVarArg);
4429 PointerType *PFT = PointerType::getUnqual(FT);
4432 if (!FunctionName.empty()) {
4433 // If this was a definition of a forward reference, remove the definition
4434 // from the forward reference table and fill in the forward ref.
4435 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4436 ForwardRefVals.find(FunctionName);
4437 if (FRVI != ForwardRefVals.end()) {
4438 Fn = M->getFunction(FunctionName);
4440 return Error(FRVI->second.second, "invalid forward reference to "
4441 "function as global value!");
4442 if (Fn->getType() != PFT)
4443 return Error(FRVI->second.second, "invalid forward reference to "
4444 "function '" + FunctionName + "' with wrong type!");
4446 ForwardRefVals.erase(FRVI);
4447 } else if ((Fn = M->getFunction(FunctionName))) {
4448 // Reject redefinitions.
4449 return Error(NameLoc, "invalid redefinition of function '" +
4450 FunctionName + "'");
4451 } else if (M->getNamedValue(FunctionName)) {
4452 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4456 // If this is a definition of a forward referenced function, make sure the
4458 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4459 = ForwardRefValIDs.find(NumberedVals.size());
4460 if (I != ForwardRefValIDs.end()) {
4461 Fn = cast<Function>(I->second.first);
4462 if (Fn->getType() != PFT)
4463 return Error(NameLoc, "type of definition and forward reference of '@" +
4464 Twine(NumberedVals.size()) + "' disagree");
4465 ForwardRefValIDs.erase(I);
4470 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4471 else // Move the forward-reference to the correct spot in the module.
4472 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4474 if (FunctionName.empty())
4475 NumberedVals.push_back(Fn);
4477 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4478 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4479 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4480 Fn->setCallingConv(CC);
4481 Fn->setAttributes(PAL);
4482 Fn->setUnnamedAddr(UnnamedAddr);
4483 Fn->setAlignment(Alignment);
4484 Fn->setSection(Section);
4486 Fn->setPersonalityFn(PersonalityFn);
4487 if (!GC.empty()) Fn->setGC(GC.c_str());
4488 Fn->setPrefixData(Prefix);
4489 Fn->setPrologueData(Prologue);
4490 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4492 // Add all of the arguments we parsed to the function.
4493 Function::arg_iterator ArgIt = Fn->arg_begin();
4494 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4495 // If the argument has a name, insert it into the argument symbol table.
4496 if (ArgList[i].Name.empty()) continue;
4498 // Set the name, if it conflicted, it will be auto-renamed.
4499 ArgIt->setName(ArgList[i].Name);
4501 if (ArgIt->getName() != ArgList[i].Name)
4502 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4503 ArgList[i].Name + "'");
4509 // Check the declaration has no block address forward references.
4511 if (FunctionName.empty()) {
4512 ID.Kind = ValID::t_GlobalID;
4513 ID.UIntVal = NumberedVals.size() - 1;
4515 ID.Kind = ValID::t_GlobalName;
4516 ID.StrVal = FunctionName;
4518 auto Blocks = ForwardRefBlockAddresses.find(ID);
4519 if (Blocks != ForwardRefBlockAddresses.end())
4520 return Error(Blocks->first.Loc,
4521 "cannot take blockaddress inside a declaration");
4525 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4527 if (FunctionNumber == -1) {
4528 ID.Kind = ValID::t_GlobalName;
4529 ID.StrVal = F.getName();
4531 ID.Kind = ValID::t_GlobalID;
4532 ID.UIntVal = FunctionNumber;
4535 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4536 if (Blocks == P.ForwardRefBlockAddresses.end())
4539 for (const auto &I : Blocks->second) {
4540 const ValID &BBID = I.first;
4541 GlobalValue *GV = I.second;
4543 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4544 "Expected local id or name");
4546 if (BBID.Kind == ValID::t_LocalName)
4547 BB = GetBB(BBID.StrVal, BBID.Loc);
4549 BB = GetBB(BBID.UIntVal, BBID.Loc);
4551 return P.Error(BBID.Loc, "referenced value is not a basic block");
4553 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4554 GV->eraseFromParent();
4557 P.ForwardRefBlockAddresses.erase(Blocks);
4561 /// ParseFunctionBody
4562 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4563 bool LLParser::ParseFunctionBody(Function &Fn) {
4564 if (Lex.getKind() != lltok::lbrace)
4565 return TokError("expected '{' in function body");
4566 Lex.Lex(); // eat the {.
4568 int FunctionNumber = -1;
4569 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4571 PerFunctionState PFS(*this, Fn, FunctionNumber);
4573 // Resolve block addresses and allow basic blocks to be forward-declared
4574 // within this function.
4575 if (PFS.resolveForwardRefBlockAddresses())
4577 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4579 // We need at least one basic block.
4580 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4581 return TokError("function body requires at least one basic block");
4583 while (Lex.getKind() != lltok::rbrace &&
4584 Lex.getKind() != lltok::kw_uselistorder)
4585 if (ParseBasicBlock(PFS)) return true;
4587 while (Lex.getKind() != lltok::rbrace)
4588 if (ParseUseListOrder(&PFS))
4594 // Verify function is ok.
4595 return PFS.FinishFunction();
4599 /// ::= LabelStr? Instruction*
4600 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4601 // If this basic block starts out with a name, remember it.
4603 LocTy NameLoc = Lex.getLoc();
4604 if (Lex.getKind() == lltok::LabelStr) {
4605 Name = Lex.getStrVal();
4609 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4611 return Error(NameLoc,
4612 "unable to create block named '" + Name + "'");
4614 std::string NameStr;
4616 // Parse the instructions in this block until we get a terminator.
4619 // This instruction may have three possibilities for a name: a) none
4620 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4621 LocTy NameLoc = Lex.getLoc();
4625 if (Lex.getKind() == lltok::LocalVarID) {
4626 NameID = Lex.getUIntVal();
4628 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4630 } else if (Lex.getKind() == lltok::LocalVar) {
4631 NameStr = Lex.getStrVal();
4633 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4637 switch (ParseInstruction(Inst, BB, PFS)) {
4638 default: llvm_unreachable("Unknown ParseInstruction result!");
4639 case InstError: return true;
4641 BB->getInstList().push_back(Inst);
4643 // With a normal result, we check to see if the instruction is followed by
4644 // a comma and metadata.
4645 if (EatIfPresent(lltok::comma))
4646 if (ParseInstructionMetadata(*Inst))
4649 case InstExtraComma:
4650 BB->getInstList().push_back(Inst);
4652 // If the instruction parser ate an extra comma at the end of it, it
4653 // *must* be followed by metadata.
4654 if (ParseInstructionMetadata(*Inst))
4659 // Set the name on the instruction.
4660 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4661 } while (!isa<TerminatorInst>(Inst));
4666 //===----------------------------------------------------------------------===//
4667 // Instruction Parsing.
4668 //===----------------------------------------------------------------------===//
4670 /// ParseInstruction - Parse one of the many different instructions.
4672 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4673 PerFunctionState &PFS) {
4674 lltok::Kind Token = Lex.getKind();
4675 if (Token == lltok::Eof)
4676 return TokError("found end of file when expecting more instructions");
4677 LocTy Loc = Lex.getLoc();
4678 unsigned KeywordVal = Lex.getUIntVal();
4679 Lex.Lex(); // Eat the keyword.
4682 default: return Error(Loc, "expected instruction opcode");
4683 // Terminator Instructions.
4684 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4685 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4686 case lltok::kw_br: return ParseBr(Inst, PFS);
4687 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4688 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4689 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4690 case lltok::kw_resume: return ParseResume(Inst, PFS);
4691 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4692 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4693 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4694 case lltok::kw_terminatepad: return ParseTerminatePad(Inst, PFS);
4695 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4696 case lltok::kw_catchendpad: return ParseCatchEndPad(Inst, PFS);
4697 case lltok::kw_cleanupendpad: return ParseCleanupEndPad(Inst, PFS);
4698 // Binary Operators.
4702 case lltok::kw_shl: {
4703 bool NUW = EatIfPresent(lltok::kw_nuw);
4704 bool NSW = EatIfPresent(lltok::kw_nsw);
4705 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4707 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4709 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4710 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4713 case lltok::kw_fadd:
4714 case lltok::kw_fsub:
4715 case lltok::kw_fmul:
4716 case lltok::kw_fdiv:
4717 case lltok::kw_frem: {
4718 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4719 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4723 Inst->setFastMathFlags(FMF);
4727 case lltok::kw_sdiv:
4728 case lltok::kw_udiv:
4729 case lltok::kw_lshr:
4730 case lltok::kw_ashr: {
4731 bool Exact = EatIfPresent(lltok::kw_exact);
4733 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4734 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4738 case lltok::kw_urem:
4739 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4742 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4743 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4744 case lltok::kw_fcmp: {
4745 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4746 int Res = ParseCompare(Inst, PFS, KeywordVal);
4750 Inst->setFastMathFlags(FMF);
4755 case lltok::kw_trunc:
4756 case lltok::kw_zext:
4757 case lltok::kw_sext:
4758 case lltok::kw_fptrunc:
4759 case lltok::kw_fpext:
4760 case lltok::kw_bitcast:
4761 case lltok::kw_addrspacecast:
4762 case lltok::kw_uitofp:
4763 case lltok::kw_sitofp:
4764 case lltok::kw_fptoui:
4765 case lltok::kw_fptosi:
4766 case lltok::kw_inttoptr:
4767 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4769 case lltok::kw_select: return ParseSelect(Inst, PFS);
4770 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4771 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4772 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4773 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4774 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4775 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4777 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4778 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4779 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4781 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4782 case lltok::kw_load: return ParseLoad(Inst, PFS);
4783 case lltok::kw_store: return ParseStore(Inst, PFS);
4784 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4785 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4786 case lltok::kw_fence: return ParseFence(Inst, PFS);
4787 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4788 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4789 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4793 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4794 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4795 if (Opc == Instruction::FCmp) {
4796 switch (Lex.getKind()) {
4797 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4798 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4799 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4800 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4801 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4802 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4803 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4804 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4805 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4806 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4807 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4808 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4809 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4810 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4811 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4812 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4813 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4816 switch (Lex.getKind()) {
4817 default: return TokError("expected icmp predicate (e.g. 'eq')");
4818 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4819 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4820 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4821 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4822 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4823 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4824 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4825 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4826 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4827 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4834 //===----------------------------------------------------------------------===//
4835 // Terminator Instructions.
4836 //===----------------------------------------------------------------------===//
4838 /// ParseRet - Parse a return instruction.
4839 /// ::= 'ret' void (',' !dbg, !1)*
4840 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4841 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4842 PerFunctionState &PFS) {
4843 SMLoc TypeLoc = Lex.getLoc();
4845 if (ParseType(Ty, true /*void allowed*/)) return true;
4847 Type *ResType = PFS.getFunction().getReturnType();
4849 if (Ty->isVoidTy()) {
4850 if (!ResType->isVoidTy())
4851 return Error(TypeLoc, "value doesn't match function result type '" +
4852 getTypeString(ResType) + "'");
4854 Inst = ReturnInst::Create(Context);
4859 if (ParseValue(Ty, RV, PFS)) return true;
4861 if (ResType != RV->getType())
4862 return Error(TypeLoc, "value doesn't match function result type '" +
4863 getTypeString(ResType) + "'");
4865 Inst = ReturnInst::Create(Context, RV);
4871 /// ::= 'br' TypeAndValue
4872 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4873 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4876 BasicBlock *Op1, *Op2;
4877 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4879 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4880 Inst = BranchInst::Create(BB);
4884 if (Op0->getType() != Type::getInt1Ty(Context))
4885 return Error(Loc, "branch condition must have 'i1' type");
4887 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4888 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4889 ParseToken(lltok::comma, "expected ',' after true destination") ||
4890 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4893 Inst = BranchInst::Create(Op1, Op2, Op0);
4899 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4901 /// ::= (TypeAndValue ',' TypeAndValue)*
4902 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4903 LocTy CondLoc, BBLoc;
4905 BasicBlock *DefaultBB;
4906 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4907 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4908 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4909 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4912 if (!Cond->getType()->isIntegerTy())
4913 return Error(CondLoc, "switch condition must have integer type");
4915 // Parse the jump table pairs.
4916 SmallPtrSet<Value*, 32> SeenCases;
4917 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4918 while (Lex.getKind() != lltok::rsquare) {
4922 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4923 ParseToken(lltok::comma, "expected ',' after case value") ||
4924 ParseTypeAndBasicBlock(DestBB, PFS))
4927 if (!SeenCases.insert(Constant).second)
4928 return Error(CondLoc, "duplicate case value in switch");
4929 if (!isa<ConstantInt>(Constant))
4930 return Error(CondLoc, "case value is not a constant integer");
4932 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4935 Lex.Lex(); // Eat the ']'.
4937 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4938 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4939 SI->addCase(Table[i].first, Table[i].second);
4946 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4947 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4950 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4951 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4952 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4955 if (!Address->getType()->isPointerTy())
4956 return Error(AddrLoc, "indirectbr address must have pointer type");
4958 // Parse the destination list.
4959 SmallVector<BasicBlock*, 16> DestList;
4961 if (Lex.getKind() != lltok::rsquare) {
4963 if (ParseTypeAndBasicBlock(DestBB, PFS))
4965 DestList.push_back(DestBB);
4967 while (EatIfPresent(lltok::comma)) {
4968 if (ParseTypeAndBasicBlock(DestBB, PFS))
4970 DestList.push_back(DestBB);
4974 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4977 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4978 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4979 IBI->addDestination(DestList[i]);
4986 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4987 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4988 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4989 LocTy CallLoc = Lex.getLoc();
4990 AttrBuilder RetAttrs, FnAttrs;
4991 std::vector<unsigned> FwdRefAttrGrps;
4994 Type *RetType = nullptr;
4997 SmallVector<ParamInfo, 16> ArgList;
4999 BasicBlock *NormalBB, *UnwindBB;
5000 if (ParseOptionalCallingConv(CC) ||
5001 ParseOptionalReturnAttrs(RetAttrs) ||
5002 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5003 ParseValID(CalleeID) ||
5004 ParseParameterList(ArgList, PFS) ||
5005 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5007 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5008 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5009 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5010 ParseTypeAndBasicBlock(UnwindBB, PFS))
5013 // If RetType is a non-function pointer type, then this is the short syntax
5014 // for the call, which means that RetType is just the return type. Infer the
5015 // rest of the function argument types from the arguments that are present.
5016 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5018 // Pull out the types of all of the arguments...
5019 std::vector<Type*> ParamTypes;
5020 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5021 ParamTypes.push_back(ArgList[i].V->getType());
5023 if (!FunctionType::isValidReturnType(RetType))
5024 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5026 Ty = FunctionType::get(RetType, ParamTypes, false);
5031 // Look up the callee.
5033 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5036 // Set up the Attribute for the function.
5037 SmallVector<AttributeSet, 8> Attrs;
5038 if (RetAttrs.hasAttributes())
5039 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5040 AttributeSet::ReturnIndex,
5043 SmallVector<Value*, 8> Args;
5045 // Loop through FunctionType's arguments and ensure they are specified
5046 // correctly. Also, gather any parameter attributes.
5047 FunctionType::param_iterator I = Ty->param_begin();
5048 FunctionType::param_iterator E = Ty->param_end();
5049 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5050 Type *ExpectedTy = nullptr;
5053 } else if (!Ty->isVarArg()) {
5054 return Error(ArgList[i].Loc, "too many arguments specified");
5057 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5058 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5059 getTypeString(ExpectedTy) + "'");
5060 Args.push_back(ArgList[i].V);
5061 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5062 AttrBuilder B(ArgList[i].Attrs, i + 1);
5063 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5068 return Error(CallLoc, "not enough parameters specified for call");
5070 if (FnAttrs.hasAttributes()) {
5071 if (FnAttrs.hasAlignmentAttr())
5072 return Error(CallLoc, "invoke instructions may not have an alignment");
5074 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5075 AttributeSet::FunctionIndex,
5079 // Finish off the Attribute and check them
5080 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5082 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
5083 II->setCallingConv(CC);
5084 II->setAttributes(PAL);
5085 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5091 /// ::= 'resume' TypeAndValue
5092 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5093 Value *Exn; LocTy ExnLoc;
5094 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5097 ResumeInst *RI = ResumeInst::Create(Exn);
5102 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5103 PerFunctionState &PFS) {
5104 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5107 while (Lex.getKind() != lltok::rsquare) {
5108 // If this isn't the first argument, we need a comma.
5109 if (!Args.empty() &&
5110 ParseToken(lltok::comma, "expected ',' in argument list"))
5113 // Parse the argument.
5115 Type *ArgTy = nullptr;
5116 if (ParseType(ArgTy, ArgLoc))
5120 if (ArgTy->isMetadataTy()) {
5121 if (ParseMetadataAsValue(V, PFS))
5124 if (ParseValue(ArgTy, V, PFS))
5130 Lex.Lex(); // Lex the ']'.
5135 /// ::= 'cleanupret' Value unwind ('to' 'caller' | TypeAndValue)
5136 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5137 Value *CleanupPad = nullptr;
5139 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS, OC_CleanupPad))
5142 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5145 BasicBlock *UnwindBB = nullptr;
5146 if (Lex.getKind() == lltok::kw_to) {
5148 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5151 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5156 Inst = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad), UnwindBB);
5161 /// ::= 'catchret' Value 'to' TypeAndValue
5162 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5163 Value *CatchPad = nullptr;
5165 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS, OC_CatchPad))
5169 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5170 ParseTypeAndBasicBlock(BB, PFS))
5173 Inst = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
5178 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5179 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5180 SmallVector<Value *, 8> Args;
5181 if (ParseExceptionArgs(Args, PFS))
5184 BasicBlock *NormalBB, *UnwindBB;
5185 if (ParseToken(lltok::kw_to, "expected 'to' in catchpad") ||
5186 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5187 ParseToken(lltok::kw_unwind, "expected 'unwind' in catchpad") ||
5188 ParseTypeAndBasicBlock(UnwindBB, PFS))
5191 Inst = CatchPadInst::Create(NormalBB, UnwindBB, Args);
5195 /// ParseTerminatePad
5196 /// ::= 'terminatepad' ParamList 'to' TypeAndValue
5197 bool LLParser::ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS) {
5198 SmallVector<Value *, 8> Args;
5199 if (ParseExceptionArgs(Args, PFS))
5202 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in terminatepad"))
5205 BasicBlock *UnwindBB = nullptr;
5206 if (Lex.getKind() == lltok::kw_to) {
5208 if (ParseToken(lltok::kw_caller, "expected 'caller' in terminatepad"))
5211 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5216 Inst = TerminatePadInst::Create(Context, UnwindBB, Args);
5221 /// ::= 'cleanuppad' ParamList
5222 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5223 SmallVector<Value *, 8> Args;
5224 if (ParseExceptionArgs(Args, PFS))
5227 Inst = CleanupPadInst::Create(Context, Args);
5231 /// ParseCatchEndPad
5232 /// ::= 'catchendpad' unwind ('to' 'caller' | TypeAndValue)
5233 bool LLParser::ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5234 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5237 BasicBlock *UnwindBB = nullptr;
5238 if (Lex.getKind() == lltok::kw_to) {
5240 if (Lex.getKind() == lltok::kw_caller) {
5246 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5251 Inst = CatchEndPadInst::Create(Context, UnwindBB);
5255 /// ParseCatchEndPad
5256 /// ::= 'cleanupendpad' Value unwind ('to' 'caller' | TypeAndValue)
5257 bool LLParser::ParseCleanupEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5258 Value *CleanupPad = nullptr;
5260 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS, OC_CleanupPad))
5263 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5266 BasicBlock *UnwindBB = nullptr;
5267 if (Lex.getKind() == lltok::kw_to) {
5269 if (Lex.getKind() == lltok::kw_caller) {
5275 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5280 Inst = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), UnwindBB);
5284 //===----------------------------------------------------------------------===//
5285 // Binary Operators.
5286 //===----------------------------------------------------------------------===//
5289 /// ::= ArithmeticOps TypeAndValue ',' Value
5291 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5292 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5293 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5294 unsigned Opc, unsigned OperandType) {
5295 LocTy Loc; Value *LHS, *RHS;
5296 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5297 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5298 ParseValue(LHS->getType(), RHS, PFS))
5302 switch (OperandType) {
5303 default: llvm_unreachable("Unknown operand type!");
5304 case 0: // int or FP.
5305 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5306 LHS->getType()->isFPOrFPVectorTy();
5308 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5309 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5313 return Error(Loc, "invalid operand type for instruction");
5315 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5320 /// ::= ArithmeticOps TypeAndValue ',' Value {
5321 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5323 LocTy Loc; Value *LHS, *RHS;
5324 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5325 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5326 ParseValue(LHS->getType(), RHS, PFS))
5329 if (!LHS->getType()->isIntOrIntVectorTy())
5330 return Error(Loc,"instruction requires integer or integer vector operands");
5332 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5338 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5339 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5340 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5342 // Parse the integer/fp comparison predicate.
5346 if (ParseCmpPredicate(Pred, Opc) ||
5347 ParseTypeAndValue(LHS, Loc, PFS) ||
5348 ParseToken(lltok::comma, "expected ',' after compare value") ||
5349 ParseValue(LHS->getType(), RHS, PFS))
5352 if (Opc == Instruction::FCmp) {
5353 if (!LHS->getType()->isFPOrFPVectorTy())
5354 return Error(Loc, "fcmp requires floating point operands");
5355 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5357 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5358 if (!LHS->getType()->isIntOrIntVectorTy() &&
5359 !LHS->getType()->getScalarType()->isPointerTy())
5360 return Error(Loc, "icmp requires integer operands");
5361 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5366 //===----------------------------------------------------------------------===//
5367 // Other Instructions.
5368 //===----------------------------------------------------------------------===//
5372 /// ::= CastOpc TypeAndValue 'to' Type
5373 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5377 Type *DestTy = nullptr;
5378 if (ParseTypeAndValue(Op, Loc, PFS) ||
5379 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5383 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5384 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5385 return Error(Loc, "invalid cast opcode for cast from '" +
5386 getTypeString(Op->getType()) + "' to '" +
5387 getTypeString(DestTy) + "'");
5389 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5394 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5395 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5397 Value *Op0, *Op1, *Op2;
5398 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5399 ParseToken(lltok::comma, "expected ',' after select condition") ||
5400 ParseTypeAndValue(Op1, PFS) ||
5401 ParseToken(lltok::comma, "expected ',' after select value") ||
5402 ParseTypeAndValue(Op2, PFS))
5405 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5406 return Error(Loc, Reason);
5408 Inst = SelectInst::Create(Op0, Op1, Op2);
5413 /// ::= 'va_arg' TypeAndValue ',' Type
5414 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5416 Type *EltTy = nullptr;
5418 if (ParseTypeAndValue(Op, PFS) ||
5419 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5420 ParseType(EltTy, TypeLoc))
5423 if (!EltTy->isFirstClassType())
5424 return Error(TypeLoc, "va_arg requires operand with first class type");
5426 Inst = new VAArgInst(Op, EltTy);
5430 /// ParseExtractElement
5431 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5432 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5435 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5436 ParseToken(lltok::comma, "expected ',' after extract value") ||
5437 ParseTypeAndValue(Op1, PFS))
5440 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5441 return Error(Loc, "invalid extractelement operands");
5443 Inst = ExtractElementInst::Create(Op0, Op1);
5447 /// ParseInsertElement
5448 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5449 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5451 Value *Op0, *Op1, *Op2;
5452 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5453 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5454 ParseTypeAndValue(Op1, PFS) ||
5455 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5456 ParseTypeAndValue(Op2, PFS))
5459 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5460 return Error(Loc, "invalid insertelement operands");
5462 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5466 /// ParseShuffleVector
5467 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5468 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5470 Value *Op0, *Op1, *Op2;
5471 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5472 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5473 ParseTypeAndValue(Op1, PFS) ||
5474 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5475 ParseTypeAndValue(Op2, PFS))
5478 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5479 return Error(Loc, "invalid shufflevector operands");
5481 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5486 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5487 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5488 Type *Ty = nullptr; LocTy TypeLoc;
5491 if (ParseType(Ty, TypeLoc) ||
5492 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5493 ParseValue(Ty, Op0, PFS) ||
5494 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5495 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5496 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5499 bool AteExtraComma = false;
5500 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5502 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5504 if (!EatIfPresent(lltok::comma))
5507 if (Lex.getKind() == lltok::MetadataVar) {
5508 AteExtraComma = true;
5512 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5513 ParseValue(Ty, Op0, PFS) ||
5514 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5515 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5516 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5520 if (!Ty->isFirstClassType())
5521 return Error(TypeLoc, "phi node must have first class type");
5523 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5524 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5525 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5527 return AteExtraComma ? InstExtraComma : InstNormal;
5531 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5533 /// ::= 'catch' TypeAndValue
5535 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5536 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5537 Type *Ty = nullptr; LocTy TyLoc;
5539 if (ParseType(Ty, TyLoc))
5542 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5543 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5545 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5546 LandingPadInst::ClauseType CT;
5547 if (EatIfPresent(lltok::kw_catch))
5548 CT = LandingPadInst::Catch;
5549 else if (EatIfPresent(lltok::kw_filter))
5550 CT = LandingPadInst::Filter;
5552 return TokError("expected 'catch' or 'filter' clause type");
5556 if (ParseTypeAndValue(V, VLoc, PFS))
5559 // A 'catch' type expects a non-array constant. A filter clause expects an
5561 if (CT == LandingPadInst::Catch) {
5562 if (isa<ArrayType>(V->getType()))
5563 Error(VLoc, "'catch' clause has an invalid type");
5565 if (!isa<ArrayType>(V->getType()))
5566 Error(VLoc, "'filter' clause has an invalid type");
5569 Constant *CV = dyn_cast<Constant>(V);
5571 return Error(VLoc, "clause argument must be a constant");
5575 Inst = LP.release();
5580 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5581 /// ParameterList OptionalAttrs
5582 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5583 /// ParameterList OptionalAttrs
5584 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5585 /// ParameterList OptionalAttrs
5586 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5587 CallInst::TailCallKind TCK) {
5588 AttrBuilder RetAttrs, FnAttrs;
5589 std::vector<unsigned> FwdRefAttrGrps;
5592 Type *RetType = nullptr;
5595 SmallVector<ParamInfo, 16> ArgList;
5596 LocTy CallLoc = Lex.getLoc();
5598 if ((TCK != CallInst::TCK_None &&
5599 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5600 ParseOptionalCallingConv(CC) ||
5601 ParseOptionalReturnAttrs(RetAttrs) ||
5602 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5603 ParseValID(CalleeID) ||
5604 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5605 PFS.getFunction().isVarArg()) ||
5606 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5610 // If RetType is a non-function pointer type, then this is the short syntax
5611 // for the call, which means that RetType is just the return type. Infer the
5612 // rest of the function argument types from the arguments that are present.
5613 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5615 // Pull out the types of all of the arguments...
5616 std::vector<Type*> ParamTypes;
5617 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5618 ParamTypes.push_back(ArgList[i].V->getType());
5620 if (!FunctionType::isValidReturnType(RetType))
5621 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5623 Ty = FunctionType::get(RetType, ParamTypes, false);
5628 // Look up the callee.
5630 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5633 // Set up the Attribute for the function.
5634 SmallVector<AttributeSet, 8> Attrs;
5635 if (RetAttrs.hasAttributes())
5636 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5637 AttributeSet::ReturnIndex,
5640 SmallVector<Value*, 8> Args;
5642 // Loop through FunctionType's arguments and ensure they are specified
5643 // correctly. Also, gather any parameter attributes.
5644 FunctionType::param_iterator I = Ty->param_begin();
5645 FunctionType::param_iterator E = Ty->param_end();
5646 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5647 Type *ExpectedTy = nullptr;
5650 } else if (!Ty->isVarArg()) {
5651 return Error(ArgList[i].Loc, "too many arguments specified");
5654 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5655 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5656 getTypeString(ExpectedTy) + "'");
5657 Args.push_back(ArgList[i].V);
5658 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5659 AttrBuilder B(ArgList[i].Attrs, i + 1);
5660 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5665 return Error(CallLoc, "not enough parameters specified for call");
5667 if (FnAttrs.hasAttributes()) {
5668 if (FnAttrs.hasAlignmentAttr())
5669 return Error(CallLoc, "call instructions may not have an alignment");
5671 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5672 AttributeSet::FunctionIndex,
5676 // Finish off the Attribute and check them
5677 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5679 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5680 CI->setTailCallKind(TCK);
5681 CI->setCallingConv(CC);
5682 CI->setAttributes(PAL);
5683 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5688 //===----------------------------------------------------------------------===//
5689 // Memory Instructions.
5690 //===----------------------------------------------------------------------===//
5693 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5694 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5695 Value *Size = nullptr;
5696 LocTy SizeLoc, TyLoc;
5697 unsigned Alignment = 0;
5700 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5702 if (ParseType(Ty, TyLoc)) return true;
5704 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5705 return Error(TyLoc, "invalid type for alloca");
5707 bool AteExtraComma = false;
5708 if (EatIfPresent(lltok::comma)) {
5709 if (Lex.getKind() == lltok::kw_align) {
5710 if (ParseOptionalAlignment(Alignment)) return true;
5711 } else if (Lex.getKind() == lltok::MetadataVar) {
5712 AteExtraComma = true;
5714 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5715 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5720 if (Size && !Size->getType()->isIntegerTy())
5721 return Error(SizeLoc, "element count must have integer type");
5723 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5724 AI->setUsedWithInAlloca(IsInAlloca);
5726 return AteExtraComma ? InstExtraComma : InstNormal;
5730 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5731 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5732 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5733 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5734 Value *Val; LocTy Loc;
5735 unsigned Alignment = 0;
5736 bool AteExtraComma = false;
5737 bool isAtomic = false;
5738 AtomicOrdering Ordering = NotAtomic;
5739 SynchronizationScope Scope = CrossThread;
5741 if (Lex.getKind() == lltok::kw_atomic) {
5746 bool isVolatile = false;
5747 if (Lex.getKind() == lltok::kw_volatile) {
5753 LocTy ExplicitTypeLoc = Lex.getLoc();
5754 if (ParseType(Ty) ||
5755 ParseToken(lltok::comma, "expected comma after load's type") ||
5756 ParseTypeAndValue(Val, Loc, PFS) ||
5757 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5758 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5761 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5762 return Error(Loc, "load operand must be a pointer to a first class type");
5763 if (isAtomic && !Alignment)
5764 return Error(Loc, "atomic load must have explicit non-zero alignment");
5765 if (Ordering == Release || Ordering == AcquireRelease)
5766 return Error(Loc, "atomic load cannot use Release ordering");
5768 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5769 return Error(ExplicitTypeLoc,
5770 "explicit pointee type doesn't match operand's pointee type");
5772 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5773 return AteExtraComma ? InstExtraComma : InstNormal;
5778 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5779 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5780 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5781 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5782 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5783 unsigned Alignment = 0;
5784 bool AteExtraComma = false;
5785 bool isAtomic = false;
5786 AtomicOrdering Ordering = NotAtomic;
5787 SynchronizationScope Scope = CrossThread;
5789 if (Lex.getKind() == lltok::kw_atomic) {
5794 bool isVolatile = false;
5795 if (Lex.getKind() == lltok::kw_volatile) {
5800 if (ParseTypeAndValue(Val, Loc, PFS) ||
5801 ParseToken(lltok::comma, "expected ',' after store operand") ||
5802 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5803 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5804 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5807 if (!Ptr->getType()->isPointerTy())
5808 return Error(PtrLoc, "store operand must be a pointer");
5809 if (!Val->getType()->isFirstClassType())
5810 return Error(Loc, "store operand must be a first class value");
5811 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5812 return Error(Loc, "stored value and pointer type do not match");
5813 if (isAtomic && !Alignment)
5814 return Error(Loc, "atomic store must have explicit non-zero alignment");
5815 if (Ordering == Acquire || Ordering == AcquireRelease)
5816 return Error(Loc, "atomic store cannot use Acquire ordering");
5818 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5819 return AteExtraComma ? InstExtraComma : InstNormal;
5823 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5824 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5825 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5826 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5827 bool AteExtraComma = false;
5828 AtomicOrdering SuccessOrdering = NotAtomic;
5829 AtomicOrdering FailureOrdering = NotAtomic;
5830 SynchronizationScope Scope = CrossThread;
5831 bool isVolatile = false;
5832 bool isWeak = false;
5834 if (EatIfPresent(lltok::kw_weak))
5837 if (EatIfPresent(lltok::kw_volatile))
5840 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5841 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5842 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5843 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5844 ParseTypeAndValue(New, NewLoc, PFS) ||
5845 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5846 ParseOrdering(FailureOrdering))
5849 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5850 return TokError("cmpxchg cannot be unordered");
5851 if (SuccessOrdering < FailureOrdering)
5852 return TokError("cmpxchg must be at least as ordered on success as failure");
5853 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5854 return TokError("cmpxchg failure ordering cannot include release semantics");
5855 if (!Ptr->getType()->isPointerTy())
5856 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5857 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5858 return Error(CmpLoc, "compare value and pointer type do not match");
5859 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5860 return Error(NewLoc, "new value and pointer type do not match");
5861 if (!New->getType()->isIntegerTy())
5862 return Error(NewLoc, "cmpxchg operand must be an integer");
5863 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5864 if (Size < 8 || (Size & (Size - 1)))
5865 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5868 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5869 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5870 CXI->setVolatile(isVolatile);
5871 CXI->setWeak(isWeak);
5873 return AteExtraComma ? InstExtraComma : InstNormal;
5877 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5878 /// 'singlethread'? AtomicOrdering
5879 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5880 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5881 bool AteExtraComma = false;
5882 AtomicOrdering Ordering = NotAtomic;
5883 SynchronizationScope Scope = CrossThread;
5884 bool isVolatile = false;
5885 AtomicRMWInst::BinOp Operation;
5887 if (EatIfPresent(lltok::kw_volatile))
5890 switch (Lex.getKind()) {
5891 default: return TokError("expected binary operation in atomicrmw");
5892 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5893 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5894 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5895 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5896 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5897 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5898 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5899 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5900 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5901 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5902 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5904 Lex.Lex(); // Eat the operation.
5906 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5907 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5908 ParseTypeAndValue(Val, ValLoc, PFS) ||
5909 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5912 if (Ordering == Unordered)
5913 return TokError("atomicrmw cannot be unordered");
5914 if (!Ptr->getType()->isPointerTy())
5915 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5916 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5917 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5918 if (!Val->getType()->isIntegerTy())
5919 return Error(ValLoc, "atomicrmw operand must be an integer");
5920 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5921 if (Size < 8 || (Size & (Size - 1)))
5922 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5925 AtomicRMWInst *RMWI =
5926 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5927 RMWI->setVolatile(isVolatile);
5929 return AteExtraComma ? InstExtraComma : InstNormal;
5933 /// ::= 'fence' 'singlethread'? AtomicOrdering
5934 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5935 AtomicOrdering Ordering = NotAtomic;
5936 SynchronizationScope Scope = CrossThread;
5937 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5940 if (Ordering == Unordered)
5941 return TokError("fence cannot be unordered");
5942 if (Ordering == Monotonic)
5943 return TokError("fence cannot be monotonic");
5945 Inst = new FenceInst(Context, Ordering, Scope);
5949 /// ParseGetElementPtr
5950 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5951 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5952 Value *Ptr = nullptr;
5953 Value *Val = nullptr;
5956 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5959 LocTy ExplicitTypeLoc = Lex.getLoc();
5960 if (ParseType(Ty) ||
5961 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5962 ParseTypeAndValue(Ptr, Loc, PFS))
5965 Type *BaseType = Ptr->getType();
5966 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5967 if (!BasePointerType)
5968 return Error(Loc, "base of getelementptr must be a pointer");
5970 if (Ty != BasePointerType->getElementType())
5971 return Error(ExplicitTypeLoc,
5972 "explicit pointee type doesn't match operand's pointee type");
5974 SmallVector<Value*, 16> Indices;
5975 bool AteExtraComma = false;
5976 // GEP returns a vector of pointers if at least one of parameters is a vector.
5977 // All vector parameters should have the same vector width.
5978 unsigned GEPWidth = BaseType->isVectorTy() ?
5979 BaseType->getVectorNumElements() : 0;
5981 while (EatIfPresent(lltok::comma)) {
5982 if (Lex.getKind() == lltok::MetadataVar) {
5983 AteExtraComma = true;
5986 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5987 if (!Val->getType()->getScalarType()->isIntegerTy())
5988 return Error(EltLoc, "getelementptr index must be an integer");
5990 if (Val->getType()->isVectorTy()) {
5991 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5992 if (GEPWidth && GEPWidth != ValNumEl)
5993 return Error(EltLoc,
5994 "getelementptr vector index has a wrong number of elements");
5995 GEPWidth = ValNumEl;
5997 Indices.push_back(Val);
6000 SmallPtrSet<Type*, 4> Visited;
6001 if (!Indices.empty() && !Ty->isSized(&Visited))
6002 return Error(Loc, "base element of getelementptr must be sized");
6004 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6005 return Error(Loc, "invalid getelementptr indices");
6006 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6008 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6009 return AteExtraComma ? InstExtraComma : InstNormal;
6012 /// ParseExtractValue
6013 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6014 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6015 Value *Val; LocTy Loc;
6016 SmallVector<unsigned, 4> Indices;
6018 if (ParseTypeAndValue(Val, Loc, PFS) ||
6019 ParseIndexList(Indices, AteExtraComma))
6022 if (!Val->getType()->isAggregateType())
6023 return Error(Loc, "extractvalue operand must be aggregate type");
6025 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6026 return Error(Loc, "invalid indices for extractvalue");
6027 Inst = ExtractValueInst::Create(Val, Indices);
6028 return AteExtraComma ? InstExtraComma : InstNormal;
6031 /// ParseInsertValue
6032 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6033 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6034 Value *Val0, *Val1; LocTy Loc0, Loc1;
6035 SmallVector<unsigned, 4> Indices;
6037 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6038 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6039 ParseTypeAndValue(Val1, Loc1, PFS) ||
6040 ParseIndexList(Indices, AteExtraComma))
6043 if (!Val0->getType()->isAggregateType())
6044 return Error(Loc0, "insertvalue operand must be aggregate type");
6046 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6048 return Error(Loc0, "invalid indices for insertvalue");
6049 if (IndexedType != Val1->getType())
6050 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6051 getTypeString(Val1->getType()) + "' instead of '" +
6052 getTypeString(IndexedType) + "'");
6053 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6054 return AteExtraComma ? InstExtraComma : InstNormal;
6057 //===----------------------------------------------------------------------===//
6058 // Embedded metadata.
6059 //===----------------------------------------------------------------------===//
6061 /// ParseMDNodeVector
6062 /// ::= { Element (',' Element)* }
6064 /// ::= 'null' | TypeAndValue
6065 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6066 if (ParseToken(lltok::lbrace, "expected '{' here"))
6069 // Check for an empty list.
6070 if (EatIfPresent(lltok::rbrace))
6074 // Null is a special case since it is typeless.
6075 if (EatIfPresent(lltok::kw_null)) {
6076 Elts.push_back(nullptr);
6081 if (ParseMetadata(MD, nullptr))
6084 } while (EatIfPresent(lltok::comma));
6086 return ParseToken(lltok::rbrace, "expected end of metadata node");
6089 //===----------------------------------------------------------------------===//
6090 // Use-list order directives.
6091 //===----------------------------------------------------------------------===//
6092 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6095 return Error(Loc, "value has no uses");
6097 unsigned NumUses = 0;
6098 SmallDenseMap<const Use *, unsigned, 16> Order;
6099 for (const Use &U : V->uses()) {
6100 if (++NumUses > Indexes.size())
6102 Order[&U] = Indexes[NumUses - 1];
6105 return Error(Loc, "value only has one use");
6106 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6107 return Error(Loc, "wrong number of indexes, expected " +
6108 Twine(std::distance(V->use_begin(), V->use_end())));
6110 V->sortUseList([&](const Use &L, const Use &R) {
6111 return Order.lookup(&L) < Order.lookup(&R);
6116 /// ParseUseListOrderIndexes
6117 /// ::= '{' uint32 (',' uint32)+ '}'
6118 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6119 SMLoc Loc = Lex.getLoc();
6120 if (ParseToken(lltok::lbrace, "expected '{' here"))
6122 if (Lex.getKind() == lltok::rbrace)
6123 return Lex.Error("expected non-empty list of uselistorder indexes");
6125 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6126 // indexes should be distinct numbers in the range [0, size-1], and should
6128 unsigned Offset = 0;
6130 bool IsOrdered = true;
6131 assert(Indexes.empty() && "Expected empty order vector");
6134 if (ParseUInt32(Index))
6137 // Update consistency checks.
6138 Offset += Index - Indexes.size();
6139 Max = std::max(Max, Index);
6140 IsOrdered &= Index == Indexes.size();
6142 Indexes.push_back(Index);
6143 } while (EatIfPresent(lltok::comma));
6145 if (ParseToken(lltok::rbrace, "expected '}' here"))
6148 if (Indexes.size() < 2)
6149 return Error(Loc, "expected >= 2 uselistorder indexes");
6150 if (Offset != 0 || Max >= Indexes.size())
6151 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6153 return Error(Loc, "expected uselistorder indexes to change the order");
6158 /// ParseUseListOrder
6159 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6160 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6161 SMLoc Loc = Lex.getLoc();
6162 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6166 SmallVector<unsigned, 16> Indexes;
6167 if (ParseTypeAndValue(V, PFS) ||
6168 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6169 ParseUseListOrderIndexes(Indexes))
6172 return sortUseListOrder(V, Indexes, Loc);
6175 /// ParseUseListOrderBB
6176 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6177 bool LLParser::ParseUseListOrderBB() {
6178 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6179 SMLoc Loc = Lex.getLoc();
6183 SmallVector<unsigned, 16> Indexes;
6184 if (ParseValID(Fn) ||
6185 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6186 ParseValID(Label) ||
6187 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6188 ParseUseListOrderIndexes(Indexes))
6191 // Check the function.
6193 if (Fn.Kind == ValID::t_GlobalName)
6194 GV = M->getNamedValue(Fn.StrVal);
6195 else if (Fn.Kind == ValID::t_GlobalID)
6196 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6198 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6200 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6201 auto *F = dyn_cast<Function>(GV);
6203 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6204 if (F->isDeclaration())
6205 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6207 // Check the basic block.
6208 if (Label.Kind == ValID::t_LocalID)
6209 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6210 if (Label.Kind != ValID::t_LocalName)
6211 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6212 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6214 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6215 if (!isa<BasicBlock>(V))
6216 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6218 return sortUseListOrder(V, Indexes, Loc);