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/SaveAndRestore.h"
28 #include "llvm/Support/raw_ostream.h"
31 static std::string getTypeString(Type *T) {
33 raw_string_ostream Tmp(Result);
38 /// Run: module ::= toplevelentity*
39 bool LLParser::Run() {
43 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
47 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
49 bool LLParser::ValidateEndOfModule() {
50 // Handle any instruction metadata forward references.
51 if (!ForwardRefInstMetadata.empty()) {
52 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
53 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
55 Instruction *Inst = I->first;
56 const std::vector<MDRef> &MDList = I->second;
58 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
59 unsigned SlotNo = MDList[i].MDSlot;
61 if (SlotNo >= NumberedMetadata.size() ||
62 NumberedMetadata[SlotNo] == nullptr)
63 return Error(MDList[i].Loc, "use of undefined metadata '!" +
65 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
68 ForwardRefInstMetadata.clear();
71 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
72 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
74 // Handle any function attribute group forward references.
75 for (std::map<Value*, std::vector<unsigned> >::iterator
76 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
79 std::vector<unsigned> &Vec = I->second;
82 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
84 B.merge(NumberedAttrBuilders[*VI]);
86 if (Function *Fn = dyn_cast<Function>(V)) {
87 AttributeSet AS = Fn->getAttributes();
88 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
89 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
90 AS.getFnAttributes());
94 // If the alignment was parsed as an attribute, move to the alignment
96 if (FnAttrs.hasAlignmentAttr()) {
97 Fn->setAlignment(FnAttrs.getAlignment());
98 FnAttrs.removeAttribute(Attribute::Alignment);
101 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
102 AttributeSet::get(Context,
103 AttributeSet::FunctionIndex,
105 Fn->setAttributes(AS);
106 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
107 AttributeSet AS = CI->getAttributes();
108 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
109 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
110 AS.getFnAttributes());
112 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
113 AttributeSet::get(Context,
114 AttributeSet::FunctionIndex,
116 CI->setAttributes(AS);
117 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
118 AttributeSet AS = II->getAttributes();
119 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
120 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
121 AS.getFnAttributes());
123 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
124 AttributeSet::get(Context,
125 AttributeSet::FunctionIndex,
127 II->setAttributes(AS);
129 llvm_unreachable("invalid object with forward attribute group reference");
133 // If there are entries in ForwardRefBlockAddresses at this point, the
134 // function was never defined.
135 if (!ForwardRefBlockAddresses.empty())
136 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
137 "expected function name in blockaddress");
139 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
140 if (NumberedTypes[i].second.isValid())
141 return Error(NumberedTypes[i].second,
142 "use of undefined type '%" + Twine(i) + "'");
144 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
145 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
146 if (I->second.second.isValid())
147 return Error(I->second.second,
148 "use of undefined type named '" + I->getKey() + "'");
150 if (!ForwardRefComdats.empty())
151 return Error(ForwardRefComdats.begin()->second,
152 "use of undefined comdat '$" +
153 ForwardRefComdats.begin()->first + "'");
155 if (!ForwardRefVals.empty())
156 return Error(ForwardRefVals.begin()->second.second,
157 "use of undefined value '@" + ForwardRefVals.begin()->first +
160 if (!ForwardRefValIDs.empty())
161 return Error(ForwardRefValIDs.begin()->second.second,
162 "use of undefined value '@" +
163 Twine(ForwardRefValIDs.begin()->first) + "'");
165 if (!ForwardRefMDNodes.empty())
166 return Error(ForwardRefMDNodes.begin()->second.second,
167 "use of undefined metadata '!" +
168 Twine(ForwardRefMDNodes.begin()->first) + "'");
171 // Look for intrinsic functions and CallInst that need to be upgraded
172 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
173 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
175 UpgradeDebugInfo(*M);
180 //===----------------------------------------------------------------------===//
181 // Top-Level Entities
182 //===----------------------------------------------------------------------===//
184 bool LLParser::ParseTopLevelEntities() {
186 switch (Lex.getKind()) {
187 default: return TokError("expected top-level entity");
188 case lltok::Eof: return false;
189 case lltok::kw_declare: if (ParseDeclare()) return true; break;
190 case lltok::kw_define: if (ParseDefine()) return true; break;
191 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
192 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
193 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
194 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
195 case lltok::LocalVar: if (ParseNamedType()) return true; break;
196 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
197 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
198 case lltok::ComdatVar: if (parseComdat()) return true; break;
199 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
200 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
202 // The Global variable production with no name can have many different
203 // optional leading prefixes, the production is:
204 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
205 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
206 // ('constant'|'global') ...
207 case lltok::kw_private: // OptionalLinkage
208 case lltok::kw_internal: // OptionalLinkage
209 case lltok::kw_weak: // OptionalLinkage
210 case lltok::kw_weak_odr: // OptionalLinkage
211 case lltok::kw_linkonce: // OptionalLinkage
212 case lltok::kw_linkonce_odr: // OptionalLinkage
213 case lltok::kw_appending: // OptionalLinkage
214 case lltok::kw_common: // OptionalLinkage
215 case lltok::kw_extern_weak: // OptionalLinkage
216 case lltok::kw_external: // OptionalLinkage
217 case lltok::kw_default: // OptionalVisibility
218 case lltok::kw_hidden: // OptionalVisibility
219 case lltok::kw_protected: // OptionalVisibility
220 case lltok::kw_dllimport: // OptionalDLLStorageClass
221 case lltok::kw_dllexport: // OptionalDLLStorageClass
222 case lltok::kw_thread_local: // OptionalThreadLocal
223 case lltok::kw_addrspace: // OptionalAddrSpace
224 case lltok::kw_constant: // GlobalType
225 case lltok::kw_global: { // GlobalType
226 unsigned Linkage, Visibility, DLLStorageClass;
228 GlobalVariable::ThreadLocalMode TLM;
230 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
231 ParseOptionalVisibility(Visibility) ||
232 ParseOptionalDLLStorageClass(DLLStorageClass) ||
233 ParseOptionalThreadLocal(TLM) ||
234 parseOptionalUnnamedAddr(UnnamedAddr) ||
235 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
236 DLLStorageClass, TLM, UnnamedAddr))
241 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
248 /// ::= 'module' 'asm' STRINGCONSTANT
249 bool LLParser::ParseModuleAsm() {
250 assert(Lex.getKind() == lltok::kw_module);
254 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
255 ParseStringConstant(AsmStr)) return true;
257 M->appendModuleInlineAsm(AsmStr);
262 /// ::= 'target' 'triple' '=' STRINGCONSTANT
263 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
264 bool LLParser::ParseTargetDefinition() {
265 assert(Lex.getKind() == lltok::kw_target);
268 default: return TokError("unknown target property");
269 case lltok::kw_triple:
271 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
272 ParseStringConstant(Str))
274 M->setTargetTriple(Str);
276 case lltok::kw_datalayout:
278 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
279 ParseStringConstant(Str))
281 M->setDataLayout(Str);
287 /// ::= 'deplibs' '=' '[' ']'
288 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
289 /// FIXME: Remove in 4.0. Currently parse, but ignore.
290 bool LLParser::ParseDepLibs() {
291 assert(Lex.getKind() == lltok::kw_deplibs);
293 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
294 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
297 if (EatIfPresent(lltok::rsquare))
302 if (ParseStringConstant(Str)) return true;
303 } while (EatIfPresent(lltok::comma));
305 return ParseToken(lltok::rsquare, "expected ']' at end of list");
308 /// ParseUnnamedType:
309 /// ::= LocalVarID '=' 'type' type
310 bool LLParser::ParseUnnamedType() {
311 LocTy TypeLoc = Lex.getLoc();
312 unsigned TypeID = Lex.getUIntVal();
313 Lex.Lex(); // eat LocalVarID;
315 if (ParseToken(lltok::equal, "expected '=' after name") ||
316 ParseToken(lltok::kw_type, "expected 'type' after '='"))
319 if (TypeID >= NumberedTypes.size())
320 NumberedTypes.resize(TypeID+1);
322 Type *Result = nullptr;
323 if (ParseStructDefinition(TypeLoc, "",
324 NumberedTypes[TypeID], Result)) return true;
326 if (!isa<StructType>(Result)) {
327 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
329 return Error(TypeLoc, "non-struct types may not be recursive");
330 Entry.first = Result;
331 Entry.second = SMLoc();
339 /// ::= LocalVar '=' 'type' type
340 bool LLParser::ParseNamedType() {
341 std::string Name = Lex.getStrVal();
342 LocTy NameLoc = Lex.getLoc();
343 Lex.Lex(); // eat LocalVar.
345 if (ParseToken(lltok::equal, "expected '=' after name") ||
346 ParseToken(lltok::kw_type, "expected 'type' after name"))
349 Type *Result = nullptr;
350 if (ParseStructDefinition(NameLoc, Name,
351 NamedTypes[Name], Result)) return true;
353 if (!isa<StructType>(Result)) {
354 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
356 return Error(NameLoc, "non-struct types may not be recursive");
357 Entry.first = Result;
358 Entry.second = SMLoc();
366 /// ::= 'declare' FunctionHeader
367 bool LLParser::ParseDeclare() {
368 assert(Lex.getKind() == lltok::kw_declare);
372 return ParseFunctionHeader(F, false);
376 /// ::= 'define' FunctionHeader '{' ...
377 bool LLParser::ParseDefine() {
378 assert(Lex.getKind() == lltok::kw_define);
382 return ParseFunctionHeader(F, true) ||
383 ParseFunctionBody(*F);
389 bool LLParser::ParseGlobalType(bool &IsConstant) {
390 if (Lex.getKind() == lltok::kw_constant)
392 else if (Lex.getKind() == lltok::kw_global)
396 return TokError("expected 'global' or 'constant'");
402 /// ParseUnnamedGlobal:
403 /// OptionalVisibility ALIAS ...
404 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
405 /// ... -> global variable
406 /// GlobalID '=' OptionalVisibility ALIAS ...
407 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
408 /// ... -> global variable
409 bool LLParser::ParseUnnamedGlobal() {
410 unsigned VarID = NumberedVals.size();
412 LocTy NameLoc = Lex.getLoc();
414 // Handle the GlobalID form.
415 if (Lex.getKind() == lltok::GlobalID) {
416 if (Lex.getUIntVal() != VarID)
417 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
419 Lex.Lex(); // eat GlobalID;
421 if (ParseToken(lltok::equal, "expected '=' after name"))
426 unsigned Linkage, Visibility, DLLStorageClass;
427 GlobalVariable::ThreadLocalMode TLM;
429 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
430 ParseOptionalVisibility(Visibility) ||
431 ParseOptionalDLLStorageClass(DLLStorageClass) ||
432 ParseOptionalThreadLocal(TLM) ||
433 parseOptionalUnnamedAddr(UnnamedAddr))
436 if (Lex.getKind() != lltok::kw_alias)
437 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
438 DLLStorageClass, TLM, UnnamedAddr);
439 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
443 /// ParseNamedGlobal:
444 /// GlobalVar '=' OptionalVisibility ALIAS ...
445 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
446 /// ... -> global variable
447 bool LLParser::ParseNamedGlobal() {
448 assert(Lex.getKind() == lltok::GlobalVar);
449 LocTy NameLoc = Lex.getLoc();
450 std::string Name = Lex.getStrVal();
454 unsigned Linkage, Visibility, DLLStorageClass;
455 GlobalVariable::ThreadLocalMode TLM;
457 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
458 ParseOptionalLinkage(Linkage, HasLinkage) ||
459 ParseOptionalVisibility(Visibility) ||
460 ParseOptionalDLLStorageClass(DLLStorageClass) ||
461 ParseOptionalThreadLocal(TLM) ||
462 parseOptionalUnnamedAddr(UnnamedAddr))
465 if (Lex.getKind() != lltok::kw_alias)
466 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
467 DLLStorageClass, TLM, UnnamedAddr);
469 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
473 bool LLParser::parseComdat() {
474 assert(Lex.getKind() == lltok::ComdatVar);
475 std::string Name = Lex.getStrVal();
476 LocTy NameLoc = Lex.getLoc();
479 if (ParseToken(lltok::equal, "expected '=' here"))
482 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
483 return TokError("expected comdat type");
485 Comdat::SelectionKind SK;
486 switch (Lex.getKind()) {
488 return TokError("unknown selection kind");
492 case lltok::kw_exactmatch:
493 SK = Comdat::ExactMatch;
495 case lltok::kw_largest:
496 SK = Comdat::Largest;
498 case lltok::kw_noduplicates:
499 SK = Comdat::NoDuplicates;
501 case lltok::kw_samesize:
502 SK = Comdat::SameSize;
507 // See if the comdat was forward referenced, if so, use the comdat.
508 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
509 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
510 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
511 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
514 if (I != ComdatSymTab.end())
517 C = M->getOrInsertComdat(Name);
518 C->setSelectionKind(SK);
524 // ::= '!' STRINGCONSTANT
525 bool LLParser::ParseMDString(MDString *&Result) {
527 if (ParseStringConstant(Str)) return true;
528 llvm::UpgradeMDStringConstant(Str);
529 Result = MDString::get(Context, Str);
534 // ::= '!' MDNodeNumber
536 /// This version of ParseMDNodeID returns the slot number and null in the case
537 /// of a forward reference.
538 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
539 // !{ ..., !42, ... }
540 if (ParseUInt32(SlotNo)) return true;
542 // Check existing MDNode.
543 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
544 Result = NumberedMetadata[SlotNo];
550 bool LLParser::ParseMDNodeID(MDNode *&Result) {
551 // !{ ..., !42, ... }
553 if (ParseMDNodeID(Result, MID)) return true;
555 // If not a forward reference, just return it now.
556 if (Result) return false;
558 // Otherwise, create MDNode forward reference.
559 MDNode *FwdNode = MDNode::getTemporary(Context, None);
560 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
562 if (NumberedMetadata.size() <= MID)
563 NumberedMetadata.resize(MID+1);
564 NumberedMetadata[MID] = FwdNode;
569 /// ParseNamedMetadata:
570 /// !foo = !{ !1, !2 }
571 bool LLParser::ParseNamedMetadata() {
572 assert(Lex.getKind() == lltok::MetadataVar);
573 std::string Name = Lex.getStrVal();
576 if (ParseToken(lltok::equal, "expected '=' here") ||
577 ParseToken(lltok::exclaim, "Expected '!' here") ||
578 ParseToken(lltok::lbrace, "Expected '{' here"))
581 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
582 if (Lex.getKind() != lltok::rbrace)
584 if (ParseToken(lltok::exclaim, "Expected '!' here"))
588 if (ParseMDNodeID(N)) return true;
590 } while (EatIfPresent(lltok::comma));
592 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
598 /// ParseStandaloneMetadata:
600 bool LLParser::ParseStandaloneMetadata() {
601 assert(Lex.getKind() == lltok::exclaim);
603 unsigned MetadataID = 0;
607 SmallVector<Value *, 16> Elts;
608 if (ParseUInt32(MetadataID) ||
609 ParseToken(lltok::equal, "expected '=' here") ||
610 ParseType(Ty, TyLoc) ||
611 ParseToken(lltok::exclaim, "Expected '!' here") ||
612 ParseToken(lltok::lbrace, "Expected '{' here") ||
613 ParseMDNodeVector(Elts, nullptr) ||
614 ParseToken(lltok::rbrace, "expected end of metadata node"))
617 MDNode *Init = MDNode::get(Context, Elts);
619 // See if this was forward referenced, if so, handle it.
620 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
621 FI = ForwardRefMDNodes.find(MetadataID);
622 if (FI != ForwardRefMDNodes.end()) {
623 MDNode *Temp = FI->second.first;
624 Temp->replaceAllUsesWith(Init);
625 MDNode::deleteTemporary(Temp);
626 ForwardRefMDNodes.erase(FI);
628 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
630 if (MetadataID >= NumberedMetadata.size())
631 NumberedMetadata.resize(MetadataID+1);
633 if (NumberedMetadata[MetadataID] != nullptr)
634 return TokError("Metadata id is already used");
635 NumberedMetadata[MetadataID] = Init;
641 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
642 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
643 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
647 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
648 /// OptionalDLLStorageClass OptionalThreadLocal
649 /// OptionalUnNammedAddr 'alias' Aliasee
654 /// Everything through OptionalUnNammedAddr has already been parsed.
656 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
657 unsigned Visibility, unsigned DLLStorageClass,
658 GlobalVariable::ThreadLocalMode TLM,
660 assert(Lex.getKind() == lltok::kw_alias);
663 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
665 if(!GlobalAlias::isValidLinkage(Linkage))
666 return Error(NameLoc, "invalid linkage type for alias");
668 if (!isValidVisibilityForLinkage(Visibility, L))
669 return Error(NameLoc,
670 "symbol with local linkage must have default visibility");
673 LocTy AliaseeLoc = Lex.getLoc();
674 if (Lex.getKind() != lltok::kw_bitcast &&
675 Lex.getKind() != lltok::kw_getelementptr &&
676 Lex.getKind() != lltok::kw_addrspacecast &&
677 Lex.getKind() != lltok::kw_inttoptr) {
678 if (ParseGlobalTypeAndValue(Aliasee))
681 // The bitcast dest type is not present, it is implied by the dest type.
685 if (ID.Kind != ValID::t_Constant)
686 return Error(AliaseeLoc, "invalid aliasee");
687 Aliasee = ID.ConstantVal;
690 Type *AliaseeType = Aliasee->getType();
691 auto *PTy = dyn_cast<PointerType>(AliaseeType);
693 return Error(AliaseeLoc, "An alias must have pointer type");
694 Type *Ty = PTy->getElementType();
695 unsigned AddrSpace = PTy->getAddressSpace();
697 // Okay, create the alias but do not insert it into the module yet.
698 std::unique_ptr<GlobalAlias> GA(
699 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
700 Name, Aliasee, /*Parent*/ nullptr));
701 GA->setThreadLocalMode(TLM);
702 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
703 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
704 GA->setUnnamedAddr(UnnamedAddr);
706 // See if this value already exists in the symbol table. If so, it is either
707 // a redefinition or a definition of a forward reference.
708 if (GlobalValue *Val = M->getNamedValue(Name)) {
709 // See if this was a redefinition. If so, there is no entry in
711 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
712 I = ForwardRefVals.find(Name);
713 if (I == ForwardRefVals.end())
714 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
716 // Otherwise, this was a definition of forward ref. Verify that types
718 if (Val->getType() != GA->getType())
719 return Error(NameLoc,
720 "forward reference and definition of alias have different types");
722 // If they agree, just RAUW the old value with the alias and remove the
724 Val->replaceAllUsesWith(GA.get());
725 Val->eraseFromParent();
726 ForwardRefVals.erase(I);
729 // Insert into the module, we know its name won't collide now.
730 M->getAliasList().push_back(GA.get());
731 assert(GA->getName() == Name && "Should not be a name conflict!");
733 // The module owns this now
740 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
741 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
742 /// OptionalExternallyInitialized GlobalType Type Const
743 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
744 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
745 /// OptionalExternallyInitialized GlobalType Type Const
747 /// Everything up to and including OptionalUnNammedAddr has been parsed
750 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
751 unsigned Linkage, bool HasLinkage,
752 unsigned Visibility, unsigned DLLStorageClass,
753 GlobalVariable::ThreadLocalMode TLM,
755 if (!isValidVisibilityForLinkage(Visibility, Linkage))
756 return Error(NameLoc,
757 "symbol with local linkage must have default visibility");
760 bool IsConstant, IsExternallyInitialized;
761 LocTy IsExternallyInitializedLoc;
765 if (ParseOptionalAddrSpace(AddrSpace) ||
766 ParseOptionalToken(lltok::kw_externally_initialized,
767 IsExternallyInitialized,
768 &IsExternallyInitializedLoc) ||
769 ParseGlobalType(IsConstant) ||
770 ParseType(Ty, TyLoc))
773 // If the linkage is specified and is external, then no initializer is
775 Constant *Init = nullptr;
776 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
777 Linkage != GlobalValue::ExternalLinkage)) {
778 if (ParseGlobalValue(Ty, Init))
782 if (Ty->isFunctionTy() || Ty->isLabelTy())
783 return Error(TyLoc, "invalid type for global variable");
785 GlobalVariable *GV = nullptr;
787 // See if the global was forward referenced, if so, use the global.
789 if (GlobalValue *GVal = M->getNamedValue(Name)) {
790 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
791 return Error(NameLoc, "redefinition of global '@" + Name + "'");
792 GV = cast<GlobalVariable>(GVal);
795 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
796 I = ForwardRefValIDs.find(NumberedVals.size());
797 if (I != ForwardRefValIDs.end()) {
798 GV = cast<GlobalVariable>(I->second.first);
799 ForwardRefValIDs.erase(I);
804 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
805 Name, nullptr, GlobalVariable::NotThreadLocal,
808 if (GV->getType()->getElementType() != Ty)
810 "forward reference and definition of global have different types");
812 // Move the forward-reference to the correct spot in the module.
813 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
817 NumberedVals.push_back(GV);
819 // Set the parsed properties on the global.
821 GV->setInitializer(Init);
822 GV->setConstant(IsConstant);
823 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
824 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
825 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
826 GV->setExternallyInitialized(IsExternallyInitialized);
827 GV->setThreadLocalMode(TLM);
828 GV->setUnnamedAddr(UnnamedAddr);
830 // Parse attributes on the global.
831 while (Lex.getKind() == lltok::comma) {
834 if (Lex.getKind() == lltok::kw_section) {
836 GV->setSection(Lex.getStrVal());
837 if (ParseToken(lltok::StringConstant, "expected global section string"))
839 } else if (Lex.getKind() == lltok::kw_align) {
841 if (ParseOptionalAlignment(Alignment)) return true;
842 GV->setAlignment(Alignment);
845 if (parseOptionalComdat(C))
850 return TokError("unknown global variable property!");
857 /// ParseUnnamedAttrGrp
858 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
859 bool LLParser::ParseUnnamedAttrGrp() {
860 assert(Lex.getKind() == lltok::kw_attributes);
861 LocTy AttrGrpLoc = Lex.getLoc();
864 assert(Lex.getKind() == lltok::AttrGrpID);
865 unsigned VarID = Lex.getUIntVal();
866 std::vector<unsigned> unused;
870 if (ParseToken(lltok::equal, "expected '=' here") ||
871 ParseToken(lltok::lbrace, "expected '{' here") ||
872 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
874 ParseToken(lltok::rbrace, "expected end of attribute group"))
877 if (!NumberedAttrBuilders[VarID].hasAttributes())
878 return Error(AttrGrpLoc, "attribute group has no attributes");
883 /// ParseFnAttributeValuePairs
884 /// ::= <attr> | <attr> '=' <value>
885 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
886 std::vector<unsigned> &FwdRefAttrGrps,
887 bool inAttrGrp, LocTy &BuiltinLoc) {
888 bool HaveError = false;
893 lltok::Kind Token = Lex.getKind();
894 if (Token == lltok::kw_builtin)
895 BuiltinLoc = Lex.getLoc();
898 if (!inAttrGrp) return HaveError;
899 return Error(Lex.getLoc(), "unterminated attribute group");
904 case lltok::AttrGrpID: {
905 // Allow a function to reference an attribute group:
907 // define void @foo() #1 { ... }
911 "cannot have an attribute group reference in an attribute group");
913 unsigned AttrGrpNum = Lex.getUIntVal();
914 if (inAttrGrp) break;
916 // Save the reference to the attribute group. We'll fill it in later.
917 FwdRefAttrGrps.push_back(AttrGrpNum);
920 // Target-dependent attributes:
921 case lltok::StringConstant: {
922 std::string Attr = Lex.getStrVal();
925 if (EatIfPresent(lltok::equal) &&
926 ParseStringConstant(Val))
929 B.addAttribute(Attr, Val);
933 // Target-independent attributes:
934 case lltok::kw_align: {
935 // As a hack, we allow function alignment to be initially parsed as an
936 // attribute on a function declaration/definition or added to an attribute
937 // group and later moved to the alignment field.
941 if (ParseToken(lltok::equal, "expected '=' here") ||
942 ParseUInt32(Alignment))
945 if (ParseOptionalAlignment(Alignment))
948 B.addAlignmentAttr(Alignment);
951 case lltok::kw_alignstack: {
955 if (ParseToken(lltok::equal, "expected '=' here") ||
956 ParseUInt32(Alignment))
959 if (ParseOptionalStackAlignment(Alignment))
962 B.addStackAlignmentAttr(Alignment);
965 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
966 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
967 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
968 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
969 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
970 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
971 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
972 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
973 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
974 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
975 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
976 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
977 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
978 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
979 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
980 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
981 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
982 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
983 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
984 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
985 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
986 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
987 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
988 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
989 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
990 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
991 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
994 case lltok::kw_inreg:
995 case lltok::kw_signext:
996 case lltok::kw_zeroext:
999 "invalid use of attribute on a function");
1001 case lltok::kw_byval:
1002 case lltok::kw_dereferenceable:
1003 case lltok::kw_inalloca:
1004 case lltok::kw_nest:
1005 case lltok::kw_noalias:
1006 case lltok::kw_nocapture:
1007 case lltok::kw_nonnull:
1008 case lltok::kw_returned:
1009 case lltok::kw_sret:
1012 "invalid use of parameter-only attribute on a function");
1020 //===----------------------------------------------------------------------===//
1021 // GlobalValue Reference/Resolution Routines.
1022 //===----------------------------------------------------------------------===//
1024 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1025 /// forward reference record if needed. This can return null if the value
1026 /// exists but does not have the right type.
1027 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1029 PointerType *PTy = dyn_cast<PointerType>(Ty);
1031 Error(Loc, "global variable reference must have pointer type");
1035 // Look this name up in the normal function symbol table.
1037 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1039 // If this is a forward reference for the value, see if we already created a
1040 // forward ref record.
1042 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1043 I = ForwardRefVals.find(Name);
1044 if (I != ForwardRefVals.end())
1045 Val = I->second.first;
1048 // If we have the value in the symbol table or fwd-ref table, return it.
1050 if (Val->getType() == Ty) return Val;
1051 Error(Loc, "'@" + Name + "' defined with type '" +
1052 getTypeString(Val->getType()) + "'");
1056 // Otherwise, create a new forward reference for this value and remember it.
1057 GlobalValue *FwdVal;
1058 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1059 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1061 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1062 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1063 nullptr, GlobalVariable::NotThreadLocal,
1064 PTy->getAddressSpace());
1066 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1070 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1071 PointerType *PTy = dyn_cast<PointerType>(Ty);
1073 Error(Loc, "global variable reference must have pointer type");
1077 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1079 // If this is a forward reference for the value, see if we already created a
1080 // forward ref record.
1082 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1083 I = ForwardRefValIDs.find(ID);
1084 if (I != ForwardRefValIDs.end())
1085 Val = I->second.first;
1088 // If we have the value in the symbol table or fwd-ref table, return it.
1090 if (Val->getType() == Ty) return Val;
1091 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1092 getTypeString(Val->getType()) + "'");
1096 // Otherwise, create a new forward reference for this value and remember it.
1097 GlobalValue *FwdVal;
1098 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1099 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1101 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1102 GlobalValue::ExternalWeakLinkage, nullptr, "");
1104 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1109 //===----------------------------------------------------------------------===//
1110 // Comdat Reference/Resolution Routines.
1111 //===----------------------------------------------------------------------===//
1113 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1114 // Look this name up in the comdat symbol table.
1115 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1116 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1117 if (I != ComdatSymTab.end())
1120 // Otherwise, create a new forward reference for this value and remember it.
1121 Comdat *C = M->getOrInsertComdat(Name);
1122 ForwardRefComdats[Name] = Loc;
1127 //===----------------------------------------------------------------------===//
1129 //===----------------------------------------------------------------------===//
1131 /// ParseToken - If the current token has the specified kind, eat it and return
1132 /// success. Otherwise, emit the specified error and return failure.
1133 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1134 if (Lex.getKind() != T)
1135 return TokError(ErrMsg);
1140 /// ParseStringConstant
1141 /// ::= StringConstant
1142 bool LLParser::ParseStringConstant(std::string &Result) {
1143 if (Lex.getKind() != lltok::StringConstant)
1144 return TokError("expected string constant");
1145 Result = Lex.getStrVal();
1152 bool LLParser::ParseUInt32(unsigned &Val) {
1153 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1154 return TokError("expected integer");
1155 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1156 if (Val64 != unsigned(Val64))
1157 return TokError("expected 32-bit integer (too large)");
1165 bool LLParser::ParseUInt64(uint64_t &Val) {
1166 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1167 return TokError("expected integer");
1168 Val = Lex.getAPSIntVal().getLimitedValue();
1174 /// := 'localdynamic'
1175 /// := 'initialexec'
1177 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1178 switch (Lex.getKind()) {
1180 return TokError("expected localdynamic, initialexec or localexec");
1181 case lltok::kw_localdynamic:
1182 TLM = GlobalVariable::LocalDynamicTLSModel;
1184 case lltok::kw_initialexec:
1185 TLM = GlobalVariable::InitialExecTLSModel;
1187 case lltok::kw_localexec:
1188 TLM = GlobalVariable::LocalExecTLSModel;
1196 /// ParseOptionalThreadLocal
1198 /// := 'thread_local'
1199 /// := 'thread_local' '(' tlsmodel ')'
1200 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1201 TLM = GlobalVariable::NotThreadLocal;
1202 if (!EatIfPresent(lltok::kw_thread_local))
1205 TLM = GlobalVariable::GeneralDynamicTLSModel;
1206 if (Lex.getKind() == lltok::lparen) {
1208 return ParseTLSModel(TLM) ||
1209 ParseToken(lltok::rparen, "expected ')' after thread local model");
1214 /// ParseOptionalAddrSpace
1216 /// := 'addrspace' '(' uint32 ')'
1217 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1219 if (!EatIfPresent(lltok::kw_addrspace))
1221 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1222 ParseUInt32(AddrSpace) ||
1223 ParseToken(lltok::rparen, "expected ')' in address space");
1226 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1227 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1228 bool HaveError = false;
1233 lltok::Kind Token = Lex.getKind();
1235 default: // End of attributes.
1237 case lltok::kw_align: {
1239 if (ParseOptionalAlignment(Alignment))
1241 B.addAlignmentAttr(Alignment);
1244 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1245 case lltok::kw_dereferenceable: {
1247 if (ParseOptionalDereferenceableBytes(Bytes))
1249 B.addDereferenceableAttr(Bytes);
1252 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1253 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1254 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1255 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1256 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1257 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1258 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1259 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1260 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1261 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1262 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1263 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1265 case lltok::kw_alignstack:
1266 case lltok::kw_alwaysinline:
1267 case lltok::kw_builtin:
1268 case lltok::kw_inlinehint:
1269 case lltok::kw_jumptable:
1270 case lltok::kw_minsize:
1271 case lltok::kw_naked:
1272 case lltok::kw_nobuiltin:
1273 case lltok::kw_noduplicate:
1274 case lltok::kw_noimplicitfloat:
1275 case lltok::kw_noinline:
1276 case lltok::kw_nonlazybind:
1277 case lltok::kw_noredzone:
1278 case lltok::kw_noreturn:
1279 case lltok::kw_nounwind:
1280 case lltok::kw_optnone:
1281 case lltok::kw_optsize:
1282 case lltok::kw_returns_twice:
1283 case lltok::kw_sanitize_address:
1284 case lltok::kw_sanitize_memory:
1285 case lltok::kw_sanitize_thread:
1287 case lltok::kw_sspreq:
1288 case lltok::kw_sspstrong:
1289 case lltok::kw_uwtable:
1290 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1298 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1299 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1300 bool HaveError = false;
1305 lltok::Kind Token = Lex.getKind();
1307 default: // End of attributes.
1309 case lltok::kw_dereferenceable: {
1311 if (ParseOptionalDereferenceableBytes(Bytes))
1313 B.addDereferenceableAttr(Bytes);
1316 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1317 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1318 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1319 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1320 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1323 case lltok::kw_align:
1324 case lltok::kw_byval:
1325 case lltok::kw_inalloca:
1326 case lltok::kw_nest:
1327 case lltok::kw_nocapture:
1328 case lltok::kw_returned:
1329 case lltok::kw_sret:
1330 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1333 case lltok::kw_alignstack:
1334 case lltok::kw_alwaysinline:
1335 case lltok::kw_builtin:
1336 case lltok::kw_cold:
1337 case lltok::kw_inlinehint:
1338 case lltok::kw_jumptable:
1339 case lltok::kw_minsize:
1340 case lltok::kw_naked:
1341 case lltok::kw_nobuiltin:
1342 case lltok::kw_noduplicate:
1343 case lltok::kw_noimplicitfloat:
1344 case lltok::kw_noinline:
1345 case lltok::kw_nonlazybind:
1346 case lltok::kw_noredzone:
1347 case lltok::kw_noreturn:
1348 case lltok::kw_nounwind:
1349 case lltok::kw_optnone:
1350 case lltok::kw_optsize:
1351 case lltok::kw_returns_twice:
1352 case lltok::kw_sanitize_address:
1353 case lltok::kw_sanitize_memory:
1354 case lltok::kw_sanitize_thread:
1356 case lltok::kw_sspreq:
1357 case lltok::kw_sspstrong:
1358 case lltok::kw_uwtable:
1359 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1362 case lltok::kw_readnone:
1363 case lltok::kw_readonly:
1364 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1371 /// ParseOptionalLinkage
1378 /// ::= 'linkonce_odr'
1379 /// ::= 'available_externally'
1382 /// ::= 'extern_weak'
1384 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1386 switch (Lex.getKind()) {
1387 default: Res=GlobalValue::ExternalLinkage; return false;
1388 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1389 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1390 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1391 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1392 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1393 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1394 case lltok::kw_available_externally:
1395 Res = GlobalValue::AvailableExternallyLinkage;
1397 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1398 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1399 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1400 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1407 /// ParseOptionalVisibility
1413 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1414 switch (Lex.getKind()) {
1415 default: Res = GlobalValue::DefaultVisibility; return false;
1416 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1417 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1418 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1424 /// ParseOptionalDLLStorageClass
1429 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1430 switch (Lex.getKind()) {
1431 default: Res = GlobalValue::DefaultStorageClass; return false;
1432 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1433 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1439 /// ParseOptionalCallingConv
1443 /// ::= 'kw_intel_ocl_bicc'
1445 /// ::= 'x86_stdcallcc'
1446 /// ::= 'x86_fastcallcc'
1447 /// ::= 'x86_thiscallcc'
1448 /// ::= 'arm_apcscc'
1449 /// ::= 'arm_aapcscc'
1450 /// ::= 'arm_aapcs_vfpcc'
1451 /// ::= 'msp430_intrcc'
1452 /// ::= 'ptx_kernel'
1453 /// ::= 'ptx_device'
1455 /// ::= 'spir_kernel'
1456 /// ::= 'x86_64_sysvcc'
1457 /// ::= 'x86_64_win64cc'
1458 /// ::= 'webkit_jscc'
1460 /// ::= 'preserve_mostcc'
1461 /// ::= 'preserve_allcc'
1464 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1465 switch (Lex.getKind()) {
1466 default: CC = CallingConv::C; return false;
1467 case lltok::kw_ccc: CC = CallingConv::C; break;
1468 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1469 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1470 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1471 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1472 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1473 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1474 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1475 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1476 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1477 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1478 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1479 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1480 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1481 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1482 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1483 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1484 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1485 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1486 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1487 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1488 case lltok::kw_cc: {
1489 unsigned ArbitraryCC;
1491 if (ParseUInt32(ArbitraryCC))
1493 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1502 /// ParseInstructionMetadata
1503 /// ::= !dbg !42 (',' !dbg !57)*
1504 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1505 PerFunctionState *PFS) {
1507 if (Lex.getKind() != lltok::MetadataVar)
1508 return TokError("expected metadata after comma");
1510 std::string Name = Lex.getStrVal();
1511 unsigned MDK = M->getMDKindID(Name);
1515 SMLoc Loc = Lex.getLoc();
1517 if (ParseToken(lltok::exclaim, "expected '!' here"))
1520 // This code is similar to that of ParseMetadataValue, however it needs to
1521 // have special-case code for a forward reference; see the comments on
1522 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1523 // at the top level here.
1524 if (Lex.getKind() == lltok::lbrace) {
1526 if (ParseMetadataListValue(ID, PFS))
1528 assert(ID.Kind == ValID::t_MDNode);
1529 Inst->setMetadata(MDK, ID.MDNodeVal);
1531 unsigned NodeID = 0;
1532 if (ParseMDNodeID(Node, NodeID))
1535 // If we got the node, add it to the instruction.
1536 Inst->setMetadata(MDK, Node);
1538 MDRef R = { Loc, MDK, NodeID };
1539 // Otherwise, remember that this should be resolved later.
1540 ForwardRefInstMetadata[Inst].push_back(R);
1544 if (MDK == LLVMContext::MD_tbaa)
1545 InstsWithTBAATag.push_back(Inst);
1547 // If this is the end of the list, we're done.
1548 } while (EatIfPresent(lltok::comma));
1552 /// ParseOptionalAlignment
1555 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1557 if (!EatIfPresent(lltok::kw_align))
1559 LocTy AlignLoc = Lex.getLoc();
1560 if (ParseUInt32(Alignment)) return true;
1561 if (!isPowerOf2_32(Alignment))
1562 return Error(AlignLoc, "alignment is not a power of two");
1563 if (Alignment > Value::MaximumAlignment)
1564 return Error(AlignLoc, "huge alignments are not supported yet");
1568 /// ParseOptionalDereferenceableBytes
1570 /// ::= 'dereferenceable' '(' 4 ')'
1571 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1573 if (!EatIfPresent(lltok::kw_dereferenceable))
1575 LocTy ParenLoc = Lex.getLoc();
1576 if (!EatIfPresent(lltok::lparen))
1577 return Error(ParenLoc, "expected '('");
1578 LocTy DerefLoc = Lex.getLoc();
1579 if (ParseUInt64(Bytes)) return true;
1580 ParenLoc = Lex.getLoc();
1581 if (!EatIfPresent(lltok::rparen))
1582 return Error(ParenLoc, "expected ')'");
1584 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1588 /// ParseOptionalCommaAlign
1592 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1594 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1595 bool &AteExtraComma) {
1596 AteExtraComma = false;
1597 while (EatIfPresent(lltok::comma)) {
1598 // Metadata at the end is an early exit.
1599 if (Lex.getKind() == lltok::MetadataVar) {
1600 AteExtraComma = true;
1604 if (Lex.getKind() != lltok::kw_align)
1605 return Error(Lex.getLoc(), "expected metadata or 'align'");
1607 if (ParseOptionalAlignment(Alignment)) return true;
1613 /// ParseScopeAndOrdering
1614 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1617 /// This sets Scope and Ordering to the parsed values.
1618 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1619 AtomicOrdering &Ordering) {
1623 Scope = CrossThread;
1624 if (EatIfPresent(lltok::kw_singlethread))
1625 Scope = SingleThread;
1627 return ParseOrdering(Ordering);
1631 /// ::= AtomicOrdering
1633 /// This sets Ordering to the parsed value.
1634 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1635 switch (Lex.getKind()) {
1636 default: return TokError("Expected ordering on atomic instruction");
1637 case lltok::kw_unordered: Ordering = Unordered; break;
1638 case lltok::kw_monotonic: Ordering = Monotonic; break;
1639 case lltok::kw_acquire: Ordering = Acquire; break;
1640 case lltok::kw_release: Ordering = Release; break;
1641 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1642 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1648 /// ParseOptionalStackAlignment
1650 /// ::= 'alignstack' '(' 4 ')'
1651 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1653 if (!EatIfPresent(lltok::kw_alignstack))
1655 LocTy ParenLoc = Lex.getLoc();
1656 if (!EatIfPresent(lltok::lparen))
1657 return Error(ParenLoc, "expected '('");
1658 LocTy AlignLoc = Lex.getLoc();
1659 if (ParseUInt32(Alignment)) return true;
1660 ParenLoc = Lex.getLoc();
1661 if (!EatIfPresent(lltok::rparen))
1662 return Error(ParenLoc, "expected ')'");
1663 if (!isPowerOf2_32(Alignment))
1664 return Error(AlignLoc, "stack alignment is not a power of two");
1668 /// ParseIndexList - This parses the index list for an insert/extractvalue
1669 /// instruction. This sets AteExtraComma in the case where we eat an extra
1670 /// comma at the end of the line and find that it is followed by metadata.
1671 /// Clients that don't allow metadata can call the version of this function that
1672 /// only takes one argument.
1675 /// ::= (',' uint32)+
1677 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1678 bool &AteExtraComma) {
1679 AteExtraComma = false;
1681 if (Lex.getKind() != lltok::comma)
1682 return TokError("expected ',' as start of index list");
1684 while (EatIfPresent(lltok::comma)) {
1685 if (Lex.getKind() == lltok::MetadataVar) {
1686 AteExtraComma = true;
1690 if (ParseUInt32(Idx)) return true;
1691 Indices.push_back(Idx);
1697 //===----------------------------------------------------------------------===//
1699 //===----------------------------------------------------------------------===//
1701 /// ParseType - Parse a type.
1702 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1703 SMLoc TypeLoc = Lex.getLoc();
1704 switch (Lex.getKind()) {
1706 return TokError("expected type");
1708 // Type ::= 'float' | 'void' (etc)
1709 Result = Lex.getTyVal();
1713 // Type ::= StructType
1714 if (ParseAnonStructType(Result, false))
1717 case lltok::lsquare:
1718 // Type ::= '[' ... ']'
1719 Lex.Lex(); // eat the lsquare.
1720 if (ParseArrayVectorType(Result, false))
1723 case lltok::less: // Either vector or packed struct.
1724 // Type ::= '<' ... '>'
1726 if (Lex.getKind() == lltok::lbrace) {
1727 if (ParseAnonStructType(Result, true) ||
1728 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1730 } else if (ParseArrayVectorType(Result, true))
1733 case lltok::LocalVar: {
1735 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1737 // If the type hasn't been defined yet, create a forward definition and
1738 // remember where that forward def'n was seen (in case it never is defined).
1740 Entry.first = StructType::create(Context, Lex.getStrVal());
1741 Entry.second = Lex.getLoc();
1743 Result = Entry.first;
1748 case lltok::LocalVarID: {
1750 if (Lex.getUIntVal() >= NumberedTypes.size())
1751 NumberedTypes.resize(Lex.getUIntVal()+1);
1752 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1754 // If the type hasn't been defined yet, create a forward definition and
1755 // remember where that forward def'n was seen (in case it never is defined).
1757 Entry.first = StructType::create(Context);
1758 Entry.second = Lex.getLoc();
1760 Result = Entry.first;
1766 // Parse the type suffixes.
1768 switch (Lex.getKind()) {
1771 if (!AllowVoid && Result->isVoidTy())
1772 return Error(TypeLoc, "void type only allowed for function results");
1775 // Type ::= Type '*'
1777 if (Result->isLabelTy())
1778 return TokError("basic block pointers are invalid");
1779 if (Result->isVoidTy())
1780 return TokError("pointers to void are invalid - use i8* instead");
1781 if (!PointerType::isValidElementType(Result))
1782 return TokError("pointer to this type is invalid");
1783 Result = PointerType::getUnqual(Result);
1787 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1788 case lltok::kw_addrspace: {
1789 if (Result->isLabelTy())
1790 return TokError("basic block pointers are invalid");
1791 if (Result->isVoidTy())
1792 return TokError("pointers to void are invalid; use i8* instead");
1793 if (!PointerType::isValidElementType(Result))
1794 return TokError("pointer to this type is invalid");
1796 if (ParseOptionalAddrSpace(AddrSpace) ||
1797 ParseToken(lltok::star, "expected '*' in address space"))
1800 Result = PointerType::get(Result, AddrSpace);
1804 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1806 if (ParseFunctionType(Result))
1813 /// ParseParameterList
1815 /// ::= '(' Arg (',' Arg)* ')'
1817 /// ::= Type OptionalAttributes Value OptionalAttributes
1818 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1819 PerFunctionState &PFS) {
1820 if (ParseToken(lltok::lparen, "expected '(' in call"))
1823 unsigned AttrIndex = 1;
1824 while (Lex.getKind() != lltok::rparen) {
1825 // If this isn't the first argument, we need a comma.
1826 if (!ArgList.empty() &&
1827 ParseToken(lltok::comma, "expected ',' in argument list"))
1830 // Parse the argument.
1832 Type *ArgTy = nullptr;
1833 AttrBuilder ArgAttrs;
1835 if (ParseType(ArgTy, ArgLoc))
1838 // Otherwise, handle normal operands.
1839 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1841 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1846 Lex.Lex(); // Lex the ')'.
1852 /// ParseArgumentList - Parse the argument list for a function type or function
1854 /// ::= '(' ArgTypeListI ')'
1858 /// ::= ArgTypeList ',' '...'
1859 /// ::= ArgType (',' ArgType)*
1861 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1864 assert(Lex.getKind() == lltok::lparen);
1865 Lex.Lex(); // eat the (.
1867 if (Lex.getKind() == lltok::rparen) {
1869 } else if (Lex.getKind() == lltok::dotdotdot) {
1873 LocTy TypeLoc = Lex.getLoc();
1874 Type *ArgTy = nullptr;
1878 if (ParseType(ArgTy) ||
1879 ParseOptionalParamAttrs(Attrs)) return true;
1881 if (ArgTy->isVoidTy())
1882 return Error(TypeLoc, "argument can not have void type");
1884 if (Lex.getKind() == lltok::LocalVar) {
1885 Name = Lex.getStrVal();
1889 if (!FunctionType::isValidArgumentType(ArgTy))
1890 return Error(TypeLoc, "invalid type for function argument");
1892 unsigned AttrIndex = 1;
1893 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1894 AttributeSet::get(ArgTy->getContext(),
1895 AttrIndex++, Attrs), Name));
1897 while (EatIfPresent(lltok::comma)) {
1898 // Handle ... at end of arg list.
1899 if (EatIfPresent(lltok::dotdotdot)) {
1904 // Otherwise must be an argument type.
1905 TypeLoc = Lex.getLoc();
1906 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1908 if (ArgTy->isVoidTy())
1909 return Error(TypeLoc, "argument can not have void type");
1911 if (Lex.getKind() == lltok::LocalVar) {
1912 Name = Lex.getStrVal();
1918 if (!ArgTy->isFirstClassType())
1919 return Error(TypeLoc, "invalid type for function argument");
1921 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1922 AttributeSet::get(ArgTy->getContext(),
1923 AttrIndex++, Attrs),
1928 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1931 /// ParseFunctionType
1932 /// ::= Type ArgumentList OptionalAttrs
1933 bool LLParser::ParseFunctionType(Type *&Result) {
1934 assert(Lex.getKind() == lltok::lparen);
1936 if (!FunctionType::isValidReturnType(Result))
1937 return TokError("invalid function return type");
1939 SmallVector<ArgInfo, 8> ArgList;
1941 if (ParseArgumentList(ArgList, isVarArg))
1944 // Reject names on the arguments lists.
1945 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1946 if (!ArgList[i].Name.empty())
1947 return Error(ArgList[i].Loc, "argument name invalid in function type");
1948 if (ArgList[i].Attrs.hasAttributes(i + 1))
1949 return Error(ArgList[i].Loc,
1950 "argument attributes invalid in function type");
1953 SmallVector<Type*, 16> ArgListTy;
1954 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1955 ArgListTy.push_back(ArgList[i].Ty);
1957 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1961 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1963 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1964 SmallVector<Type*, 8> Elts;
1965 if (ParseStructBody(Elts)) return true;
1967 Result = StructType::get(Context, Elts, Packed);
1971 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1972 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1973 std::pair<Type*, LocTy> &Entry,
1975 // If the type was already defined, diagnose the redefinition.
1976 if (Entry.first && !Entry.second.isValid())
1977 return Error(TypeLoc, "redefinition of type");
1979 // If we have opaque, just return without filling in the definition for the
1980 // struct. This counts as a definition as far as the .ll file goes.
1981 if (EatIfPresent(lltok::kw_opaque)) {
1982 // This type is being defined, so clear the location to indicate this.
1983 Entry.second = SMLoc();
1985 // If this type number has never been uttered, create it.
1987 Entry.first = StructType::create(Context, Name);
1988 ResultTy = Entry.first;
1992 // If the type starts with '<', then it is either a packed struct or a vector.
1993 bool isPacked = EatIfPresent(lltok::less);
1995 // If we don't have a struct, then we have a random type alias, which we
1996 // accept for compatibility with old files. These types are not allowed to be
1997 // forward referenced and not allowed to be recursive.
1998 if (Lex.getKind() != lltok::lbrace) {
2000 return Error(TypeLoc, "forward references to non-struct type");
2004 return ParseArrayVectorType(ResultTy, true);
2005 return ParseType(ResultTy);
2008 // This type is being defined, so clear the location to indicate this.
2009 Entry.second = SMLoc();
2011 // If this type number has never been uttered, create it.
2013 Entry.first = StructType::create(Context, Name);
2015 StructType *STy = cast<StructType>(Entry.first);
2017 SmallVector<Type*, 8> Body;
2018 if (ParseStructBody(Body) ||
2019 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2022 STy->setBody(Body, isPacked);
2028 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2031 /// ::= '{' Type (',' Type)* '}'
2032 /// ::= '<' '{' '}' '>'
2033 /// ::= '<' '{' Type (',' Type)* '}' '>'
2034 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2035 assert(Lex.getKind() == lltok::lbrace);
2036 Lex.Lex(); // Consume the '{'
2038 // Handle the empty struct.
2039 if (EatIfPresent(lltok::rbrace))
2042 LocTy EltTyLoc = Lex.getLoc();
2044 if (ParseType(Ty)) return true;
2047 if (!StructType::isValidElementType(Ty))
2048 return Error(EltTyLoc, "invalid element type for struct");
2050 while (EatIfPresent(lltok::comma)) {
2051 EltTyLoc = Lex.getLoc();
2052 if (ParseType(Ty)) return true;
2054 if (!StructType::isValidElementType(Ty))
2055 return Error(EltTyLoc, "invalid element type for struct");
2060 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2063 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2064 /// token has already been consumed.
2066 /// ::= '[' APSINTVAL 'x' Types ']'
2067 /// ::= '<' APSINTVAL 'x' Types '>'
2068 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2069 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2070 Lex.getAPSIntVal().getBitWidth() > 64)
2071 return TokError("expected number in address space");
2073 LocTy SizeLoc = Lex.getLoc();
2074 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2077 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2080 LocTy TypeLoc = Lex.getLoc();
2081 Type *EltTy = nullptr;
2082 if (ParseType(EltTy)) return true;
2084 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2085 "expected end of sequential type"))
2090 return Error(SizeLoc, "zero element vector is illegal");
2091 if ((unsigned)Size != Size)
2092 return Error(SizeLoc, "size too large for vector");
2093 if (!VectorType::isValidElementType(EltTy))
2094 return Error(TypeLoc, "invalid vector element type");
2095 Result = VectorType::get(EltTy, unsigned(Size));
2097 if (!ArrayType::isValidElementType(EltTy))
2098 return Error(TypeLoc, "invalid array element type");
2099 Result = ArrayType::get(EltTy, Size);
2104 //===----------------------------------------------------------------------===//
2105 // Function Semantic Analysis.
2106 //===----------------------------------------------------------------------===//
2108 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2110 : P(p), F(f), FunctionNumber(functionNumber) {
2112 // Insert unnamed arguments into the NumberedVals list.
2113 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2116 NumberedVals.push_back(AI);
2119 LLParser::PerFunctionState::~PerFunctionState() {
2120 // If there were any forward referenced non-basicblock values, delete them.
2121 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2122 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2123 if (!isa<BasicBlock>(I->second.first)) {
2124 I->second.first->replaceAllUsesWith(
2125 UndefValue::get(I->second.first->getType()));
2126 delete I->second.first;
2127 I->second.first = nullptr;
2130 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2131 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2132 if (!isa<BasicBlock>(I->second.first)) {
2133 I->second.first->replaceAllUsesWith(
2134 UndefValue::get(I->second.first->getType()));
2135 delete I->second.first;
2136 I->second.first = nullptr;
2140 bool LLParser::PerFunctionState::FinishFunction() {
2141 if (!ForwardRefVals.empty())
2142 return P.Error(ForwardRefVals.begin()->second.second,
2143 "use of undefined value '%" + ForwardRefVals.begin()->first +
2145 if (!ForwardRefValIDs.empty())
2146 return P.Error(ForwardRefValIDs.begin()->second.second,
2147 "use of undefined value '%" +
2148 Twine(ForwardRefValIDs.begin()->first) + "'");
2153 /// GetVal - Get a value with the specified name or ID, creating a
2154 /// forward reference record if needed. This can return null if the value
2155 /// exists but does not have the right type.
2156 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2157 Type *Ty, LocTy Loc) {
2158 // Look this name up in the normal function symbol table.
2159 Value *Val = F.getValueSymbolTable().lookup(Name);
2161 // If this is a forward reference for the value, see if we already created a
2162 // forward ref record.
2164 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2165 I = ForwardRefVals.find(Name);
2166 if (I != ForwardRefVals.end())
2167 Val = I->second.first;
2170 // If we have the value in the symbol table or fwd-ref table, return it.
2172 if (Val->getType() == Ty) return Val;
2173 if (Ty->isLabelTy())
2174 P.Error(Loc, "'%" + Name + "' is not a basic block");
2176 P.Error(Loc, "'%" + Name + "' defined with type '" +
2177 getTypeString(Val->getType()) + "'");
2181 // Don't make placeholders with invalid type.
2182 if (!Ty->isFirstClassType()) {
2183 P.Error(Loc, "invalid use of a non-first-class type");
2187 // Otherwise, create a new forward reference for this value and remember it.
2189 if (Ty->isLabelTy())
2190 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2192 FwdVal = new Argument(Ty, Name);
2194 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2198 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2200 // Look this name up in the normal function symbol table.
2201 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2203 // If this is a forward reference for the value, see if we already created a
2204 // forward ref record.
2206 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2207 I = ForwardRefValIDs.find(ID);
2208 if (I != ForwardRefValIDs.end())
2209 Val = I->second.first;
2212 // If we have the value in the symbol table or fwd-ref table, return it.
2214 if (Val->getType() == Ty) return Val;
2215 if (Ty->isLabelTy())
2216 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2218 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2219 getTypeString(Val->getType()) + "'");
2223 if (!Ty->isFirstClassType()) {
2224 P.Error(Loc, "invalid use of a non-first-class type");
2228 // Otherwise, create a new forward reference for this value and remember it.
2230 if (Ty->isLabelTy())
2231 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2233 FwdVal = new Argument(Ty);
2235 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2239 /// SetInstName - After an instruction is parsed and inserted into its
2240 /// basic block, this installs its name.
2241 bool LLParser::PerFunctionState::SetInstName(int NameID,
2242 const std::string &NameStr,
2243 LocTy NameLoc, Instruction *Inst) {
2244 // If this instruction has void type, it cannot have a name or ID specified.
2245 if (Inst->getType()->isVoidTy()) {
2246 if (NameID != -1 || !NameStr.empty())
2247 return P.Error(NameLoc, "instructions returning void cannot have a name");
2251 // If this was a numbered instruction, verify that the instruction is the
2252 // expected value and resolve any forward references.
2253 if (NameStr.empty()) {
2254 // If neither a name nor an ID was specified, just use the next ID.
2256 NameID = NumberedVals.size();
2258 if (unsigned(NameID) != NumberedVals.size())
2259 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2260 Twine(NumberedVals.size()) + "'");
2262 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2263 ForwardRefValIDs.find(NameID);
2264 if (FI != ForwardRefValIDs.end()) {
2265 if (FI->second.first->getType() != Inst->getType())
2266 return P.Error(NameLoc, "instruction forward referenced with type '" +
2267 getTypeString(FI->second.first->getType()) + "'");
2268 FI->second.first->replaceAllUsesWith(Inst);
2269 delete FI->second.first;
2270 ForwardRefValIDs.erase(FI);
2273 NumberedVals.push_back(Inst);
2277 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2278 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2279 FI = ForwardRefVals.find(NameStr);
2280 if (FI != ForwardRefVals.end()) {
2281 if (FI->second.first->getType() != Inst->getType())
2282 return P.Error(NameLoc, "instruction forward referenced with type '" +
2283 getTypeString(FI->second.first->getType()) + "'");
2284 FI->second.first->replaceAllUsesWith(Inst);
2285 delete FI->second.first;
2286 ForwardRefVals.erase(FI);
2289 // Set the name on the instruction.
2290 Inst->setName(NameStr);
2292 if (Inst->getName() != NameStr)
2293 return P.Error(NameLoc, "multiple definition of local value named '" +
2298 /// GetBB - Get a basic block with the specified name or ID, creating a
2299 /// forward reference record if needed.
2300 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2302 return cast_or_null<BasicBlock>(GetVal(Name,
2303 Type::getLabelTy(F.getContext()), Loc));
2306 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2307 return cast_or_null<BasicBlock>(GetVal(ID,
2308 Type::getLabelTy(F.getContext()), Loc));
2311 /// DefineBB - Define the specified basic block, which is either named or
2312 /// unnamed. If there is an error, this returns null otherwise it returns
2313 /// the block being defined.
2314 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2318 BB = GetBB(NumberedVals.size(), Loc);
2320 BB = GetBB(Name, Loc);
2321 if (!BB) return nullptr; // Already diagnosed error.
2323 // Move the block to the end of the function. Forward ref'd blocks are
2324 // inserted wherever they happen to be referenced.
2325 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2327 // Remove the block from forward ref sets.
2329 ForwardRefValIDs.erase(NumberedVals.size());
2330 NumberedVals.push_back(BB);
2332 // BB forward references are already in the function symbol table.
2333 ForwardRefVals.erase(Name);
2339 //===----------------------------------------------------------------------===//
2341 //===----------------------------------------------------------------------===//
2343 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2344 /// type implied. For example, if we parse "4" we don't know what integer type
2345 /// it has. The value will later be combined with its type and checked for
2346 /// sanity. PFS is used to convert function-local operands of metadata (since
2347 /// metadata operands are not just parsed here but also converted to values).
2348 /// PFS can be null when we are not parsing metadata values inside a function.
2349 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2350 ID.Loc = Lex.getLoc();
2351 switch (Lex.getKind()) {
2352 default: return TokError("expected value token");
2353 case lltok::GlobalID: // @42
2354 ID.UIntVal = Lex.getUIntVal();
2355 ID.Kind = ValID::t_GlobalID;
2357 case lltok::GlobalVar: // @foo
2358 ID.StrVal = Lex.getStrVal();
2359 ID.Kind = ValID::t_GlobalName;
2361 case lltok::LocalVarID: // %42
2362 ID.UIntVal = Lex.getUIntVal();
2363 ID.Kind = ValID::t_LocalID;
2365 case lltok::LocalVar: // %foo
2366 ID.StrVal = Lex.getStrVal();
2367 ID.Kind = ValID::t_LocalName;
2369 case lltok::exclaim: // !42, !{...}, or !"foo"
2370 return ParseMetadataValue(ID, PFS);
2372 ID.APSIntVal = Lex.getAPSIntVal();
2373 ID.Kind = ValID::t_APSInt;
2375 case lltok::APFloat:
2376 ID.APFloatVal = Lex.getAPFloatVal();
2377 ID.Kind = ValID::t_APFloat;
2379 case lltok::kw_true:
2380 ID.ConstantVal = ConstantInt::getTrue(Context);
2381 ID.Kind = ValID::t_Constant;
2383 case lltok::kw_false:
2384 ID.ConstantVal = ConstantInt::getFalse(Context);
2385 ID.Kind = ValID::t_Constant;
2387 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2388 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2389 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2391 case lltok::lbrace: {
2392 // ValID ::= '{' ConstVector '}'
2394 SmallVector<Constant*, 16> Elts;
2395 if (ParseGlobalValueVector(Elts) ||
2396 ParseToken(lltok::rbrace, "expected end of struct constant"))
2399 ID.ConstantStructElts = new Constant*[Elts.size()];
2400 ID.UIntVal = Elts.size();
2401 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2402 ID.Kind = ValID::t_ConstantStruct;
2406 // ValID ::= '<' ConstVector '>' --> Vector.
2407 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2409 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2411 SmallVector<Constant*, 16> Elts;
2412 LocTy FirstEltLoc = Lex.getLoc();
2413 if (ParseGlobalValueVector(Elts) ||
2415 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2416 ParseToken(lltok::greater, "expected end of constant"))
2419 if (isPackedStruct) {
2420 ID.ConstantStructElts = new Constant*[Elts.size()];
2421 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2422 ID.UIntVal = Elts.size();
2423 ID.Kind = ValID::t_PackedConstantStruct;
2428 return Error(ID.Loc, "constant vector must not be empty");
2430 if (!Elts[0]->getType()->isIntegerTy() &&
2431 !Elts[0]->getType()->isFloatingPointTy() &&
2432 !Elts[0]->getType()->isPointerTy())
2433 return Error(FirstEltLoc,
2434 "vector elements must have integer, pointer or floating point type");
2436 // Verify that all the vector elements have the same type.
2437 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2438 if (Elts[i]->getType() != Elts[0]->getType())
2439 return Error(FirstEltLoc,
2440 "vector element #" + Twine(i) +
2441 " is not of type '" + getTypeString(Elts[0]->getType()));
2443 ID.ConstantVal = ConstantVector::get(Elts);
2444 ID.Kind = ValID::t_Constant;
2447 case lltok::lsquare: { // Array Constant
2449 SmallVector<Constant*, 16> Elts;
2450 LocTy FirstEltLoc = Lex.getLoc();
2451 if (ParseGlobalValueVector(Elts) ||
2452 ParseToken(lltok::rsquare, "expected end of array constant"))
2455 // Handle empty element.
2457 // Use undef instead of an array because it's inconvenient to determine
2458 // the element type at this point, there being no elements to examine.
2459 ID.Kind = ValID::t_EmptyArray;
2463 if (!Elts[0]->getType()->isFirstClassType())
2464 return Error(FirstEltLoc, "invalid array element type: " +
2465 getTypeString(Elts[0]->getType()));
2467 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2469 // Verify all elements are correct type!
2470 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2471 if (Elts[i]->getType() != Elts[0]->getType())
2472 return Error(FirstEltLoc,
2473 "array element #" + Twine(i) +
2474 " is not of type '" + getTypeString(Elts[0]->getType()));
2477 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2478 ID.Kind = ValID::t_Constant;
2481 case lltok::kw_c: // c "foo"
2483 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2485 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2486 ID.Kind = ValID::t_Constant;
2489 case lltok::kw_asm: {
2490 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2492 bool HasSideEffect, AlignStack, AsmDialect;
2494 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2495 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2496 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2497 ParseStringConstant(ID.StrVal) ||
2498 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2499 ParseToken(lltok::StringConstant, "expected constraint string"))
2501 ID.StrVal2 = Lex.getStrVal();
2502 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2503 (unsigned(AsmDialect)<<2);
2504 ID.Kind = ValID::t_InlineAsm;
2508 case lltok::kw_blockaddress: {
2509 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2514 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2516 ParseToken(lltok::comma, "expected comma in block address expression")||
2517 ParseValID(Label) ||
2518 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2521 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2522 return Error(Fn.Loc, "expected function name in blockaddress");
2523 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2524 return Error(Label.Loc, "expected basic block name in blockaddress");
2526 // Try to find the function (but skip it if it's forward-referenced).
2527 GlobalValue *GV = nullptr;
2528 if (Fn.Kind == ValID::t_GlobalID) {
2529 if (Fn.UIntVal < NumberedVals.size())
2530 GV = NumberedVals[Fn.UIntVal];
2531 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2532 GV = M->getNamedValue(Fn.StrVal);
2534 Function *F = nullptr;
2536 // Confirm that it's actually a function with a definition.
2537 if (!isa<Function>(GV))
2538 return Error(Fn.Loc, "expected function name in blockaddress");
2539 F = cast<Function>(GV);
2540 if (F->isDeclaration())
2541 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2545 // Make a global variable as a placeholder for this reference.
2546 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2548 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2549 GlobalValue::InternalLinkage, nullptr, "");
2550 ID.ConstantVal = FwdRef;
2551 ID.Kind = ValID::t_Constant;
2555 // We found the function; now find the basic block. Don't use PFS, since we
2556 // might be inside a constant expression.
2558 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2559 if (Label.Kind == ValID::t_LocalID)
2560 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2562 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2564 return Error(Label.Loc, "referenced value is not a basic block");
2566 if (Label.Kind == ValID::t_LocalID)
2567 return Error(Label.Loc, "cannot take address of numeric label after "
2568 "the function is defined");
2569 BB = dyn_cast_or_null<BasicBlock>(
2570 F->getValueSymbolTable().lookup(Label.StrVal));
2572 return Error(Label.Loc, "referenced value is not a basic block");
2575 ID.ConstantVal = BlockAddress::get(F, BB);
2576 ID.Kind = ValID::t_Constant;
2580 case lltok::kw_trunc:
2581 case lltok::kw_zext:
2582 case lltok::kw_sext:
2583 case lltok::kw_fptrunc:
2584 case lltok::kw_fpext:
2585 case lltok::kw_bitcast:
2586 case lltok::kw_addrspacecast:
2587 case lltok::kw_uitofp:
2588 case lltok::kw_sitofp:
2589 case lltok::kw_fptoui:
2590 case lltok::kw_fptosi:
2591 case lltok::kw_inttoptr:
2592 case lltok::kw_ptrtoint: {
2593 unsigned Opc = Lex.getUIntVal();
2594 Type *DestTy = nullptr;
2597 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2598 ParseGlobalTypeAndValue(SrcVal) ||
2599 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2600 ParseType(DestTy) ||
2601 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2603 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2604 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2605 getTypeString(SrcVal->getType()) + "' to '" +
2606 getTypeString(DestTy) + "'");
2607 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2609 ID.Kind = ValID::t_Constant;
2612 case lltok::kw_extractvalue: {
2615 SmallVector<unsigned, 4> Indices;
2616 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2617 ParseGlobalTypeAndValue(Val) ||
2618 ParseIndexList(Indices) ||
2619 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2622 if (!Val->getType()->isAggregateType())
2623 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2624 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2625 return Error(ID.Loc, "invalid indices for extractvalue");
2626 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2627 ID.Kind = ValID::t_Constant;
2630 case lltok::kw_insertvalue: {
2632 Constant *Val0, *Val1;
2633 SmallVector<unsigned, 4> Indices;
2634 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2635 ParseGlobalTypeAndValue(Val0) ||
2636 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2637 ParseGlobalTypeAndValue(Val1) ||
2638 ParseIndexList(Indices) ||
2639 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2641 if (!Val0->getType()->isAggregateType())
2642 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2643 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2644 return Error(ID.Loc, "invalid indices for insertvalue");
2645 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2646 ID.Kind = ValID::t_Constant;
2649 case lltok::kw_icmp:
2650 case lltok::kw_fcmp: {
2651 unsigned PredVal, Opc = Lex.getUIntVal();
2652 Constant *Val0, *Val1;
2654 if (ParseCmpPredicate(PredVal, Opc) ||
2655 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2656 ParseGlobalTypeAndValue(Val0) ||
2657 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2658 ParseGlobalTypeAndValue(Val1) ||
2659 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2662 if (Val0->getType() != Val1->getType())
2663 return Error(ID.Loc, "compare operands must have the same type");
2665 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2667 if (Opc == Instruction::FCmp) {
2668 if (!Val0->getType()->isFPOrFPVectorTy())
2669 return Error(ID.Loc, "fcmp requires floating point operands");
2670 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2672 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2673 if (!Val0->getType()->isIntOrIntVectorTy() &&
2674 !Val0->getType()->getScalarType()->isPointerTy())
2675 return Error(ID.Loc, "icmp requires pointer or integer operands");
2676 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2678 ID.Kind = ValID::t_Constant;
2682 // Binary Operators.
2684 case lltok::kw_fadd:
2686 case lltok::kw_fsub:
2688 case lltok::kw_fmul:
2689 case lltok::kw_udiv:
2690 case lltok::kw_sdiv:
2691 case lltok::kw_fdiv:
2692 case lltok::kw_urem:
2693 case lltok::kw_srem:
2694 case lltok::kw_frem:
2696 case lltok::kw_lshr:
2697 case lltok::kw_ashr: {
2701 unsigned Opc = Lex.getUIntVal();
2702 Constant *Val0, *Val1;
2704 LocTy ModifierLoc = Lex.getLoc();
2705 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2706 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2707 if (EatIfPresent(lltok::kw_nuw))
2709 if (EatIfPresent(lltok::kw_nsw)) {
2711 if (EatIfPresent(lltok::kw_nuw))
2714 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2715 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2716 if (EatIfPresent(lltok::kw_exact))
2719 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2720 ParseGlobalTypeAndValue(Val0) ||
2721 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2722 ParseGlobalTypeAndValue(Val1) ||
2723 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2725 if (Val0->getType() != Val1->getType())
2726 return Error(ID.Loc, "operands of constexpr must have same type");
2727 if (!Val0->getType()->isIntOrIntVectorTy()) {
2729 return Error(ModifierLoc, "nuw only applies to integer operations");
2731 return Error(ModifierLoc, "nsw only applies to integer operations");
2733 // Check that the type is valid for the operator.
2735 case Instruction::Add:
2736 case Instruction::Sub:
2737 case Instruction::Mul:
2738 case Instruction::UDiv:
2739 case Instruction::SDiv:
2740 case Instruction::URem:
2741 case Instruction::SRem:
2742 case Instruction::Shl:
2743 case Instruction::AShr:
2744 case Instruction::LShr:
2745 if (!Val0->getType()->isIntOrIntVectorTy())
2746 return Error(ID.Loc, "constexpr requires integer operands");
2748 case Instruction::FAdd:
2749 case Instruction::FSub:
2750 case Instruction::FMul:
2751 case Instruction::FDiv:
2752 case Instruction::FRem:
2753 if (!Val0->getType()->isFPOrFPVectorTy())
2754 return Error(ID.Loc, "constexpr requires fp operands");
2756 default: llvm_unreachable("Unknown binary operator!");
2759 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2760 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2761 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2762 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2764 ID.Kind = ValID::t_Constant;
2768 // Logical Operations
2771 case lltok::kw_xor: {
2772 unsigned Opc = Lex.getUIntVal();
2773 Constant *Val0, *Val1;
2775 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2776 ParseGlobalTypeAndValue(Val0) ||
2777 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2778 ParseGlobalTypeAndValue(Val1) ||
2779 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2781 if (Val0->getType() != Val1->getType())
2782 return Error(ID.Loc, "operands of constexpr must have same type");
2783 if (!Val0->getType()->isIntOrIntVectorTy())
2784 return Error(ID.Loc,
2785 "constexpr requires integer or integer vector operands");
2786 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2787 ID.Kind = ValID::t_Constant;
2791 case lltok::kw_getelementptr:
2792 case lltok::kw_shufflevector:
2793 case lltok::kw_insertelement:
2794 case lltok::kw_extractelement:
2795 case lltok::kw_select: {
2796 unsigned Opc = Lex.getUIntVal();
2797 SmallVector<Constant*, 16> Elts;
2798 bool InBounds = false;
2800 if (Opc == Instruction::GetElementPtr)
2801 InBounds = EatIfPresent(lltok::kw_inbounds);
2802 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2803 ParseGlobalValueVector(Elts) ||
2804 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2807 if (Opc == Instruction::GetElementPtr) {
2808 if (Elts.size() == 0 ||
2809 !Elts[0]->getType()->getScalarType()->isPointerTy())
2810 return Error(ID.Loc, "getelementptr requires pointer operand");
2812 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2813 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2814 return Error(ID.Loc, "invalid indices for getelementptr");
2815 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2817 } else if (Opc == Instruction::Select) {
2818 if (Elts.size() != 3)
2819 return Error(ID.Loc, "expected three operands to select");
2820 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2822 return Error(ID.Loc, Reason);
2823 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2824 } else if (Opc == Instruction::ShuffleVector) {
2825 if (Elts.size() != 3)
2826 return Error(ID.Loc, "expected three operands to shufflevector");
2827 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2828 return Error(ID.Loc, "invalid operands to shufflevector");
2830 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2831 } else if (Opc == Instruction::ExtractElement) {
2832 if (Elts.size() != 2)
2833 return Error(ID.Loc, "expected two operands to extractelement");
2834 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2835 return Error(ID.Loc, "invalid extractelement operands");
2836 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2838 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2839 if (Elts.size() != 3)
2840 return Error(ID.Loc, "expected three operands to insertelement");
2841 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2842 return Error(ID.Loc, "invalid insertelement operands");
2844 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2847 ID.Kind = ValID::t_Constant;
2856 /// ParseGlobalValue - Parse a global value with the specified type.
2857 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2861 bool Parsed = ParseValID(ID) ||
2862 ConvertValIDToValue(Ty, ID, V, nullptr);
2863 if (V && !(C = dyn_cast<Constant>(V)))
2864 return Error(ID.Loc, "global values must be constants");
2868 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2870 return ParseType(Ty) ||
2871 ParseGlobalValue(Ty, V);
2874 bool LLParser::parseOptionalComdat(Comdat *&C) {
2876 if (!EatIfPresent(lltok::kw_comdat))
2878 if (Lex.getKind() != lltok::ComdatVar)
2879 return TokError("expected comdat variable");
2880 LocTy Loc = Lex.getLoc();
2881 StringRef Name = Lex.getStrVal();
2882 C = getComdat(Name, Loc);
2887 /// ParseGlobalValueVector
2889 /// ::= TypeAndValue (',' TypeAndValue)*
2890 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2892 if (Lex.getKind() == lltok::rbrace ||
2893 Lex.getKind() == lltok::rsquare ||
2894 Lex.getKind() == lltok::greater ||
2895 Lex.getKind() == lltok::rparen)
2899 if (ParseGlobalTypeAndValue(C)) return true;
2902 while (EatIfPresent(lltok::comma)) {
2903 if (ParseGlobalTypeAndValue(C)) return true;
2910 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2911 assert(Lex.getKind() == lltok::lbrace);
2914 SmallVector<Value*, 16> Elts;
2915 if (ParseMDNodeVector(Elts, PFS) ||
2916 ParseToken(lltok::rbrace, "expected end of metadata node"))
2919 ID.MDNodeVal = MDNode::get(Context, Elts);
2920 ID.Kind = ValID::t_MDNode;
2924 /// ParseMetadataValue
2928 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2929 assert(Lex.getKind() == lltok::exclaim);
2934 if (Lex.getKind() == lltok::lbrace)
2935 return ParseMetadataListValue(ID, PFS);
2937 // Standalone metadata reference
2939 if (Lex.getKind() == lltok::APSInt) {
2940 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2941 ID.Kind = ValID::t_MDNode;
2946 // ::= '!' STRINGCONSTANT
2947 if (ParseMDString(ID.MDStringVal)) return true;
2948 ID.Kind = ValID::t_MDString;
2953 //===----------------------------------------------------------------------===//
2954 // Function Parsing.
2955 //===----------------------------------------------------------------------===//
2957 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2958 PerFunctionState *PFS) {
2959 if (Ty->isFunctionTy())
2960 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2963 case ValID::t_LocalID:
2964 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2965 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2966 return V == nullptr;
2967 case ValID::t_LocalName:
2968 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2969 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2970 return V == nullptr;
2971 case ValID::t_InlineAsm: {
2972 PointerType *PTy = dyn_cast<PointerType>(Ty);
2974 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2975 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2976 return Error(ID.Loc, "invalid type for inline asm constraint string");
2977 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2978 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2981 case ValID::t_MDNode:
2982 if (!Ty->isMetadataTy())
2983 return Error(ID.Loc, "metadata value must have metadata type");
2986 case ValID::t_MDString:
2987 if (!Ty->isMetadataTy())
2988 return Error(ID.Loc, "metadata value must have metadata type");
2991 case ValID::t_GlobalName:
2992 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2993 return V == nullptr;
2994 case ValID::t_GlobalID:
2995 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2996 return V == nullptr;
2997 case ValID::t_APSInt:
2998 if (!Ty->isIntegerTy())
2999 return Error(ID.Loc, "integer constant must have integer type");
3000 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3001 V = ConstantInt::get(Context, ID.APSIntVal);
3003 case ValID::t_APFloat:
3004 if (!Ty->isFloatingPointTy() ||
3005 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3006 return Error(ID.Loc, "floating point constant invalid for type");
3008 // The lexer has no type info, so builds all half, float, and double FP
3009 // constants as double. Fix this here. Long double does not need this.
3010 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3013 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3015 else if (Ty->isFloatTy())
3016 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3019 V = ConstantFP::get(Context, ID.APFloatVal);
3021 if (V->getType() != Ty)
3022 return Error(ID.Loc, "floating point constant does not have type '" +
3023 getTypeString(Ty) + "'");
3027 if (!Ty->isPointerTy())
3028 return Error(ID.Loc, "null must be a pointer type");
3029 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3031 case ValID::t_Undef:
3032 // FIXME: LabelTy should not be a first-class type.
3033 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3034 return Error(ID.Loc, "invalid type for undef constant");
3035 V = UndefValue::get(Ty);
3037 case ValID::t_EmptyArray:
3038 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3039 return Error(ID.Loc, "invalid empty array initializer");
3040 V = UndefValue::get(Ty);
3043 // FIXME: LabelTy should not be a first-class type.
3044 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3045 return Error(ID.Loc, "invalid type for null constant");
3046 V = Constant::getNullValue(Ty);
3048 case ValID::t_Constant:
3049 if (ID.ConstantVal->getType() != Ty)
3050 return Error(ID.Loc, "constant expression type mismatch");
3054 case ValID::t_ConstantStruct:
3055 case ValID::t_PackedConstantStruct:
3056 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3057 if (ST->getNumElements() != ID.UIntVal)
3058 return Error(ID.Loc,
3059 "initializer with struct type has wrong # elements");
3060 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3061 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3063 // Verify that the elements are compatible with the structtype.
3064 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3065 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3066 return Error(ID.Loc, "element " + Twine(i) +
3067 " of struct initializer doesn't match struct element type");
3069 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3072 return Error(ID.Loc, "constant expression type mismatch");
3075 llvm_unreachable("Invalid ValID");
3078 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3081 return ParseValID(ID, PFS) ||
3082 ConvertValIDToValue(Ty, ID, V, PFS);
3085 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3087 return ParseType(Ty) ||
3088 ParseValue(Ty, V, PFS);
3091 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3092 PerFunctionState &PFS) {
3095 if (ParseTypeAndValue(V, PFS)) return true;
3096 if (!isa<BasicBlock>(V))
3097 return Error(Loc, "expected a basic block");
3098 BB = cast<BasicBlock>(V);
3104 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3105 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3106 /// OptionalAlign OptGC OptionalPrefix
3107 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3108 // Parse the linkage.
3109 LocTy LinkageLoc = Lex.getLoc();
3112 unsigned Visibility;
3113 unsigned DLLStorageClass;
3114 AttrBuilder RetAttrs;
3116 Type *RetType = nullptr;
3117 LocTy RetTypeLoc = Lex.getLoc();
3118 if (ParseOptionalLinkage(Linkage) ||
3119 ParseOptionalVisibility(Visibility) ||
3120 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3121 ParseOptionalCallingConv(CC) ||
3122 ParseOptionalReturnAttrs(RetAttrs) ||
3123 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3126 // Verify that the linkage is ok.
3127 switch ((GlobalValue::LinkageTypes)Linkage) {
3128 case GlobalValue::ExternalLinkage:
3129 break; // always ok.
3130 case GlobalValue::ExternalWeakLinkage:
3132 return Error(LinkageLoc, "invalid linkage for function definition");
3134 case GlobalValue::PrivateLinkage:
3135 case GlobalValue::InternalLinkage:
3136 case GlobalValue::AvailableExternallyLinkage:
3137 case GlobalValue::LinkOnceAnyLinkage:
3138 case GlobalValue::LinkOnceODRLinkage:
3139 case GlobalValue::WeakAnyLinkage:
3140 case GlobalValue::WeakODRLinkage:
3142 return Error(LinkageLoc, "invalid linkage for function declaration");
3144 case GlobalValue::AppendingLinkage:
3145 case GlobalValue::CommonLinkage:
3146 return Error(LinkageLoc, "invalid function linkage type");
3149 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3150 return Error(LinkageLoc,
3151 "symbol with local linkage must have default visibility");
3153 if (!FunctionType::isValidReturnType(RetType))
3154 return Error(RetTypeLoc, "invalid function return type");
3156 LocTy NameLoc = Lex.getLoc();
3158 std::string FunctionName;
3159 if (Lex.getKind() == lltok::GlobalVar) {
3160 FunctionName = Lex.getStrVal();
3161 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3162 unsigned NameID = Lex.getUIntVal();
3164 if (NameID != NumberedVals.size())
3165 return TokError("function expected to be numbered '%" +
3166 Twine(NumberedVals.size()) + "'");
3168 return TokError("expected function name");
3173 if (Lex.getKind() != lltok::lparen)
3174 return TokError("expected '(' in function argument list");
3176 SmallVector<ArgInfo, 8> ArgList;
3178 AttrBuilder FuncAttrs;
3179 std::vector<unsigned> FwdRefAttrGrps;
3181 std::string Section;
3185 LocTy UnnamedAddrLoc;
3186 Constant *Prefix = nullptr;
3189 if (ParseArgumentList(ArgList, isVarArg) ||
3190 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3192 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3194 (EatIfPresent(lltok::kw_section) &&
3195 ParseStringConstant(Section)) ||
3196 parseOptionalComdat(C) ||
3197 ParseOptionalAlignment(Alignment) ||
3198 (EatIfPresent(lltok::kw_gc) &&
3199 ParseStringConstant(GC)) ||
3200 (EatIfPresent(lltok::kw_prefix) &&
3201 ParseGlobalTypeAndValue(Prefix)))
3204 if (FuncAttrs.contains(Attribute::Builtin))
3205 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3207 // If the alignment was parsed as an attribute, move to the alignment field.
3208 if (FuncAttrs.hasAlignmentAttr()) {
3209 Alignment = FuncAttrs.getAlignment();
3210 FuncAttrs.removeAttribute(Attribute::Alignment);
3213 // Okay, if we got here, the function is syntactically valid. Convert types
3214 // and do semantic checks.
3215 std::vector<Type*> ParamTypeList;
3216 SmallVector<AttributeSet, 8> Attrs;
3218 if (RetAttrs.hasAttributes())
3219 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3220 AttributeSet::ReturnIndex,
3223 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3224 ParamTypeList.push_back(ArgList[i].Ty);
3225 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3226 AttrBuilder B(ArgList[i].Attrs, i + 1);
3227 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3231 if (FuncAttrs.hasAttributes())
3232 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3233 AttributeSet::FunctionIndex,
3236 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3238 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3239 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3242 FunctionType::get(RetType, ParamTypeList, isVarArg);
3243 PointerType *PFT = PointerType::getUnqual(FT);
3246 if (!FunctionName.empty()) {
3247 // If this was a definition of a forward reference, remove the definition
3248 // from the forward reference table and fill in the forward ref.
3249 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3250 ForwardRefVals.find(FunctionName);
3251 if (FRVI != ForwardRefVals.end()) {
3252 Fn = M->getFunction(FunctionName);
3254 return Error(FRVI->second.second, "invalid forward reference to "
3255 "function as global value!");
3256 if (Fn->getType() != PFT)
3257 return Error(FRVI->second.second, "invalid forward reference to "
3258 "function '" + FunctionName + "' with wrong type!");
3260 ForwardRefVals.erase(FRVI);
3261 } else if ((Fn = M->getFunction(FunctionName))) {
3262 // Reject redefinitions.
3263 return Error(NameLoc, "invalid redefinition of function '" +
3264 FunctionName + "'");
3265 } else if (M->getNamedValue(FunctionName)) {
3266 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3270 // If this is a definition of a forward referenced function, make sure the
3272 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3273 = ForwardRefValIDs.find(NumberedVals.size());
3274 if (I != ForwardRefValIDs.end()) {
3275 Fn = cast<Function>(I->second.first);
3276 if (Fn->getType() != PFT)
3277 return Error(NameLoc, "type of definition and forward reference of '@" +
3278 Twine(NumberedVals.size()) + "' disagree");
3279 ForwardRefValIDs.erase(I);
3284 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3285 else // Move the forward-reference to the correct spot in the module.
3286 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3288 if (FunctionName.empty())
3289 NumberedVals.push_back(Fn);
3291 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3292 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3293 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3294 Fn->setCallingConv(CC);
3295 Fn->setAttributes(PAL);
3296 Fn->setUnnamedAddr(UnnamedAddr);
3297 Fn->setAlignment(Alignment);
3298 Fn->setSection(Section);
3300 if (!GC.empty()) Fn->setGC(GC.c_str());
3301 Fn->setPrefixData(Prefix);
3302 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3304 // Add all of the arguments we parsed to the function.
3305 Function::arg_iterator ArgIt = Fn->arg_begin();
3306 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3307 // If the argument has a name, insert it into the argument symbol table.
3308 if (ArgList[i].Name.empty()) continue;
3310 // Set the name, if it conflicted, it will be auto-renamed.
3311 ArgIt->setName(ArgList[i].Name);
3313 if (ArgIt->getName() != ArgList[i].Name)
3314 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3315 ArgList[i].Name + "'");
3321 // Check the a declaration has no block address forward references.
3323 if (FunctionName.empty()) {
3324 ID.Kind = ValID::t_GlobalID;
3325 ID.UIntVal = NumberedVals.size() - 1;
3327 ID.Kind = ValID::t_GlobalName;
3328 ID.StrVal = FunctionName;
3330 auto Blocks = ForwardRefBlockAddresses.find(ID);
3331 if (Blocks != ForwardRefBlockAddresses.end())
3332 return Error(Blocks->first.Loc,
3333 "cannot take blockaddress inside a declaration");
3337 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3339 if (FunctionNumber == -1) {
3340 ID.Kind = ValID::t_GlobalName;
3341 ID.StrVal = F.getName();
3343 ID.Kind = ValID::t_GlobalID;
3344 ID.UIntVal = FunctionNumber;
3347 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3348 if (Blocks == P.ForwardRefBlockAddresses.end())
3351 for (const auto &I : Blocks->second) {
3352 const ValID &BBID = I.first;
3353 GlobalValue *GV = I.second;
3355 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3356 "Expected local id or name");
3358 if (BBID.Kind == ValID::t_LocalName)
3359 BB = GetBB(BBID.StrVal, BBID.Loc);
3361 BB = GetBB(BBID.UIntVal, BBID.Loc);
3363 return P.Error(BBID.Loc, "referenced value is not a basic block");
3365 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3366 GV->eraseFromParent();
3369 P.ForwardRefBlockAddresses.erase(Blocks);
3373 /// ParseFunctionBody
3374 /// ::= '{' BasicBlock+ '}'
3376 bool LLParser::ParseFunctionBody(Function &Fn) {
3377 if (Lex.getKind() != lltok::lbrace)
3378 return TokError("expected '{' in function body");
3379 Lex.Lex(); // eat the {.
3381 int FunctionNumber = -1;
3382 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3384 PerFunctionState PFS(*this, Fn, FunctionNumber);
3386 // Resolve block addresses and allow basic blocks to be forward-declared
3387 // within this function.
3388 if (PFS.resolveForwardRefBlockAddresses())
3390 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3392 // We need at least one basic block.
3393 if (Lex.getKind() == lltok::rbrace)
3394 return TokError("function body requires at least one basic block");
3396 while (Lex.getKind() != lltok::rbrace)
3397 if (ParseBasicBlock(PFS)) return true;
3402 // Verify function is ok.
3403 return PFS.FinishFunction();
3407 /// ::= LabelStr? Instruction*
3408 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3409 // If this basic block starts out with a name, remember it.
3411 LocTy NameLoc = Lex.getLoc();
3412 if (Lex.getKind() == lltok::LabelStr) {
3413 Name = Lex.getStrVal();
3417 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3418 if (!BB) return true;
3420 std::string NameStr;
3422 // Parse the instructions in this block until we get a terminator.
3425 // This instruction may have three possibilities for a name: a) none
3426 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3427 LocTy NameLoc = Lex.getLoc();
3431 if (Lex.getKind() == lltok::LocalVarID) {
3432 NameID = Lex.getUIntVal();
3434 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3436 } else if (Lex.getKind() == lltok::LocalVar) {
3437 NameStr = Lex.getStrVal();
3439 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3443 switch (ParseInstruction(Inst, BB, PFS)) {
3444 default: llvm_unreachable("Unknown ParseInstruction result!");
3445 case InstError: return true;
3447 BB->getInstList().push_back(Inst);
3449 // With a normal result, we check to see if the instruction is followed by
3450 // a comma and metadata.
3451 if (EatIfPresent(lltok::comma))
3452 if (ParseInstructionMetadata(Inst, &PFS))
3455 case InstExtraComma:
3456 BB->getInstList().push_back(Inst);
3458 // If the instruction parser ate an extra comma at the end of it, it
3459 // *must* be followed by metadata.
3460 if (ParseInstructionMetadata(Inst, &PFS))
3465 // Set the name on the instruction.
3466 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3467 } while (!isa<TerminatorInst>(Inst));
3472 //===----------------------------------------------------------------------===//
3473 // Instruction Parsing.
3474 //===----------------------------------------------------------------------===//
3476 /// ParseInstruction - Parse one of the many different instructions.
3478 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3479 PerFunctionState &PFS) {
3480 lltok::Kind Token = Lex.getKind();
3481 if (Token == lltok::Eof)
3482 return TokError("found end of file when expecting more instructions");
3483 LocTy Loc = Lex.getLoc();
3484 unsigned KeywordVal = Lex.getUIntVal();
3485 Lex.Lex(); // Eat the keyword.
3488 default: return Error(Loc, "expected instruction opcode");
3489 // Terminator Instructions.
3490 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3491 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3492 case lltok::kw_br: return ParseBr(Inst, PFS);
3493 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3494 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3495 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3496 case lltok::kw_resume: return ParseResume(Inst, PFS);
3497 // Binary Operators.
3501 case lltok::kw_shl: {
3502 bool NUW = EatIfPresent(lltok::kw_nuw);
3503 bool NSW = EatIfPresent(lltok::kw_nsw);
3504 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3506 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3508 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3509 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3512 case lltok::kw_fadd:
3513 case lltok::kw_fsub:
3514 case lltok::kw_fmul:
3515 case lltok::kw_fdiv:
3516 case lltok::kw_frem: {
3517 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3518 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3522 Inst->setFastMathFlags(FMF);
3526 case lltok::kw_sdiv:
3527 case lltok::kw_udiv:
3528 case lltok::kw_lshr:
3529 case lltok::kw_ashr: {
3530 bool Exact = EatIfPresent(lltok::kw_exact);
3532 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3533 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3537 case lltok::kw_urem:
3538 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3541 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3542 case lltok::kw_icmp:
3543 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3545 case lltok::kw_trunc:
3546 case lltok::kw_zext:
3547 case lltok::kw_sext:
3548 case lltok::kw_fptrunc:
3549 case lltok::kw_fpext:
3550 case lltok::kw_bitcast:
3551 case lltok::kw_addrspacecast:
3552 case lltok::kw_uitofp:
3553 case lltok::kw_sitofp:
3554 case lltok::kw_fptoui:
3555 case lltok::kw_fptosi:
3556 case lltok::kw_inttoptr:
3557 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3559 case lltok::kw_select: return ParseSelect(Inst, PFS);
3560 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3561 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3562 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3563 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3564 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3565 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3567 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3568 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3569 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3571 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3572 case lltok::kw_load: return ParseLoad(Inst, PFS);
3573 case lltok::kw_store: return ParseStore(Inst, PFS);
3574 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3575 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3576 case lltok::kw_fence: return ParseFence(Inst, PFS);
3577 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3578 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3579 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3583 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3584 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3585 if (Opc == Instruction::FCmp) {
3586 switch (Lex.getKind()) {
3587 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3588 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3589 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3590 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3591 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3592 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3593 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3594 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3595 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3596 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3597 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3598 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3599 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3600 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3601 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3602 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3603 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3606 switch (Lex.getKind()) {
3607 default: return TokError("expected icmp predicate (e.g. 'eq')");
3608 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3609 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3610 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3611 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3612 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3613 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3614 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3615 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3616 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3617 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3624 //===----------------------------------------------------------------------===//
3625 // Terminator Instructions.
3626 //===----------------------------------------------------------------------===//
3628 /// ParseRet - Parse a return instruction.
3629 /// ::= 'ret' void (',' !dbg, !1)*
3630 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3631 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3632 PerFunctionState &PFS) {
3633 SMLoc TypeLoc = Lex.getLoc();
3635 if (ParseType(Ty, true /*void allowed*/)) return true;
3637 Type *ResType = PFS.getFunction().getReturnType();
3639 if (Ty->isVoidTy()) {
3640 if (!ResType->isVoidTy())
3641 return Error(TypeLoc, "value doesn't match function result type '" +
3642 getTypeString(ResType) + "'");
3644 Inst = ReturnInst::Create(Context);
3649 if (ParseValue(Ty, RV, PFS)) return true;
3651 if (ResType != RV->getType())
3652 return Error(TypeLoc, "value doesn't match function result type '" +
3653 getTypeString(ResType) + "'");
3655 Inst = ReturnInst::Create(Context, RV);
3661 /// ::= 'br' TypeAndValue
3662 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3663 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3666 BasicBlock *Op1, *Op2;
3667 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3669 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3670 Inst = BranchInst::Create(BB);
3674 if (Op0->getType() != Type::getInt1Ty(Context))
3675 return Error(Loc, "branch condition must have 'i1' type");
3677 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3678 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3679 ParseToken(lltok::comma, "expected ',' after true destination") ||
3680 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3683 Inst = BranchInst::Create(Op1, Op2, Op0);
3689 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3691 /// ::= (TypeAndValue ',' TypeAndValue)*
3692 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3693 LocTy CondLoc, BBLoc;
3695 BasicBlock *DefaultBB;
3696 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3697 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3698 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3699 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3702 if (!Cond->getType()->isIntegerTy())
3703 return Error(CondLoc, "switch condition must have integer type");
3705 // Parse the jump table pairs.
3706 SmallPtrSet<Value*, 32> SeenCases;
3707 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3708 while (Lex.getKind() != lltok::rsquare) {
3712 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3713 ParseToken(lltok::comma, "expected ',' after case value") ||
3714 ParseTypeAndBasicBlock(DestBB, PFS))
3717 if (!SeenCases.insert(Constant))
3718 return Error(CondLoc, "duplicate case value in switch");
3719 if (!isa<ConstantInt>(Constant))
3720 return Error(CondLoc, "case value is not a constant integer");
3722 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3725 Lex.Lex(); // Eat the ']'.
3727 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3728 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3729 SI->addCase(Table[i].first, Table[i].second);
3736 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3737 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3740 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3741 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3742 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3745 if (!Address->getType()->isPointerTy())
3746 return Error(AddrLoc, "indirectbr address must have pointer type");
3748 // Parse the destination list.
3749 SmallVector<BasicBlock*, 16> DestList;
3751 if (Lex.getKind() != lltok::rsquare) {
3753 if (ParseTypeAndBasicBlock(DestBB, PFS))
3755 DestList.push_back(DestBB);
3757 while (EatIfPresent(lltok::comma)) {
3758 if (ParseTypeAndBasicBlock(DestBB, PFS))
3760 DestList.push_back(DestBB);
3764 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3767 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3768 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3769 IBI->addDestination(DestList[i]);
3776 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3777 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3778 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3779 LocTy CallLoc = Lex.getLoc();
3780 AttrBuilder RetAttrs, FnAttrs;
3781 std::vector<unsigned> FwdRefAttrGrps;
3784 Type *RetType = nullptr;
3787 SmallVector<ParamInfo, 16> ArgList;
3789 BasicBlock *NormalBB, *UnwindBB;
3790 if (ParseOptionalCallingConv(CC) ||
3791 ParseOptionalReturnAttrs(RetAttrs) ||
3792 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3793 ParseValID(CalleeID) ||
3794 ParseParameterList(ArgList, PFS) ||
3795 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3797 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3798 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3799 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3800 ParseTypeAndBasicBlock(UnwindBB, PFS))
3803 // If RetType is a non-function pointer type, then this is the short syntax
3804 // for the call, which means that RetType is just the return type. Infer the
3805 // rest of the function argument types from the arguments that are present.
3806 PointerType *PFTy = nullptr;
3807 FunctionType *Ty = nullptr;
3808 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3809 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3810 // Pull out the types of all of the arguments...
3811 std::vector<Type*> ParamTypes;
3812 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3813 ParamTypes.push_back(ArgList[i].V->getType());
3815 if (!FunctionType::isValidReturnType(RetType))
3816 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3818 Ty = FunctionType::get(RetType, ParamTypes, false);
3819 PFTy = PointerType::getUnqual(Ty);
3822 // Look up the callee.
3824 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3826 // Set up the Attribute for the function.
3827 SmallVector<AttributeSet, 8> Attrs;
3828 if (RetAttrs.hasAttributes())
3829 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3830 AttributeSet::ReturnIndex,
3833 SmallVector<Value*, 8> Args;
3835 // Loop through FunctionType's arguments and ensure they are specified
3836 // correctly. Also, gather any parameter attributes.
3837 FunctionType::param_iterator I = Ty->param_begin();
3838 FunctionType::param_iterator E = Ty->param_end();
3839 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3840 Type *ExpectedTy = nullptr;
3843 } else if (!Ty->isVarArg()) {
3844 return Error(ArgList[i].Loc, "too many arguments specified");
3847 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3848 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3849 getTypeString(ExpectedTy) + "'");
3850 Args.push_back(ArgList[i].V);
3851 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3852 AttrBuilder B(ArgList[i].Attrs, i + 1);
3853 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3858 return Error(CallLoc, "not enough parameters specified for call");
3860 if (FnAttrs.hasAttributes())
3861 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3862 AttributeSet::FunctionIndex,
3865 // Finish off the Attribute and check them
3866 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3868 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3869 II->setCallingConv(CC);
3870 II->setAttributes(PAL);
3871 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3877 /// ::= 'resume' TypeAndValue
3878 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3879 Value *Exn; LocTy ExnLoc;
3880 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3883 ResumeInst *RI = ResumeInst::Create(Exn);
3888 //===----------------------------------------------------------------------===//
3889 // Binary Operators.
3890 //===----------------------------------------------------------------------===//
3893 /// ::= ArithmeticOps TypeAndValue ',' Value
3895 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3896 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3897 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3898 unsigned Opc, unsigned OperandType) {
3899 LocTy Loc; Value *LHS, *RHS;
3900 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3901 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3902 ParseValue(LHS->getType(), RHS, PFS))
3906 switch (OperandType) {
3907 default: llvm_unreachable("Unknown operand type!");
3908 case 0: // int or FP.
3909 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3910 LHS->getType()->isFPOrFPVectorTy();
3912 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3913 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3917 return Error(Loc, "invalid operand type for instruction");
3919 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3924 /// ::= ArithmeticOps TypeAndValue ',' Value {
3925 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3927 LocTy Loc; Value *LHS, *RHS;
3928 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3929 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3930 ParseValue(LHS->getType(), RHS, PFS))
3933 if (!LHS->getType()->isIntOrIntVectorTy())
3934 return Error(Loc,"instruction requires integer or integer vector operands");
3936 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3942 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3943 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3944 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3946 // Parse the integer/fp comparison predicate.
3950 if (ParseCmpPredicate(Pred, Opc) ||
3951 ParseTypeAndValue(LHS, Loc, PFS) ||
3952 ParseToken(lltok::comma, "expected ',' after compare value") ||
3953 ParseValue(LHS->getType(), RHS, PFS))
3956 if (Opc == Instruction::FCmp) {
3957 if (!LHS->getType()->isFPOrFPVectorTy())
3958 return Error(Loc, "fcmp requires floating point operands");
3959 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3961 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3962 if (!LHS->getType()->isIntOrIntVectorTy() &&
3963 !LHS->getType()->getScalarType()->isPointerTy())
3964 return Error(Loc, "icmp requires integer operands");
3965 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3970 //===----------------------------------------------------------------------===//
3971 // Other Instructions.
3972 //===----------------------------------------------------------------------===//
3976 /// ::= CastOpc TypeAndValue 'to' Type
3977 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3981 Type *DestTy = nullptr;
3982 if (ParseTypeAndValue(Op, Loc, PFS) ||
3983 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3987 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3988 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3989 return Error(Loc, "invalid cast opcode for cast from '" +
3990 getTypeString(Op->getType()) + "' to '" +
3991 getTypeString(DestTy) + "'");
3993 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3998 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3999 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4001 Value *Op0, *Op1, *Op2;
4002 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4003 ParseToken(lltok::comma, "expected ',' after select condition") ||
4004 ParseTypeAndValue(Op1, PFS) ||
4005 ParseToken(lltok::comma, "expected ',' after select value") ||
4006 ParseTypeAndValue(Op2, PFS))
4009 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4010 return Error(Loc, Reason);
4012 Inst = SelectInst::Create(Op0, Op1, Op2);
4017 /// ::= 'va_arg' TypeAndValue ',' Type
4018 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4020 Type *EltTy = nullptr;
4022 if (ParseTypeAndValue(Op, PFS) ||
4023 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4024 ParseType(EltTy, TypeLoc))
4027 if (!EltTy->isFirstClassType())
4028 return Error(TypeLoc, "va_arg requires operand with first class type");
4030 Inst = new VAArgInst(Op, EltTy);
4034 /// ParseExtractElement
4035 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4036 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4039 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4040 ParseToken(lltok::comma, "expected ',' after extract value") ||
4041 ParseTypeAndValue(Op1, PFS))
4044 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4045 return Error(Loc, "invalid extractelement operands");
4047 Inst = ExtractElementInst::Create(Op0, Op1);
4051 /// ParseInsertElement
4052 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4053 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4055 Value *Op0, *Op1, *Op2;
4056 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4057 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4058 ParseTypeAndValue(Op1, PFS) ||
4059 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4060 ParseTypeAndValue(Op2, PFS))
4063 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4064 return Error(Loc, "invalid insertelement operands");
4066 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4070 /// ParseShuffleVector
4071 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4072 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4074 Value *Op0, *Op1, *Op2;
4075 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4076 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4077 ParseTypeAndValue(Op1, PFS) ||
4078 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4079 ParseTypeAndValue(Op2, PFS))
4082 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4083 return Error(Loc, "invalid shufflevector operands");
4085 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4090 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4091 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4092 Type *Ty = nullptr; LocTy TypeLoc;
4095 if (ParseType(Ty, TypeLoc) ||
4096 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4097 ParseValue(Ty, Op0, PFS) ||
4098 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4099 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4100 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4103 bool AteExtraComma = false;
4104 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4106 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4108 if (!EatIfPresent(lltok::comma))
4111 if (Lex.getKind() == lltok::MetadataVar) {
4112 AteExtraComma = true;
4116 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4117 ParseValue(Ty, Op0, PFS) ||
4118 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4119 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4120 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4124 if (!Ty->isFirstClassType())
4125 return Error(TypeLoc, "phi node must have first class type");
4127 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4128 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4129 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4131 return AteExtraComma ? InstExtraComma : InstNormal;
4135 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4137 /// ::= 'catch' TypeAndValue
4139 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4140 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4141 Type *Ty = nullptr; LocTy TyLoc;
4142 Value *PersFn; LocTy PersFnLoc;
4144 if (ParseType(Ty, TyLoc) ||
4145 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4146 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4149 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4150 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4152 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4153 LandingPadInst::ClauseType CT;
4154 if (EatIfPresent(lltok::kw_catch))
4155 CT = LandingPadInst::Catch;
4156 else if (EatIfPresent(lltok::kw_filter))
4157 CT = LandingPadInst::Filter;
4159 return TokError("expected 'catch' or 'filter' clause type");
4163 if (ParseTypeAndValue(V, VLoc, PFS)) {
4168 // A 'catch' type expects a non-array constant. A filter clause expects an
4170 if (CT == LandingPadInst::Catch) {
4171 if (isa<ArrayType>(V->getType()))
4172 Error(VLoc, "'catch' clause has an invalid type");
4174 if (!isa<ArrayType>(V->getType()))
4175 Error(VLoc, "'filter' clause has an invalid type");
4178 LP->addClause(cast<Constant>(V));
4186 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4187 /// ParameterList OptionalAttrs
4188 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4189 /// ParameterList OptionalAttrs
4190 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4191 /// ParameterList OptionalAttrs
4192 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4193 CallInst::TailCallKind TCK) {
4194 AttrBuilder RetAttrs, FnAttrs;
4195 std::vector<unsigned> FwdRefAttrGrps;
4198 Type *RetType = nullptr;
4201 SmallVector<ParamInfo, 16> ArgList;
4202 LocTy CallLoc = Lex.getLoc();
4204 if ((TCK != CallInst::TCK_None &&
4205 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4206 ParseOptionalCallingConv(CC) ||
4207 ParseOptionalReturnAttrs(RetAttrs) ||
4208 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4209 ParseValID(CalleeID) ||
4210 ParseParameterList(ArgList, PFS) ||
4211 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4215 // If RetType is a non-function pointer type, then this is the short syntax
4216 // for the call, which means that RetType is just the return type. Infer the
4217 // rest of the function argument types from the arguments that are present.
4218 PointerType *PFTy = nullptr;
4219 FunctionType *Ty = nullptr;
4220 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4221 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4222 // Pull out the types of all of the arguments...
4223 std::vector<Type*> ParamTypes;
4224 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4225 ParamTypes.push_back(ArgList[i].V->getType());
4227 if (!FunctionType::isValidReturnType(RetType))
4228 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4230 Ty = FunctionType::get(RetType, ParamTypes, false);
4231 PFTy = PointerType::getUnqual(Ty);
4234 // Look up the callee.
4236 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4238 // Set up the Attribute for the function.
4239 SmallVector<AttributeSet, 8> Attrs;
4240 if (RetAttrs.hasAttributes())
4241 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4242 AttributeSet::ReturnIndex,
4245 SmallVector<Value*, 8> Args;
4247 // Loop through FunctionType's arguments and ensure they are specified
4248 // correctly. Also, gather any parameter attributes.
4249 FunctionType::param_iterator I = Ty->param_begin();
4250 FunctionType::param_iterator E = Ty->param_end();
4251 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4252 Type *ExpectedTy = nullptr;
4255 } else if (!Ty->isVarArg()) {
4256 return Error(ArgList[i].Loc, "too many arguments specified");
4259 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4260 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4261 getTypeString(ExpectedTy) + "'");
4262 Args.push_back(ArgList[i].V);
4263 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4264 AttrBuilder B(ArgList[i].Attrs, i + 1);
4265 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4270 return Error(CallLoc, "not enough parameters specified for call");
4272 if (FnAttrs.hasAttributes())
4273 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4274 AttributeSet::FunctionIndex,
4277 // Finish off the Attribute and check them
4278 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4280 CallInst *CI = CallInst::Create(Callee, Args);
4281 CI->setTailCallKind(TCK);
4282 CI->setCallingConv(CC);
4283 CI->setAttributes(PAL);
4284 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4289 //===----------------------------------------------------------------------===//
4290 // Memory Instructions.
4291 //===----------------------------------------------------------------------===//
4294 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4295 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4296 Value *Size = nullptr;
4298 unsigned Alignment = 0;
4301 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4303 if (ParseType(Ty)) return true;
4305 bool AteExtraComma = false;
4306 if (EatIfPresent(lltok::comma)) {
4307 if (Lex.getKind() == lltok::kw_align) {
4308 if (ParseOptionalAlignment(Alignment)) return true;
4309 } else if (Lex.getKind() == lltok::MetadataVar) {
4310 AteExtraComma = true;
4312 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4313 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4318 if (Size && !Size->getType()->isIntegerTy())
4319 return Error(SizeLoc, "element count must have integer type");
4321 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4322 AI->setUsedWithInAlloca(IsInAlloca);
4324 return AteExtraComma ? InstExtraComma : InstNormal;
4328 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4329 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4330 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4331 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4332 Value *Val; LocTy Loc;
4333 unsigned Alignment = 0;
4334 bool AteExtraComma = false;
4335 bool isAtomic = false;
4336 AtomicOrdering Ordering = NotAtomic;
4337 SynchronizationScope Scope = CrossThread;
4339 if (Lex.getKind() == lltok::kw_atomic) {
4344 bool isVolatile = false;
4345 if (Lex.getKind() == lltok::kw_volatile) {
4350 if (ParseTypeAndValue(Val, Loc, PFS) ||
4351 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4352 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4355 if (!Val->getType()->isPointerTy() ||
4356 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4357 return Error(Loc, "load operand must be a pointer to a first class type");
4358 if (isAtomic && !Alignment)
4359 return Error(Loc, "atomic load must have explicit non-zero alignment");
4360 if (Ordering == Release || Ordering == AcquireRelease)
4361 return Error(Loc, "atomic load cannot use Release ordering");
4363 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4364 return AteExtraComma ? InstExtraComma : InstNormal;
4369 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4370 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4371 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4372 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4373 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4374 unsigned Alignment = 0;
4375 bool AteExtraComma = false;
4376 bool isAtomic = false;
4377 AtomicOrdering Ordering = NotAtomic;
4378 SynchronizationScope Scope = CrossThread;
4380 if (Lex.getKind() == lltok::kw_atomic) {
4385 bool isVolatile = false;
4386 if (Lex.getKind() == lltok::kw_volatile) {
4391 if (ParseTypeAndValue(Val, Loc, PFS) ||
4392 ParseToken(lltok::comma, "expected ',' after store operand") ||
4393 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4394 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4395 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4398 if (!Ptr->getType()->isPointerTy())
4399 return Error(PtrLoc, "store operand must be a pointer");
4400 if (!Val->getType()->isFirstClassType())
4401 return Error(Loc, "store operand must be a first class value");
4402 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4403 return Error(Loc, "stored value and pointer type do not match");
4404 if (isAtomic && !Alignment)
4405 return Error(Loc, "atomic store must have explicit non-zero alignment");
4406 if (Ordering == Acquire || Ordering == AcquireRelease)
4407 return Error(Loc, "atomic store cannot use Acquire ordering");
4409 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4410 return AteExtraComma ? InstExtraComma : InstNormal;
4414 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4415 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4416 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4417 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4418 bool AteExtraComma = false;
4419 AtomicOrdering SuccessOrdering = NotAtomic;
4420 AtomicOrdering FailureOrdering = NotAtomic;
4421 SynchronizationScope Scope = CrossThread;
4422 bool isVolatile = false;
4423 bool isWeak = false;
4425 if (EatIfPresent(lltok::kw_weak))
4428 if (EatIfPresent(lltok::kw_volatile))
4431 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4432 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4433 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4434 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4435 ParseTypeAndValue(New, NewLoc, PFS) ||
4436 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4437 ParseOrdering(FailureOrdering))
4440 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4441 return TokError("cmpxchg cannot be unordered");
4442 if (SuccessOrdering < FailureOrdering)
4443 return TokError("cmpxchg must be at least as ordered on success as failure");
4444 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4445 return TokError("cmpxchg failure ordering cannot include release semantics");
4446 if (!Ptr->getType()->isPointerTy())
4447 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4448 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4449 return Error(CmpLoc, "compare value and pointer type do not match");
4450 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4451 return Error(NewLoc, "new value and pointer type do not match");
4452 if (!New->getType()->isIntegerTy())
4453 return Error(NewLoc, "cmpxchg operand must be an integer");
4454 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4455 if (Size < 8 || (Size & (Size - 1)))
4456 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4459 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4460 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4461 CXI->setVolatile(isVolatile);
4462 CXI->setWeak(isWeak);
4464 return AteExtraComma ? InstExtraComma : InstNormal;
4468 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4469 /// 'singlethread'? AtomicOrdering
4470 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4471 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4472 bool AteExtraComma = false;
4473 AtomicOrdering Ordering = NotAtomic;
4474 SynchronizationScope Scope = CrossThread;
4475 bool isVolatile = false;
4476 AtomicRMWInst::BinOp Operation;
4478 if (EatIfPresent(lltok::kw_volatile))
4481 switch (Lex.getKind()) {
4482 default: return TokError("expected binary operation in atomicrmw");
4483 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4484 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4485 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4486 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4487 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4488 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4489 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4490 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4491 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4492 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4493 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4495 Lex.Lex(); // Eat the operation.
4497 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4498 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4499 ParseTypeAndValue(Val, ValLoc, PFS) ||
4500 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4503 if (Ordering == Unordered)
4504 return TokError("atomicrmw cannot be unordered");
4505 if (!Ptr->getType()->isPointerTy())
4506 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4507 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4508 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4509 if (!Val->getType()->isIntegerTy())
4510 return Error(ValLoc, "atomicrmw operand must be an integer");
4511 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4512 if (Size < 8 || (Size & (Size - 1)))
4513 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4516 AtomicRMWInst *RMWI =
4517 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4518 RMWI->setVolatile(isVolatile);
4520 return AteExtraComma ? InstExtraComma : InstNormal;
4524 /// ::= 'fence' 'singlethread'? AtomicOrdering
4525 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4526 AtomicOrdering Ordering = NotAtomic;
4527 SynchronizationScope Scope = CrossThread;
4528 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4531 if (Ordering == Unordered)
4532 return TokError("fence cannot be unordered");
4533 if (Ordering == Monotonic)
4534 return TokError("fence cannot be monotonic");
4536 Inst = new FenceInst(Context, Ordering, Scope);
4540 /// ParseGetElementPtr
4541 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4542 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4543 Value *Ptr = nullptr;
4544 Value *Val = nullptr;
4547 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4549 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4551 Type *BaseType = Ptr->getType();
4552 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4553 if (!BasePointerType)
4554 return Error(Loc, "base of getelementptr must be a pointer");
4556 SmallVector<Value*, 16> Indices;
4557 bool AteExtraComma = false;
4558 while (EatIfPresent(lltok::comma)) {
4559 if (Lex.getKind() == lltok::MetadataVar) {
4560 AteExtraComma = true;
4563 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4564 if (!Val->getType()->getScalarType()->isIntegerTy())
4565 return Error(EltLoc, "getelementptr index must be an integer");
4566 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4567 return Error(EltLoc, "getelementptr index type missmatch");
4568 if (Val->getType()->isVectorTy()) {
4569 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4570 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4571 if (ValNumEl != PtrNumEl)
4572 return Error(EltLoc,
4573 "getelementptr vector index has a wrong number of elements");
4575 Indices.push_back(Val);
4578 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4579 return Error(Loc, "base element of getelementptr must be sized");
4581 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4582 return Error(Loc, "invalid getelementptr indices");
4583 Inst = GetElementPtrInst::Create(Ptr, Indices);
4585 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4586 return AteExtraComma ? InstExtraComma : InstNormal;
4589 /// ParseExtractValue
4590 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4591 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4592 Value *Val; LocTy Loc;
4593 SmallVector<unsigned, 4> Indices;
4595 if (ParseTypeAndValue(Val, Loc, PFS) ||
4596 ParseIndexList(Indices, AteExtraComma))
4599 if (!Val->getType()->isAggregateType())
4600 return Error(Loc, "extractvalue operand must be aggregate type");
4602 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4603 return Error(Loc, "invalid indices for extractvalue");
4604 Inst = ExtractValueInst::Create(Val, Indices);
4605 return AteExtraComma ? InstExtraComma : InstNormal;
4608 /// ParseInsertValue
4609 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4610 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4611 Value *Val0, *Val1; LocTy Loc0, Loc1;
4612 SmallVector<unsigned, 4> Indices;
4614 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4615 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4616 ParseTypeAndValue(Val1, Loc1, PFS) ||
4617 ParseIndexList(Indices, AteExtraComma))
4620 if (!Val0->getType()->isAggregateType())
4621 return Error(Loc0, "insertvalue operand must be aggregate type");
4623 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4624 return Error(Loc0, "invalid indices for insertvalue");
4625 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4626 return AteExtraComma ? InstExtraComma : InstNormal;
4629 //===----------------------------------------------------------------------===//
4630 // Embedded metadata.
4631 //===----------------------------------------------------------------------===//
4633 /// ParseMDNodeVector
4634 /// ::= Element (',' Element)*
4636 /// ::= 'null' | TypeAndValue
4637 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4638 PerFunctionState *PFS) {
4639 // Check for an empty list.
4640 if (Lex.getKind() == lltok::rbrace)
4644 // Null is a special case since it is typeless.
4645 if (EatIfPresent(lltok::kw_null)) {
4646 Elts.push_back(nullptr);
4651 if (ParseTypeAndValue(V, PFS)) return true;
4653 } while (EatIfPresent(lltok::comma));