1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
67 ForwardRefInstMetadata.clear();
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
78 std::vector<unsigned> &Vec = I->second;
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 B.merge(NumberedAttrBuilders[*VI]);
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
93 // If the alignment was parsed as an attribute, move to the alignment
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
126 II->setAttributes(AS);
128 llvm_unreachable("invalid object with forward attribute group reference");
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
166 if (!ForwardRefVals.empty())
167 return Error(ForwardRefVals.begin()->second.second,
168 "use of undefined value '@" + ForwardRefVals.begin()->first +
171 if (!ForwardRefValIDs.empty())
172 return Error(ForwardRefValIDs.begin()->second.second,
173 "use of undefined value '@" +
174 Twine(ForwardRefValIDs.begin()->first) + "'");
176 if (!ForwardRefMDNodes.empty())
177 return Error(ForwardRefMDNodes.begin()->second.second,
178 "use of undefined metadata '!" +
179 Twine(ForwardRefMDNodes.begin()->first) + "'");
182 // Look for intrinsic functions and CallInst that need to be upgraded
183 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
184 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
186 UpgradeDebugInfo(*M);
191 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
192 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
193 PerFunctionState *PFS) {
194 // Loop over all the references, resolving them.
195 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
198 if (Refs[i].first.Kind == ValID::t_LocalName)
199 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
201 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
202 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
203 return Error(Refs[i].first.Loc,
204 "cannot take address of numeric label after the function is defined");
206 Res = dyn_cast_or_null<BasicBlock>(
207 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
211 return Error(Refs[i].first.Loc,
212 "referenced value is not a basic block");
214 // Get the BlockAddress for this and update references to use it.
215 BlockAddress *BA = BlockAddress::get(TheFn, Res);
216 Refs[i].second->replaceAllUsesWith(BA);
217 Refs[i].second->eraseFromParent();
223 //===----------------------------------------------------------------------===//
224 // Top-Level Entities
225 //===----------------------------------------------------------------------===//
227 bool LLParser::ParseTopLevelEntities() {
229 switch (Lex.getKind()) {
230 default: return TokError("expected top-level entity");
231 case lltok::Eof: return false;
232 case lltok::kw_declare: if (ParseDeclare()) return true; break;
233 case lltok::kw_define: if (ParseDefine()) return true; break;
234 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
235 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
236 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
237 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
238 case lltok::LocalVar: if (ParseNamedType()) return true; break;
239 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
240 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
241 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
242 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
244 // The Global variable production with no name can have many different
245 // optional leading prefixes, the production is:
246 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
247 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
248 // ('constant'|'global') ...
249 case lltok::kw_private: // OptionalLinkage
250 case lltok::kw_internal: // OptionalLinkage
251 case lltok::kw_linker_private: // Obsolete OptionalLinkage
252 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
253 case lltok::kw_weak: // OptionalLinkage
254 case lltok::kw_weak_odr: // OptionalLinkage
255 case lltok::kw_linkonce: // OptionalLinkage
256 case lltok::kw_linkonce_odr: // OptionalLinkage
257 case lltok::kw_appending: // OptionalLinkage
258 case lltok::kw_common: // OptionalLinkage
259 case lltok::kw_extern_weak: // OptionalLinkage
260 case lltok::kw_external: { // OptionalLinkage
261 unsigned Linkage, Visibility, DLLStorageClass;
262 GlobalVariable::ThreadLocalMode TLM;
263 if (ParseOptionalLinkage(Linkage) ||
264 ParseOptionalVisibility(Visibility) ||
265 ParseOptionalDLLStorageClass(DLLStorageClass) ||
266 ParseOptionalThreadLocal(TLM) ||
267 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass,
272 case lltok::kw_default: // OptionalVisibility
273 case lltok::kw_hidden: // OptionalVisibility
274 case lltok::kw_protected: { // OptionalVisibility
275 unsigned Visibility, DLLStorageClass;
276 GlobalVariable::ThreadLocalMode TLM;
277 if (ParseOptionalVisibility(Visibility) ||
278 ParseOptionalDLLStorageClass(DLLStorageClass) ||
279 ParseOptionalThreadLocal(TLM) ||
280 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass, TLM))
285 case lltok::kw_thread_local: { // OptionalThreadLocal
286 GlobalVariable::ThreadLocalMode TLM;
287 if (ParseOptionalThreadLocal(TLM) ||
288 ParseGlobal("", SMLoc(), 0, false, 0, 0, TLM))
293 case lltok::kw_addrspace: // OptionalAddrSpace
294 case lltok::kw_constant: // GlobalType
295 case lltok::kw_global: // GlobalType
296 if (ParseGlobal("", SMLoc(), 0, false, 0, 0, GlobalValue::NotThreadLocal))
300 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
307 /// ::= 'module' 'asm' STRINGCONSTANT
308 bool LLParser::ParseModuleAsm() {
309 assert(Lex.getKind() == lltok::kw_module);
313 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
314 ParseStringConstant(AsmStr)) return true;
316 M->appendModuleInlineAsm(AsmStr);
321 /// ::= 'target' 'triple' '=' STRINGCONSTANT
322 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
323 bool LLParser::ParseTargetDefinition() {
324 assert(Lex.getKind() == lltok::kw_target);
327 default: return TokError("unknown target property");
328 case lltok::kw_triple:
330 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
331 ParseStringConstant(Str))
333 M->setTargetTriple(Str);
335 case lltok::kw_datalayout:
337 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
338 ParseStringConstant(Str))
340 M->setDataLayout(Str);
346 /// ::= 'deplibs' '=' '[' ']'
347 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
348 /// FIXME: Remove in 4.0. Currently parse, but ignore.
349 bool LLParser::ParseDepLibs() {
350 assert(Lex.getKind() == lltok::kw_deplibs);
352 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
353 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
356 if (EatIfPresent(lltok::rsquare))
361 if (ParseStringConstant(Str)) return true;
362 } while (EatIfPresent(lltok::comma));
364 return ParseToken(lltok::rsquare, "expected ']' at end of list");
367 /// ParseUnnamedType:
368 /// ::= LocalVarID '=' 'type' type
369 bool LLParser::ParseUnnamedType() {
370 LocTy TypeLoc = Lex.getLoc();
371 unsigned TypeID = Lex.getUIntVal();
372 Lex.Lex(); // eat LocalVarID;
374 if (ParseToken(lltok::equal, "expected '=' after name") ||
375 ParseToken(lltok::kw_type, "expected 'type' after '='"))
378 if (TypeID >= NumberedTypes.size())
379 NumberedTypes.resize(TypeID+1);
381 Type *Result = nullptr;
382 if (ParseStructDefinition(TypeLoc, "",
383 NumberedTypes[TypeID], Result)) return true;
385 if (!isa<StructType>(Result)) {
386 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
388 return Error(TypeLoc, "non-struct types may not be recursive");
389 Entry.first = Result;
390 Entry.second = SMLoc();
398 /// ::= LocalVar '=' 'type' type
399 bool LLParser::ParseNamedType() {
400 std::string Name = Lex.getStrVal();
401 LocTy NameLoc = Lex.getLoc();
402 Lex.Lex(); // eat LocalVar.
404 if (ParseToken(lltok::equal, "expected '=' after name") ||
405 ParseToken(lltok::kw_type, "expected 'type' after name"))
408 Type *Result = nullptr;
409 if (ParseStructDefinition(NameLoc, Name,
410 NamedTypes[Name], Result)) return true;
412 if (!isa<StructType>(Result)) {
413 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
415 return Error(NameLoc, "non-struct types may not be recursive");
416 Entry.first = Result;
417 Entry.second = SMLoc();
425 /// ::= 'declare' FunctionHeader
426 bool LLParser::ParseDeclare() {
427 assert(Lex.getKind() == lltok::kw_declare);
431 return ParseFunctionHeader(F, false);
435 /// ::= 'define' FunctionHeader '{' ...
436 bool LLParser::ParseDefine() {
437 assert(Lex.getKind() == lltok::kw_define);
441 return ParseFunctionHeader(F, true) ||
442 ParseFunctionBody(*F);
448 bool LLParser::ParseGlobalType(bool &IsConstant) {
449 if (Lex.getKind() == lltok::kw_constant)
451 else if (Lex.getKind() == lltok::kw_global)
455 return TokError("expected 'global' or 'constant'");
461 /// ParseUnnamedGlobal:
462 /// OptionalVisibility ALIAS ...
463 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
464 /// ... -> global variable
465 /// GlobalID '=' OptionalVisibility ALIAS ...
466 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
467 /// ... -> global variable
468 bool LLParser::ParseUnnamedGlobal() {
469 unsigned VarID = NumberedVals.size();
471 LocTy NameLoc = Lex.getLoc();
473 // Handle the GlobalID form.
474 if (Lex.getKind() == lltok::GlobalID) {
475 if (Lex.getUIntVal() != VarID)
476 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
478 Lex.Lex(); // eat GlobalID;
480 if (ParseToken(lltok::equal, "expected '=' after name"))
485 unsigned Linkage, Visibility, DLLStorageClass;
486 GlobalVariable::ThreadLocalMode TLM;
487 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
488 ParseOptionalVisibility(Visibility) ||
489 ParseOptionalDLLStorageClass(DLLStorageClass) ||
490 ParseOptionalThreadLocal(TLM))
493 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
494 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
495 DLLStorageClass, TLM);
496 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
499 /// ParseNamedGlobal:
500 /// GlobalVar '=' OptionalVisibility ALIAS ...
501 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
502 /// ... -> global variable
503 bool LLParser::ParseNamedGlobal() {
504 assert(Lex.getKind() == lltok::GlobalVar);
505 LocTy NameLoc = Lex.getLoc();
506 std::string Name = Lex.getStrVal();
510 unsigned Linkage, Visibility, DLLStorageClass;
511 GlobalVariable::ThreadLocalMode TLM;
512 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
513 ParseOptionalLinkage(Linkage, HasLinkage) ||
514 ParseOptionalVisibility(Visibility) ||
515 ParseOptionalDLLStorageClass(DLLStorageClass) ||
516 ParseOptionalThreadLocal(TLM))
519 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
520 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
521 DLLStorageClass, TLM);
522 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
526 // ::= '!' STRINGCONSTANT
527 bool LLParser::ParseMDString(MDString *&Result) {
529 if (ParseStringConstant(Str)) return true;
530 Result = MDString::get(Context, Str);
535 // ::= '!' MDNodeNumber
537 /// This version of ParseMDNodeID returns the slot number and null in the case
538 /// of a forward reference.
539 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
540 // !{ ..., !42, ... }
541 if (ParseUInt32(SlotNo)) return true;
543 // Check existing MDNode.
544 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
545 Result = NumberedMetadata[SlotNo];
551 bool LLParser::ParseMDNodeID(MDNode *&Result) {
552 // !{ ..., !42, ... }
554 if (ParseMDNodeID(Result, MID)) return true;
556 // If not a forward reference, just return it now.
557 if (Result) return false;
559 // Otherwise, create MDNode forward reference.
560 MDNode *FwdNode = MDNode::getTemporary(Context, None);
561 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
563 if (NumberedMetadata.size() <= MID)
564 NumberedMetadata.resize(MID+1);
565 NumberedMetadata[MID] = FwdNode;
570 /// ParseNamedMetadata:
571 /// !foo = !{ !1, !2 }
572 bool LLParser::ParseNamedMetadata() {
573 assert(Lex.getKind() == lltok::MetadataVar);
574 std::string Name = Lex.getStrVal();
577 if (ParseToken(lltok::equal, "expected '=' here") ||
578 ParseToken(lltok::exclaim, "Expected '!' here") ||
579 ParseToken(lltok::lbrace, "Expected '{' here"))
582 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
583 if (Lex.getKind() != lltok::rbrace)
585 if (ParseToken(lltok::exclaim, "Expected '!' here"))
589 if (ParseMDNodeID(N)) return true;
591 } while (EatIfPresent(lltok::comma));
593 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
599 /// ParseStandaloneMetadata:
601 bool LLParser::ParseStandaloneMetadata() {
602 assert(Lex.getKind() == lltok::exclaim);
604 unsigned MetadataID = 0;
608 SmallVector<Value *, 16> Elts;
609 if (ParseUInt32(MetadataID) ||
610 ParseToken(lltok::equal, "expected '=' here") ||
611 ParseType(Ty, TyLoc) ||
612 ParseToken(lltok::exclaim, "Expected '!' here") ||
613 ParseToken(lltok::lbrace, "Expected '{' here") ||
614 ParseMDNodeVector(Elts, nullptr) ||
615 ParseToken(lltok::rbrace, "expected end of metadata node"))
618 MDNode *Init = MDNode::get(Context, Elts);
620 // See if this was forward referenced, if so, handle it.
621 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
622 FI = ForwardRefMDNodes.find(MetadataID);
623 if (FI != ForwardRefMDNodes.end()) {
624 MDNode *Temp = FI->second.first;
625 Temp->replaceAllUsesWith(Init);
626 MDNode::deleteTemporary(Temp);
627 ForwardRefMDNodes.erase(FI);
629 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
631 if (MetadataID >= NumberedMetadata.size())
632 NumberedMetadata.resize(MetadataID+1);
634 if (NumberedMetadata[MetadataID] != nullptr)
635 return TokError("Metadata id is already used");
636 NumberedMetadata[MetadataID] = Init;
642 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
643 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
644 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
648 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
649 /// OptionalLinkage Aliasee
650 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
651 /// OptionalLinkage OptionalAddrSpace Type, Aliasee
656 /// Everything through DLL storage class has already been parsed.
658 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
659 unsigned Visibility, unsigned DLLStorageClass,
660 GlobalVariable::ThreadLocalMode TLM) {
661 assert(Lex.getKind() == lltok::kw_alias);
663 LocTy LinkageLoc = Lex.getLoc();
665 if (ParseOptionalLinkage(L))
668 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
670 if(!GlobalAlias::isValidLinkage(Linkage))
671 return Error(LinkageLoc, "invalid linkage type for alias");
673 if (!isValidVisibilityForLinkage(Visibility, L))
674 return Error(LinkageLoc,
675 "symbol with local linkage must have default visibility");
677 bool HasAddrSpace = Lex.getKind() == lltok::kw_addrspace;
679 LocTy AddrSpaceLoc = Lex.getLoc();
680 if (ParseOptionalAddrSpace(AddrSpace))
683 LocTy TyLoc = Lex.getLoc();
688 bool DifferentType = EatIfPresent(lltok::comma);
689 if (HasAddrSpace && !DifferentType)
690 return Error(AddrSpaceLoc, "A type is required if addrspace is given");
692 Type *AliaseeType = nullptr;
694 if (ParseType(AliaseeType))
698 auto *PTy = dyn_cast<PointerType>(Ty);
700 return Error(TyLoc, "An alias must have pointer type");
701 Ty = PTy->getElementType();
702 AddrSpace = PTy->getAddressSpace();
705 LocTy AliaseeLoc = Lex.getLoc();
707 if (ParseGlobalValue(AliaseeType, C))
710 auto *Aliasee = dyn_cast<GlobalObject>(C);
712 return Error(AliaseeLoc, "Alias must point to function or variable");
714 assert(Aliasee->getType()->isPointerTy());
716 // Okay, create the alias but do not insert it into the module yet.
717 std::unique_ptr<GlobalAlias> GA(
718 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
719 Name, Aliasee, /*Parent*/ nullptr));
720 GA->setThreadLocalMode(TLM);
721 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
722 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
724 // See if this value already exists in the symbol table. If so, it is either
725 // a redefinition or a definition of a forward reference.
726 if (GlobalValue *Val = M->getNamedValue(Name)) {
727 // See if this was a redefinition. If so, there is no entry in
729 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
730 I = ForwardRefVals.find(Name);
731 if (I == ForwardRefVals.end())
732 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
734 // Otherwise, this was a definition of forward ref. Verify that types
736 if (Val->getType() != GA->getType())
737 return Error(NameLoc,
738 "forward reference and definition of alias have different types");
740 // If they agree, just RAUW the old value with the alias and remove the
742 for (auto *User : Val->users()) {
743 if (auto *GA = dyn_cast<GlobalAlias>(User))
744 return Error(NameLoc, "Alias is pointed by alias " + GA->getName());
747 Val->replaceAllUsesWith(GA.get());
748 Val->eraseFromParent();
749 ForwardRefVals.erase(I);
752 // Insert into the module, we know its name won't collide now.
753 M->getAliasList().push_back(GA.get());
754 assert(GA->getName() == Name && "Should not be a name conflict!");
756 // The module owns this now
763 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
764 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
765 /// OptionalExternallyInitialized GlobalType Type Const
766 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
767 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
768 /// OptionalExternallyInitialized GlobalType Type Const
770 /// Everything up to and including OptionalDLLStorageClass has been parsed
773 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
774 unsigned Linkage, bool HasLinkage,
775 unsigned Visibility, unsigned DLLStorageClass,
776 GlobalVariable::ThreadLocalMode TLM) {
777 if (!isValidVisibilityForLinkage(Visibility, Linkage))
778 return Error(NameLoc,
779 "symbol with local linkage must have default visibility");
782 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
783 LocTy UnnamedAddrLoc;
784 LocTy IsExternallyInitializedLoc;
788 if (ParseOptionalAddrSpace(AddrSpace) ||
789 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
791 ParseOptionalToken(lltok::kw_externally_initialized,
792 IsExternallyInitialized,
793 &IsExternallyInitializedLoc) ||
794 ParseGlobalType(IsConstant) ||
795 ParseType(Ty, TyLoc))
798 // If the linkage is specified and is external, then no initializer is
800 Constant *Init = nullptr;
801 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
802 Linkage != GlobalValue::ExternalLinkage)) {
803 if (ParseGlobalValue(Ty, Init))
807 if (Ty->isFunctionTy() || Ty->isLabelTy())
808 return Error(TyLoc, "invalid type for global variable");
810 GlobalVariable *GV = nullptr;
812 // See if the global was forward referenced, if so, use the global.
814 if (GlobalValue *GVal = M->getNamedValue(Name)) {
815 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
816 return Error(NameLoc, "redefinition of global '@" + Name + "'");
817 GV = cast<GlobalVariable>(GVal);
820 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
821 I = ForwardRefValIDs.find(NumberedVals.size());
822 if (I != ForwardRefValIDs.end()) {
823 GV = cast<GlobalVariable>(I->second.first);
824 ForwardRefValIDs.erase(I);
829 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
830 Name, nullptr, GlobalVariable::NotThreadLocal,
833 if (GV->getType()->getElementType() != Ty)
835 "forward reference and definition of global have different types");
837 // Move the forward-reference to the correct spot in the module.
838 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
842 NumberedVals.push_back(GV);
844 // Set the parsed properties on the global.
846 GV->setInitializer(Init);
847 GV->setConstant(IsConstant);
848 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
849 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
850 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
851 GV->setExternallyInitialized(IsExternallyInitialized);
852 GV->setThreadLocalMode(TLM);
853 GV->setUnnamedAddr(UnnamedAddr);
855 // Parse attributes on the global.
856 while (Lex.getKind() == lltok::comma) {
859 if (Lex.getKind() == lltok::kw_section) {
861 GV->setSection(Lex.getStrVal());
862 if (ParseToken(lltok::StringConstant, "expected global section string"))
864 } else if (Lex.getKind() == lltok::kw_align) {
866 if (ParseOptionalAlignment(Alignment)) return true;
867 GV->setAlignment(Alignment);
869 TokError("unknown global variable property!");
876 /// ParseUnnamedAttrGrp
877 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
878 bool LLParser::ParseUnnamedAttrGrp() {
879 assert(Lex.getKind() == lltok::kw_attributes);
880 LocTy AttrGrpLoc = Lex.getLoc();
883 assert(Lex.getKind() == lltok::AttrGrpID);
884 unsigned VarID = Lex.getUIntVal();
885 std::vector<unsigned> unused;
889 if (ParseToken(lltok::equal, "expected '=' here") ||
890 ParseToken(lltok::lbrace, "expected '{' here") ||
891 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
893 ParseToken(lltok::rbrace, "expected end of attribute group"))
896 if (!NumberedAttrBuilders[VarID].hasAttributes())
897 return Error(AttrGrpLoc, "attribute group has no attributes");
902 /// ParseFnAttributeValuePairs
903 /// ::= <attr> | <attr> '=' <value>
904 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
905 std::vector<unsigned> &FwdRefAttrGrps,
906 bool inAttrGrp, LocTy &BuiltinLoc) {
907 bool HaveError = false;
912 lltok::Kind Token = Lex.getKind();
913 if (Token == lltok::kw_builtin)
914 BuiltinLoc = Lex.getLoc();
917 if (!inAttrGrp) return HaveError;
918 return Error(Lex.getLoc(), "unterminated attribute group");
923 case lltok::AttrGrpID: {
924 // Allow a function to reference an attribute group:
926 // define void @foo() #1 { ... }
930 "cannot have an attribute group reference in an attribute group");
932 unsigned AttrGrpNum = Lex.getUIntVal();
933 if (inAttrGrp) break;
935 // Save the reference to the attribute group. We'll fill it in later.
936 FwdRefAttrGrps.push_back(AttrGrpNum);
939 // Target-dependent attributes:
940 case lltok::StringConstant: {
941 std::string Attr = Lex.getStrVal();
944 if (EatIfPresent(lltok::equal) &&
945 ParseStringConstant(Val))
948 B.addAttribute(Attr, Val);
952 // Target-independent attributes:
953 case lltok::kw_align: {
954 // As a hack, we allow function alignment to be initially parsed as an
955 // attribute on a function declaration/definition or added to an attribute
956 // group and later moved to the alignment field.
960 if (ParseToken(lltok::equal, "expected '=' here") ||
961 ParseUInt32(Alignment))
964 if (ParseOptionalAlignment(Alignment))
967 B.addAlignmentAttr(Alignment);
970 case lltok::kw_alignstack: {
974 if (ParseToken(lltok::equal, "expected '=' here") ||
975 ParseUInt32(Alignment))
978 if (ParseOptionalStackAlignment(Alignment))
981 B.addStackAlignmentAttr(Alignment);
984 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
985 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
986 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
987 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
988 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
989 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
990 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
991 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
992 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
993 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
994 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
995 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
996 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
997 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
998 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
999 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1000 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1001 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1002 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
1003 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1004 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1005 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
1006 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
1007 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
1008 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
1009 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1012 case lltok::kw_inreg:
1013 case lltok::kw_signext:
1014 case lltok::kw_zeroext:
1017 "invalid use of attribute on a function");
1019 case lltok::kw_byval:
1020 case lltok::kw_inalloca:
1021 case lltok::kw_nest:
1022 case lltok::kw_noalias:
1023 case lltok::kw_nocapture:
1024 case lltok::kw_nonnull:
1025 case lltok::kw_returned:
1026 case lltok::kw_sret:
1029 "invalid use of parameter-only attribute on a function");
1037 //===----------------------------------------------------------------------===//
1038 // GlobalValue Reference/Resolution Routines.
1039 //===----------------------------------------------------------------------===//
1041 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1042 /// forward reference record if needed. This can return null if the value
1043 /// exists but does not have the right type.
1044 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1046 PointerType *PTy = dyn_cast<PointerType>(Ty);
1048 Error(Loc, "global variable reference must have pointer type");
1052 // Look this name up in the normal function symbol table.
1054 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1056 // If this is a forward reference for the value, see if we already created a
1057 // forward ref record.
1059 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1060 I = ForwardRefVals.find(Name);
1061 if (I != ForwardRefVals.end())
1062 Val = I->second.first;
1065 // If we have the value in the symbol table or fwd-ref table, return it.
1067 if (Val->getType() == Ty) return Val;
1068 Error(Loc, "'@" + Name + "' defined with type '" +
1069 getTypeString(Val->getType()) + "'");
1073 // Otherwise, create a new forward reference for this value and remember it.
1074 GlobalValue *FwdVal;
1075 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1076 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1078 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1079 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1080 nullptr, GlobalVariable::NotThreadLocal,
1081 PTy->getAddressSpace());
1083 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1087 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1088 PointerType *PTy = dyn_cast<PointerType>(Ty);
1090 Error(Loc, "global variable reference must have pointer type");
1094 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1096 // If this is a forward reference for the value, see if we already created a
1097 // forward ref record.
1099 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1100 I = ForwardRefValIDs.find(ID);
1101 if (I != ForwardRefValIDs.end())
1102 Val = I->second.first;
1105 // If we have the value in the symbol table or fwd-ref table, return it.
1107 if (Val->getType() == Ty) return Val;
1108 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1109 getTypeString(Val->getType()) + "'");
1113 // Otherwise, create a new forward reference for this value and remember it.
1114 GlobalValue *FwdVal;
1115 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1116 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1118 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1119 GlobalValue::ExternalWeakLinkage, nullptr, "");
1121 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1126 //===----------------------------------------------------------------------===//
1128 //===----------------------------------------------------------------------===//
1130 /// ParseToken - If the current token has the specified kind, eat it and return
1131 /// success. Otherwise, emit the specified error and return failure.
1132 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1133 if (Lex.getKind() != T)
1134 return TokError(ErrMsg);
1139 /// ParseStringConstant
1140 /// ::= StringConstant
1141 bool LLParser::ParseStringConstant(std::string &Result) {
1142 if (Lex.getKind() != lltok::StringConstant)
1143 return TokError("expected string constant");
1144 Result = Lex.getStrVal();
1151 bool LLParser::ParseUInt32(unsigned &Val) {
1152 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1153 return TokError("expected integer");
1154 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1155 if (Val64 != unsigned(Val64))
1156 return TokError("expected 32-bit integer (too large)");
1163 /// := 'localdynamic'
1164 /// := 'initialexec'
1166 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1167 switch (Lex.getKind()) {
1169 return TokError("expected localdynamic, initialexec or localexec");
1170 case lltok::kw_localdynamic:
1171 TLM = GlobalVariable::LocalDynamicTLSModel;
1173 case lltok::kw_initialexec:
1174 TLM = GlobalVariable::InitialExecTLSModel;
1176 case lltok::kw_localexec:
1177 TLM = GlobalVariable::LocalExecTLSModel;
1185 /// ParseOptionalThreadLocal
1187 /// := 'thread_local'
1188 /// := 'thread_local' '(' tlsmodel ')'
1189 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1190 TLM = GlobalVariable::NotThreadLocal;
1191 if (!EatIfPresent(lltok::kw_thread_local))
1194 TLM = GlobalVariable::GeneralDynamicTLSModel;
1195 if (Lex.getKind() == lltok::lparen) {
1197 return ParseTLSModel(TLM) ||
1198 ParseToken(lltok::rparen, "expected ')' after thread local model");
1203 /// ParseOptionalAddrSpace
1205 /// := 'addrspace' '(' uint32 ')'
1206 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1208 if (!EatIfPresent(lltok::kw_addrspace))
1210 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1211 ParseUInt32(AddrSpace) ||
1212 ParseToken(lltok::rparen, "expected ')' in address space");
1215 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1216 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1217 bool HaveError = false;
1222 lltok::Kind Token = Lex.getKind();
1224 default: // End of attributes.
1226 case lltok::kw_align: {
1228 if (ParseOptionalAlignment(Alignment))
1230 B.addAlignmentAttr(Alignment);
1233 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1234 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1235 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1236 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1237 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1238 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1239 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1240 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1241 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1242 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1243 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1244 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1245 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1247 case lltok::kw_alignstack:
1248 case lltok::kw_alwaysinline:
1249 case lltok::kw_builtin:
1250 case lltok::kw_inlinehint:
1251 case lltok::kw_minsize:
1252 case lltok::kw_naked:
1253 case lltok::kw_nobuiltin:
1254 case lltok::kw_noduplicate:
1255 case lltok::kw_noimplicitfloat:
1256 case lltok::kw_noinline:
1257 case lltok::kw_nonlazybind:
1258 case lltok::kw_noredzone:
1259 case lltok::kw_noreturn:
1260 case lltok::kw_nounwind:
1261 case lltok::kw_optnone:
1262 case lltok::kw_optsize:
1263 case lltok::kw_returns_twice:
1264 case lltok::kw_sanitize_address:
1265 case lltok::kw_sanitize_memory:
1266 case lltok::kw_sanitize_thread:
1268 case lltok::kw_sspreq:
1269 case lltok::kw_sspstrong:
1270 case lltok::kw_uwtable:
1271 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1279 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1280 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1281 bool HaveError = false;
1286 lltok::Kind Token = Lex.getKind();
1288 default: // End of attributes.
1290 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1291 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1292 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1293 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1294 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1297 case lltok::kw_align:
1298 case lltok::kw_byval:
1299 case lltok::kw_inalloca:
1300 case lltok::kw_nest:
1301 case lltok::kw_nocapture:
1302 case lltok::kw_returned:
1303 case lltok::kw_sret:
1304 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1307 case lltok::kw_alignstack:
1308 case lltok::kw_alwaysinline:
1309 case lltok::kw_builtin:
1310 case lltok::kw_cold:
1311 case lltok::kw_inlinehint:
1312 case lltok::kw_minsize:
1313 case lltok::kw_naked:
1314 case lltok::kw_nobuiltin:
1315 case lltok::kw_noduplicate:
1316 case lltok::kw_noimplicitfloat:
1317 case lltok::kw_noinline:
1318 case lltok::kw_nonlazybind:
1319 case lltok::kw_noredzone:
1320 case lltok::kw_noreturn:
1321 case lltok::kw_nounwind:
1322 case lltok::kw_optnone:
1323 case lltok::kw_optsize:
1324 case lltok::kw_returns_twice:
1325 case lltok::kw_sanitize_address:
1326 case lltok::kw_sanitize_memory:
1327 case lltok::kw_sanitize_thread:
1329 case lltok::kw_sspreq:
1330 case lltok::kw_sspstrong:
1331 case lltok::kw_uwtable:
1332 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1335 case lltok::kw_readnone:
1336 case lltok::kw_readonly:
1337 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1344 /// ParseOptionalLinkage
1351 /// ::= 'linkonce_odr'
1352 /// ::= 'available_externally'
1355 /// ::= 'extern_weak'
1358 /// Deprecated Values:
1359 /// ::= 'linker_private'
1360 /// ::= 'linker_private_weak'
1361 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1363 switch (Lex.getKind()) {
1364 default: Res=GlobalValue::ExternalLinkage; return false;
1365 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1366 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1367 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1368 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1369 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1370 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1371 case lltok::kw_available_externally:
1372 Res = GlobalValue::AvailableExternallyLinkage;
1374 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1375 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1376 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1377 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1379 case lltok::kw_linker_private:
1380 case lltok::kw_linker_private_weak:
1381 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1384 // treat linker_private and linker_private_weak as PrivateLinkage
1385 Res = GlobalValue::PrivateLinkage;
1393 /// ParseOptionalVisibility
1399 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1400 switch (Lex.getKind()) {
1401 default: Res = GlobalValue::DefaultVisibility; return false;
1402 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1403 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1404 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1410 /// ParseOptionalDLLStorageClass
1415 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1416 switch (Lex.getKind()) {
1417 default: Res = GlobalValue::DefaultStorageClass; return false;
1418 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1419 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1425 /// ParseOptionalCallingConv
1429 /// ::= 'kw_intel_ocl_bicc'
1431 /// ::= 'x86_stdcallcc'
1432 /// ::= 'x86_fastcallcc'
1433 /// ::= 'x86_thiscallcc'
1434 /// ::= 'arm_apcscc'
1435 /// ::= 'arm_aapcscc'
1436 /// ::= 'arm_aapcs_vfpcc'
1437 /// ::= 'msp430_intrcc'
1438 /// ::= 'ptx_kernel'
1439 /// ::= 'ptx_device'
1441 /// ::= 'spir_kernel'
1442 /// ::= 'x86_64_sysvcc'
1443 /// ::= 'x86_64_win64cc'
1444 /// ::= 'webkit_jscc'
1446 /// ::= 'preserve_mostcc'
1447 /// ::= 'preserve_allcc'
1450 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1451 switch (Lex.getKind()) {
1452 default: CC = CallingConv::C; return false;
1453 case lltok::kw_ccc: CC = CallingConv::C; break;
1454 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1455 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1456 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1457 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1458 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1459 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1460 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1461 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1462 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1463 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1464 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1465 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1466 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1467 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1468 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1469 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1470 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1471 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1472 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1473 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1474 case lltok::kw_cc: {
1475 unsigned ArbitraryCC;
1477 if (ParseUInt32(ArbitraryCC))
1479 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1488 /// ParseInstructionMetadata
1489 /// ::= !dbg !42 (',' !dbg !57)*
1490 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1491 PerFunctionState *PFS) {
1493 if (Lex.getKind() != lltok::MetadataVar)
1494 return TokError("expected metadata after comma");
1496 std::string Name = Lex.getStrVal();
1497 unsigned MDK = M->getMDKindID(Name);
1501 SMLoc Loc = Lex.getLoc();
1503 if (ParseToken(lltok::exclaim, "expected '!' here"))
1506 // This code is similar to that of ParseMetadataValue, however it needs to
1507 // have special-case code for a forward reference; see the comments on
1508 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1509 // at the top level here.
1510 if (Lex.getKind() == lltok::lbrace) {
1512 if (ParseMetadataListValue(ID, PFS))
1514 assert(ID.Kind == ValID::t_MDNode);
1515 Inst->setMetadata(MDK, ID.MDNodeVal);
1517 unsigned NodeID = 0;
1518 if (ParseMDNodeID(Node, NodeID))
1521 // If we got the node, add it to the instruction.
1522 Inst->setMetadata(MDK, Node);
1524 MDRef R = { Loc, MDK, NodeID };
1525 // Otherwise, remember that this should be resolved later.
1526 ForwardRefInstMetadata[Inst].push_back(R);
1530 if (MDK == LLVMContext::MD_tbaa)
1531 InstsWithTBAATag.push_back(Inst);
1533 // If this is the end of the list, we're done.
1534 } while (EatIfPresent(lltok::comma));
1538 /// ParseOptionalAlignment
1541 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1543 if (!EatIfPresent(lltok::kw_align))
1545 LocTy AlignLoc = Lex.getLoc();
1546 if (ParseUInt32(Alignment)) return true;
1547 if (!isPowerOf2_32(Alignment))
1548 return Error(AlignLoc, "alignment is not a power of two");
1549 if (Alignment > Value::MaximumAlignment)
1550 return Error(AlignLoc, "huge alignments are not supported yet");
1554 /// ParseOptionalCommaAlign
1558 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1560 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1561 bool &AteExtraComma) {
1562 AteExtraComma = false;
1563 while (EatIfPresent(lltok::comma)) {
1564 // Metadata at the end is an early exit.
1565 if (Lex.getKind() == lltok::MetadataVar) {
1566 AteExtraComma = true;
1570 if (Lex.getKind() != lltok::kw_align)
1571 return Error(Lex.getLoc(), "expected metadata or 'align'");
1573 if (ParseOptionalAlignment(Alignment)) return true;
1579 /// ParseScopeAndOrdering
1580 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1583 /// This sets Scope and Ordering to the parsed values.
1584 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1585 AtomicOrdering &Ordering) {
1589 Scope = CrossThread;
1590 if (EatIfPresent(lltok::kw_singlethread))
1591 Scope = SingleThread;
1593 return ParseOrdering(Ordering);
1597 /// ::= AtomicOrdering
1599 /// This sets Ordering to the parsed value.
1600 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1601 switch (Lex.getKind()) {
1602 default: return TokError("Expected ordering on atomic instruction");
1603 case lltok::kw_unordered: Ordering = Unordered; break;
1604 case lltok::kw_monotonic: Ordering = Monotonic; break;
1605 case lltok::kw_acquire: Ordering = Acquire; break;
1606 case lltok::kw_release: Ordering = Release; break;
1607 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1608 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1614 /// ParseOptionalStackAlignment
1616 /// ::= 'alignstack' '(' 4 ')'
1617 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1619 if (!EatIfPresent(lltok::kw_alignstack))
1621 LocTy ParenLoc = Lex.getLoc();
1622 if (!EatIfPresent(lltok::lparen))
1623 return Error(ParenLoc, "expected '('");
1624 LocTy AlignLoc = Lex.getLoc();
1625 if (ParseUInt32(Alignment)) return true;
1626 ParenLoc = Lex.getLoc();
1627 if (!EatIfPresent(lltok::rparen))
1628 return Error(ParenLoc, "expected ')'");
1629 if (!isPowerOf2_32(Alignment))
1630 return Error(AlignLoc, "stack alignment is not a power of two");
1634 /// ParseIndexList - This parses the index list for an insert/extractvalue
1635 /// instruction. This sets AteExtraComma in the case where we eat an extra
1636 /// comma at the end of the line and find that it is followed by metadata.
1637 /// Clients that don't allow metadata can call the version of this function that
1638 /// only takes one argument.
1641 /// ::= (',' uint32)+
1643 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1644 bool &AteExtraComma) {
1645 AteExtraComma = false;
1647 if (Lex.getKind() != lltok::comma)
1648 return TokError("expected ',' as start of index list");
1650 while (EatIfPresent(lltok::comma)) {
1651 if (Lex.getKind() == lltok::MetadataVar) {
1652 AteExtraComma = true;
1656 if (ParseUInt32(Idx)) return true;
1657 Indices.push_back(Idx);
1663 //===----------------------------------------------------------------------===//
1665 //===----------------------------------------------------------------------===//
1667 /// ParseType - Parse a type.
1668 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1669 SMLoc TypeLoc = Lex.getLoc();
1670 switch (Lex.getKind()) {
1672 return TokError("expected type");
1674 // Type ::= 'float' | 'void' (etc)
1675 Result = Lex.getTyVal();
1679 // Type ::= StructType
1680 if (ParseAnonStructType(Result, false))
1683 case lltok::lsquare:
1684 // Type ::= '[' ... ']'
1685 Lex.Lex(); // eat the lsquare.
1686 if (ParseArrayVectorType(Result, false))
1689 case lltok::less: // Either vector or packed struct.
1690 // Type ::= '<' ... '>'
1692 if (Lex.getKind() == lltok::lbrace) {
1693 if (ParseAnonStructType(Result, true) ||
1694 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1696 } else if (ParseArrayVectorType(Result, true))
1699 case lltok::LocalVar: {
1701 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1703 // If the type hasn't been defined yet, create a forward definition and
1704 // remember where that forward def'n was seen (in case it never is defined).
1706 Entry.first = StructType::create(Context, Lex.getStrVal());
1707 Entry.second = Lex.getLoc();
1709 Result = Entry.first;
1714 case lltok::LocalVarID: {
1716 if (Lex.getUIntVal() >= NumberedTypes.size())
1717 NumberedTypes.resize(Lex.getUIntVal()+1);
1718 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1720 // If the type hasn't been defined yet, create a forward definition and
1721 // remember where that forward def'n was seen (in case it never is defined).
1723 Entry.first = StructType::create(Context);
1724 Entry.second = Lex.getLoc();
1726 Result = Entry.first;
1732 // Parse the type suffixes.
1734 switch (Lex.getKind()) {
1737 if (!AllowVoid && Result->isVoidTy())
1738 return Error(TypeLoc, "void type only allowed for function results");
1741 // Type ::= Type '*'
1743 if (Result->isLabelTy())
1744 return TokError("basic block pointers are invalid");
1745 if (Result->isVoidTy())
1746 return TokError("pointers to void are invalid - use i8* instead");
1747 if (!PointerType::isValidElementType(Result))
1748 return TokError("pointer to this type is invalid");
1749 Result = PointerType::getUnqual(Result);
1753 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1754 case lltok::kw_addrspace: {
1755 if (Result->isLabelTy())
1756 return TokError("basic block pointers are invalid");
1757 if (Result->isVoidTy())
1758 return TokError("pointers to void are invalid; use i8* instead");
1759 if (!PointerType::isValidElementType(Result))
1760 return TokError("pointer to this type is invalid");
1762 if (ParseOptionalAddrSpace(AddrSpace) ||
1763 ParseToken(lltok::star, "expected '*' in address space"))
1766 Result = PointerType::get(Result, AddrSpace);
1770 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1772 if (ParseFunctionType(Result))
1779 /// ParseParameterList
1781 /// ::= '(' Arg (',' Arg)* ')'
1783 /// ::= Type OptionalAttributes Value OptionalAttributes
1784 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1785 PerFunctionState &PFS) {
1786 if (ParseToken(lltok::lparen, "expected '(' in call"))
1789 unsigned AttrIndex = 1;
1790 while (Lex.getKind() != lltok::rparen) {
1791 // If this isn't the first argument, we need a comma.
1792 if (!ArgList.empty() &&
1793 ParseToken(lltok::comma, "expected ',' in argument list"))
1796 // Parse the argument.
1798 Type *ArgTy = nullptr;
1799 AttrBuilder ArgAttrs;
1801 if (ParseType(ArgTy, ArgLoc))
1804 // Otherwise, handle normal operands.
1805 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1807 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1812 Lex.Lex(); // Lex the ')'.
1818 /// ParseArgumentList - Parse the argument list for a function type or function
1820 /// ::= '(' ArgTypeListI ')'
1824 /// ::= ArgTypeList ',' '...'
1825 /// ::= ArgType (',' ArgType)*
1827 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1830 assert(Lex.getKind() == lltok::lparen);
1831 Lex.Lex(); // eat the (.
1833 if (Lex.getKind() == lltok::rparen) {
1835 } else if (Lex.getKind() == lltok::dotdotdot) {
1839 LocTy TypeLoc = Lex.getLoc();
1840 Type *ArgTy = nullptr;
1844 if (ParseType(ArgTy) ||
1845 ParseOptionalParamAttrs(Attrs)) return true;
1847 if (ArgTy->isVoidTy())
1848 return Error(TypeLoc, "argument can not have void type");
1850 if (Lex.getKind() == lltok::LocalVar) {
1851 Name = Lex.getStrVal();
1855 if (!FunctionType::isValidArgumentType(ArgTy))
1856 return Error(TypeLoc, "invalid type for function argument");
1858 unsigned AttrIndex = 1;
1859 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1860 AttributeSet::get(ArgTy->getContext(),
1861 AttrIndex++, Attrs), Name));
1863 while (EatIfPresent(lltok::comma)) {
1864 // Handle ... at end of arg list.
1865 if (EatIfPresent(lltok::dotdotdot)) {
1870 // Otherwise must be an argument type.
1871 TypeLoc = Lex.getLoc();
1872 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1874 if (ArgTy->isVoidTy())
1875 return Error(TypeLoc, "argument can not have void type");
1877 if (Lex.getKind() == lltok::LocalVar) {
1878 Name = Lex.getStrVal();
1884 if (!ArgTy->isFirstClassType())
1885 return Error(TypeLoc, "invalid type for function argument");
1887 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1888 AttributeSet::get(ArgTy->getContext(),
1889 AttrIndex++, Attrs),
1894 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1897 /// ParseFunctionType
1898 /// ::= Type ArgumentList OptionalAttrs
1899 bool LLParser::ParseFunctionType(Type *&Result) {
1900 assert(Lex.getKind() == lltok::lparen);
1902 if (!FunctionType::isValidReturnType(Result))
1903 return TokError("invalid function return type");
1905 SmallVector<ArgInfo, 8> ArgList;
1907 if (ParseArgumentList(ArgList, isVarArg))
1910 // Reject names on the arguments lists.
1911 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1912 if (!ArgList[i].Name.empty())
1913 return Error(ArgList[i].Loc, "argument name invalid in function type");
1914 if (ArgList[i].Attrs.hasAttributes(i + 1))
1915 return Error(ArgList[i].Loc,
1916 "argument attributes invalid in function type");
1919 SmallVector<Type*, 16> ArgListTy;
1920 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1921 ArgListTy.push_back(ArgList[i].Ty);
1923 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1927 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1929 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1930 SmallVector<Type*, 8> Elts;
1931 if (ParseStructBody(Elts)) return true;
1933 Result = StructType::get(Context, Elts, Packed);
1937 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1938 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1939 std::pair<Type*, LocTy> &Entry,
1941 // If the type was already defined, diagnose the redefinition.
1942 if (Entry.first && !Entry.second.isValid())
1943 return Error(TypeLoc, "redefinition of type");
1945 // If we have opaque, just return without filling in the definition for the
1946 // struct. This counts as a definition as far as the .ll file goes.
1947 if (EatIfPresent(lltok::kw_opaque)) {
1948 // This type is being defined, so clear the location to indicate this.
1949 Entry.second = SMLoc();
1951 // If this type number has never been uttered, create it.
1953 Entry.first = StructType::create(Context, Name);
1954 ResultTy = Entry.first;
1958 // If the type starts with '<', then it is either a packed struct or a vector.
1959 bool isPacked = EatIfPresent(lltok::less);
1961 // If we don't have a struct, then we have a random type alias, which we
1962 // accept for compatibility with old files. These types are not allowed to be
1963 // forward referenced and not allowed to be recursive.
1964 if (Lex.getKind() != lltok::lbrace) {
1966 return Error(TypeLoc, "forward references to non-struct type");
1970 return ParseArrayVectorType(ResultTy, true);
1971 return ParseType(ResultTy);
1974 // This type is being defined, so clear the location to indicate this.
1975 Entry.second = SMLoc();
1977 // If this type number has never been uttered, create it.
1979 Entry.first = StructType::create(Context, Name);
1981 StructType *STy = cast<StructType>(Entry.first);
1983 SmallVector<Type*, 8> Body;
1984 if (ParseStructBody(Body) ||
1985 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1988 STy->setBody(Body, isPacked);
1994 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1997 /// ::= '{' Type (',' Type)* '}'
1998 /// ::= '<' '{' '}' '>'
1999 /// ::= '<' '{' Type (',' Type)* '}' '>'
2000 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2001 assert(Lex.getKind() == lltok::lbrace);
2002 Lex.Lex(); // Consume the '{'
2004 // Handle the empty struct.
2005 if (EatIfPresent(lltok::rbrace))
2008 LocTy EltTyLoc = Lex.getLoc();
2010 if (ParseType(Ty)) return true;
2013 if (!StructType::isValidElementType(Ty))
2014 return Error(EltTyLoc, "invalid element type for struct");
2016 while (EatIfPresent(lltok::comma)) {
2017 EltTyLoc = Lex.getLoc();
2018 if (ParseType(Ty)) return true;
2020 if (!StructType::isValidElementType(Ty))
2021 return Error(EltTyLoc, "invalid element type for struct");
2026 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2029 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2030 /// token has already been consumed.
2032 /// ::= '[' APSINTVAL 'x' Types ']'
2033 /// ::= '<' APSINTVAL 'x' Types '>'
2034 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2035 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2036 Lex.getAPSIntVal().getBitWidth() > 64)
2037 return TokError("expected number in address space");
2039 LocTy SizeLoc = Lex.getLoc();
2040 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2043 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2046 LocTy TypeLoc = Lex.getLoc();
2047 Type *EltTy = nullptr;
2048 if (ParseType(EltTy)) return true;
2050 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2051 "expected end of sequential type"))
2056 return Error(SizeLoc, "zero element vector is illegal");
2057 if ((unsigned)Size != Size)
2058 return Error(SizeLoc, "size too large for vector");
2059 if (!VectorType::isValidElementType(EltTy))
2060 return Error(TypeLoc, "invalid vector element type");
2061 Result = VectorType::get(EltTy, unsigned(Size));
2063 if (!ArrayType::isValidElementType(EltTy))
2064 return Error(TypeLoc, "invalid array element type");
2065 Result = ArrayType::get(EltTy, Size);
2070 //===----------------------------------------------------------------------===//
2071 // Function Semantic Analysis.
2072 //===----------------------------------------------------------------------===//
2074 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2076 : P(p), F(f), FunctionNumber(functionNumber) {
2078 // Insert unnamed arguments into the NumberedVals list.
2079 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2082 NumberedVals.push_back(AI);
2085 LLParser::PerFunctionState::~PerFunctionState() {
2086 // If there were any forward referenced non-basicblock values, delete them.
2087 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2088 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2089 if (!isa<BasicBlock>(I->second.first)) {
2090 I->second.first->replaceAllUsesWith(
2091 UndefValue::get(I->second.first->getType()));
2092 delete I->second.first;
2093 I->second.first = nullptr;
2096 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2097 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2098 if (!isa<BasicBlock>(I->second.first)) {
2099 I->second.first->replaceAllUsesWith(
2100 UndefValue::get(I->second.first->getType()));
2101 delete I->second.first;
2102 I->second.first = nullptr;
2106 bool LLParser::PerFunctionState::FinishFunction() {
2107 // Check to see if someone took the address of labels in this block.
2108 if (!P.ForwardRefBlockAddresses.empty()) {
2110 if (!F.getName().empty()) {
2111 FunctionID.Kind = ValID::t_GlobalName;
2112 FunctionID.StrVal = F.getName();
2114 FunctionID.Kind = ValID::t_GlobalID;
2115 FunctionID.UIntVal = FunctionNumber;
2118 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2119 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2120 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2121 // Resolve all these references.
2122 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2125 P.ForwardRefBlockAddresses.erase(FRBAI);
2129 if (!ForwardRefVals.empty())
2130 return P.Error(ForwardRefVals.begin()->second.second,
2131 "use of undefined value '%" + ForwardRefVals.begin()->first +
2133 if (!ForwardRefValIDs.empty())
2134 return P.Error(ForwardRefValIDs.begin()->second.second,
2135 "use of undefined value '%" +
2136 Twine(ForwardRefValIDs.begin()->first) + "'");
2141 /// GetVal - Get a value with the specified name or ID, creating a
2142 /// forward reference record if needed. This can return null if the value
2143 /// exists but does not have the right type.
2144 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2145 Type *Ty, LocTy Loc) {
2146 // Look this name up in the normal function symbol table.
2147 Value *Val = F.getValueSymbolTable().lookup(Name);
2149 // If this is a forward reference for the value, see if we already created a
2150 // forward ref record.
2152 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2153 I = ForwardRefVals.find(Name);
2154 if (I != ForwardRefVals.end())
2155 Val = I->second.first;
2158 // If we have the value in the symbol table or fwd-ref table, return it.
2160 if (Val->getType() == Ty) return Val;
2161 if (Ty->isLabelTy())
2162 P.Error(Loc, "'%" + Name + "' is not a basic block");
2164 P.Error(Loc, "'%" + Name + "' defined with type '" +
2165 getTypeString(Val->getType()) + "'");
2169 // Don't make placeholders with invalid type.
2170 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2171 P.Error(Loc, "invalid use of a non-first-class type");
2175 // Otherwise, create a new forward reference for this value and remember it.
2177 if (Ty->isLabelTy())
2178 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2180 FwdVal = new Argument(Ty, Name);
2182 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2186 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2188 // Look this name up in the normal function symbol table.
2189 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2191 // If this is a forward reference for the value, see if we already created a
2192 // forward ref record.
2194 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2195 I = ForwardRefValIDs.find(ID);
2196 if (I != ForwardRefValIDs.end())
2197 Val = I->second.first;
2200 // If we have the value in the symbol table or fwd-ref table, return it.
2202 if (Val->getType() == Ty) return Val;
2203 if (Ty->isLabelTy())
2204 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2206 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2207 getTypeString(Val->getType()) + "'");
2211 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2212 P.Error(Loc, "invalid use of a non-first-class type");
2216 // Otherwise, create a new forward reference for this value and remember it.
2218 if (Ty->isLabelTy())
2219 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2221 FwdVal = new Argument(Ty);
2223 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2227 /// SetInstName - After an instruction is parsed and inserted into its
2228 /// basic block, this installs its name.
2229 bool LLParser::PerFunctionState::SetInstName(int NameID,
2230 const std::string &NameStr,
2231 LocTy NameLoc, Instruction *Inst) {
2232 // If this instruction has void type, it cannot have a name or ID specified.
2233 if (Inst->getType()->isVoidTy()) {
2234 if (NameID != -1 || !NameStr.empty())
2235 return P.Error(NameLoc, "instructions returning void cannot have a name");
2239 // If this was a numbered instruction, verify that the instruction is the
2240 // expected value and resolve any forward references.
2241 if (NameStr.empty()) {
2242 // If neither a name nor an ID was specified, just use the next ID.
2244 NameID = NumberedVals.size();
2246 if (unsigned(NameID) != NumberedVals.size())
2247 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2248 Twine(NumberedVals.size()) + "'");
2250 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2251 ForwardRefValIDs.find(NameID);
2252 if (FI != ForwardRefValIDs.end()) {
2253 if (FI->second.first->getType() != Inst->getType())
2254 return P.Error(NameLoc, "instruction forward referenced with type '" +
2255 getTypeString(FI->second.first->getType()) + "'");
2256 FI->second.first->replaceAllUsesWith(Inst);
2257 delete FI->second.first;
2258 ForwardRefValIDs.erase(FI);
2261 NumberedVals.push_back(Inst);
2265 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2266 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2267 FI = ForwardRefVals.find(NameStr);
2268 if (FI != ForwardRefVals.end()) {
2269 if (FI->second.first->getType() != Inst->getType())
2270 return P.Error(NameLoc, "instruction forward referenced with type '" +
2271 getTypeString(FI->second.first->getType()) + "'");
2272 FI->second.first->replaceAllUsesWith(Inst);
2273 delete FI->second.first;
2274 ForwardRefVals.erase(FI);
2277 // Set the name on the instruction.
2278 Inst->setName(NameStr);
2280 if (Inst->getName() != NameStr)
2281 return P.Error(NameLoc, "multiple definition of local value named '" +
2286 /// GetBB - Get a basic block with the specified name or ID, creating a
2287 /// forward reference record if needed.
2288 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2290 return cast_or_null<BasicBlock>(GetVal(Name,
2291 Type::getLabelTy(F.getContext()), Loc));
2294 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2295 return cast_or_null<BasicBlock>(GetVal(ID,
2296 Type::getLabelTy(F.getContext()), Loc));
2299 /// DefineBB - Define the specified basic block, which is either named or
2300 /// unnamed. If there is an error, this returns null otherwise it returns
2301 /// the block being defined.
2302 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2306 BB = GetBB(NumberedVals.size(), Loc);
2308 BB = GetBB(Name, Loc);
2309 if (!BB) return nullptr; // Already diagnosed error.
2311 // Move the block to the end of the function. Forward ref'd blocks are
2312 // inserted wherever they happen to be referenced.
2313 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2315 // Remove the block from forward ref sets.
2317 ForwardRefValIDs.erase(NumberedVals.size());
2318 NumberedVals.push_back(BB);
2320 // BB forward references are already in the function symbol table.
2321 ForwardRefVals.erase(Name);
2327 //===----------------------------------------------------------------------===//
2329 //===----------------------------------------------------------------------===//
2331 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2332 /// type implied. For example, if we parse "4" we don't know what integer type
2333 /// it has. The value will later be combined with its type and checked for
2334 /// sanity. PFS is used to convert function-local operands of metadata (since
2335 /// metadata operands are not just parsed here but also converted to values).
2336 /// PFS can be null when we are not parsing metadata values inside a function.
2337 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2338 ID.Loc = Lex.getLoc();
2339 switch (Lex.getKind()) {
2340 default: return TokError("expected value token");
2341 case lltok::GlobalID: // @42
2342 ID.UIntVal = Lex.getUIntVal();
2343 ID.Kind = ValID::t_GlobalID;
2345 case lltok::GlobalVar: // @foo
2346 ID.StrVal = Lex.getStrVal();
2347 ID.Kind = ValID::t_GlobalName;
2349 case lltok::LocalVarID: // %42
2350 ID.UIntVal = Lex.getUIntVal();
2351 ID.Kind = ValID::t_LocalID;
2353 case lltok::LocalVar: // %foo
2354 ID.StrVal = Lex.getStrVal();
2355 ID.Kind = ValID::t_LocalName;
2357 case lltok::exclaim: // !42, !{...}, or !"foo"
2358 return ParseMetadataValue(ID, PFS);
2360 ID.APSIntVal = Lex.getAPSIntVal();
2361 ID.Kind = ValID::t_APSInt;
2363 case lltok::APFloat:
2364 ID.APFloatVal = Lex.getAPFloatVal();
2365 ID.Kind = ValID::t_APFloat;
2367 case lltok::kw_true:
2368 ID.ConstantVal = ConstantInt::getTrue(Context);
2369 ID.Kind = ValID::t_Constant;
2371 case lltok::kw_false:
2372 ID.ConstantVal = ConstantInt::getFalse(Context);
2373 ID.Kind = ValID::t_Constant;
2375 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2376 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2377 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2379 case lltok::lbrace: {
2380 // ValID ::= '{' ConstVector '}'
2382 SmallVector<Constant*, 16> Elts;
2383 if (ParseGlobalValueVector(Elts) ||
2384 ParseToken(lltok::rbrace, "expected end of struct constant"))
2387 ID.ConstantStructElts = new Constant*[Elts.size()];
2388 ID.UIntVal = Elts.size();
2389 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2390 ID.Kind = ValID::t_ConstantStruct;
2394 // ValID ::= '<' ConstVector '>' --> Vector.
2395 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2397 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2399 SmallVector<Constant*, 16> Elts;
2400 LocTy FirstEltLoc = Lex.getLoc();
2401 if (ParseGlobalValueVector(Elts) ||
2403 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2404 ParseToken(lltok::greater, "expected end of constant"))
2407 if (isPackedStruct) {
2408 ID.ConstantStructElts = new Constant*[Elts.size()];
2409 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2410 ID.UIntVal = Elts.size();
2411 ID.Kind = ValID::t_PackedConstantStruct;
2416 return Error(ID.Loc, "constant vector must not be empty");
2418 if (!Elts[0]->getType()->isIntegerTy() &&
2419 !Elts[0]->getType()->isFloatingPointTy() &&
2420 !Elts[0]->getType()->isPointerTy())
2421 return Error(FirstEltLoc,
2422 "vector elements must have integer, pointer or floating point type");
2424 // Verify that all the vector elements have the same type.
2425 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2426 if (Elts[i]->getType() != Elts[0]->getType())
2427 return Error(FirstEltLoc,
2428 "vector element #" + Twine(i) +
2429 " is not of type '" + getTypeString(Elts[0]->getType()));
2431 ID.ConstantVal = ConstantVector::get(Elts);
2432 ID.Kind = ValID::t_Constant;
2435 case lltok::lsquare: { // Array Constant
2437 SmallVector<Constant*, 16> Elts;
2438 LocTy FirstEltLoc = Lex.getLoc();
2439 if (ParseGlobalValueVector(Elts) ||
2440 ParseToken(lltok::rsquare, "expected end of array constant"))
2443 // Handle empty element.
2445 // Use undef instead of an array because it's inconvenient to determine
2446 // the element type at this point, there being no elements to examine.
2447 ID.Kind = ValID::t_EmptyArray;
2451 if (!Elts[0]->getType()->isFirstClassType())
2452 return Error(FirstEltLoc, "invalid array element type: " +
2453 getTypeString(Elts[0]->getType()));
2455 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2457 // Verify all elements are correct type!
2458 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2459 if (Elts[i]->getType() != Elts[0]->getType())
2460 return Error(FirstEltLoc,
2461 "array element #" + Twine(i) +
2462 " is not of type '" + getTypeString(Elts[0]->getType()));
2465 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2466 ID.Kind = ValID::t_Constant;
2469 case lltok::kw_c: // c "foo"
2471 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2473 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2474 ID.Kind = ValID::t_Constant;
2477 case lltok::kw_asm: {
2478 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2480 bool HasSideEffect, AlignStack, AsmDialect;
2482 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2483 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2484 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2485 ParseStringConstant(ID.StrVal) ||
2486 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2487 ParseToken(lltok::StringConstant, "expected constraint string"))
2489 ID.StrVal2 = Lex.getStrVal();
2490 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2491 (unsigned(AsmDialect)<<2);
2492 ID.Kind = ValID::t_InlineAsm;
2496 case lltok::kw_blockaddress: {
2497 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2502 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2504 ParseToken(lltok::comma, "expected comma in block address expression")||
2505 ParseValID(Label) ||
2506 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2509 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2510 return Error(Fn.Loc, "expected function name in blockaddress");
2511 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2512 return Error(Label.Loc, "expected basic block name in blockaddress");
2514 // Make a global variable as a placeholder for this reference.
2515 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2516 false, GlobalValue::InternalLinkage,
2518 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2519 ID.ConstantVal = FwdRef;
2520 ID.Kind = ValID::t_Constant;
2524 case lltok::kw_trunc:
2525 case lltok::kw_zext:
2526 case lltok::kw_sext:
2527 case lltok::kw_fptrunc:
2528 case lltok::kw_fpext:
2529 case lltok::kw_bitcast:
2530 case lltok::kw_addrspacecast:
2531 case lltok::kw_uitofp:
2532 case lltok::kw_sitofp:
2533 case lltok::kw_fptoui:
2534 case lltok::kw_fptosi:
2535 case lltok::kw_inttoptr:
2536 case lltok::kw_ptrtoint: {
2537 unsigned Opc = Lex.getUIntVal();
2538 Type *DestTy = nullptr;
2541 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2542 ParseGlobalTypeAndValue(SrcVal) ||
2543 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2544 ParseType(DestTy) ||
2545 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2547 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2548 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2549 getTypeString(SrcVal->getType()) + "' to '" +
2550 getTypeString(DestTy) + "'");
2551 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2553 ID.Kind = ValID::t_Constant;
2556 case lltok::kw_extractvalue: {
2559 SmallVector<unsigned, 4> Indices;
2560 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2561 ParseGlobalTypeAndValue(Val) ||
2562 ParseIndexList(Indices) ||
2563 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2566 if (!Val->getType()->isAggregateType())
2567 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2568 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2569 return Error(ID.Loc, "invalid indices for extractvalue");
2570 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2571 ID.Kind = ValID::t_Constant;
2574 case lltok::kw_insertvalue: {
2576 Constant *Val0, *Val1;
2577 SmallVector<unsigned, 4> Indices;
2578 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2579 ParseGlobalTypeAndValue(Val0) ||
2580 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2581 ParseGlobalTypeAndValue(Val1) ||
2582 ParseIndexList(Indices) ||
2583 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2585 if (!Val0->getType()->isAggregateType())
2586 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2587 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2588 return Error(ID.Loc, "invalid indices for insertvalue");
2589 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2590 ID.Kind = ValID::t_Constant;
2593 case lltok::kw_icmp:
2594 case lltok::kw_fcmp: {
2595 unsigned PredVal, Opc = Lex.getUIntVal();
2596 Constant *Val0, *Val1;
2598 if (ParseCmpPredicate(PredVal, Opc) ||
2599 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2600 ParseGlobalTypeAndValue(Val0) ||
2601 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2602 ParseGlobalTypeAndValue(Val1) ||
2603 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2606 if (Val0->getType() != Val1->getType())
2607 return Error(ID.Loc, "compare operands must have the same type");
2609 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2611 if (Opc == Instruction::FCmp) {
2612 if (!Val0->getType()->isFPOrFPVectorTy())
2613 return Error(ID.Loc, "fcmp requires floating point operands");
2614 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2616 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2617 if (!Val0->getType()->isIntOrIntVectorTy() &&
2618 !Val0->getType()->getScalarType()->isPointerTy())
2619 return Error(ID.Loc, "icmp requires pointer or integer operands");
2620 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2622 ID.Kind = ValID::t_Constant;
2626 // Binary Operators.
2628 case lltok::kw_fadd:
2630 case lltok::kw_fsub:
2632 case lltok::kw_fmul:
2633 case lltok::kw_udiv:
2634 case lltok::kw_sdiv:
2635 case lltok::kw_fdiv:
2636 case lltok::kw_urem:
2637 case lltok::kw_srem:
2638 case lltok::kw_frem:
2640 case lltok::kw_lshr:
2641 case lltok::kw_ashr: {
2645 unsigned Opc = Lex.getUIntVal();
2646 Constant *Val0, *Val1;
2648 LocTy ModifierLoc = Lex.getLoc();
2649 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2650 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2651 if (EatIfPresent(lltok::kw_nuw))
2653 if (EatIfPresent(lltok::kw_nsw)) {
2655 if (EatIfPresent(lltok::kw_nuw))
2658 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2659 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2660 if (EatIfPresent(lltok::kw_exact))
2663 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2664 ParseGlobalTypeAndValue(Val0) ||
2665 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2666 ParseGlobalTypeAndValue(Val1) ||
2667 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2669 if (Val0->getType() != Val1->getType())
2670 return Error(ID.Loc, "operands of constexpr must have same type");
2671 if (!Val0->getType()->isIntOrIntVectorTy()) {
2673 return Error(ModifierLoc, "nuw only applies to integer operations");
2675 return Error(ModifierLoc, "nsw only applies to integer operations");
2677 // Check that the type is valid for the operator.
2679 case Instruction::Add:
2680 case Instruction::Sub:
2681 case Instruction::Mul:
2682 case Instruction::UDiv:
2683 case Instruction::SDiv:
2684 case Instruction::URem:
2685 case Instruction::SRem:
2686 case Instruction::Shl:
2687 case Instruction::AShr:
2688 case Instruction::LShr:
2689 if (!Val0->getType()->isIntOrIntVectorTy())
2690 return Error(ID.Loc, "constexpr requires integer operands");
2692 case Instruction::FAdd:
2693 case Instruction::FSub:
2694 case Instruction::FMul:
2695 case Instruction::FDiv:
2696 case Instruction::FRem:
2697 if (!Val0->getType()->isFPOrFPVectorTy())
2698 return Error(ID.Loc, "constexpr requires fp operands");
2700 default: llvm_unreachable("Unknown binary operator!");
2703 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2704 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2705 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2706 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2708 ID.Kind = ValID::t_Constant;
2712 // Logical Operations
2715 case lltok::kw_xor: {
2716 unsigned Opc = Lex.getUIntVal();
2717 Constant *Val0, *Val1;
2719 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2720 ParseGlobalTypeAndValue(Val0) ||
2721 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2722 ParseGlobalTypeAndValue(Val1) ||
2723 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2725 if (Val0->getType() != Val1->getType())
2726 return Error(ID.Loc, "operands of constexpr must have same type");
2727 if (!Val0->getType()->isIntOrIntVectorTy())
2728 return Error(ID.Loc,
2729 "constexpr requires integer or integer vector operands");
2730 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2731 ID.Kind = ValID::t_Constant;
2735 case lltok::kw_getelementptr:
2736 case lltok::kw_shufflevector:
2737 case lltok::kw_insertelement:
2738 case lltok::kw_extractelement:
2739 case lltok::kw_select: {
2740 unsigned Opc = Lex.getUIntVal();
2741 SmallVector<Constant*, 16> Elts;
2742 bool InBounds = false;
2744 if (Opc == Instruction::GetElementPtr)
2745 InBounds = EatIfPresent(lltok::kw_inbounds);
2746 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2747 ParseGlobalValueVector(Elts) ||
2748 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2751 if (Opc == Instruction::GetElementPtr) {
2752 if (Elts.size() == 0 ||
2753 !Elts[0]->getType()->getScalarType()->isPointerTy())
2754 return Error(ID.Loc, "getelementptr requires pointer operand");
2756 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2757 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2758 return Error(ID.Loc, "invalid indices for getelementptr");
2759 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2761 } else if (Opc == Instruction::Select) {
2762 if (Elts.size() != 3)
2763 return Error(ID.Loc, "expected three operands to select");
2764 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2766 return Error(ID.Loc, Reason);
2767 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2768 } else if (Opc == Instruction::ShuffleVector) {
2769 if (Elts.size() != 3)
2770 return Error(ID.Loc, "expected three operands to shufflevector");
2771 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2772 return Error(ID.Loc, "invalid operands to shufflevector");
2774 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2775 } else if (Opc == Instruction::ExtractElement) {
2776 if (Elts.size() != 2)
2777 return Error(ID.Loc, "expected two operands to extractelement");
2778 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2779 return Error(ID.Loc, "invalid extractelement operands");
2780 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2782 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2783 if (Elts.size() != 3)
2784 return Error(ID.Loc, "expected three operands to insertelement");
2785 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2786 return Error(ID.Loc, "invalid insertelement operands");
2788 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2791 ID.Kind = ValID::t_Constant;
2800 /// ParseGlobalValue - Parse a global value with the specified type.
2801 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2805 bool Parsed = ParseValID(ID) ||
2806 ConvertValIDToValue(Ty, ID, V, nullptr);
2807 if (V && !(C = dyn_cast<Constant>(V)))
2808 return Error(ID.Loc, "global values must be constants");
2812 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2814 return ParseType(Ty) ||
2815 ParseGlobalValue(Ty, V);
2818 /// ParseGlobalValueVector
2820 /// ::= TypeAndValue (',' TypeAndValue)*
2821 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2823 if (Lex.getKind() == lltok::rbrace ||
2824 Lex.getKind() == lltok::rsquare ||
2825 Lex.getKind() == lltok::greater ||
2826 Lex.getKind() == lltok::rparen)
2830 if (ParseGlobalTypeAndValue(C)) return true;
2833 while (EatIfPresent(lltok::comma)) {
2834 if (ParseGlobalTypeAndValue(C)) return true;
2841 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2842 assert(Lex.getKind() == lltok::lbrace);
2845 SmallVector<Value*, 16> Elts;
2846 if (ParseMDNodeVector(Elts, PFS) ||
2847 ParseToken(lltok::rbrace, "expected end of metadata node"))
2850 ID.MDNodeVal = MDNode::get(Context, Elts);
2851 ID.Kind = ValID::t_MDNode;
2855 /// ParseMetadataValue
2859 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2860 assert(Lex.getKind() == lltok::exclaim);
2865 if (Lex.getKind() == lltok::lbrace)
2866 return ParseMetadataListValue(ID, PFS);
2868 // Standalone metadata reference
2870 if (Lex.getKind() == lltok::APSInt) {
2871 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2872 ID.Kind = ValID::t_MDNode;
2877 // ::= '!' STRINGCONSTANT
2878 if (ParseMDString(ID.MDStringVal)) return true;
2879 ID.Kind = ValID::t_MDString;
2884 //===----------------------------------------------------------------------===//
2885 // Function Parsing.
2886 //===----------------------------------------------------------------------===//
2888 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2889 PerFunctionState *PFS) {
2890 if (Ty->isFunctionTy())
2891 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2894 case ValID::t_LocalID:
2895 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2896 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2897 return V == nullptr;
2898 case ValID::t_LocalName:
2899 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2900 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2901 return V == nullptr;
2902 case ValID::t_InlineAsm: {
2903 PointerType *PTy = dyn_cast<PointerType>(Ty);
2905 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2906 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2907 return Error(ID.Loc, "invalid type for inline asm constraint string");
2908 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2909 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2912 case ValID::t_MDNode:
2913 if (!Ty->isMetadataTy())
2914 return Error(ID.Loc, "metadata value must have metadata type");
2917 case ValID::t_MDString:
2918 if (!Ty->isMetadataTy())
2919 return Error(ID.Loc, "metadata value must have metadata type");
2922 case ValID::t_GlobalName:
2923 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2924 return V == nullptr;
2925 case ValID::t_GlobalID:
2926 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2927 return V == nullptr;
2928 case ValID::t_APSInt:
2929 if (!Ty->isIntegerTy())
2930 return Error(ID.Loc, "integer constant must have integer type");
2931 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2932 V = ConstantInt::get(Context, ID.APSIntVal);
2934 case ValID::t_APFloat:
2935 if (!Ty->isFloatingPointTy() ||
2936 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2937 return Error(ID.Loc, "floating point constant invalid for type");
2939 // The lexer has no type info, so builds all half, float, and double FP
2940 // constants as double. Fix this here. Long double does not need this.
2941 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2944 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2946 else if (Ty->isFloatTy())
2947 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2950 V = ConstantFP::get(Context, ID.APFloatVal);
2952 if (V->getType() != Ty)
2953 return Error(ID.Loc, "floating point constant does not have type '" +
2954 getTypeString(Ty) + "'");
2958 if (!Ty->isPointerTy())
2959 return Error(ID.Loc, "null must be a pointer type");
2960 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2962 case ValID::t_Undef:
2963 // FIXME: LabelTy should not be a first-class type.
2964 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2965 return Error(ID.Loc, "invalid type for undef constant");
2966 V = UndefValue::get(Ty);
2968 case ValID::t_EmptyArray:
2969 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2970 return Error(ID.Loc, "invalid empty array initializer");
2971 V = UndefValue::get(Ty);
2974 // FIXME: LabelTy should not be a first-class type.
2975 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2976 return Error(ID.Loc, "invalid type for null constant");
2977 V = Constant::getNullValue(Ty);
2979 case ValID::t_Constant:
2980 if (ID.ConstantVal->getType() != Ty)
2981 return Error(ID.Loc, "constant expression type mismatch");
2985 case ValID::t_ConstantStruct:
2986 case ValID::t_PackedConstantStruct:
2987 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2988 if (ST->getNumElements() != ID.UIntVal)
2989 return Error(ID.Loc,
2990 "initializer with struct type has wrong # elements");
2991 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2992 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2994 // Verify that the elements are compatible with the structtype.
2995 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2996 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2997 return Error(ID.Loc, "element " + Twine(i) +
2998 " of struct initializer doesn't match struct element type");
3000 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3003 return Error(ID.Loc, "constant expression type mismatch");
3006 llvm_unreachable("Invalid ValID");
3009 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3012 return ParseValID(ID, PFS) ||
3013 ConvertValIDToValue(Ty, ID, V, PFS);
3016 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3018 return ParseType(Ty) ||
3019 ParseValue(Ty, V, PFS);
3022 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3023 PerFunctionState &PFS) {
3026 if (ParseTypeAndValue(V, PFS)) return true;
3027 if (!isa<BasicBlock>(V))
3028 return Error(Loc, "expected a basic block");
3029 BB = cast<BasicBlock>(V);
3035 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3036 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3037 /// OptionalAlign OptGC OptionalPrefix
3038 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3039 // Parse the linkage.
3040 LocTy LinkageLoc = Lex.getLoc();
3043 unsigned Visibility;
3044 unsigned DLLStorageClass;
3045 AttrBuilder RetAttrs;
3047 Type *RetType = nullptr;
3048 LocTy RetTypeLoc = Lex.getLoc();
3049 if (ParseOptionalLinkage(Linkage) ||
3050 ParseOptionalVisibility(Visibility) ||
3051 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3052 ParseOptionalCallingConv(CC) ||
3053 ParseOptionalReturnAttrs(RetAttrs) ||
3054 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3057 // Verify that the linkage is ok.
3058 switch ((GlobalValue::LinkageTypes)Linkage) {
3059 case GlobalValue::ExternalLinkage:
3060 break; // always ok.
3061 case GlobalValue::ExternalWeakLinkage:
3063 return Error(LinkageLoc, "invalid linkage for function definition");
3065 case GlobalValue::PrivateLinkage:
3066 case GlobalValue::InternalLinkage:
3067 case GlobalValue::AvailableExternallyLinkage:
3068 case GlobalValue::LinkOnceAnyLinkage:
3069 case GlobalValue::LinkOnceODRLinkage:
3070 case GlobalValue::WeakAnyLinkage:
3071 case GlobalValue::WeakODRLinkage:
3073 return Error(LinkageLoc, "invalid linkage for function declaration");
3075 case GlobalValue::AppendingLinkage:
3076 case GlobalValue::CommonLinkage:
3077 return Error(LinkageLoc, "invalid function linkage type");
3080 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3081 return Error(LinkageLoc,
3082 "symbol with local linkage must have default visibility");
3084 if (!FunctionType::isValidReturnType(RetType))
3085 return Error(RetTypeLoc, "invalid function return type");
3087 LocTy NameLoc = Lex.getLoc();
3089 std::string FunctionName;
3090 if (Lex.getKind() == lltok::GlobalVar) {
3091 FunctionName = Lex.getStrVal();
3092 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3093 unsigned NameID = Lex.getUIntVal();
3095 if (NameID != NumberedVals.size())
3096 return TokError("function expected to be numbered '%" +
3097 Twine(NumberedVals.size()) + "'");
3099 return TokError("expected function name");
3104 if (Lex.getKind() != lltok::lparen)
3105 return TokError("expected '(' in function argument list");
3107 SmallVector<ArgInfo, 8> ArgList;
3109 AttrBuilder FuncAttrs;
3110 std::vector<unsigned> FwdRefAttrGrps;
3112 std::string Section;
3116 LocTy UnnamedAddrLoc;
3117 Constant *Prefix = nullptr;
3119 if (ParseArgumentList(ArgList, isVarArg) ||
3120 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3122 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3124 (EatIfPresent(lltok::kw_section) &&
3125 ParseStringConstant(Section)) ||
3126 ParseOptionalAlignment(Alignment) ||
3127 (EatIfPresent(lltok::kw_gc) &&
3128 ParseStringConstant(GC)) ||
3129 (EatIfPresent(lltok::kw_prefix) &&
3130 ParseGlobalTypeAndValue(Prefix)))
3133 if (FuncAttrs.contains(Attribute::Builtin))
3134 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3136 // If the alignment was parsed as an attribute, move to the alignment field.
3137 if (FuncAttrs.hasAlignmentAttr()) {
3138 Alignment = FuncAttrs.getAlignment();
3139 FuncAttrs.removeAttribute(Attribute::Alignment);
3142 // Okay, if we got here, the function is syntactically valid. Convert types
3143 // and do semantic checks.
3144 std::vector<Type*> ParamTypeList;
3145 SmallVector<AttributeSet, 8> Attrs;
3147 if (RetAttrs.hasAttributes())
3148 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3149 AttributeSet::ReturnIndex,
3152 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3153 ParamTypeList.push_back(ArgList[i].Ty);
3154 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3155 AttrBuilder B(ArgList[i].Attrs, i + 1);
3156 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3160 if (FuncAttrs.hasAttributes())
3161 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3162 AttributeSet::FunctionIndex,
3165 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3167 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3168 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3171 FunctionType::get(RetType, ParamTypeList, isVarArg);
3172 PointerType *PFT = PointerType::getUnqual(FT);
3175 if (!FunctionName.empty()) {
3176 // If this was a definition of a forward reference, remove the definition
3177 // from the forward reference table and fill in the forward ref.
3178 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3179 ForwardRefVals.find(FunctionName);
3180 if (FRVI != ForwardRefVals.end()) {
3181 Fn = M->getFunction(FunctionName);
3183 return Error(FRVI->second.second, "invalid forward reference to "
3184 "function as global value!");
3185 if (Fn->getType() != PFT)
3186 return Error(FRVI->second.second, "invalid forward reference to "
3187 "function '" + FunctionName + "' with wrong type!");
3189 ForwardRefVals.erase(FRVI);
3190 } else if ((Fn = M->getFunction(FunctionName))) {
3191 // Reject redefinitions.
3192 return Error(NameLoc, "invalid redefinition of function '" +
3193 FunctionName + "'");
3194 } else if (M->getNamedValue(FunctionName)) {
3195 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3199 // If this is a definition of a forward referenced function, make sure the
3201 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3202 = ForwardRefValIDs.find(NumberedVals.size());
3203 if (I != ForwardRefValIDs.end()) {
3204 Fn = cast<Function>(I->second.first);
3205 if (Fn->getType() != PFT)
3206 return Error(NameLoc, "type of definition and forward reference of '@" +
3207 Twine(NumberedVals.size()) + "' disagree");
3208 ForwardRefValIDs.erase(I);
3213 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3214 else // Move the forward-reference to the correct spot in the module.
3215 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3217 if (FunctionName.empty())
3218 NumberedVals.push_back(Fn);
3220 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3221 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3222 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3223 Fn->setCallingConv(CC);
3224 Fn->setAttributes(PAL);
3225 Fn->setUnnamedAddr(UnnamedAddr);
3226 Fn->setAlignment(Alignment);
3227 Fn->setSection(Section);
3228 if (!GC.empty()) Fn->setGC(GC.c_str());
3229 Fn->setPrefixData(Prefix);
3230 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3232 // Add all of the arguments we parsed to the function.
3233 Function::arg_iterator ArgIt = Fn->arg_begin();
3234 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3235 // If the argument has a name, insert it into the argument symbol table.
3236 if (ArgList[i].Name.empty()) continue;
3238 // Set the name, if it conflicted, it will be auto-renamed.
3239 ArgIt->setName(ArgList[i].Name);
3241 if (ArgIt->getName() != ArgList[i].Name)
3242 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3243 ArgList[i].Name + "'");
3250 /// ParseFunctionBody
3251 /// ::= '{' BasicBlock+ '}'
3253 bool LLParser::ParseFunctionBody(Function &Fn) {
3254 if (Lex.getKind() != lltok::lbrace)
3255 return TokError("expected '{' in function body");
3256 Lex.Lex(); // eat the {.
3258 int FunctionNumber = -1;
3259 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3261 PerFunctionState PFS(*this, Fn, FunctionNumber);
3263 // We need at least one basic block.
3264 if (Lex.getKind() == lltok::rbrace)
3265 return TokError("function body requires at least one basic block");
3267 while (Lex.getKind() != lltok::rbrace)
3268 if (ParseBasicBlock(PFS)) return true;
3273 // Verify function is ok.
3274 return PFS.FinishFunction();
3278 /// ::= LabelStr? Instruction*
3279 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3280 // If this basic block starts out with a name, remember it.
3282 LocTy NameLoc = Lex.getLoc();
3283 if (Lex.getKind() == lltok::LabelStr) {
3284 Name = Lex.getStrVal();
3288 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3289 if (!BB) return true;
3291 std::string NameStr;
3293 // Parse the instructions in this block until we get a terminator.
3296 // This instruction may have three possibilities for a name: a) none
3297 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3298 LocTy NameLoc = Lex.getLoc();
3302 if (Lex.getKind() == lltok::LocalVarID) {
3303 NameID = Lex.getUIntVal();
3305 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3307 } else if (Lex.getKind() == lltok::LocalVar) {
3308 NameStr = Lex.getStrVal();
3310 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3314 switch (ParseInstruction(Inst, BB, PFS)) {
3315 default: llvm_unreachable("Unknown ParseInstruction result!");
3316 case InstError: return true;
3318 BB->getInstList().push_back(Inst);
3320 // With a normal result, we check to see if the instruction is followed by
3321 // a comma and metadata.
3322 if (EatIfPresent(lltok::comma))
3323 if (ParseInstructionMetadata(Inst, &PFS))
3326 case InstExtraComma:
3327 BB->getInstList().push_back(Inst);
3329 // If the instruction parser ate an extra comma at the end of it, it
3330 // *must* be followed by metadata.
3331 if (ParseInstructionMetadata(Inst, &PFS))
3336 // Set the name on the instruction.
3337 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3338 } while (!isa<TerminatorInst>(Inst));
3343 //===----------------------------------------------------------------------===//
3344 // Instruction Parsing.
3345 //===----------------------------------------------------------------------===//
3347 /// ParseInstruction - Parse one of the many different instructions.
3349 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3350 PerFunctionState &PFS) {
3351 lltok::Kind Token = Lex.getKind();
3352 if (Token == lltok::Eof)
3353 return TokError("found end of file when expecting more instructions");
3354 LocTy Loc = Lex.getLoc();
3355 unsigned KeywordVal = Lex.getUIntVal();
3356 Lex.Lex(); // Eat the keyword.
3359 default: return Error(Loc, "expected instruction opcode");
3360 // Terminator Instructions.
3361 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3362 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3363 case lltok::kw_br: return ParseBr(Inst, PFS);
3364 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3365 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3366 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3367 case lltok::kw_resume: return ParseResume(Inst, PFS);
3368 // Binary Operators.
3372 case lltok::kw_shl: {
3373 bool NUW = EatIfPresent(lltok::kw_nuw);
3374 bool NSW = EatIfPresent(lltok::kw_nsw);
3375 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3377 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3379 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3380 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3383 case lltok::kw_fadd:
3384 case lltok::kw_fsub:
3385 case lltok::kw_fmul:
3386 case lltok::kw_fdiv:
3387 case lltok::kw_frem: {
3388 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3389 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3393 Inst->setFastMathFlags(FMF);
3397 case lltok::kw_sdiv:
3398 case lltok::kw_udiv:
3399 case lltok::kw_lshr:
3400 case lltok::kw_ashr: {
3401 bool Exact = EatIfPresent(lltok::kw_exact);
3403 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3404 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3408 case lltok::kw_urem:
3409 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3412 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3413 case lltok::kw_icmp:
3414 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3416 case lltok::kw_trunc:
3417 case lltok::kw_zext:
3418 case lltok::kw_sext:
3419 case lltok::kw_fptrunc:
3420 case lltok::kw_fpext:
3421 case lltok::kw_bitcast:
3422 case lltok::kw_addrspacecast:
3423 case lltok::kw_uitofp:
3424 case lltok::kw_sitofp:
3425 case lltok::kw_fptoui:
3426 case lltok::kw_fptosi:
3427 case lltok::kw_inttoptr:
3428 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3430 case lltok::kw_select: return ParseSelect(Inst, PFS);
3431 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3432 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3433 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3434 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3435 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3436 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3438 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3439 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3440 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3442 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3443 case lltok::kw_load: return ParseLoad(Inst, PFS);
3444 case lltok::kw_store: return ParseStore(Inst, PFS);
3445 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3446 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3447 case lltok::kw_fence: return ParseFence(Inst, PFS);
3448 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3449 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3450 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3454 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3455 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3456 if (Opc == Instruction::FCmp) {
3457 switch (Lex.getKind()) {
3458 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3459 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3460 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3461 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3462 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3463 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3464 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3465 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3466 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3467 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3468 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3469 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3470 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3471 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3472 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3473 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3474 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3477 switch (Lex.getKind()) {
3478 default: return TokError("expected icmp predicate (e.g. 'eq')");
3479 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3480 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3481 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3482 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3483 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3484 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3485 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3486 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3487 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3488 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3495 //===----------------------------------------------------------------------===//
3496 // Terminator Instructions.
3497 //===----------------------------------------------------------------------===//
3499 /// ParseRet - Parse a return instruction.
3500 /// ::= 'ret' void (',' !dbg, !1)*
3501 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3502 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3503 PerFunctionState &PFS) {
3504 SMLoc TypeLoc = Lex.getLoc();
3506 if (ParseType(Ty, true /*void allowed*/)) return true;
3508 Type *ResType = PFS.getFunction().getReturnType();
3510 if (Ty->isVoidTy()) {
3511 if (!ResType->isVoidTy())
3512 return Error(TypeLoc, "value doesn't match function result type '" +
3513 getTypeString(ResType) + "'");
3515 Inst = ReturnInst::Create(Context);
3520 if (ParseValue(Ty, RV, PFS)) return true;
3522 if (ResType != RV->getType())
3523 return Error(TypeLoc, "value doesn't match function result type '" +
3524 getTypeString(ResType) + "'");
3526 Inst = ReturnInst::Create(Context, RV);
3532 /// ::= 'br' TypeAndValue
3533 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3534 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3537 BasicBlock *Op1, *Op2;
3538 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3540 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3541 Inst = BranchInst::Create(BB);
3545 if (Op0->getType() != Type::getInt1Ty(Context))
3546 return Error(Loc, "branch condition must have 'i1' type");
3548 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3549 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3550 ParseToken(lltok::comma, "expected ',' after true destination") ||
3551 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3554 Inst = BranchInst::Create(Op1, Op2, Op0);
3560 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3562 /// ::= (TypeAndValue ',' TypeAndValue)*
3563 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3564 LocTy CondLoc, BBLoc;
3566 BasicBlock *DefaultBB;
3567 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3568 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3569 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3570 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3573 if (!Cond->getType()->isIntegerTy())
3574 return Error(CondLoc, "switch condition must have integer type");
3576 // Parse the jump table pairs.
3577 SmallPtrSet<Value*, 32> SeenCases;
3578 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3579 while (Lex.getKind() != lltok::rsquare) {
3583 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3584 ParseToken(lltok::comma, "expected ',' after case value") ||
3585 ParseTypeAndBasicBlock(DestBB, PFS))
3588 if (!SeenCases.insert(Constant))
3589 return Error(CondLoc, "duplicate case value in switch");
3590 if (!isa<ConstantInt>(Constant))
3591 return Error(CondLoc, "case value is not a constant integer");
3593 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3596 Lex.Lex(); // Eat the ']'.
3598 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3599 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3600 SI->addCase(Table[i].first, Table[i].second);
3607 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3608 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3611 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3612 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3613 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3616 if (!Address->getType()->isPointerTy())
3617 return Error(AddrLoc, "indirectbr address must have pointer type");
3619 // Parse the destination list.
3620 SmallVector<BasicBlock*, 16> DestList;
3622 if (Lex.getKind() != lltok::rsquare) {
3624 if (ParseTypeAndBasicBlock(DestBB, PFS))
3626 DestList.push_back(DestBB);
3628 while (EatIfPresent(lltok::comma)) {
3629 if (ParseTypeAndBasicBlock(DestBB, PFS))
3631 DestList.push_back(DestBB);
3635 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3638 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3639 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3640 IBI->addDestination(DestList[i]);
3647 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3648 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3649 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3650 LocTy CallLoc = Lex.getLoc();
3651 AttrBuilder RetAttrs, FnAttrs;
3652 std::vector<unsigned> FwdRefAttrGrps;
3655 Type *RetType = nullptr;
3658 SmallVector<ParamInfo, 16> ArgList;
3660 BasicBlock *NormalBB, *UnwindBB;
3661 if (ParseOptionalCallingConv(CC) ||
3662 ParseOptionalReturnAttrs(RetAttrs) ||
3663 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3664 ParseValID(CalleeID) ||
3665 ParseParameterList(ArgList, PFS) ||
3666 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3668 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3669 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3670 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3671 ParseTypeAndBasicBlock(UnwindBB, PFS))
3674 // If RetType is a non-function pointer type, then this is the short syntax
3675 // for the call, which means that RetType is just the return type. Infer the
3676 // rest of the function argument types from the arguments that are present.
3677 PointerType *PFTy = nullptr;
3678 FunctionType *Ty = nullptr;
3679 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3680 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3681 // Pull out the types of all of the arguments...
3682 std::vector<Type*> ParamTypes;
3683 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3684 ParamTypes.push_back(ArgList[i].V->getType());
3686 if (!FunctionType::isValidReturnType(RetType))
3687 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3689 Ty = FunctionType::get(RetType, ParamTypes, false);
3690 PFTy = PointerType::getUnqual(Ty);
3693 // Look up the callee.
3695 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3697 // Set up the Attribute for the function.
3698 SmallVector<AttributeSet, 8> Attrs;
3699 if (RetAttrs.hasAttributes())
3700 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3701 AttributeSet::ReturnIndex,
3704 SmallVector<Value*, 8> Args;
3706 // Loop through FunctionType's arguments and ensure they are specified
3707 // correctly. Also, gather any parameter attributes.
3708 FunctionType::param_iterator I = Ty->param_begin();
3709 FunctionType::param_iterator E = Ty->param_end();
3710 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3711 Type *ExpectedTy = nullptr;
3714 } else if (!Ty->isVarArg()) {
3715 return Error(ArgList[i].Loc, "too many arguments specified");
3718 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3719 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3720 getTypeString(ExpectedTy) + "'");
3721 Args.push_back(ArgList[i].V);
3722 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3723 AttrBuilder B(ArgList[i].Attrs, i + 1);
3724 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3729 return Error(CallLoc, "not enough parameters specified for call");
3731 if (FnAttrs.hasAttributes())
3732 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3733 AttributeSet::FunctionIndex,
3736 // Finish off the Attribute and check them
3737 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3739 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3740 II->setCallingConv(CC);
3741 II->setAttributes(PAL);
3742 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3748 /// ::= 'resume' TypeAndValue
3749 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3750 Value *Exn; LocTy ExnLoc;
3751 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3754 ResumeInst *RI = ResumeInst::Create(Exn);
3759 //===----------------------------------------------------------------------===//
3760 // Binary Operators.
3761 //===----------------------------------------------------------------------===//
3764 /// ::= ArithmeticOps TypeAndValue ',' Value
3766 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3767 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3768 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3769 unsigned Opc, unsigned OperandType) {
3770 LocTy Loc; Value *LHS, *RHS;
3771 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3772 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3773 ParseValue(LHS->getType(), RHS, PFS))
3777 switch (OperandType) {
3778 default: llvm_unreachable("Unknown operand type!");
3779 case 0: // int or FP.
3780 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3781 LHS->getType()->isFPOrFPVectorTy();
3783 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3784 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3788 return Error(Loc, "invalid operand type for instruction");
3790 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3795 /// ::= ArithmeticOps TypeAndValue ',' Value {
3796 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3798 LocTy Loc; Value *LHS, *RHS;
3799 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3800 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3801 ParseValue(LHS->getType(), RHS, PFS))
3804 if (!LHS->getType()->isIntOrIntVectorTy())
3805 return Error(Loc,"instruction requires integer or integer vector operands");
3807 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3813 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3814 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3815 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3817 // Parse the integer/fp comparison predicate.
3821 if (ParseCmpPredicate(Pred, Opc) ||
3822 ParseTypeAndValue(LHS, Loc, PFS) ||
3823 ParseToken(lltok::comma, "expected ',' after compare value") ||
3824 ParseValue(LHS->getType(), RHS, PFS))
3827 if (Opc == Instruction::FCmp) {
3828 if (!LHS->getType()->isFPOrFPVectorTy())
3829 return Error(Loc, "fcmp requires floating point operands");
3830 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3832 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3833 if (!LHS->getType()->isIntOrIntVectorTy() &&
3834 !LHS->getType()->getScalarType()->isPointerTy())
3835 return Error(Loc, "icmp requires integer operands");
3836 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3841 //===----------------------------------------------------------------------===//
3842 // Other Instructions.
3843 //===----------------------------------------------------------------------===//
3847 /// ::= CastOpc TypeAndValue 'to' Type
3848 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3852 Type *DestTy = nullptr;
3853 if (ParseTypeAndValue(Op, Loc, PFS) ||
3854 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3858 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3859 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3860 return Error(Loc, "invalid cast opcode for cast from '" +
3861 getTypeString(Op->getType()) + "' to '" +
3862 getTypeString(DestTy) + "'");
3864 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3869 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3870 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3872 Value *Op0, *Op1, *Op2;
3873 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3874 ParseToken(lltok::comma, "expected ',' after select condition") ||
3875 ParseTypeAndValue(Op1, PFS) ||
3876 ParseToken(lltok::comma, "expected ',' after select value") ||
3877 ParseTypeAndValue(Op2, PFS))
3880 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3881 return Error(Loc, Reason);
3883 Inst = SelectInst::Create(Op0, Op1, Op2);
3888 /// ::= 'va_arg' TypeAndValue ',' Type
3889 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3891 Type *EltTy = nullptr;
3893 if (ParseTypeAndValue(Op, PFS) ||
3894 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3895 ParseType(EltTy, TypeLoc))
3898 if (!EltTy->isFirstClassType())
3899 return Error(TypeLoc, "va_arg requires operand with first class type");
3901 Inst = new VAArgInst(Op, EltTy);
3905 /// ParseExtractElement
3906 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3907 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3910 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3911 ParseToken(lltok::comma, "expected ',' after extract value") ||
3912 ParseTypeAndValue(Op1, PFS))
3915 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3916 return Error(Loc, "invalid extractelement operands");
3918 Inst = ExtractElementInst::Create(Op0, Op1);
3922 /// ParseInsertElement
3923 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3924 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3926 Value *Op0, *Op1, *Op2;
3927 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3928 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3929 ParseTypeAndValue(Op1, PFS) ||
3930 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3931 ParseTypeAndValue(Op2, PFS))
3934 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3935 return Error(Loc, "invalid insertelement operands");
3937 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3941 /// ParseShuffleVector
3942 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3943 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3945 Value *Op0, *Op1, *Op2;
3946 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3947 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3948 ParseTypeAndValue(Op1, PFS) ||
3949 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3950 ParseTypeAndValue(Op2, PFS))
3953 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3954 return Error(Loc, "invalid shufflevector operands");
3956 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3961 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3962 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3963 Type *Ty = nullptr; LocTy TypeLoc;
3966 if (ParseType(Ty, TypeLoc) ||
3967 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3968 ParseValue(Ty, Op0, PFS) ||
3969 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3970 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3971 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3974 bool AteExtraComma = false;
3975 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3977 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3979 if (!EatIfPresent(lltok::comma))
3982 if (Lex.getKind() == lltok::MetadataVar) {
3983 AteExtraComma = true;
3987 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3988 ParseValue(Ty, Op0, PFS) ||
3989 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3990 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3991 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3995 if (!Ty->isFirstClassType())
3996 return Error(TypeLoc, "phi node must have first class type");
3998 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3999 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4000 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4002 return AteExtraComma ? InstExtraComma : InstNormal;
4006 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4008 /// ::= 'catch' TypeAndValue
4010 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4011 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4012 Type *Ty = nullptr; LocTy TyLoc;
4013 Value *PersFn; LocTy PersFnLoc;
4015 if (ParseType(Ty, TyLoc) ||
4016 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4017 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4020 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4021 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4023 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4024 LandingPadInst::ClauseType CT;
4025 if (EatIfPresent(lltok::kw_catch))
4026 CT = LandingPadInst::Catch;
4027 else if (EatIfPresent(lltok::kw_filter))
4028 CT = LandingPadInst::Filter;
4030 return TokError("expected 'catch' or 'filter' clause type");
4032 Value *V; LocTy VLoc;
4033 if (ParseTypeAndValue(V, VLoc, PFS)) {
4038 // A 'catch' type expects a non-array constant. A filter clause expects an
4040 if (CT == LandingPadInst::Catch) {
4041 if (isa<ArrayType>(V->getType()))
4042 Error(VLoc, "'catch' clause has an invalid type");
4044 if (!isa<ArrayType>(V->getType()))
4045 Error(VLoc, "'filter' clause has an invalid type");
4056 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4057 /// ParameterList OptionalAttrs
4058 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4059 /// ParameterList OptionalAttrs
4060 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4061 /// ParameterList OptionalAttrs
4062 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4063 CallInst::TailCallKind TCK) {
4064 AttrBuilder RetAttrs, FnAttrs;
4065 std::vector<unsigned> FwdRefAttrGrps;
4068 Type *RetType = nullptr;
4071 SmallVector<ParamInfo, 16> ArgList;
4072 LocTy CallLoc = Lex.getLoc();
4074 if ((TCK != CallInst::TCK_None &&
4075 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4076 ParseOptionalCallingConv(CC) ||
4077 ParseOptionalReturnAttrs(RetAttrs) ||
4078 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4079 ParseValID(CalleeID) ||
4080 ParseParameterList(ArgList, PFS) ||
4081 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4085 // If RetType is a non-function pointer type, then this is the short syntax
4086 // for the call, which means that RetType is just the return type. Infer the
4087 // rest of the function argument types from the arguments that are present.
4088 PointerType *PFTy = nullptr;
4089 FunctionType *Ty = nullptr;
4090 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4091 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4092 // Pull out the types of all of the arguments...
4093 std::vector<Type*> ParamTypes;
4094 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4095 ParamTypes.push_back(ArgList[i].V->getType());
4097 if (!FunctionType::isValidReturnType(RetType))
4098 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4100 Ty = FunctionType::get(RetType, ParamTypes, false);
4101 PFTy = PointerType::getUnqual(Ty);
4104 // Look up the callee.
4106 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4108 // Set up the Attribute for the function.
4109 SmallVector<AttributeSet, 8> Attrs;
4110 if (RetAttrs.hasAttributes())
4111 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4112 AttributeSet::ReturnIndex,
4115 SmallVector<Value*, 8> Args;
4117 // Loop through FunctionType's arguments and ensure they are specified
4118 // correctly. Also, gather any parameter attributes.
4119 FunctionType::param_iterator I = Ty->param_begin();
4120 FunctionType::param_iterator E = Ty->param_end();
4121 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4122 Type *ExpectedTy = nullptr;
4125 } else if (!Ty->isVarArg()) {
4126 return Error(ArgList[i].Loc, "too many arguments specified");
4129 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4130 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4131 getTypeString(ExpectedTy) + "'");
4132 Args.push_back(ArgList[i].V);
4133 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4134 AttrBuilder B(ArgList[i].Attrs, i + 1);
4135 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4140 return Error(CallLoc, "not enough parameters specified for call");
4142 if (FnAttrs.hasAttributes())
4143 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4144 AttributeSet::FunctionIndex,
4147 // Finish off the Attribute and check them
4148 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4150 CallInst *CI = CallInst::Create(Callee, Args);
4151 CI->setTailCallKind(TCK);
4152 CI->setCallingConv(CC);
4153 CI->setAttributes(PAL);
4154 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4159 //===----------------------------------------------------------------------===//
4160 // Memory Instructions.
4161 //===----------------------------------------------------------------------===//
4164 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4165 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4166 Value *Size = nullptr;
4168 unsigned Alignment = 0;
4171 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4173 if (ParseType(Ty)) return true;
4175 bool AteExtraComma = false;
4176 if (EatIfPresent(lltok::comma)) {
4177 if (Lex.getKind() == lltok::kw_align) {
4178 if (ParseOptionalAlignment(Alignment)) return true;
4179 } else if (Lex.getKind() == lltok::MetadataVar) {
4180 AteExtraComma = true;
4182 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4183 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4188 if (Size && !Size->getType()->isIntegerTy())
4189 return Error(SizeLoc, "element count must have integer type");
4191 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4192 AI->setUsedWithInAlloca(IsInAlloca);
4194 return AteExtraComma ? InstExtraComma : InstNormal;
4198 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4199 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4200 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4201 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4202 Value *Val; LocTy Loc;
4203 unsigned Alignment = 0;
4204 bool AteExtraComma = false;
4205 bool isAtomic = false;
4206 AtomicOrdering Ordering = NotAtomic;
4207 SynchronizationScope Scope = CrossThread;
4209 if (Lex.getKind() == lltok::kw_atomic) {
4214 bool isVolatile = false;
4215 if (Lex.getKind() == lltok::kw_volatile) {
4220 if (ParseTypeAndValue(Val, Loc, PFS) ||
4221 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4222 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4225 if (!Val->getType()->isPointerTy() ||
4226 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4227 return Error(Loc, "load operand must be a pointer to a first class type");
4228 if (isAtomic && !Alignment)
4229 return Error(Loc, "atomic load must have explicit non-zero alignment");
4230 if (Ordering == Release || Ordering == AcquireRelease)
4231 return Error(Loc, "atomic load cannot use Release ordering");
4233 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4234 return AteExtraComma ? InstExtraComma : InstNormal;
4239 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4240 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4241 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4242 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4243 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4244 unsigned Alignment = 0;
4245 bool AteExtraComma = false;
4246 bool isAtomic = false;
4247 AtomicOrdering Ordering = NotAtomic;
4248 SynchronizationScope Scope = CrossThread;
4250 if (Lex.getKind() == lltok::kw_atomic) {
4255 bool isVolatile = false;
4256 if (Lex.getKind() == lltok::kw_volatile) {
4261 if (ParseTypeAndValue(Val, Loc, PFS) ||
4262 ParseToken(lltok::comma, "expected ',' after store operand") ||
4263 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4264 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4265 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4268 if (!Ptr->getType()->isPointerTy())
4269 return Error(PtrLoc, "store operand must be a pointer");
4270 if (!Val->getType()->isFirstClassType())
4271 return Error(Loc, "store operand must be a first class value");
4272 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4273 return Error(Loc, "stored value and pointer type do not match");
4274 if (isAtomic && !Alignment)
4275 return Error(Loc, "atomic store must have explicit non-zero alignment");
4276 if (Ordering == Acquire || Ordering == AcquireRelease)
4277 return Error(Loc, "atomic store cannot use Acquire ordering");
4279 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4280 return AteExtraComma ? InstExtraComma : InstNormal;
4284 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4285 /// 'singlethread'? AtomicOrdering AtomicOrdering
4286 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4287 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4288 bool AteExtraComma = false;
4289 AtomicOrdering SuccessOrdering = NotAtomic;
4290 AtomicOrdering FailureOrdering = NotAtomic;
4291 SynchronizationScope Scope = CrossThread;
4292 bool isVolatile = false;
4294 if (EatIfPresent(lltok::kw_volatile))
4297 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4298 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4299 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4300 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4301 ParseTypeAndValue(New, NewLoc, PFS) ||
4302 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4303 ParseOrdering(FailureOrdering))
4306 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4307 return TokError("cmpxchg cannot be unordered");
4308 if (SuccessOrdering < FailureOrdering)
4309 return TokError("cmpxchg must be at least as ordered on success as failure");
4310 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4311 return TokError("cmpxchg failure ordering cannot include release semantics");
4312 if (!Ptr->getType()->isPointerTy())
4313 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4314 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4315 return Error(CmpLoc, "compare value and pointer type do not match");
4316 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4317 return Error(NewLoc, "new value and pointer type do not match");
4318 if (!New->getType()->isIntegerTy())
4319 return Error(NewLoc, "cmpxchg operand must be an integer");
4320 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4321 if (Size < 8 || (Size & (Size - 1)))
4322 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4325 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4326 FailureOrdering, Scope);
4327 CXI->setVolatile(isVolatile);
4329 return AteExtraComma ? InstExtraComma : InstNormal;
4333 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4334 /// 'singlethread'? AtomicOrdering
4335 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4336 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4337 bool AteExtraComma = false;
4338 AtomicOrdering Ordering = NotAtomic;
4339 SynchronizationScope Scope = CrossThread;
4340 bool isVolatile = false;
4341 AtomicRMWInst::BinOp Operation;
4343 if (EatIfPresent(lltok::kw_volatile))
4346 switch (Lex.getKind()) {
4347 default: return TokError("expected binary operation in atomicrmw");
4348 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4349 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4350 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4351 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4352 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4353 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4354 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4355 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4356 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4357 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4358 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4360 Lex.Lex(); // Eat the operation.
4362 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4363 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4364 ParseTypeAndValue(Val, ValLoc, PFS) ||
4365 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4368 if (Ordering == Unordered)
4369 return TokError("atomicrmw cannot be unordered");
4370 if (!Ptr->getType()->isPointerTy())
4371 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4372 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4373 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4374 if (!Val->getType()->isIntegerTy())
4375 return Error(ValLoc, "atomicrmw operand must be an integer");
4376 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4377 if (Size < 8 || (Size & (Size - 1)))
4378 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4381 AtomicRMWInst *RMWI =
4382 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4383 RMWI->setVolatile(isVolatile);
4385 return AteExtraComma ? InstExtraComma : InstNormal;
4389 /// ::= 'fence' 'singlethread'? AtomicOrdering
4390 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4391 AtomicOrdering Ordering = NotAtomic;
4392 SynchronizationScope Scope = CrossThread;
4393 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4396 if (Ordering == Unordered)
4397 return TokError("fence cannot be unordered");
4398 if (Ordering == Monotonic)
4399 return TokError("fence cannot be monotonic");
4401 Inst = new FenceInst(Context, Ordering, Scope);
4405 /// ParseGetElementPtr
4406 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4407 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4408 Value *Ptr = nullptr;
4409 Value *Val = nullptr;
4412 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4414 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4416 Type *BaseType = Ptr->getType();
4417 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4418 if (!BasePointerType)
4419 return Error(Loc, "base of getelementptr must be a pointer");
4421 SmallVector<Value*, 16> Indices;
4422 bool AteExtraComma = false;
4423 while (EatIfPresent(lltok::comma)) {
4424 if (Lex.getKind() == lltok::MetadataVar) {
4425 AteExtraComma = true;
4428 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4429 if (!Val->getType()->getScalarType()->isIntegerTy())
4430 return Error(EltLoc, "getelementptr index must be an integer");
4431 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4432 return Error(EltLoc, "getelementptr index type missmatch");
4433 if (Val->getType()->isVectorTy()) {
4434 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4435 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4436 if (ValNumEl != PtrNumEl)
4437 return Error(EltLoc,
4438 "getelementptr vector index has a wrong number of elements");
4440 Indices.push_back(Val);
4443 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4444 return Error(Loc, "base element of getelementptr must be sized");
4446 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4447 return Error(Loc, "invalid getelementptr indices");
4448 Inst = GetElementPtrInst::Create(Ptr, Indices);
4450 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4451 return AteExtraComma ? InstExtraComma : InstNormal;
4454 /// ParseExtractValue
4455 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4456 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4457 Value *Val; LocTy Loc;
4458 SmallVector<unsigned, 4> Indices;
4460 if (ParseTypeAndValue(Val, Loc, PFS) ||
4461 ParseIndexList(Indices, AteExtraComma))
4464 if (!Val->getType()->isAggregateType())
4465 return Error(Loc, "extractvalue operand must be aggregate type");
4467 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4468 return Error(Loc, "invalid indices for extractvalue");
4469 Inst = ExtractValueInst::Create(Val, Indices);
4470 return AteExtraComma ? InstExtraComma : InstNormal;
4473 /// ParseInsertValue
4474 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4475 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4476 Value *Val0, *Val1; LocTy Loc0, Loc1;
4477 SmallVector<unsigned, 4> Indices;
4479 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4480 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4481 ParseTypeAndValue(Val1, Loc1, PFS) ||
4482 ParseIndexList(Indices, AteExtraComma))
4485 if (!Val0->getType()->isAggregateType())
4486 return Error(Loc0, "insertvalue operand must be aggregate type");
4488 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4489 return Error(Loc0, "invalid indices for insertvalue");
4490 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4491 return AteExtraComma ? InstExtraComma : InstNormal;
4494 //===----------------------------------------------------------------------===//
4495 // Embedded metadata.
4496 //===----------------------------------------------------------------------===//
4498 /// ParseMDNodeVector
4499 /// ::= Element (',' Element)*
4501 /// ::= 'null' | TypeAndValue
4502 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4503 PerFunctionState *PFS) {
4504 // Check for an empty list.
4505 if (Lex.getKind() == lltok::rbrace)
4509 // Null is a special case since it is typeless.
4510 if (EatIfPresent(lltok::kw_null)) {
4511 Elts.push_back(nullptr);
4516 if (ParseTypeAndValue(V, PFS)) return true;
4518 } while (EatIfPresent(lltok::comma));