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/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
67 ForwardRefInstMetadata.clear();
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
78 std::vector<unsigned> &Vec = I->second;
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 B.merge(NumberedAttrBuilders[*VI]);
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
93 // If the alignment was parsed as an attribute, move to the alignment
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->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 II->setAttributes(AS);
128 llvm_unreachable("invalid object with forward attribute group reference");
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
166 if (!ForwardRefComdats.empty())
167 return Error(ForwardRefComdats.begin()->second,
168 "use of undefined comdat '$" +
169 ForwardRefComdats.begin()->first + "'");
171 if (!ForwardRefVals.empty())
172 return Error(ForwardRefVals.begin()->second.second,
173 "use of undefined value '@" + ForwardRefVals.begin()->first +
176 if (!ForwardRefValIDs.empty())
177 return Error(ForwardRefValIDs.begin()->second.second,
178 "use of undefined value '@" +
179 Twine(ForwardRefValIDs.begin()->first) + "'");
181 if (!ForwardRefMDNodes.empty())
182 return Error(ForwardRefMDNodes.begin()->second.second,
183 "use of undefined metadata '!" +
184 Twine(ForwardRefMDNodes.begin()->first) + "'");
187 // Look for intrinsic functions and CallInst that need to be upgraded
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
189 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
191 UpgradeDebugInfo(*M);
196 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
197 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
198 PerFunctionState *PFS) {
199 // Loop over all the references, resolving them.
200 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
203 if (Refs[i].first.Kind == ValID::t_LocalName)
204 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
206 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
207 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
208 return Error(Refs[i].first.Loc,
209 "cannot take address of numeric label after the function is defined");
211 Res = dyn_cast_or_null<BasicBlock>(
212 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
216 return Error(Refs[i].first.Loc,
217 "referenced value is not a basic block");
219 // Get the BlockAddress for this and update references to use it.
220 BlockAddress *BA = BlockAddress::get(TheFn, Res);
221 Refs[i].second->replaceAllUsesWith(BA);
222 Refs[i].second->eraseFromParent();
228 //===----------------------------------------------------------------------===//
229 // Top-Level Entities
230 //===----------------------------------------------------------------------===//
232 bool LLParser::ParseTopLevelEntities() {
234 switch (Lex.getKind()) {
235 default: return TokError("expected top-level entity");
236 case lltok::Eof: return false;
237 case lltok::kw_declare: if (ParseDeclare()) return true; break;
238 case lltok::kw_define: if (ParseDefine()) return true; break;
239 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
240 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
241 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
242 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
243 case lltok::LocalVar: if (ParseNamedType()) return true; break;
244 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
245 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
246 case lltok::ComdatVar: if (parseComdat()) return true; break;
247 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
248 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
250 // The Global variable production with no name can have many different
251 // optional leading prefixes, the production is:
252 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
253 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
254 // ('constant'|'global') ...
255 case lltok::kw_private: // OptionalLinkage
256 case lltok::kw_internal: // OptionalLinkage
257 case lltok::kw_weak: // OptionalLinkage
258 case lltok::kw_weak_odr: // OptionalLinkage
259 case lltok::kw_linkonce: // OptionalLinkage
260 case lltok::kw_linkonce_odr: // OptionalLinkage
261 case lltok::kw_appending: // OptionalLinkage
262 case lltok::kw_common: // OptionalLinkage
263 case lltok::kw_extern_weak: // OptionalLinkage
264 case lltok::kw_external: // OptionalLinkage
265 case lltok::kw_default: // OptionalVisibility
266 case lltok::kw_hidden: // OptionalVisibility
267 case lltok::kw_protected: // OptionalVisibility
268 case lltok::kw_dllimport: // OptionalDLLStorageClass
269 case lltok::kw_dllexport: // OptionalDLLStorageClass
270 case lltok::kw_thread_local: // OptionalThreadLocal
271 case lltok::kw_addrspace: // OptionalAddrSpace
272 case lltok::kw_constant: // GlobalType
273 case lltok::kw_global: { // GlobalType
274 unsigned Linkage, Visibility, DLLStorageClass;
276 GlobalVariable::ThreadLocalMode TLM;
278 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
279 ParseOptionalVisibility(Visibility) ||
280 ParseOptionalDLLStorageClass(DLLStorageClass) ||
281 ParseOptionalThreadLocal(TLM) ||
282 parseOptionalUnnamedAddr(UnnamedAddr) ||
283 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
284 DLLStorageClass, TLM, UnnamedAddr))
289 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
296 /// ::= 'module' 'asm' STRINGCONSTANT
297 bool LLParser::ParseModuleAsm() {
298 assert(Lex.getKind() == lltok::kw_module);
302 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
303 ParseStringConstant(AsmStr)) return true;
305 M->appendModuleInlineAsm(AsmStr);
310 /// ::= 'target' 'triple' '=' STRINGCONSTANT
311 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
312 bool LLParser::ParseTargetDefinition() {
313 assert(Lex.getKind() == lltok::kw_target);
316 default: return TokError("unknown target property");
317 case lltok::kw_triple:
319 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
320 ParseStringConstant(Str))
322 M->setTargetTriple(Str);
324 case lltok::kw_datalayout:
326 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
327 ParseStringConstant(Str))
329 M->setDataLayout(Str);
335 /// ::= 'deplibs' '=' '[' ']'
336 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
337 /// FIXME: Remove in 4.0. Currently parse, but ignore.
338 bool LLParser::ParseDepLibs() {
339 assert(Lex.getKind() == lltok::kw_deplibs);
341 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
342 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
345 if (EatIfPresent(lltok::rsquare))
350 if (ParseStringConstant(Str)) return true;
351 } while (EatIfPresent(lltok::comma));
353 return ParseToken(lltok::rsquare, "expected ']' at end of list");
356 /// ParseUnnamedType:
357 /// ::= LocalVarID '=' 'type' type
358 bool LLParser::ParseUnnamedType() {
359 LocTy TypeLoc = Lex.getLoc();
360 unsigned TypeID = Lex.getUIntVal();
361 Lex.Lex(); // eat LocalVarID;
363 if (ParseToken(lltok::equal, "expected '=' after name") ||
364 ParseToken(lltok::kw_type, "expected 'type' after '='"))
367 if (TypeID >= NumberedTypes.size())
368 NumberedTypes.resize(TypeID+1);
370 Type *Result = nullptr;
371 if (ParseStructDefinition(TypeLoc, "",
372 NumberedTypes[TypeID], Result)) return true;
374 if (!isa<StructType>(Result)) {
375 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
377 return Error(TypeLoc, "non-struct types may not be recursive");
378 Entry.first = Result;
379 Entry.second = SMLoc();
387 /// ::= LocalVar '=' 'type' type
388 bool LLParser::ParseNamedType() {
389 std::string Name = Lex.getStrVal();
390 LocTy NameLoc = Lex.getLoc();
391 Lex.Lex(); // eat LocalVar.
393 if (ParseToken(lltok::equal, "expected '=' after name") ||
394 ParseToken(lltok::kw_type, "expected 'type' after name"))
397 Type *Result = nullptr;
398 if (ParseStructDefinition(NameLoc, Name,
399 NamedTypes[Name], Result)) return true;
401 if (!isa<StructType>(Result)) {
402 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
404 return Error(NameLoc, "non-struct types may not be recursive");
405 Entry.first = Result;
406 Entry.second = SMLoc();
414 /// ::= 'declare' FunctionHeader
415 bool LLParser::ParseDeclare() {
416 assert(Lex.getKind() == lltok::kw_declare);
420 return ParseFunctionHeader(F, false);
424 /// ::= 'define' FunctionHeader '{' ...
425 bool LLParser::ParseDefine() {
426 assert(Lex.getKind() == lltok::kw_define);
430 return ParseFunctionHeader(F, true) ||
431 ParseFunctionBody(*F);
437 bool LLParser::ParseGlobalType(bool &IsConstant) {
438 if (Lex.getKind() == lltok::kw_constant)
440 else if (Lex.getKind() == lltok::kw_global)
444 return TokError("expected 'global' or 'constant'");
450 /// ParseUnnamedGlobal:
451 /// OptionalVisibility ALIAS ...
452 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
453 /// ... -> global variable
454 /// GlobalID '=' OptionalVisibility ALIAS ...
455 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
456 /// ... -> global variable
457 bool LLParser::ParseUnnamedGlobal() {
458 unsigned VarID = NumberedVals.size();
460 LocTy NameLoc = Lex.getLoc();
462 // Handle the GlobalID form.
463 if (Lex.getKind() == lltok::GlobalID) {
464 if (Lex.getUIntVal() != VarID)
465 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
467 Lex.Lex(); // eat GlobalID;
469 if (ParseToken(lltok::equal, "expected '=' after name"))
474 unsigned Linkage, Visibility, DLLStorageClass;
475 GlobalVariable::ThreadLocalMode TLM;
477 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
478 ParseOptionalVisibility(Visibility) ||
479 ParseOptionalDLLStorageClass(DLLStorageClass) ||
480 ParseOptionalThreadLocal(TLM) ||
481 parseOptionalUnnamedAddr(UnnamedAddr))
484 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
485 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
486 DLLStorageClass, TLM, UnnamedAddr);
487 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
491 /// ParseNamedGlobal:
492 /// GlobalVar '=' OptionalVisibility ALIAS ...
493 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
494 /// ... -> global variable
495 bool LLParser::ParseNamedGlobal() {
496 assert(Lex.getKind() == lltok::GlobalVar);
497 LocTy NameLoc = Lex.getLoc();
498 std::string Name = Lex.getStrVal();
502 unsigned Linkage, Visibility, DLLStorageClass;
503 GlobalVariable::ThreadLocalMode TLM;
505 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
506 ParseOptionalLinkage(Linkage, HasLinkage) ||
507 ParseOptionalVisibility(Visibility) ||
508 ParseOptionalDLLStorageClass(DLLStorageClass) ||
509 ParseOptionalThreadLocal(TLM) ||
510 parseOptionalUnnamedAddr(UnnamedAddr))
513 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
514 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
515 DLLStorageClass, TLM, UnnamedAddr);
516 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
520 bool LLParser::parseComdat() {
521 assert(Lex.getKind() == lltok::ComdatVar);
522 std::string Name = Lex.getStrVal();
523 LocTy NameLoc = Lex.getLoc();
526 if (ParseToken(lltok::equal, "expected '=' here"))
529 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
530 return TokError("expected comdat type");
532 Comdat::SelectionKind SK;
533 switch (Lex.getKind()) {
535 return TokError("unknown selection kind");
539 case lltok::kw_exactmatch:
540 SK = Comdat::ExactMatch;
542 case lltok::kw_largest:
543 SK = Comdat::Largest;
545 case lltok::kw_noduplicates:
546 SK = Comdat::NoDuplicates;
548 case lltok::kw_samesize:
549 SK = Comdat::SameSize;
554 // See if the comdat was forward referenced, if so, use the comdat.
555 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
556 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
557 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
558 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
561 if (I != ComdatSymTab.end())
564 C = M->getOrInsertComdat(Name);
565 C->setSelectionKind(SK);
571 // ::= '!' STRINGCONSTANT
572 bool LLParser::ParseMDString(MDString *&Result) {
574 if (ParseStringConstant(Str)) return true;
575 llvm::UpgradeMDStringConstant(Str);
576 Result = MDString::get(Context, Str);
581 // ::= '!' MDNodeNumber
583 /// This version of ParseMDNodeID returns the slot number and null in the case
584 /// of a forward reference.
585 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
586 // !{ ..., !42, ... }
587 if (ParseUInt32(SlotNo)) return true;
589 // Check existing MDNode.
590 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
591 Result = NumberedMetadata[SlotNo];
597 bool LLParser::ParseMDNodeID(MDNode *&Result) {
598 // !{ ..., !42, ... }
600 if (ParseMDNodeID(Result, MID)) return true;
602 // If not a forward reference, just return it now.
603 if (Result) return false;
605 // Otherwise, create MDNode forward reference.
606 MDNode *FwdNode = MDNode::getTemporary(Context, None);
607 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
609 if (NumberedMetadata.size() <= MID)
610 NumberedMetadata.resize(MID+1);
611 NumberedMetadata[MID] = FwdNode;
616 /// ParseNamedMetadata:
617 /// !foo = !{ !1, !2 }
618 bool LLParser::ParseNamedMetadata() {
619 assert(Lex.getKind() == lltok::MetadataVar);
620 std::string Name = Lex.getStrVal();
623 if (ParseToken(lltok::equal, "expected '=' here") ||
624 ParseToken(lltok::exclaim, "Expected '!' here") ||
625 ParseToken(lltok::lbrace, "Expected '{' here"))
628 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
629 if (Lex.getKind() != lltok::rbrace)
631 if (ParseToken(lltok::exclaim, "Expected '!' here"))
635 if (ParseMDNodeID(N)) return true;
637 } while (EatIfPresent(lltok::comma));
639 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
645 /// ParseStandaloneMetadata:
647 bool LLParser::ParseStandaloneMetadata() {
648 assert(Lex.getKind() == lltok::exclaim);
650 unsigned MetadataID = 0;
654 SmallVector<Value *, 16> Elts;
655 if (ParseUInt32(MetadataID) ||
656 ParseToken(lltok::equal, "expected '=' here") ||
657 ParseType(Ty, TyLoc) ||
658 ParseToken(lltok::exclaim, "Expected '!' here") ||
659 ParseToken(lltok::lbrace, "Expected '{' here") ||
660 ParseMDNodeVector(Elts, nullptr) ||
661 ParseToken(lltok::rbrace, "expected end of metadata node"))
664 MDNode *Init = MDNode::get(Context, Elts);
666 // See if this was forward referenced, if so, handle it.
667 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
668 FI = ForwardRefMDNodes.find(MetadataID);
669 if (FI != ForwardRefMDNodes.end()) {
670 MDNode *Temp = FI->second.first;
671 Temp->replaceAllUsesWith(Init);
672 MDNode::deleteTemporary(Temp);
673 ForwardRefMDNodes.erase(FI);
675 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
677 if (MetadataID >= NumberedMetadata.size())
678 NumberedMetadata.resize(MetadataID+1);
680 if (NumberedMetadata[MetadataID] != nullptr)
681 return TokError("Metadata id is already used");
682 NumberedMetadata[MetadataID] = Init;
688 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
689 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
690 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
694 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass
695 /// OptionalThreadLocal OptionalUnNammedAddr 'alias'
696 /// OptionalLinkage Aliasee
701 /// Everything through OptionalUnNammedAddr has already been parsed.
703 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
704 unsigned Visibility, unsigned DLLStorageClass,
705 GlobalVariable::ThreadLocalMode TLM,
707 assert(Lex.getKind() == lltok::kw_alias);
709 LocTy LinkageLoc = Lex.getLoc();
711 if (ParseOptionalLinkage(L))
714 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
716 if(!GlobalAlias::isValidLinkage(Linkage))
717 return Error(LinkageLoc, "invalid linkage type for alias");
719 if (!isValidVisibilityForLinkage(Visibility, L))
720 return Error(LinkageLoc,
721 "symbol with local linkage must have default visibility");
724 LocTy AliaseeLoc = Lex.getLoc();
725 if (Lex.getKind() != lltok::kw_bitcast &&
726 Lex.getKind() != lltok::kw_getelementptr &&
727 Lex.getKind() != lltok::kw_addrspacecast &&
728 Lex.getKind() != lltok::kw_inttoptr) {
729 if (ParseGlobalTypeAndValue(Aliasee))
732 // The bitcast dest type is not present, it is implied by the dest type.
736 if (ID.Kind != ValID::t_Constant)
737 return Error(AliaseeLoc, "invalid aliasee");
738 Aliasee = ID.ConstantVal;
741 Type *AliaseeType = Aliasee->getType();
742 auto *PTy = dyn_cast<PointerType>(AliaseeType);
744 return Error(AliaseeLoc, "An alias must have pointer type");
745 Type *Ty = PTy->getElementType();
746 unsigned AddrSpace = PTy->getAddressSpace();
748 // Okay, create the alias but do not insert it into the module yet.
749 std::unique_ptr<GlobalAlias> GA(
750 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
751 Name, Aliasee, /*Parent*/ nullptr));
752 GA->setThreadLocalMode(TLM);
753 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
754 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
755 GA->setUnnamedAddr(UnnamedAddr);
757 // See if this value already exists in the symbol table. If so, it is either
758 // a redefinition or a definition of a forward reference.
759 if (GlobalValue *Val = M->getNamedValue(Name)) {
760 // See if this was a redefinition. If so, there is no entry in
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I == ForwardRefVals.end())
765 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
767 // Otherwise, this was a definition of forward ref. Verify that types
769 if (Val->getType() != GA->getType())
770 return Error(NameLoc,
771 "forward reference and definition of alias have different types");
773 // If they agree, just RAUW the old value with the alias and remove the
775 Val->replaceAllUsesWith(GA.get());
776 Val->eraseFromParent();
777 ForwardRefVals.erase(I);
780 // Insert into the module, we know its name won't collide now.
781 M->getAliasList().push_back(GA.get());
782 assert(GA->getName() == Name && "Should not be a name conflict!");
784 // The module owns this now
791 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
792 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
793 /// OptionalExternallyInitialized GlobalType Type Const
794 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
795 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
796 /// OptionalExternallyInitialized GlobalType Type Const
798 /// Everything up to and including OptionalUnNammedAddr has been parsed
801 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
802 unsigned Linkage, bool HasLinkage,
803 unsigned Visibility, unsigned DLLStorageClass,
804 GlobalVariable::ThreadLocalMode TLM,
806 if (!isValidVisibilityForLinkage(Visibility, Linkage))
807 return Error(NameLoc,
808 "symbol with local linkage must have default visibility");
811 bool IsConstant, IsExternallyInitialized;
812 LocTy IsExternallyInitializedLoc;
816 if (ParseOptionalAddrSpace(AddrSpace) ||
817 ParseOptionalToken(lltok::kw_externally_initialized,
818 IsExternallyInitialized,
819 &IsExternallyInitializedLoc) ||
820 ParseGlobalType(IsConstant) ||
821 ParseType(Ty, TyLoc))
824 // If the linkage is specified and is external, then no initializer is
826 Constant *Init = nullptr;
827 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
828 Linkage != GlobalValue::ExternalLinkage)) {
829 if (ParseGlobalValue(Ty, Init))
833 if (Ty->isFunctionTy() || Ty->isLabelTy())
834 return Error(TyLoc, "invalid type for global variable");
836 GlobalVariable *GV = nullptr;
838 // See if the global was forward referenced, if so, use the global.
840 if (GlobalValue *GVal = M->getNamedValue(Name)) {
841 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
842 return Error(NameLoc, "redefinition of global '@" + Name + "'");
843 GV = cast<GlobalVariable>(GVal);
846 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
847 I = ForwardRefValIDs.find(NumberedVals.size());
848 if (I != ForwardRefValIDs.end()) {
849 GV = cast<GlobalVariable>(I->second.first);
850 ForwardRefValIDs.erase(I);
855 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
856 Name, nullptr, GlobalVariable::NotThreadLocal,
859 if (GV->getType()->getElementType() != Ty)
861 "forward reference and definition of global have different types");
863 // Move the forward-reference to the correct spot in the module.
864 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
868 NumberedVals.push_back(GV);
870 // Set the parsed properties on the global.
872 GV->setInitializer(Init);
873 GV->setConstant(IsConstant);
874 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
875 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
876 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
877 GV->setExternallyInitialized(IsExternallyInitialized);
878 GV->setThreadLocalMode(TLM);
879 GV->setUnnamedAddr(UnnamedAddr);
881 // Parse attributes on the global.
882 while (Lex.getKind() == lltok::comma) {
885 if (Lex.getKind() == lltok::kw_section) {
887 GV->setSection(Lex.getStrVal());
888 if (ParseToken(lltok::StringConstant, "expected global section string"))
890 } else if (Lex.getKind() == lltok::kw_align) {
892 if (ParseOptionalAlignment(Alignment)) return true;
893 GV->setAlignment(Alignment);
896 if (parseOptionalComdat(C))
901 return TokError("unknown global variable property!");
908 /// ParseUnnamedAttrGrp
909 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
910 bool LLParser::ParseUnnamedAttrGrp() {
911 assert(Lex.getKind() == lltok::kw_attributes);
912 LocTy AttrGrpLoc = Lex.getLoc();
915 assert(Lex.getKind() == lltok::AttrGrpID);
916 unsigned VarID = Lex.getUIntVal();
917 std::vector<unsigned> unused;
921 if (ParseToken(lltok::equal, "expected '=' here") ||
922 ParseToken(lltok::lbrace, "expected '{' here") ||
923 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
925 ParseToken(lltok::rbrace, "expected end of attribute group"))
928 if (!NumberedAttrBuilders[VarID].hasAttributes())
929 return Error(AttrGrpLoc, "attribute group has no attributes");
934 /// ParseFnAttributeValuePairs
935 /// ::= <attr> | <attr> '=' <value>
936 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
937 std::vector<unsigned> &FwdRefAttrGrps,
938 bool inAttrGrp, LocTy &BuiltinLoc) {
939 bool HaveError = false;
944 lltok::Kind Token = Lex.getKind();
945 if (Token == lltok::kw_builtin)
946 BuiltinLoc = Lex.getLoc();
949 if (!inAttrGrp) return HaveError;
950 return Error(Lex.getLoc(), "unterminated attribute group");
955 case lltok::AttrGrpID: {
956 // Allow a function to reference an attribute group:
958 // define void @foo() #1 { ... }
962 "cannot have an attribute group reference in an attribute group");
964 unsigned AttrGrpNum = Lex.getUIntVal();
965 if (inAttrGrp) break;
967 // Save the reference to the attribute group. We'll fill it in later.
968 FwdRefAttrGrps.push_back(AttrGrpNum);
971 // Target-dependent attributes:
972 case lltok::StringConstant: {
973 std::string Attr = Lex.getStrVal();
976 if (EatIfPresent(lltok::equal) &&
977 ParseStringConstant(Val))
980 B.addAttribute(Attr, Val);
984 // Target-independent attributes:
985 case lltok::kw_align: {
986 // As a hack, we allow function alignment to be initially parsed as an
987 // attribute on a function declaration/definition or added to an attribute
988 // group and later moved to the alignment field.
992 if (ParseToken(lltok::equal, "expected '=' here") ||
993 ParseUInt32(Alignment))
996 if (ParseOptionalAlignment(Alignment))
999 B.addAlignmentAttr(Alignment);
1002 case lltok::kw_alignstack: {
1006 if (ParseToken(lltok::equal, "expected '=' here") ||
1007 ParseUInt32(Alignment))
1010 if (ParseOptionalStackAlignment(Alignment))
1013 B.addStackAlignmentAttr(Alignment);
1016 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1017 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1018 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1019 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1020 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1021 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1022 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1023 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1024 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1025 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
1026 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1027 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1028 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1029 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1030 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1031 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1032 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1033 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1034 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1035 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
1036 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1037 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1038 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
1039 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
1040 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
1041 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
1042 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1045 case lltok::kw_inreg:
1046 case lltok::kw_signext:
1047 case lltok::kw_zeroext:
1050 "invalid use of attribute on a function");
1052 case lltok::kw_byval:
1053 case lltok::kw_dereferenceable:
1054 case lltok::kw_inalloca:
1055 case lltok::kw_nest:
1056 case lltok::kw_noalias:
1057 case lltok::kw_nocapture:
1058 case lltok::kw_nonnull:
1059 case lltok::kw_returned:
1060 case lltok::kw_sret:
1063 "invalid use of parameter-only attribute on a function");
1071 //===----------------------------------------------------------------------===//
1072 // GlobalValue Reference/Resolution Routines.
1073 //===----------------------------------------------------------------------===//
1075 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1076 /// forward reference record if needed. This can return null if the value
1077 /// exists but does not have the right type.
1078 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1080 PointerType *PTy = dyn_cast<PointerType>(Ty);
1082 Error(Loc, "global variable reference must have pointer type");
1086 // Look this name up in the normal function symbol table.
1088 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1090 // If this is a forward reference for the value, see if we already created a
1091 // forward ref record.
1093 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1094 I = ForwardRefVals.find(Name);
1095 if (I != ForwardRefVals.end())
1096 Val = I->second.first;
1099 // If we have the value in the symbol table or fwd-ref table, return it.
1101 if (Val->getType() == Ty) return Val;
1102 Error(Loc, "'@" + Name + "' defined with type '" +
1103 getTypeString(Val->getType()) + "'");
1107 // Otherwise, create a new forward reference for this value and remember it.
1108 GlobalValue *FwdVal;
1109 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1110 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1112 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1113 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1114 nullptr, GlobalVariable::NotThreadLocal,
1115 PTy->getAddressSpace());
1117 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1121 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1122 PointerType *PTy = dyn_cast<PointerType>(Ty);
1124 Error(Loc, "global variable reference must have pointer type");
1128 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1130 // If this is a forward reference for the value, see if we already created a
1131 // forward ref record.
1133 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1134 I = ForwardRefValIDs.find(ID);
1135 if (I != ForwardRefValIDs.end())
1136 Val = I->second.first;
1139 // If we have the value in the symbol table or fwd-ref table, return it.
1141 if (Val->getType() == Ty) return Val;
1142 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1143 getTypeString(Val->getType()) + "'");
1147 // Otherwise, create a new forward reference for this value and remember it.
1148 GlobalValue *FwdVal;
1149 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1150 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1152 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1153 GlobalValue::ExternalWeakLinkage, nullptr, "");
1155 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1160 //===----------------------------------------------------------------------===//
1161 // Comdat Reference/Resolution Routines.
1162 //===----------------------------------------------------------------------===//
1164 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1165 // Look this name up in the comdat symbol table.
1166 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1167 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1168 if (I != ComdatSymTab.end())
1171 // Otherwise, create a new forward reference for this value and remember it.
1172 Comdat *C = M->getOrInsertComdat(Name);
1173 ForwardRefComdats[Name] = Loc;
1178 //===----------------------------------------------------------------------===//
1180 //===----------------------------------------------------------------------===//
1182 /// ParseToken - If the current token has the specified kind, eat it and return
1183 /// success. Otherwise, emit the specified error and return failure.
1184 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1185 if (Lex.getKind() != T)
1186 return TokError(ErrMsg);
1191 /// ParseStringConstant
1192 /// ::= StringConstant
1193 bool LLParser::ParseStringConstant(std::string &Result) {
1194 if (Lex.getKind() != lltok::StringConstant)
1195 return TokError("expected string constant");
1196 Result = Lex.getStrVal();
1203 bool LLParser::ParseUInt32(unsigned &Val) {
1204 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1205 return TokError("expected integer");
1206 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1207 if (Val64 != unsigned(Val64))
1208 return TokError("expected 32-bit integer (too large)");
1216 bool LLParser::ParseUInt64(uint64_t &Val) {
1217 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1218 return TokError("expected integer");
1219 Val = Lex.getAPSIntVal().getLimitedValue();
1225 /// := 'localdynamic'
1226 /// := 'initialexec'
1228 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1229 switch (Lex.getKind()) {
1231 return TokError("expected localdynamic, initialexec or localexec");
1232 case lltok::kw_localdynamic:
1233 TLM = GlobalVariable::LocalDynamicTLSModel;
1235 case lltok::kw_initialexec:
1236 TLM = GlobalVariable::InitialExecTLSModel;
1238 case lltok::kw_localexec:
1239 TLM = GlobalVariable::LocalExecTLSModel;
1247 /// ParseOptionalThreadLocal
1249 /// := 'thread_local'
1250 /// := 'thread_local' '(' tlsmodel ')'
1251 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1252 TLM = GlobalVariable::NotThreadLocal;
1253 if (!EatIfPresent(lltok::kw_thread_local))
1256 TLM = GlobalVariable::GeneralDynamicTLSModel;
1257 if (Lex.getKind() == lltok::lparen) {
1259 return ParseTLSModel(TLM) ||
1260 ParseToken(lltok::rparen, "expected ')' after thread local model");
1265 /// ParseOptionalAddrSpace
1267 /// := 'addrspace' '(' uint32 ')'
1268 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1270 if (!EatIfPresent(lltok::kw_addrspace))
1272 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1273 ParseUInt32(AddrSpace) ||
1274 ParseToken(lltok::rparen, "expected ')' in address space");
1277 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1278 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1279 bool HaveError = false;
1284 lltok::Kind Token = Lex.getKind();
1286 default: // End of attributes.
1288 case lltok::kw_align: {
1290 if (ParseOptionalAlignment(Alignment))
1292 B.addAlignmentAttr(Alignment);
1295 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1296 case lltok::kw_dereferenceable: {
1298 if (ParseOptionalDereferenceableBytes(Bytes))
1300 B.addDereferenceableAttr(Bytes);
1303 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1304 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1305 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1306 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1307 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1308 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1309 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1310 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1311 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1312 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1313 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1314 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1316 case lltok::kw_alignstack:
1317 case lltok::kw_alwaysinline:
1318 case lltok::kw_builtin:
1319 case lltok::kw_inlinehint:
1320 case lltok::kw_jumptable:
1321 case lltok::kw_minsize:
1322 case lltok::kw_naked:
1323 case lltok::kw_nobuiltin:
1324 case lltok::kw_noduplicate:
1325 case lltok::kw_noimplicitfloat:
1326 case lltok::kw_noinline:
1327 case lltok::kw_nonlazybind:
1328 case lltok::kw_noredzone:
1329 case lltok::kw_noreturn:
1330 case lltok::kw_nounwind:
1331 case lltok::kw_optnone:
1332 case lltok::kw_optsize:
1333 case lltok::kw_returns_twice:
1334 case lltok::kw_sanitize_address:
1335 case lltok::kw_sanitize_memory:
1336 case lltok::kw_sanitize_thread:
1338 case lltok::kw_sspreq:
1339 case lltok::kw_sspstrong:
1340 case lltok::kw_uwtable:
1341 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1349 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1350 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1351 bool HaveError = false;
1356 lltok::Kind Token = Lex.getKind();
1358 default: // End of attributes.
1360 case lltok::kw_dereferenceable: {
1362 if (ParseOptionalDereferenceableBytes(Bytes))
1364 B.addDereferenceableAttr(Bytes);
1367 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1368 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1369 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1370 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1371 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1374 case lltok::kw_align:
1375 case lltok::kw_byval:
1376 case lltok::kw_inalloca:
1377 case lltok::kw_nest:
1378 case lltok::kw_nocapture:
1379 case lltok::kw_returned:
1380 case lltok::kw_sret:
1381 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1384 case lltok::kw_alignstack:
1385 case lltok::kw_alwaysinline:
1386 case lltok::kw_builtin:
1387 case lltok::kw_cold:
1388 case lltok::kw_inlinehint:
1389 case lltok::kw_jumptable:
1390 case lltok::kw_minsize:
1391 case lltok::kw_naked:
1392 case lltok::kw_nobuiltin:
1393 case lltok::kw_noduplicate:
1394 case lltok::kw_noimplicitfloat:
1395 case lltok::kw_noinline:
1396 case lltok::kw_nonlazybind:
1397 case lltok::kw_noredzone:
1398 case lltok::kw_noreturn:
1399 case lltok::kw_nounwind:
1400 case lltok::kw_optnone:
1401 case lltok::kw_optsize:
1402 case lltok::kw_returns_twice:
1403 case lltok::kw_sanitize_address:
1404 case lltok::kw_sanitize_memory:
1405 case lltok::kw_sanitize_thread:
1407 case lltok::kw_sspreq:
1408 case lltok::kw_sspstrong:
1409 case lltok::kw_uwtable:
1410 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1413 case lltok::kw_readnone:
1414 case lltok::kw_readonly:
1415 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1422 /// ParseOptionalLinkage
1429 /// ::= 'linkonce_odr'
1430 /// ::= 'available_externally'
1433 /// ::= 'extern_weak'
1435 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1437 switch (Lex.getKind()) {
1438 default: Res=GlobalValue::ExternalLinkage; return false;
1439 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1440 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1441 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1442 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1443 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1444 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1445 case lltok::kw_available_externally:
1446 Res = GlobalValue::AvailableExternallyLinkage;
1448 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1449 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1450 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1451 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1458 /// ParseOptionalVisibility
1464 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1465 switch (Lex.getKind()) {
1466 default: Res = GlobalValue::DefaultVisibility; return false;
1467 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1468 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1469 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1475 /// ParseOptionalDLLStorageClass
1480 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1481 switch (Lex.getKind()) {
1482 default: Res = GlobalValue::DefaultStorageClass; return false;
1483 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1484 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1490 /// ParseOptionalCallingConv
1494 /// ::= 'kw_intel_ocl_bicc'
1496 /// ::= 'x86_stdcallcc'
1497 /// ::= 'x86_fastcallcc'
1498 /// ::= 'x86_thiscallcc'
1499 /// ::= 'arm_apcscc'
1500 /// ::= 'arm_aapcscc'
1501 /// ::= 'arm_aapcs_vfpcc'
1502 /// ::= 'msp430_intrcc'
1503 /// ::= 'ptx_kernel'
1504 /// ::= 'ptx_device'
1506 /// ::= 'spir_kernel'
1507 /// ::= 'x86_64_sysvcc'
1508 /// ::= 'x86_64_win64cc'
1509 /// ::= 'webkit_jscc'
1511 /// ::= 'preserve_mostcc'
1512 /// ::= 'preserve_allcc'
1515 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1516 switch (Lex.getKind()) {
1517 default: CC = CallingConv::C; return false;
1518 case lltok::kw_ccc: CC = CallingConv::C; break;
1519 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1520 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1521 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1522 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1523 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1524 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1525 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1526 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1527 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1528 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1529 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1530 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1531 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1532 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1533 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1534 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1535 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1536 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1537 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1538 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1539 case lltok::kw_cc: {
1540 unsigned ArbitraryCC;
1542 if (ParseUInt32(ArbitraryCC))
1544 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1553 /// ParseInstructionMetadata
1554 /// ::= !dbg !42 (',' !dbg !57)*
1555 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1556 PerFunctionState *PFS) {
1558 if (Lex.getKind() != lltok::MetadataVar)
1559 return TokError("expected metadata after comma");
1561 std::string Name = Lex.getStrVal();
1562 unsigned MDK = M->getMDKindID(Name);
1566 SMLoc Loc = Lex.getLoc();
1568 if (ParseToken(lltok::exclaim, "expected '!' here"))
1571 // This code is similar to that of ParseMetadataValue, however it needs to
1572 // have special-case code for a forward reference; see the comments on
1573 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1574 // at the top level here.
1575 if (Lex.getKind() == lltok::lbrace) {
1577 if (ParseMetadataListValue(ID, PFS))
1579 assert(ID.Kind == ValID::t_MDNode);
1580 Inst->setMetadata(MDK, ID.MDNodeVal);
1582 unsigned NodeID = 0;
1583 if (ParseMDNodeID(Node, NodeID))
1586 // If we got the node, add it to the instruction.
1587 Inst->setMetadata(MDK, Node);
1589 MDRef R = { Loc, MDK, NodeID };
1590 // Otherwise, remember that this should be resolved later.
1591 ForwardRefInstMetadata[Inst].push_back(R);
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 /// ParseOptionalAlignment
1606 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1608 if (!EatIfPresent(lltok::kw_align))
1610 LocTy AlignLoc = Lex.getLoc();
1611 if (ParseUInt32(Alignment)) return true;
1612 if (!isPowerOf2_32(Alignment))
1613 return Error(AlignLoc, "alignment is not a power of two");
1614 if (Alignment > Value::MaximumAlignment)
1615 return Error(AlignLoc, "huge alignments are not supported yet");
1619 /// ParseOptionalDereferenceableBytes
1621 /// ::= 'dereferenceable' '(' 4 ')'
1622 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1624 if (!EatIfPresent(lltok::kw_dereferenceable))
1626 LocTy ParenLoc = Lex.getLoc();
1627 if (!EatIfPresent(lltok::lparen))
1628 return Error(ParenLoc, "expected '('");
1629 LocTy DerefLoc = Lex.getLoc();
1630 if (ParseUInt64(Bytes)) return true;
1631 ParenLoc = Lex.getLoc();
1632 if (!EatIfPresent(lltok::rparen))
1633 return Error(ParenLoc, "expected ')'");
1635 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1639 /// ParseOptionalCommaAlign
1643 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1645 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1646 bool &AteExtraComma) {
1647 AteExtraComma = false;
1648 while (EatIfPresent(lltok::comma)) {
1649 // Metadata at the end is an early exit.
1650 if (Lex.getKind() == lltok::MetadataVar) {
1651 AteExtraComma = true;
1655 if (Lex.getKind() != lltok::kw_align)
1656 return Error(Lex.getLoc(), "expected metadata or 'align'");
1658 if (ParseOptionalAlignment(Alignment)) return true;
1664 /// ParseScopeAndOrdering
1665 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1668 /// This sets Scope and Ordering to the parsed values.
1669 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1670 AtomicOrdering &Ordering) {
1674 Scope = CrossThread;
1675 if (EatIfPresent(lltok::kw_singlethread))
1676 Scope = SingleThread;
1678 return ParseOrdering(Ordering);
1682 /// ::= AtomicOrdering
1684 /// This sets Ordering to the parsed value.
1685 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1686 switch (Lex.getKind()) {
1687 default: return TokError("Expected ordering on atomic instruction");
1688 case lltok::kw_unordered: Ordering = Unordered; break;
1689 case lltok::kw_monotonic: Ordering = Monotonic; break;
1690 case lltok::kw_acquire: Ordering = Acquire; break;
1691 case lltok::kw_release: Ordering = Release; break;
1692 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1693 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1699 /// ParseOptionalStackAlignment
1701 /// ::= 'alignstack' '(' 4 ')'
1702 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1704 if (!EatIfPresent(lltok::kw_alignstack))
1706 LocTy ParenLoc = Lex.getLoc();
1707 if (!EatIfPresent(lltok::lparen))
1708 return Error(ParenLoc, "expected '('");
1709 LocTy AlignLoc = Lex.getLoc();
1710 if (ParseUInt32(Alignment)) return true;
1711 ParenLoc = Lex.getLoc();
1712 if (!EatIfPresent(lltok::rparen))
1713 return Error(ParenLoc, "expected ')'");
1714 if (!isPowerOf2_32(Alignment))
1715 return Error(AlignLoc, "stack alignment is not a power of two");
1719 /// ParseIndexList - This parses the index list for an insert/extractvalue
1720 /// instruction. This sets AteExtraComma in the case where we eat an extra
1721 /// comma at the end of the line and find that it is followed by metadata.
1722 /// Clients that don't allow metadata can call the version of this function that
1723 /// only takes one argument.
1726 /// ::= (',' uint32)+
1728 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1729 bool &AteExtraComma) {
1730 AteExtraComma = false;
1732 if (Lex.getKind() != lltok::comma)
1733 return TokError("expected ',' as start of index list");
1735 while (EatIfPresent(lltok::comma)) {
1736 if (Lex.getKind() == lltok::MetadataVar) {
1737 AteExtraComma = true;
1741 if (ParseUInt32(Idx)) return true;
1742 Indices.push_back(Idx);
1748 //===----------------------------------------------------------------------===//
1750 //===----------------------------------------------------------------------===//
1752 /// ParseType - Parse a type.
1753 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1754 SMLoc TypeLoc = Lex.getLoc();
1755 switch (Lex.getKind()) {
1757 return TokError("expected type");
1759 // Type ::= 'float' | 'void' (etc)
1760 Result = Lex.getTyVal();
1764 // Type ::= StructType
1765 if (ParseAnonStructType(Result, false))
1768 case lltok::lsquare:
1769 // Type ::= '[' ... ']'
1770 Lex.Lex(); // eat the lsquare.
1771 if (ParseArrayVectorType(Result, false))
1774 case lltok::less: // Either vector or packed struct.
1775 // Type ::= '<' ... '>'
1777 if (Lex.getKind() == lltok::lbrace) {
1778 if (ParseAnonStructType(Result, true) ||
1779 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1781 } else if (ParseArrayVectorType(Result, true))
1784 case lltok::LocalVar: {
1786 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1788 // If the type hasn't been defined yet, create a forward definition and
1789 // remember where that forward def'n was seen (in case it never is defined).
1791 Entry.first = StructType::create(Context, Lex.getStrVal());
1792 Entry.second = Lex.getLoc();
1794 Result = Entry.first;
1799 case lltok::LocalVarID: {
1801 if (Lex.getUIntVal() >= NumberedTypes.size())
1802 NumberedTypes.resize(Lex.getUIntVal()+1);
1803 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1805 // If the type hasn't been defined yet, create a forward definition and
1806 // remember where that forward def'n was seen (in case it never is defined).
1808 Entry.first = StructType::create(Context);
1809 Entry.second = Lex.getLoc();
1811 Result = Entry.first;
1817 // Parse the type suffixes.
1819 switch (Lex.getKind()) {
1822 if (!AllowVoid && Result->isVoidTy())
1823 return Error(TypeLoc, "void type only allowed for function results");
1826 // Type ::= Type '*'
1828 if (Result->isLabelTy())
1829 return TokError("basic block pointers are invalid");
1830 if (Result->isVoidTy())
1831 return TokError("pointers to void are invalid - use i8* instead");
1832 if (!PointerType::isValidElementType(Result))
1833 return TokError("pointer to this type is invalid");
1834 Result = PointerType::getUnqual(Result);
1838 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1839 case lltok::kw_addrspace: {
1840 if (Result->isLabelTy())
1841 return TokError("basic block pointers are invalid");
1842 if (Result->isVoidTy())
1843 return TokError("pointers to void are invalid; use i8* instead");
1844 if (!PointerType::isValidElementType(Result))
1845 return TokError("pointer to this type is invalid");
1847 if (ParseOptionalAddrSpace(AddrSpace) ||
1848 ParseToken(lltok::star, "expected '*' in address space"))
1851 Result = PointerType::get(Result, AddrSpace);
1855 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1857 if (ParseFunctionType(Result))
1864 /// ParseParameterList
1866 /// ::= '(' Arg (',' Arg)* ')'
1868 /// ::= Type OptionalAttributes Value OptionalAttributes
1869 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1870 PerFunctionState &PFS) {
1871 if (ParseToken(lltok::lparen, "expected '(' in call"))
1874 unsigned AttrIndex = 1;
1875 while (Lex.getKind() != lltok::rparen) {
1876 // If this isn't the first argument, we need a comma.
1877 if (!ArgList.empty() &&
1878 ParseToken(lltok::comma, "expected ',' in argument list"))
1881 // Parse the argument.
1883 Type *ArgTy = nullptr;
1884 AttrBuilder ArgAttrs;
1886 if (ParseType(ArgTy, ArgLoc))
1889 // Otherwise, handle normal operands.
1890 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1892 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1897 Lex.Lex(); // Lex the ')'.
1903 /// ParseArgumentList - Parse the argument list for a function type or function
1905 /// ::= '(' ArgTypeListI ')'
1909 /// ::= ArgTypeList ',' '...'
1910 /// ::= ArgType (',' ArgType)*
1912 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1915 assert(Lex.getKind() == lltok::lparen);
1916 Lex.Lex(); // eat the (.
1918 if (Lex.getKind() == lltok::rparen) {
1920 } else if (Lex.getKind() == lltok::dotdotdot) {
1924 LocTy TypeLoc = Lex.getLoc();
1925 Type *ArgTy = nullptr;
1929 if (ParseType(ArgTy) ||
1930 ParseOptionalParamAttrs(Attrs)) return true;
1932 if (ArgTy->isVoidTy())
1933 return Error(TypeLoc, "argument can not have void type");
1935 if (Lex.getKind() == lltok::LocalVar) {
1936 Name = Lex.getStrVal();
1940 if (!FunctionType::isValidArgumentType(ArgTy))
1941 return Error(TypeLoc, "invalid type for function argument");
1943 unsigned AttrIndex = 1;
1944 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1945 AttributeSet::get(ArgTy->getContext(),
1946 AttrIndex++, Attrs), Name));
1948 while (EatIfPresent(lltok::comma)) {
1949 // Handle ... at end of arg list.
1950 if (EatIfPresent(lltok::dotdotdot)) {
1955 // Otherwise must be an argument type.
1956 TypeLoc = Lex.getLoc();
1957 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1959 if (ArgTy->isVoidTy())
1960 return Error(TypeLoc, "argument can not have void type");
1962 if (Lex.getKind() == lltok::LocalVar) {
1963 Name = Lex.getStrVal();
1969 if (!ArgTy->isFirstClassType())
1970 return Error(TypeLoc, "invalid type for function argument");
1972 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1973 AttributeSet::get(ArgTy->getContext(),
1974 AttrIndex++, Attrs),
1979 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1982 /// ParseFunctionType
1983 /// ::= Type ArgumentList OptionalAttrs
1984 bool LLParser::ParseFunctionType(Type *&Result) {
1985 assert(Lex.getKind() == lltok::lparen);
1987 if (!FunctionType::isValidReturnType(Result))
1988 return TokError("invalid function return type");
1990 SmallVector<ArgInfo, 8> ArgList;
1992 if (ParseArgumentList(ArgList, isVarArg))
1995 // Reject names on the arguments lists.
1996 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1997 if (!ArgList[i].Name.empty())
1998 return Error(ArgList[i].Loc, "argument name invalid in function type");
1999 if (ArgList[i].Attrs.hasAttributes(i + 1))
2000 return Error(ArgList[i].Loc,
2001 "argument attributes invalid in function type");
2004 SmallVector<Type*, 16> ArgListTy;
2005 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2006 ArgListTy.push_back(ArgList[i].Ty);
2008 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2012 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2014 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2015 SmallVector<Type*, 8> Elts;
2016 if (ParseStructBody(Elts)) return true;
2018 Result = StructType::get(Context, Elts, Packed);
2022 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2023 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2024 std::pair<Type*, LocTy> &Entry,
2026 // If the type was already defined, diagnose the redefinition.
2027 if (Entry.first && !Entry.second.isValid())
2028 return Error(TypeLoc, "redefinition of type");
2030 // If we have opaque, just return without filling in the definition for the
2031 // struct. This counts as a definition as far as the .ll file goes.
2032 if (EatIfPresent(lltok::kw_opaque)) {
2033 // This type is being defined, so clear the location to indicate this.
2034 Entry.second = SMLoc();
2036 // If this type number has never been uttered, create it.
2038 Entry.first = StructType::create(Context, Name);
2039 ResultTy = Entry.first;
2043 // If the type starts with '<', then it is either a packed struct or a vector.
2044 bool isPacked = EatIfPresent(lltok::less);
2046 // If we don't have a struct, then we have a random type alias, which we
2047 // accept for compatibility with old files. These types are not allowed to be
2048 // forward referenced and not allowed to be recursive.
2049 if (Lex.getKind() != lltok::lbrace) {
2051 return Error(TypeLoc, "forward references to non-struct type");
2055 return ParseArrayVectorType(ResultTy, true);
2056 return ParseType(ResultTy);
2059 // This type is being defined, so clear the location to indicate this.
2060 Entry.second = SMLoc();
2062 // If this type number has never been uttered, create it.
2064 Entry.first = StructType::create(Context, Name);
2066 StructType *STy = cast<StructType>(Entry.first);
2068 SmallVector<Type*, 8> Body;
2069 if (ParseStructBody(Body) ||
2070 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2073 STy->setBody(Body, isPacked);
2079 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2082 /// ::= '{' Type (',' Type)* '}'
2083 /// ::= '<' '{' '}' '>'
2084 /// ::= '<' '{' Type (',' Type)* '}' '>'
2085 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2086 assert(Lex.getKind() == lltok::lbrace);
2087 Lex.Lex(); // Consume the '{'
2089 // Handle the empty struct.
2090 if (EatIfPresent(lltok::rbrace))
2093 LocTy EltTyLoc = Lex.getLoc();
2095 if (ParseType(Ty)) return true;
2098 if (!StructType::isValidElementType(Ty))
2099 return Error(EltTyLoc, "invalid element type for struct");
2101 while (EatIfPresent(lltok::comma)) {
2102 EltTyLoc = Lex.getLoc();
2103 if (ParseType(Ty)) return true;
2105 if (!StructType::isValidElementType(Ty))
2106 return Error(EltTyLoc, "invalid element type for struct");
2111 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2114 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2115 /// token has already been consumed.
2117 /// ::= '[' APSINTVAL 'x' Types ']'
2118 /// ::= '<' APSINTVAL 'x' Types '>'
2119 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2120 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2121 Lex.getAPSIntVal().getBitWidth() > 64)
2122 return TokError("expected number in address space");
2124 LocTy SizeLoc = Lex.getLoc();
2125 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2128 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2131 LocTy TypeLoc = Lex.getLoc();
2132 Type *EltTy = nullptr;
2133 if (ParseType(EltTy)) return true;
2135 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2136 "expected end of sequential type"))
2141 return Error(SizeLoc, "zero element vector is illegal");
2142 if ((unsigned)Size != Size)
2143 return Error(SizeLoc, "size too large for vector");
2144 if (!VectorType::isValidElementType(EltTy))
2145 return Error(TypeLoc, "invalid vector element type");
2146 Result = VectorType::get(EltTy, unsigned(Size));
2148 if (!ArrayType::isValidElementType(EltTy))
2149 return Error(TypeLoc, "invalid array element type");
2150 Result = ArrayType::get(EltTy, Size);
2155 //===----------------------------------------------------------------------===//
2156 // Function Semantic Analysis.
2157 //===----------------------------------------------------------------------===//
2159 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2161 : P(p), F(f), FunctionNumber(functionNumber) {
2163 // Insert unnamed arguments into the NumberedVals list.
2164 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2167 NumberedVals.push_back(AI);
2170 LLParser::PerFunctionState::~PerFunctionState() {
2171 // If there were any forward referenced non-basicblock values, delete them.
2172 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2173 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2174 if (!isa<BasicBlock>(I->second.first)) {
2175 I->second.first->replaceAllUsesWith(
2176 UndefValue::get(I->second.first->getType()));
2177 delete I->second.first;
2178 I->second.first = nullptr;
2181 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2182 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2183 if (!isa<BasicBlock>(I->second.first)) {
2184 I->second.first->replaceAllUsesWith(
2185 UndefValue::get(I->second.first->getType()));
2186 delete I->second.first;
2187 I->second.first = nullptr;
2191 bool LLParser::PerFunctionState::FinishFunction() {
2192 // Check to see if someone took the address of labels in this block.
2193 if (!P.ForwardRefBlockAddresses.empty()) {
2195 if (!F.getName().empty()) {
2196 FunctionID.Kind = ValID::t_GlobalName;
2197 FunctionID.StrVal = F.getName();
2199 FunctionID.Kind = ValID::t_GlobalID;
2200 FunctionID.UIntVal = FunctionNumber;
2203 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2204 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2205 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2206 // Resolve all these references.
2207 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2210 P.ForwardRefBlockAddresses.erase(FRBAI);
2214 if (!ForwardRefVals.empty())
2215 return P.Error(ForwardRefVals.begin()->second.second,
2216 "use of undefined value '%" + ForwardRefVals.begin()->first +
2218 if (!ForwardRefValIDs.empty())
2219 return P.Error(ForwardRefValIDs.begin()->second.second,
2220 "use of undefined value '%" +
2221 Twine(ForwardRefValIDs.begin()->first) + "'");
2226 /// GetVal - Get a value with the specified name or ID, creating a
2227 /// forward reference record if needed. This can return null if the value
2228 /// exists but does not have the right type.
2229 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2230 Type *Ty, LocTy Loc) {
2231 // Look this name up in the normal function symbol table.
2232 Value *Val = F.getValueSymbolTable().lookup(Name);
2234 // If this is a forward reference for the value, see if we already created a
2235 // forward ref record.
2237 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2238 I = ForwardRefVals.find(Name);
2239 if (I != ForwardRefVals.end())
2240 Val = I->second.first;
2243 // If we have the value in the symbol table or fwd-ref table, return it.
2245 if (Val->getType() == Ty) return Val;
2246 if (Ty->isLabelTy())
2247 P.Error(Loc, "'%" + Name + "' is not a basic block");
2249 P.Error(Loc, "'%" + Name + "' defined with type '" +
2250 getTypeString(Val->getType()) + "'");
2254 // Don't make placeholders with invalid type.
2255 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2256 P.Error(Loc, "invalid use of a non-first-class type");
2260 // Otherwise, create a new forward reference for this value and remember it.
2262 if (Ty->isLabelTy())
2263 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2265 FwdVal = new Argument(Ty, Name);
2267 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2271 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2273 // Look this name up in the normal function symbol table.
2274 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2276 // If this is a forward reference for the value, see if we already created a
2277 // forward ref record.
2279 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2280 I = ForwardRefValIDs.find(ID);
2281 if (I != ForwardRefValIDs.end())
2282 Val = I->second.first;
2285 // If we have the value in the symbol table or fwd-ref table, return it.
2287 if (Val->getType() == Ty) return Val;
2288 if (Ty->isLabelTy())
2289 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2291 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2292 getTypeString(Val->getType()) + "'");
2296 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2297 P.Error(Loc, "invalid use of a non-first-class type");
2301 // Otherwise, create a new forward reference for this value and remember it.
2303 if (Ty->isLabelTy())
2304 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2306 FwdVal = new Argument(Ty);
2308 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2312 /// SetInstName - After an instruction is parsed and inserted into its
2313 /// basic block, this installs its name.
2314 bool LLParser::PerFunctionState::SetInstName(int NameID,
2315 const std::string &NameStr,
2316 LocTy NameLoc, Instruction *Inst) {
2317 // If this instruction has void type, it cannot have a name or ID specified.
2318 if (Inst->getType()->isVoidTy()) {
2319 if (NameID != -1 || !NameStr.empty())
2320 return P.Error(NameLoc, "instructions returning void cannot have a name");
2324 // If this was a numbered instruction, verify that the instruction is the
2325 // expected value and resolve any forward references.
2326 if (NameStr.empty()) {
2327 // If neither a name nor an ID was specified, just use the next ID.
2329 NameID = NumberedVals.size();
2331 if (unsigned(NameID) != NumberedVals.size())
2332 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2333 Twine(NumberedVals.size()) + "'");
2335 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2336 ForwardRefValIDs.find(NameID);
2337 if (FI != ForwardRefValIDs.end()) {
2338 if (FI->second.first->getType() != Inst->getType())
2339 return P.Error(NameLoc, "instruction forward referenced with type '" +
2340 getTypeString(FI->second.first->getType()) + "'");
2341 FI->second.first->replaceAllUsesWith(Inst);
2342 delete FI->second.first;
2343 ForwardRefValIDs.erase(FI);
2346 NumberedVals.push_back(Inst);
2350 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2351 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2352 FI = ForwardRefVals.find(NameStr);
2353 if (FI != ForwardRefVals.end()) {
2354 if (FI->second.first->getType() != Inst->getType())
2355 return P.Error(NameLoc, "instruction forward referenced with type '" +
2356 getTypeString(FI->second.first->getType()) + "'");
2357 FI->second.first->replaceAllUsesWith(Inst);
2358 delete FI->second.first;
2359 ForwardRefVals.erase(FI);
2362 // Set the name on the instruction.
2363 Inst->setName(NameStr);
2365 if (Inst->getName() != NameStr)
2366 return P.Error(NameLoc, "multiple definition of local value named '" +
2371 /// GetBB - Get a basic block with the specified name or ID, creating a
2372 /// forward reference record if needed.
2373 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2375 return cast_or_null<BasicBlock>(GetVal(Name,
2376 Type::getLabelTy(F.getContext()), Loc));
2379 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2380 return cast_or_null<BasicBlock>(GetVal(ID,
2381 Type::getLabelTy(F.getContext()), Loc));
2384 /// DefineBB - Define the specified basic block, which is either named or
2385 /// unnamed. If there is an error, this returns null otherwise it returns
2386 /// the block being defined.
2387 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2391 BB = GetBB(NumberedVals.size(), Loc);
2393 BB = GetBB(Name, Loc);
2394 if (!BB) return nullptr; // Already diagnosed error.
2396 // Move the block to the end of the function. Forward ref'd blocks are
2397 // inserted wherever they happen to be referenced.
2398 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2400 // Remove the block from forward ref sets.
2402 ForwardRefValIDs.erase(NumberedVals.size());
2403 NumberedVals.push_back(BB);
2405 // BB forward references are already in the function symbol table.
2406 ForwardRefVals.erase(Name);
2412 //===----------------------------------------------------------------------===//
2414 //===----------------------------------------------------------------------===//
2416 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2417 /// type implied. For example, if we parse "4" we don't know what integer type
2418 /// it has. The value will later be combined with its type and checked for
2419 /// sanity. PFS is used to convert function-local operands of metadata (since
2420 /// metadata operands are not just parsed here but also converted to values).
2421 /// PFS can be null when we are not parsing metadata values inside a function.
2422 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2423 ID.Loc = Lex.getLoc();
2424 switch (Lex.getKind()) {
2425 default: return TokError("expected value token");
2426 case lltok::GlobalID: // @42
2427 ID.UIntVal = Lex.getUIntVal();
2428 ID.Kind = ValID::t_GlobalID;
2430 case lltok::GlobalVar: // @foo
2431 ID.StrVal = Lex.getStrVal();
2432 ID.Kind = ValID::t_GlobalName;
2434 case lltok::LocalVarID: // %42
2435 ID.UIntVal = Lex.getUIntVal();
2436 ID.Kind = ValID::t_LocalID;
2438 case lltok::LocalVar: // %foo
2439 ID.StrVal = Lex.getStrVal();
2440 ID.Kind = ValID::t_LocalName;
2442 case lltok::exclaim: // !42, !{...}, or !"foo"
2443 return ParseMetadataValue(ID, PFS);
2445 ID.APSIntVal = Lex.getAPSIntVal();
2446 ID.Kind = ValID::t_APSInt;
2448 case lltok::APFloat:
2449 ID.APFloatVal = Lex.getAPFloatVal();
2450 ID.Kind = ValID::t_APFloat;
2452 case lltok::kw_true:
2453 ID.ConstantVal = ConstantInt::getTrue(Context);
2454 ID.Kind = ValID::t_Constant;
2456 case lltok::kw_false:
2457 ID.ConstantVal = ConstantInt::getFalse(Context);
2458 ID.Kind = ValID::t_Constant;
2460 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2461 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2462 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2464 case lltok::lbrace: {
2465 // ValID ::= '{' ConstVector '}'
2467 SmallVector<Constant*, 16> Elts;
2468 if (ParseGlobalValueVector(Elts) ||
2469 ParseToken(lltok::rbrace, "expected end of struct constant"))
2472 ID.ConstantStructElts = new Constant*[Elts.size()];
2473 ID.UIntVal = Elts.size();
2474 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2475 ID.Kind = ValID::t_ConstantStruct;
2479 // ValID ::= '<' ConstVector '>' --> Vector.
2480 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2482 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2484 SmallVector<Constant*, 16> Elts;
2485 LocTy FirstEltLoc = Lex.getLoc();
2486 if (ParseGlobalValueVector(Elts) ||
2488 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2489 ParseToken(lltok::greater, "expected end of constant"))
2492 if (isPackedStruct) {
2493 ID.ConstantStructElts = new Constant*[Elts.size()];
2494 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2495 ID.UIntVal = Elts.size();
2496 ID.Kind = ValID::t_PackedConstantStruct;
2501 return Error(ID.Loc, "constant vector must not be empty");
2503 if (!Elts[0]->getType()->isIntegerTy() &&
2504 !Elts[0]->getType()->isFloatingPointTy() &&
2505 !Elts[0]->getType()->isPointerTy())
2506 return Error(FirstEltLoc,
2507 "vector elements must have integer, pointer or floating point type");
2509 // Verify that all the vector elements have the same type.
2510 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2511 if (Elts[i]->getType() != Elts[0]->getType())
2512 return Error(FirstEltLoc,
2513 "vector element #" + Twine(i) +
2514 " is not of type '" + getTypeString(Elts[0]->getType()));
2516 ID.ConstantVal = ConstantVector::get(Elts);
2517 ID.Kind = ValID::t_Constant;
2520 case lltok::lsquare: { // Array Constant
2522 SmallVector<Constant*, 16> Elts;
2523 LocTy FirstEltLoc = Lex.getLoc();
2524 if (ParseGlobalValueVector(Elts) ||
2525 ParseToken(lltok::rsquare, "expected end of array constant"))
2528 // Handle empty element.
2530 // Use undef instead of an array because it's inconvenient to determine
2531 // the element type at this point, there being no elements to examine.
2532 ID.Kind = ValID::t_EmptyArray;
2536 if (!Elts[0]->getType()->isFirstClassType())
2537 return Error(FirstEltLoc, "invalid array element type: " +
2538 getTypeString(Elts[0]->getType()));
2540 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2542 // Verify all elements are correct type!
2543 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2544 if (Elts[i]->getType() != Elts[0]->getType())
2545 return Error(FirstEltLoc,
2546 "array element #" + Twine(i) +
2547 " is not of type '" + getTypeString(Elts[0]->getType()));
2550 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2551 ID.Kind = ValID::t_Constant;
2554 case lltok::kw_c: // c "foo"
2556 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2558 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2559 ID.Kind = ValID::t_Constant;
2562 case lltok::kw_asm: {
2563 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2565 bool HasSideEffect, AlignStack, AsmDialect;
2567 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2568 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2569 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2570 ParseStringConstant(ID.StrVal) ||
2571 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2572 ParseToken(lltok::StringConstant, "expected constraint string"))
2574 ID.StrVal2 = Lex.getStrVal();
2575 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2576 (unsigned(AsmDialect)<<2);
2577 ID.Kind = ValID::t_InlineAsm;
2581 case lltok::kw_blockaddress: {
2582 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2587 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2589 ParseToken(lltok::comma, "expected comma in block address expression")||
2590 ParseValID(Label) ||
2591 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2594 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2595 return Error(Fn.Loc, "expected function name in blockaddress");
2596 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2597 return Error(Label.Loc, "expected basic block name in blockaddress");
2599 // Make a global variable as a placeholder for this reference.
2600 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2601 false, GlobalValue::InternalLinkage,
2603 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2604 ID.ConstantVal = FwdRef;
2605 ID.Kind = ValID::t_Constant;
2609 case lltok::kw_trunc:
2610 case lltok::kw_zext:
2611 case lltok::kw_sext:
2612 case lltok::kw_fptrunc:
2613 case lltok::kw_fpext:
2614 case lltok::kw_bitcast:
2615 case lltok::kw_addrspacecast:
2616 case lltok::kw_uitofp:
2617 case lltok::kw_sitofp:
2618 case lltok::kw_fptoui:
2619 case lltok::kw_fptosi:
2620 case lltok::kw_inttoptr:
2621 case lltok::kw_ptrtoint: {
2622 unsigned Opc = Lex.getUIntVal();
2623 Type *DestTy = nullptr;
2626 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2627 ParseGlobalTypeAndValue(SrcVal) ||
2628 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2629 ParseType(DestTy) ||
2630 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2632 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2633 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2634 getTypeString(SrcVal->getType()) + "' to '" +
2635 getTypeString(DestTy) + "'");
2636 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2638 ID.Kind = ValID::t_Constant;
2641 case lltok::kw_extractvalue: {
2644 SmallVector<unsigned, 4> Indices;
2645 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2646 ParseGlobalTypeAndValue(Val) ||
2647 ParseIndexList(Indices) ||
2648 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2651 if (!Val->getType()->isAggregateType())
2652 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2653 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2654 return Error(ID.Loc, "invalid indices for extractvalue");
2655 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2656 ID.Kind = ValID::t_Constant;
2659 case lltok::kw_insertvalue: {
2661 Constant *Val0, *Val1;
2662 SmallVector<unsigned, 4> Indices;
2663 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2664 ParseGlobalTypeAndValue(Val0) ||
2665 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2666 ParseGlobalTypeAndValue(Val1) ||
2667 ParseIndexList(Indices) ||
2668 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2670 if (!Val0->getType()->isAggregateType())
2671 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2672 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2673 return Error(ID.Loc, "invalid indices for insertvalue");
2674 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2675 ID.Kind = ValID::t_Constant;
2678 case lltok::kw_icmp:
2679 case lltok::kw_fcmp: {
2680 unsigned PredVal, Opc = Lex.getUIntVal();
2681 Constant *Val0, *Val1;
2683 if (ParseCmpPredicate(PredVal, Opc) ||
2684 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2685 ParseGlobalTypeAndValue(Val0) ||
2686 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2687 ParseGlobalTypeAndValue(Val1) ||
2688 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2691 if (Val0->getType() != Val1->getType())
2692 return Error(ID.Loc, "compare operands must have the same type");
2694 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2696 if (Opc == Instruction::FCmp) {
2697 if (!Val0->getType()->isFPOrFPVectorTy())
2698 return Error(ID.Loc, "fcmp requires floating point operands");
2699 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2701 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2702 if (!Val0->getType()->isIntOrIntVectorTy() &&
2703 !Val0->getType()->getScalarType()->isPointerTy())
2704 return Error(ID.Loc, "icmp requires pointer or integer operands");
2705 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2707 ID.Kind = ValID::t_Constant;
2711 // Binary Operators.
2713 case lltok::kw_fadd:
2715 case lltok::kw_fsub:
2717 case lltok::kw_fmul:
2718 case lltok::kw_udiv:
2719 case lltok::kw_sdiv:
2720 case lltok::kw_fdiv:
2721 case lltok::kw_urem:
2722 case lltok::kw_srem:
2723 case lltok::kw_frem:
2725 case lltok::kw_lshr:
2726 case lltok::kw_ashr: {
2730 unsigned Opc = Lex.getUIntVal();
2731 Constant *Val0, *Val1;
2733 LocTy ModifierLoc = Lex.getLoc();
2734 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2735 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2736 if (EatIfPresent(lltok::kw_nuw))
2738 if (EatIfPresent(lltok::kw_nsw)) {
2740 if (EatIfPresent(lltok::kw_nuw))
2743 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2744 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2745 if (EatIfPresent(lltok::kw_exact))
2748 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2749 ParseGlobalTypeAndValue(Val0) ||
2750 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2751 ParseGlobalTypeAndValue(Val1) ||
2752 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2754 if (Val0->getType() != Val1->getType())
2755 return Error(ID.Loc, "operands of constexpr must have same type");
2756 if (!Val0->getType()->isIntOrIntVectorTy()) {
2758 return Error(ModifierLoc, "nuw only applies to integer operations");
2760 return Error(ModifierLoc, "nsw only applies to integer operations");
2762 // Check that the type is valid for the operator.
2764 case Instruction::Add:
2765 case Instruction::Sub:
2766 case Instruction::Mul:
2767 case Instruction::UDiv:
2768 case Instruction::SDiv:
2769 case Instruction::URem:
2770 case Instruction::SRem:
2771 case Instruction::Shl:
2772 case Instruction::AShr:
2773 case Instruction::LShr:
2774 if (!Val0->getType()->isIntOrIntVectorTy())
2775 return Error(ID.Loc, "constexpr requires integer operands");
2777 case Instruction::FAdd:
2778 case Instruction::FSub:
2779 case Instruction::FMul:
2780 case Instruction::FDiv:
2781 case Instruction::FRem:
2782 if (!Val0->getType()->isFPOrFPVectorTy())
2783 return Error(ID.Loc, "constexpr requires fp operands");
2785 default: llvm_unreachable("Unknown binary operator!");
2788 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2789 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2790 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2791 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2793 ID.Kind = ValID::t_Constant;
2797 // Logical Operations
2800 case lltok::kw_xor: {
2801 unsigned Opc = Lex.getUIntVal();
2802 Constant *Val0, *Val1;
2804 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2805 ParseGlobalTypeAndValue(Val0) ||
2806 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2807 ParseGlobalTypeAndValue(Val1) ||
2808 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2810 if (Val0->getType() != Val1->getType())
2811 return Error(ID.Loc, "operands of constexpr must have same type");
2812 if (!Val0->getType()->isIntOrIntVectorTy())
2813 return Error(ID.Loc,
2814 "constexpr requires integer or integer vector operands");
2815 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2816 ID.Kind = ValID::t_Constant;
2820 case lltok::kw_getelementptr:
2821 case lltok::kw_shufflevector:
2822 case lltok::kw_insertelement:
2823 case lltok::kw_extractelement:
2824 case lltok::kw_select: {
2825 unsigned Opc = Lex.getUIntVal();
2826 SmallVector<Constant*, 16> Elts;
2827 bool InBounds = false;
2829 if (Opc == Instruction::GetElementPtr)
2830 InBounds = EatIfPresent(lltok::kw_inbounds);
2831 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2832 ParseGlobalValueVector(Elts) ||
2833 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2836 if (Opc == Instruction::GetElementPtr) {
2837 if (Elts.size() == 0 ||
2838 !Elts[0]->getType()->getScalarType()->isPointerTy())
2839 return Error(ID.Loc, "getelementptr requires pointer operand");
2841 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2842 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2843 return Error(ID.Loc, "invalid indices for getelementptr");
2844 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2846 } else if (Opc == Instruction::Select) {
2847 if (Elts.size() != 3)
2848 return Error(ID.Loc, "expected three operands to select");
2849 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2851 return Error(ID.Loc, Reason);
2852 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2853 } else if (Opc == Instruction::ShuffleVector) {
2854 if (Elts.size() != 3)
2855 return Error(ID.Loc, "expected three operands to shufflevector");
2856 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2857 return Error(ID.Loc, "invalid operands to shufflevector");
2859 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2860 } else if (Opc == Instruction::ExtractElement) {
2861 if (Elts.size() != 2)
2862 return Error(ID.Loc, "expected two operands to extractelement");
2863 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2864 return Error(ID.Loc, "invalid extractelement operands");
2865 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2867 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2868 if (Elts.size() != 3)
2869 return Error(ID.Loc, "expected three operands to insertelement");
2870 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2871 return Error(ID.Loc, "invalid insertelement operands");
2873 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2876 ID.Kind = ValID::t_Constant;
2885 /// ParseGlobalValue - Parse a global value with the specified type.
2886 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2890 bool Parsed = ParseValID(ID) ||
2891 ConvertValIDToValue(Ty, ID, V, nullptr);
2892 if (V && !(C = dyn_cast<Constant>(V)))
2893 return Error(ID.Loc, "global values must be constants");
2897 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2899 return ParseType(Ty) ||
2900 ParseGlobalValue(Ty, V);
2903 bool LLParser::parseOptionalComdat(Comdat *&C) {
2905 if (!EatIfPresent(lltok::kw_comdat))
2907 if (Lex.getKind() != lltok::ComdatVar)
2908 return TokError("expected comdat variable");
2909 LocTy Loc = Lex.getLoc();
2910 StringRef Name = Lex.getStrVal();
2911 C = getComdat(Name, Loc);
2916 /// ParseGlobalValueVector
2918 /// ::= TypeAndValue (',' TypeAndValue)*
2919 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2921 if (Lex.getKind() == lltok::rbrace ||
2922 Lex.getKind() == lltok::rsquare ||
2923 Lex.getKind() == lltok::greater ||
2924 Lex.getKind() == lltok::rparen)
2928 if (ParseGlobalTypeAndValue(C)) return true;
2931 while (EatIfPresent(lltok::comma)) {
2932 if (ParseGlobalTypeAndValue(C)) return true;
2939 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2940 assert(Lex.getKind() == lltok::lbrace);
2943 SmallVector<Value*, 16> Elts;
2944 if (ParseMDNodeVector(Elts, PFS) ||
2945 ParseToken(lltok::rbrace, "expected end of metadata node"))
2948 ID.MDNodeVal = MDNode::get(Context, Elts);
2949 ID.Kind = ValID::t_MDNode;
2953 /// ParseMetadataValue
2957 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2958 assert(Lex.getKind() == lltok::exclaim);
2963 if (Lex.getKind() == lltok::lbrace)
2964 return ParseMetadataListValue(ID, PFS);
2966 // Standalone metadata reference
2968 if (Lex.getKind() == lltok::APSInt) {
2969 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2970 ID.Kind = ValID::t_MDNode;
2975 // ::= '!' STRINGCONSTANT
2976 if (ParseMDString(ID.MDStringVal)) return true;
2977 ID.Kind = ValID::t_MDString;
2982 //===----------------------------------------------------------------------===//
2983 // Function Parsing.
2984 //===----------------------------------------------------------------------===//
2986 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2987 PerFunctionState *PFS) {
2988 if (Ty->isFunctionTy())
2989 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2992 case ValID::t_LocalID:
2993 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2994 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2995 return V == nullptr;
2996 case ValID::t_LocalName:
2997 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2998 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2999 return V == nullptr;
3000 case ValID::t_InlineAsm: {
3001 PointerType *PTy = dyn_cast<PointerType>(Ty);
3003 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3004 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3005 return Error(ID.Loc, "invalid type for inline asm constraint string");
3006 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3007 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3010 case ValID::t_MDNode:
3011 if (!Ty->isMetadataTy())
3012 return Error(ID.Loc, "metadata value must have metadata type");
3015 case ValID::t_MDString:
3016 if (!Ty->isMetadataTy())
3017 return Error(ID.Loc, "metadata value must have metadata type");
3020 case ValID::t_GlobalName:
3021 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3022 return V == nullptr;
3023 case ValID::t_GlobalID:
3024 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3025 return V == nullptr;
3026 case ValID::t_APSInt:
3027 if (!Ty->isIntegerTy())
3028 return Error(ID.Loc, "integer constant must have integer type");
3029 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3030 V = ConstantInt::get(Context, ID.APSIntVal);
3032 case ValID::t_APFloat:
3033 if (!Ty->isFloatingPointTy() ||
3034 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3035 return Error(ID.Loc, "floating point constant invalid for type");
3037 // The lexer has no type info, so builds all half, float, and double FP
3038 // constants as double. Fix this here. Long double does not need this.
3039 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3042 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3044 else if (Ty->isFloatTy())
3045 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3048 V = ConstantFP::get(Context, ID.APFloatVal);
3050 if (V->getType() != Ty)
3051 return Error(ID.Loc, "floating point constant does not have type '" +
3052 getTypeString(Ty) + "'");
3056 if (!Ty->isPointerTy())
3057 return Error(ID.Loc, "null must be a pointer type");
3058 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3060 case ValID::t_Undef:
3061 // FIXME: LabelTy should not be a first-class type.
3062 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3063 return Error(ID.Loc, "invalid type for undef constant");
3064 V = UndefValue::get(Ty);
3066 case ValID::t_EmptyArray:
3067 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3068 return Error(ID.Loc, "invalid empty array initializer");
3069 V = UndefValue::get(Ty);
3072 // FIXME: LabelTy should not be a first-class type.
3073 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3074 return Error(ID.Loc, "invalid type for null constant");
3075 V = Constant::getNullValue(Ty);
3077 case ValID::t_Constant:
3078 if (ID.ConstantVal->getType() != Ty)
3079 return Error(ID.Loc, "constant expression type mismatch");
3083 case ValID::t_ConstantStruct:
3084 case ValID::t_PackedConstantStruct:
3085 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3086 if (ST->getNumElements() != ID.UIntVal)
3087 return Error(ID.Loc,
3088 "initializer with struct type has wrong # elements");
3089 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3090 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3092 // Verify that the elements are compatible with the structtype.
3093 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3094 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3095 return Error(ID.Loc, "element " + Twine(i) +
3096 " of struct initializer doesn't match struct element type");
3098 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3101 return Error(ID.Loc, "constant expression type mismatch");
3104 llvm_unreachable("Invalid ValID");
3107 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3110 return ParseValID(ID, PFS) ||
3111 ConvertValIDToValue(Ty, ID, V, PFS);
3114 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3116 return ParseType(Ty) ||
3117 ParseValue(Ty, V, PFS);
3120 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3121 PerFunctionState &PFS) {
3124 if (ParseTypeAndValue(V, PFS)) return true;
3125 if (!isa<BasicBlock>(V))
3126 return Error(Loc, "expected a basic block");
3127 BB = cast<BasicBlock>(V);
3133 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3134 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3135 /// OptionalAlign OptGC OptionalPrefix
3136 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3137 // Parse the linkage.
3138 LocTy LinkageLoc = Lex.getLoc();
3141 unsigned Visibility;
3142 unsigned DLLStorageClass;
3143 AttrBuilder RetAttrs;
3145 Type *RetType = nullptr;
3146 LocTy RetTypeLoc = Lex.getLoc();
3147 if (ParseOptionalLinkage(Linkage) ||
3148 ParseOptionalVisibility(Visibility) ||
3149 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3150 ParseOptionalCallingConv(CC) ||
3151 ParseOptionalReturnAttrs(RetAttrs) ||
3152 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3155 // Verify that the linkage is ok.
3156 switch ((GlobalValue::LinkageTypes)Linkage) {
3157 case GlobalValue::ExternalLinkage:
3158 break; // always ok.
3159 case GlobalValue::ExternalWeakLinkage:
3161 return Error(LinkageLoc, "invalid linkage for function definition");
3163 case GlobalValue::PrivateLinkage:
3164 case GlobalValue::InternalLinkage:
3165 case GlobalValue::AvailableExternallyLinkage:
3166 case GlobalValue::LinkOnceAnyLinkage:
3167 case GlobalValue::LinkOnceODRLinkage:
3168 case GlobalValue::WeakAnyLinkage:
3169 case GlobalValue::WeakODRLinkage:
3171 return Error(LinkageLoc, "invalid linkage for function declaration");
3173 case GlobalValue::AppendingLinkage:
3174 case GlobalValue::CommonLinkage:
3175 return Error(LinkageLoc, "invalid function linkage type");
3178 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3179 return Error(LinkageLoc,
3180 "symbol with local linkage must have default visibility");
3182 if (!FunctionType::isValidReturnType(RetType))
3183 return Error(RetTypeLoc, "invalid function return type");
3185 LocTy NameLoc = Lex.getLoc();
3187 std::string FunctionName;
3188 if (Lex.getKind() == lltok::GlobalVar) {
3189 FunctionName = Lex.getStrVal();
3190 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3191 unsigned NameID = Lex.getUIntVal();
3193 if (NameID != NumberedVals.size())
3194 return TokError("function expected to be numbered '%" +
3195 Twine(NumberedVals.size()) + "'");
3197 return TokError("expected function name");
3202 if (Lex.getKind() != lltok::lparen)
3203 return TokError("expected '(' in function argument list");
3205 SmallVector<ArgInfo, 8> ArgList;
3207 AttrBuilder FuncAttrs;
3208 std::vector<unsigned> FwdRefAttrGrps;
3210 std::string Section;
3214 LocTy UnnamedAddrLoc;
3215 Constant *Prefix = nullptr;
3218 if (ParseArgumentList(ArgList, isVarArg) ||
3219 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3221 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3223 (EatIfPresent(lltok::kw_section) &&
3224 ParseStringConstant(Section)) ||
3225 parseOptionalComdat(C) ||
3226 ParseOptionalAlignment(Alignment) ||
3227 (EatIfPresent(lltok::kw_gc) &&
3228 ParseStringConstant(GC)) ||
3229 (EatIfPresent(lltok::kw_prefix) &&
3230 ParseGlobalTypeAndValue(Prefix)))
3233 if (FuncAttrs.contains(Attribute::Builtin))
3234 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3236 // If the alignment was parsed as an attribute, move to the alignment field.
3237 if (FuncAttrs.hasAlignmentAttr()) {
3238 Alignment = FuncAttrs.getAlignment();
3239 FuncAttrs.removeAttribute(Attribute::Alignment);
3242 // Okay, if we got here, the function is syntactically valid. Convert types
3243 // and do semantic checks.
3244 std::vector<Type*> ParamTypeList;
3245 SmallVector<AttributeSet, 8> Attrs;
3247 if (RetAttrs.hasAttributes())
3248 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3249 AttributeSet::ReturnIndex,
3252 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3253 ParamTypeList.push_back(ArgList[i].Ty);
3254 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3255 AttrBuilder B(ArgList[i].Attrs, i + 1);
3256 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3260 if (FuncAttrs.hasAttributes())
3261 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3262 AttributeSet::FunctionIndex,
3265 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3267 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3268 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3271 FunctionType::get(RetType, ParamTypeList, isVarArg);
3272 PointerType *PFT = PointerType::getUnqual(FT);
3275 if (!FunctionName.empty()) {
3276 // If this was a definition of a forward reference, remove the definition
3277 // from the forward reference table and fill in the forward ref.
3278 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3279 ForwardRefVals.find(FunctionName);
3280 if (FRVI != ForwardRefVals.end()) {
3281 Fn = M->getFunction(FunctionName);
3283 return Error(FRVI->second.second, "invalid forward reference to "
3284 "function as global value!");
3285 if (Fn->getType() != PFT)
3286 return Error(FRVI->second.second, "invalid forward reference to "
3287 "function '" + FunctionName + "' with wrong type!");
3289 ForwardRefVals.erase(FRVI);
3290 } else if ((Fn = M->getFunction(FunctionName))) {
3291 // Reject redefinitions.
3292 return Error(NameLoc, "invalid redefinition of function '" +
3293 FunctionName + "'");
3294 } else if (M->getNamedValue(FunctionName)) {
3295 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3299 // If this is a definition of a forward referenced function, make sure the
3301 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3302 = ForwardRefValIDs.find(NumberedVals.size());
3303 if (I != ForwardRefValIDs.end()) {
3304 Fn = cast<Function>(I->second.first);
3305 if (Fn->getType() != PFT)
3306 return Error(NameLoc, "type of definition and forward reference of '@" +
3307 Twine(NumberedVals.size()) + "' disagree");
3308 ForwardRefValIDs.erase(I);
3313 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3314 else // Move the forward-reference to the correct spot in the module.
3315 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3317 if (FunctionName.empty())
3318 NumberedVals.push_back(Fn);
3320 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3321 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3322 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3323 Fn->setCallingConv(CC);
3324 Fn->setAttributes(PAL);
3325 Fn->setUnnamedAddr(UnnamedAddr);
3326 Fn->setAlignment(Alignment);
3327 Fn->setSection(Section);
3329 if (!GC.empty()) Fn->setGC(GC.c_str());
3330 Fn->setPrefixData(Prefix);
3331 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3333 // Add all of the arguments we parsed to the function.
3334 Function::arg_iterator ArgIt = Fn->arg_begin();
3335 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3336 // If the argument has a name, insert it into the argument symbol table.
3337 if (ArgList[i].Name.empty()) continue;
3339 // Set the name, if it conflicted, it will be auto-renamed.
3340 ArgIt->setName(ArgList[i].Name);
3342 if (ArgIt->getName() != ArgList[i].Name)
3343 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3344 ArgList[i].Name + "'");
3351 /// ParseFunctionBody
3352 /// ::= '{' BasicBlock+ '}'
3354 bool LLParser::ParseFunctionBody(Function &Fn) {
3355 if (Lex.getKind() != lltok::lbrace)
3356 return TokError("expected '{' in function body");
3357 Lex.Lex(); // eat the {.
3359 int FunctionNumber = -1;
3360 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3362 PerFunctionState PFS(*this, Fn, FunctionNumber);
3364 // We need at least one basic block.
3365 if (Lex.getKind() == lltok::rbrace)
3366 return TokError("function body requires at least one basic block");
3368 while (Lex.getKind() != lltok::rbrace)
3369 if (ParseBasicBlock(PFS)) return true;
3374 // Verify function is ok.
3375 return PFS.FinishFunction();
3379 /// ::= LabelStr? Instruction*
3380 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3381 // If this basic block starts out with a name, remember it.
3383 LocTy NameLoc = Lex.getLoc();
3384 if (Lex.getKind() == lltok::LabelStr) {
3385 Name = Lex.getStrVal();
3389 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3390 if (!BB) return true;
3392 std::string NameStr;
3394 // Parse the instructions in this block until we get a terminator.
3397 // This instruction may have three possibilities for a name: a) none
3398 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3399 LocTy NameLoc = Lex.getLoc();
3403 if (Lex.getKind() == lltok::LocalVarID) {
3404 NameID = Lex.getUIntVal();
3406 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3408 } else if (Lex.getKind() == lltok::LocalVar) {
3409 NameStr = Lex.getStrVal();
3411 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3415 switch (ParseInstruction(Inst, BB, PFS)) {
3416 default: llvm_unreachable("Unknown ParseInstruction result!");
3417 case InstError: return true;
3419 BB->getInstList().push_back(Inst);
3421 // With a normal result, we check to see if the instruction is followed by
3422 // a comma and metadata.
3423 if (EatIfPresent(lltok::comma))
3424 if (ParseInstructionMetadata(Inst, &PFS))
3427 case InstExtraComma:
3428 BB->getInstList().push_back(Inst);
3430 // If the instruction parser ate an extra comma at the end of it, it
3431 // *must* be followed by metadata.
3432 if (ParseInstructionMetadata(Inst, &PFS))
3437 // Set the name on the instruction.
3438 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3439 } while (!isa<TerminatorInst>(Inst));
3444 //===----------------------------------------------------------------------===//
3445 // Instruction Parsing.
3446 //===----------------------------------------------------------------------===//
3448 /// ParseInstruction - Parse one of the many different instructions.
3450 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3451 PerFunctionState &PFS) {
3452 lltok::Kind Token = Lex.getKind();
3453 if (Token == lltok::Eof)
3454 return TokError("found end of file when expecting more instructions");
3455 LocTy Loc = Lex.getLoc();
3456 unsigned KeywordVal = Lex.getUIntVal();
3457 Lex.Lex(); // Eat the keyword.
3460 default: return Error(Loc, "expected instruction opcode");
3461 // Terminator Instructions.
3462 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3463 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3464 case lltok::kw_br: return ParseBr(Inst, PFS);
3465 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3466 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3467 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3468 case lltok::kw_resume: return ParseResume(Inst, PFS);
3469 // Binary Operators.
3473 case lltok::kw_shl: {
3474 bool NUW = EatIfPresent(lltok::kw_nuw);
3475 bool NSW = EatIfPresent(lltok::kw_nsw);
3476 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3478 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3480 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3481 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3484 case lltok::kw_fadd:
3485 case lltok::kw_fsub:
3486 case lltok::kw_fmul:
3487 case lltok::kw_fdiv:
3488 case lltok::kw_frem: {
3489 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3490 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3494 Inst->setFastMathFlags(FMF);
3498 case lltok::kw_sdiv:
3499 case lltok::kw_udiv:
3500 case lltok::kw_lshr:
3501 case lltok::kw_ashr: {
3502 bool Exact = EatIfPresent(lltok::kw_exact);
3504 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3505 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3509 case lltok::kw_urem:
3510 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3513 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3514 case lltok::kw_icmp:
3515 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3517 case lltok::kw_trunc:
3518 case lltok::kw_zext:
3519 case lltok::kw_sext:
3520 case lltok::kw_fptrunc:
3521 case lltok::kw_fpext:
3522 case lltok::kw_bitcast:
3523 case lltok::kw_addrspacecast:
3524 case lltok::kw_uitofp:
3525 case lltok::kw_sitofp:
3526 case lltok::kw_fptoui:
3527 case lltok::kw_fptosi:
3528 case lltok::kw_inttoptr:
3529 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3531 case lltok::kw_select: return ParseSelect(Inst, PFS);
3532 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3533 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3534 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3535 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3536 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3537 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3539 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3540 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3541 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3543 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3544 case lltok::kw_load: return ParseLoad(Inst, PFS);
3545 case lltok::kw_store: return ParseStore(Inst, PFS);
3546 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3547 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3548 case lltok::kw_fence: return ParseFence(Inst, PFS);
3549 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3550 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3551 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3555 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3556 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3557 if (Opc == Instruction::FCmp) {
3558 switch (Lex.getKind()) {
3559 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3560 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3561 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3562 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3563 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3564 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3565 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3566 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3567 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3568 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3569 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3570 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3571 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3572 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3573 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3574 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3575 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3578 switch (Lex.getKind()) {
3579 default: return TokError("expected icmp predicate (e.g. 'eq')");
3580 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3581 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3582 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3583 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3584 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3585 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3586 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3587 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3588 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3589 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3596 //===----------------------------------------------------------------------===//
3597 // Terminator Instructions.
3598 //===----------------------------------------------------------------------===//
3600 /// ParseRet - Parse a return instruction.
3601 /// ::= 'ret' void (',' !dbg, !1)*
3602 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3603 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3604 PerFunctionState &PFS) {
3605 SMLoc TypeLoc = Lex.getLoc();
3607 if (ParseType(Ty, true /*void allowed*/)) return true;
3609 Type *ResType = PFS.getFunction().getReturnType();
3611 if (Ty->isVoidTy()) {
3612 if (!ResType->isVoidTy())
3613 return Error(TypeLoc, "value doesn't match function result type '" +
3614 getTypeString(ResType) + "'");
3616 Inst = ReturnInst::Create(Context);
3621 if (ParseValue(Ty, RV, PFS)) return true;
3623 if (ResType != RV->getType())
3624 return Error(TypeLoc, "value doesn't match function result type '" +
3625 getTypeString(ResType) + "'");
3627 Inst = ReturnInst::Create(Context, RV);
3633 /// ::= 'br' TypeAndValue
3634 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3635 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3638 BasicBlock *Op1, *Op2;
3639 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3641 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3642 Inst = BranchInst::Create(BB);
3646 if (Op0->getType() != Type::getInt1Ty(Context))
3647 return Error(Loc, "branch condition must have 'i1' type");
3649 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3650 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3651 ParseToken(lltok::comma, "expected ',' after true destination") ||
3652 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3655 Inst = BranchInst::Create(Op1, Op2, Op0);
3661 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3663 /// ::= (TypeAndValue ',' TypeAndValue)*
3664 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3665 LocTy CondLoc, BBLoc;
3667 BasicBlock *DefaultBB;
3668 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3669 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3670 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3671 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3674 if (!Cond->getType()->isIntegerTy())
3675 return Error(CondLoc, "switch condition must have integer type");
3677 // Parse the jump table pairs.
3678 SmallPtrSet<Value*, 32> SeenCases;
3679 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3680 while (Lex.getKind() != lltok::rsquare) {
3684 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3685 ParseToken(lltok::comma, "expected ',' after case value") ||
3686 ParseTypeAndBasicBlock(DestBB, PFS))
3689 if (!SeenCases.insert(Constant))
3690 return Error(CondLoc, "duplicate case value in switch");
3691 if (!isa<ConstantInt>(Constant))
3692 return Error(CondLoc, "case value is not a constant integer");
3694 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3697 Lex.Lex(); // Eat the ']'.
3699 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3700 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3701 SI->addCase(Table[i].first, Table[i].second);
3708 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3709 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3712 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3713 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3714 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3717 if (!Address->getType()->isPointerTy())
3718 return Error(AddrLoc, "indirectbr address must have pointer type");
3720 // Parse the destination list.
3721 SmallVector<BasicBlock*, 16> DestList;
3723 if (Lex.getKind() != lltok::rsquare) {
3725 if (ParseTypeAndBasicBlock(DestBB, PFS))
3727 DestList.push_back(DestBB);
3729 while (EatIfPresent(lltok::comma)) {
3730 if (ParseTypeAndBasicBlock(DestBB, PFS))
3732 DestList.push_back(DestBB);
3736 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3739 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3740 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3741 IBI->addDestination(DestList[i]);
3748 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3749 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3750 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3751 LocTy CallLoc = Lex.getLoc();
3752 AttrBuilder RetAttrs, FnAttrs;
3753 std::vector<unsigned> FwdRefAttrGrps;
3756 Type *RetType = nullptr;
3759 SmallVector<ParamInfo, 16> ArgList;
3761 BasicBlock *NormalBB, *UnwindBB;
3762 if (ParseOptionalCallingConv(CC) ||
3763 ParseOptionalReturnAttrs(RetAttrs) ||
3764 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3765 ParseValID(CalleeID) ||
3766 ParseParameterList(ArgList, PFS) ||
3767 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3769 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3770 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3771 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3772 ParseTypeAndBasicBlock(UnwindBB, PFS))
3775 // If RetType is a non-function pointer type, then this is the short syntax
3776 // for the call, which means that RetType is just the return type. Infer the
3777 // rest of the function argument types from the arguments that are present.
3778 PointerType *PFTy = nullptr;
3779 FunctionType *Ty = nullptr;
3780 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3781 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3782 // Pull out the types of all of the arguments...
3783 std::vector<Type*> ParamTypes;
3784 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3785 ParamTypes.push_back(ArgList[i].V->getType());
3787 if (!FunctionType::isValidReturnType(RetType))
3788 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3790 Ty = FunctionType::get(RetType, ParamTypes, false);
3791 PFTy = PointerType::getUnqual(Ty);
3794 // Look up the callee.
3796 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3798 // Set up the Attribute for the function.
3799 SmallVector<AttributeSet, 8> Attrs;
3800 if (RetAttrs.hasAttributes())
3801 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3802 AttributeSet::ReturnIndex,
3805 SmallVector<Value*, 8> Args;
3807 // Loop through FunctionType's arguments and ensure they are specified
3808 // correctly. Also, gather any parameter attributes.
3809 FunctionType::param_iterator I = Ty->param_begin();
3810 FunctionType::param_iterator E = Ty->param_end();
3811 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3812 Type *ExpectedTy = nullptr;
3815 } else if (!Ty->isVarArg()) {
3816 return Error(ArgList[i].Loc, "too many arguments specified");
3819 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3820 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3821 getTypeString(ExpectedTy) + "'");
3822 Args.push_back(ArgList[i].V);
3823 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3824 AttrBuilder B(ArgList[i].Attrs, i + 1);
3825 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3830 return Error(CallLoc, "not enough parameters specified for call");
3832 if (FnAttrs.hasAttributes())
3833 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3834 AttributeSet::FunctionIndex,
3837 // Finish off the Attribute and check them
3838 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3840 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3841 II->setCallingConv(CC);
3842 II->setAttributes(PAL);
3843 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3849 /// ::= 'resume' TypeAndValue
3850 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3851 Value *Exn; LocTy ExnLoc;
3852 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3855 ResumeInst *RI = ResumeInst::Create(Exn);
3860 //===----------------------------------------------------------------------===//
3861 // Binary Operators.
3862 //===----------------------------------------------------------------------===//
3865 /// ::= ArithmeticOps TypeAndValue ',' Value
3867 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3868 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3869 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3870 unsigned Opc, unsigned OperandType) {
3871 LocTy Loc; Value *LHS, *RHS;
3872 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3873 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3874 ParseValue(LHS->getType(), RHS, PFS))
3878 switch (OperandType) {
3879 default: llvm_unreachable("Unknown operand type!");
3880 case 0: // int or FP.
3881 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3882 LHS->getType()->isFPOrFPVectorTy();
3884 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3885 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3889 return Error(Loc, "invalid operand type for instruction");
3891 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3896 /// ::= ArithmeticOps TypeAndValue ',' Value {
3897 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3899 LocTy Loc; Value *LHS, *RHS;
3900 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3901 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3902 ParseValue(LHS->getType(), RHS, PFS))
3905 if (!LHS->getType()->isIntOrIntVectorTy())
3906 return Error(Loc,"instruction requires integer or integer vector operands");
3908 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3914 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3915 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3916 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3918 // Parse the integer/fp comparison predicate.
3922 if (ParseCmpPredicate(Pred, Opc) ||
3923 ParseTypeAndValue(LHS, Loc, PFS) ||
3924 ParseToken(lltok::comma, "expected ',' after compare value") ||
3925 ParseValue(LHS->getType(), RHS, PFS))
3928 if (Opc == Instruction::FCmp) {
3929 if (!LHS->getType()->isFPOrFPVectorTy())
3930 return Error(Loc, "fcmp requires floating point operands");
3931 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3933 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3934 if (!LHS->getType()->isIntOrIntVectorTy() &&
3935 !LHS->getType()->getScalarType()->isPointerTy())
3936 return Error(Loc, "icmp requires integer operands");
3937 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3942 //===----------------------------------------------------------------------===//
3943 // Other Instructions.
3944 //===----------------------------------------------------------------------===//
3948 /// ::= CastOpc TypeAndValue 'to' Type
3949 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3953 Type *DestTy = nullptr;
3954 if (ParseTypeAndValue(Op, Loc, PFS) ||
3955 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3959 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3960 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3961 return Error(Loc, "invalid cast opcode for cast from '" +
3962 getTypeString(Op->getType()) + "' to '" +
3963 getTypeString(DestTy) + "'");
3965 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3970 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3971 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3973 Value *Op0, *Op1, *Op2;
3974 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3975 ParseToken(lltok::comma, "expected ',' after select condition") ||
3976 ParseTypeAndValue(Op1, PFS) ||
3977 ParseToken(lltok::comma, "expected ',' after select value") ||
3978 ParseTypeAndValue(Op2, PFS))
3981 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3982 return Error(Loc, Reason);
3984 Inst = SelectInst::Create(Op0, Op1, Op2);
3989 /// ::= 'va_arg' TypeAndValue ',' Type
3990 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3992 Type *EltTy = nullptr;
3994 if (ParseTypeAndValue(Op, PFS) ||
3995 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3996 ParseType(EltTy, TypeLoc))
3999 if (!EltTy->isFirstClassType())
4000 return Error(TypeLoc, "va_arg requires operand with first class type");
4002 Inst = new VAArgInst(Op, EltTy);
4006 /// ParseExtractElement
4007 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4008 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4011 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4012 ParseToken(lltok::comma, "expected ',' after extract value") ||
4013 ParseTypeAndValue(Op1, PFS))
4016 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4017 return Error(Loc, "invalid extractelement operands");
4019 Inst = ExtractElementInst::Create(Op0, Op1);
4023 /// ParseInsertElement
4024 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4025 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4027 Value *Op0, *Op1, *Op2;
4028 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4029 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4030 ParseTypeAndValue(Op1, PFS) ||
4031 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4032 ParseTypeAndValue(Op2, PFS))
4035 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4036 return Error(Loc, "invalid insertelement operands");
4038 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4042 /// ParseShuffleVector
4043 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4044 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4046 Value *Op0, *Op1, *Op2;
4047 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4048 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4049 ParseTypeAndValue(Op1, PFS) ||
4050 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4051 ParseTypeAndValue(Op2, PFS))
4054 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4055 return Error(Loc, "invalid shufflevector operands");
4057 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4062 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4063 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4064 Type *Ty = nullptr; LocTy TypeLoc;
4067 if (ParseType(Ty, TypeLoc) ||
4068 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4069 ParseValue(Ty, Op0, PFS) ||
4070 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4071 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4072 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4075 bool AteExtraComma = false;
4076 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4078 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4080 if (!EatIfPresent(lltok::comma))
4083 if (Lex.getKind() == lltok::MetadataVar) {
4084 AteExtraComma = true;
4088 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4089 ParseValue(Ty, Op0, PFS) ||
4090 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4091 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4092 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4096 if (!Ty->isFirstClassType())
4097 return Error(TypeLoc, "phi node must have first class type");
4099 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4100 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4101 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4103 return AteExtraComma ? InstExtraComma : InstNormal;
4107 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4109 /// ::= 'catch' TypeAndValue
4111 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4112 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4113 Type *Ty = nullptr; LocTy TyLoc;
4114 Value *PersFn; LocTy PersFnLoc;
4116 if (ParseType(Ty, TyLoc) ||
4117 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4118 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4121 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4122 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4124 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4125 LandingPadInst::ClauseType CT;
4126 if (EatIfPresent(lltok::kw_catch))
4127 CT = LandingPadInst::Catch;
4128 else if (EatIfPresent(lltok::kw_filter))
4129 CT = LandingPadInst::Filter;
4131 return TokError("expected 'catch' or 'filter' clause type");
4135 if (ParseTypeAndValue(V, VLoc, PFS)) {
4140 // A 'catch' type expects a non-array constant. A filter clause expects an
4142 if (CT == LandingPadInst::Catch) {
4143 if (isa<ArrayType>(V->getType()))
4144 Error(VLoc, "'catch' clause has an invalid type");
4146 if (!isa<ArrayType>(V->getType()))
4147 Error(VLoc, "'filter' clause has an invalid type");
4150 LP->addClause(cast<Constant>(V));
4158 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4159 /// ParameterList OptionalAttrs
4160 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4161 /// ParameterList OptionalAttrs
4162 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4163 /// ParameterList OptionalAttrs
4164 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4165 CallInst::TailCallKind TCK) {
4166 AttrBuilder RetAttrs, FnAttrs;
4167 std::vector<unsigned> FwdRefAttrGrps;
4170 Type *RetType = nullptr;
4173 SmallVector<ParamInfo, 16> ArgList;
4174 LocTy CallLoc = Lex.getLoc();
4176 if ((TCK != CallInst::TCK_None &&
4177 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4178 ParseOptionalCallingConv(CC) ||
4179 ParseOptionalReturnAttrs(RetAttrs) ||
4180 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4181 ParseValID(CalleeID) ||
4182 ParseParameterList(ArgList, PFS) ||
4183 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4187 // If RetType is a non-function pointer type, then this is the short syntax
4188 // for the call, which means that RetType is just the return type. Infer the
4189 // rest of the function argument types from the arguments that are present.
4190 PointerType *PFTy = nullptr;
4191 FunctionType *Ty = nullptr;
4192 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4193 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4194 // Pull out the types of all of the arguments...
4195 std::vector<Type*> ParamTypes;
4196 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4197 ParamTypes.push_back(ArgList[i].V->getType());
4199 if (!FunctionType::isValidReturnType(RetType))
4200 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4202 Ty = FunctionType::get(RetType, ParamTypes, false);
4203 PFTy = PointerType::getUnqual(Ty);
4206 // Look up the callee.
4208 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4210 // Set up the Attribute for the function.
4211 SmallVector<AttributeSet, 8> Attrs;
4212 if (RetAttrs.hasAttributes())
4213 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4214 AttributeSet::ReturnIndex,
4217 SmallVector<Value*, 8> Args;
4219 // Loop through FunctionType's arguments and ensure they are specified
4220 // correctly. Also, gather any parameter attributes.
4221 FunctionType::param_iterator I = Ty->param_begin();
4222 FunctionType::param_iterator E = Ty->param_end();
4223 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4224 Type *ExpectedTy = nullptr;
4227 } else if (!Ty->isVarArg()) {
4228 return Error(ArgList[i].Loc, "too many arguments specified");
4231 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4232 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4233 getTypeString(ExpectedTy) + "'");
4234 Args.push_back(ArgList[i].V);
4235 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4236 AttrBuilder B(ArgList[i].Attrs, i + 1);
4237 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4242 return Error(CallLoc, "not enough parameters specified for call");
4244 if (FnAttrs.hasAttributes())
4245 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4246 AttributeSet::FunctionIndex,
4249 // Finish off the Attribute and check them
4250 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4252 CallInst *CI = CallInst::Create(Callee, Args);
4253 CI->setTailCallKind(TCK);
4254 CI->setCallingConv(CC);
4255 CI->setAttributes(PAL);
4256 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4261 //===----------------------------------------------------------------------===//
4262 // Memory Instructions.
4263 //===----------------------------------------------------------------------===//
4266 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4267 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4268 Value *Size = nullptr;
4270 unsigned Alignment = 0;
4273 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4275 if (ParseType(Ty)) return true;
4277 bool AteExtraComma = false;
4278 if (EatIfPresent(lltok::comma)) {
4279 if (Lex.getKind() == lltok::kw_align) {
4280 if (ParseOptionalAlignment(Alignment)) return true;
4281 } else if (Lex.getKind() == lltok::MetadataVar) {
4282 AteExtraComma = true;
4284 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4285 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4290 if (Size && !Size->getType()->isIntegerTy())
4291 return Error(SizeLoc, "element count must have integer type");
4293 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4294 AI->setUsedWithInAlloca(IsInAlloca);
4296 return AteExtraComma ? InstExtraComma : InstNormal;
4300 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4301 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4302 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4303 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4304 Value *Val; LocTy Loc;
4305 unsigned Alignment = 0;
4306 bool AteExtraComma = false;
4307 bool isAtomic = false;
4308 AtomicOrdering Ordering = NotAtomic;
4309 SynchronizationScope Scope = CrossThread;
4311 if (Lex.getKind() == lltok::kw_atomic) {
4316 bool isVolatile = false;
4317 if (Lex.getKind() == lltok::kw_volatile) {
4322 if (ParseTypeAndValue(Val, Loc, PFS) ||
4323 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4324 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4327 if (!Val->getType()->isPointerTy() ||
4328 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4329 return Error(Loc, "load operand must be a pointer to a first class type");
4330 if (isAtomic && !Alignment)
4331 return Error(Loc, "atomic load must have explicit non-zero alignment");
4332 if (Ordering == Release || Ordering == AcquireRelease)
4333 return Error(Loc, "atomic load cannot use Release ordering");
4335 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4336 return AteExtraComma ? InstExtraComma : InstNormal;
4341 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4342 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4343 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4344 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4345 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4346 unsigned Alignment = 0;
4347 bool AteExtraComma = false;
4348 bool isAtomic = false;
4349 AtomicOrdering Ordering = NotAtomic;
4350 SynchronizationScope Scope = CrossThread;
4352 if (Lex.getKind() == lltok::kw_atomic) {
4357 bool isVolatile = false;
4358 if (Lex.getKind() == lltok::kw_volatile) {
4363 if (ParseTypeAndValue(Val, Loc, PFS) ||
4364 ParseToken(lltok::comma, "expected ',' after store operand") ||
4365 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4366 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4367 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4370 if (!Ptr->getType()->isPointerTy())
4371 return Error(PtrLoc, "store operand must be a pointer");
4372 if (!Val->getType()->isFirstClassType())
4373 return Error(Loc, "store operand must be a first class value");
4374 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4375 return Error(Loc, "stored value and pointer type do not match");
4376 if (isAtomic && !Alignment)
4377 return Error(Loc, "atomic store must have explicit non-zero alignment");
4378 if (Ordering == Acquire || Ordering == AcquireRelease)
4379 return Error(Loc, "atomic store cannot use Acquire ordering");
4381 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4382 return AteExtraComma ? InstExtraComma : InstNormal;
4386 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4387 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4388 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4389 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4390 bool AteExtraComma = false;
4391 AtomicOrdering SuccessOrdering = NotAtomic;
4392 AtomicOrdering FailureOrdering = NotAtomic;
4393 SynchronizationScope Scope = CrossThread;
4394 bool isVolatile = false;
4395 bool isWeak = false;
4397 if (EatIfPresent(lltok::kw_weak))
4400 if (EatIfPresent(lltok::kw_volatile))
4403 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4404 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4405 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4406 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4407 ParseTypeAndValue(New, NewLoc, PFS) ||
4408 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4409 ParseOrdering(FailureOrdering))
4412 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4413 return TokError("cmpxchg cannot be unordered");
4414 if (SuccessOrdering < FailureOrdering)
4415 return TokError("cmpxchg must be at least as ordered on success as failure");
4416 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4417 return TokError("cmpxchg failure ordering cannot include release semantics");
4418 if (!Ptr->getType()->isPointerTy())
4419 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4420 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4421 return Error(CmpLoc, "compare value and pointer type do not match");
4422 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4423 return Error(NewLoc, "new value and pointer type do not match");
4424 if (!New->getType()->isIntegerTy())
4425 return Error(NewLoc, "cmpxchg operand must be an integer");
4426 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4427 if (Size < 8 || (Size & (Size - 1)))
4428 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4431 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4432 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4433 CXI->setVolatile(isVolatile);
4434 CXI->setWeak(isWeak);
4436 return AteExtraComma ? InstExtraComma : InstNormal;
4440 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4441 /// 'singlethread'? AtomicOrdering
4442 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4443 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4444 bool AteExtraComma = false;
4445 AtomicOrdering Ordering = NotAtomic;
4446 SynchronizationScope Scope = CrossThread;
4447 bool isVolatile = false;
4448 AtomicRMWInst::BinOp Operation;
4450 if (EatIfPresent(lltok::kw_volatile))
4453 switch (Lex.getKind()) {
4454 default: return TokError("expected binary operation in atomicrmw");
4455 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4456 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4457 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4458 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4459 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4460 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4461 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4462 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4463 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4464 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4465 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4467 Lex.Lex(); // Eat the operation.
4469 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4470 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4471 ParseTypeAndValue(Val, ValLoc, PFS) ||
4472 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4475 if (Ordering == Unordered)
4476 return TokError("atomicrmw cannot be unordered");
4477 if (!Ptr->getType()->isPointerTy())
4478 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4479 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4480 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4481 if (!Val->getType()->isIntegerTy())
4482 return Error(ValLoc, "atomicrmw operand must be an integer");
4483 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4484 if (Size < 8 || (Size & (Size - 1)))
4485 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4488 AtomicRMWInst *RMWI =
4489 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4490 RMWI->setVolatile(isVolatile);
4492 return AteExtraComma ? InstExtraComma : InstNormal;
4496 /// ::= 'fence' 'singlethread'? AtomicOrdering
4497 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4498 AtomicOrdering Ordering = NotAtomic;
4499 SynchronizationScope Scope = CrossThread;
4500 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4503 if (Ordering == Unordered)
4504 return TokError("fence cannot be unordered");
4505 if (Ordering == Monotonic)
4506 return TokError("fence cannot be monotonic");
4508 Inst = new FenceInst(Context, Ordering, Scope);
4512 /// ParseGetElementPtr
4513 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4514 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4515 Value *Ptr = nullptr;
4516 Value *Val = nullptr;
4519 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4521 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4523 Type *BaseType = Ptr->getType();
4524 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4525 if (!BasePointerType)
4526 return Error(Loc, "base of getelementptr must be a pointer");
4528 SmallVector<Value*, 16> Indices;
4529 bool AteExtraComma = false;
4530 while (EatIfPresent(lltok::comma)) {
4531 if (Lex.getKind() == lltok::MetadataVar) {
4532 AteExtraComma = true;
4535 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4536 if (!Val->getType()->getScalarType()->isIntegerTy())
4537 return Error(EltLoc, "getelementptr index must be an integer");
4538 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4539 return Error(EltLoc, "getelementptr index type missmatch");
4540 if (Val->getType()->isVectorTy()) {
4541 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4542 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4543 if (ValNumEl != PtrNumEl)
4544 return Error(EltLoc,
4545 "getelementptr vector index has a wrong number of elements");
4547 Indices.push_back(Val);
4550 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4551 return Error(Loc, "base element of getelementptr must be sized");
4553 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4554 return Error(Loc, "invalid getelementptr indices");
4555 Inst = GetElementPtrInst::Create(Ptr, Indices);
4557 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4558 return AteExtraComma ? InstExtraComma : InstNormal;
4561 /// ParseExtractValue
4562 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4563 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4564 Value *Val; LocTy Loc;
4565 SmallVector<unsigned, 4> Indices;
4567 if (ParseTypeAndValue(Val, Loc, PFS) ||
4568 ParseIndexList(Indices, AteExtraComma))
4571 if (!Val->getType()->isAggregateType())
4572 return Error(Loc, "extractvalue operand must be aggregate type");
4574 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4575 return Error(Loc, "invalid indices for extractvalue");
4576 Inst = ExtractValueInst::Create(Val, Indices);
4577 return AteExtraComma ? InstExtraComma : InstNormal;
4580 /// ParseInsertValue
4581 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4582 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4583 Value *Val0, *Val1; LocTy Loc0, Loc1;
4584 SmallVector<unsigned, 4> Indices;
4586 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4587 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4588 ParseTypeAndValue(Val1, Loc1, PFS) ||
4589 ParseIndexList(Indices, AteExtraComma))
4592 if (!Val0->getType()->isAggregateType())
4593 return Error(Loc0, "insertvalue operand must be aggregate type");
4595 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4596 return Error(Loc0, "invalid indices for insertvalue");
4597 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4598 return AteExtraComma ? InstExtraComma : InstNormal;
4601 //===----------------------------------------------------------------------===//
4602 // Embedded metadata.
4603 //===----------------------------------------------------------------------===//
4605 /// ParseMDNodeVector
4606 /// ::= Element (',' Element)*
4608 /// ::= 'null' | TypeAndValue
4609 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4610 PerFunctionState *PFS) {
4611 // Check for an empty list.
4612 if (Lex.getKind() == lltok::rbrace)
4616 // Null is a special case since it is typeless.
4617 if (EatIfPresent(lltok::kw_null)) {
4618 Elts.push_back(nullptr);
4623 if (ParseTypeAndValue(V, PFS)) return true;
4625 } while (EatIfPresent(lltok::comma));