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 case lltok::kw_default: // OptionalVisibility
262 case lltok::kw_hidden: // OptionalVisibility
263 case lltok::kw_protected: // OptionalVisibility
264 case lltok::kw_dllimport: // OptionalDLLStorageClass
265 case lltok::kw_dllexport: // OptionalDLLStorageClass
266 case lltok::kw_thread_local: // OptionalThreadLocal
267 case lltok::kw_addrspace: // OptionalAddrSpace
268 case lltok::kw_constant: // GlobalType
269 case lltok::kw_global: { // GlobalType
270 unsigned Linkage, Visibility, DLLStorageClass;
272 GlobalVariable::ThreadLocalMode TLM;
274 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
275 ParseOptionalVisibility(Visibility) ||
276 ParseOptionalDLLStorageClass(DLLStorageClass) ||
277 ParseOptionalThreadLocal(TLM) ||
278 parseOptionalUnnamedAddr(UnnamedAddr) ||
279 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
280 DLLStorageClass, TLM, UnnamedAddr))
285 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
292 /// ::= 'module' 'asm' STRINGCONSTANT
293 bool LLParser::ParseModuleAsm() {
294 assert(Lex.getKind() == lltok::kw_module);
298 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
299 ParseStringConstant(AsmStr)) return true;
301 M->appendModuleInlineAsm(AsmStr);
306 /// ::= 'target' 'triple' '=' STRINGCONSTANT
307 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
308 bool LLParser::ParseTargetDefinition() {
309 assert(Lex.getKind() == lltok::kw_target);
312 default: return TokError("unknown target property");
313 case lltok::kw_triple:
315 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
316 ParseStringConstant(Str))
318 M->setTargetTriple(Str);
320 case lltok::kw_datalayout:
322 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
323 ParseStringConstant(Str))
325 M->setDataLayout(Str);
331 /// ::= 'deplibs' '=' '[' ']'
332 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
333 /// FIXME: Remove in 4.0. Currently parse, but ignore.
334 bool LLParser::ParseDepLibs() {
335 assert(Lex.getKind() == lltok::kw_deplibs);
337 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
338 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
341 if (EatIfPresent(lltok::rsquare))
346 if (ParseStringConstant(Str)) return true;
347 } while (EatIfPresent(lltok::comma));
349 return ParseToken(lltok::rsquare, "expected ']' at end of list");
352 /// ParseUnnamedType:
353 /// ::= LocalVarID '=' 'type' type
354 bool LLParser::ParseUnnamedType() {
355 LocTy TypeLoc = Lex.getLoc();
356 unsigned TypeID = Lex.getUIntVal();
357 Lex.Lex(); // eat LocalVarID;
359 if (ParseToken(lltok::equal, "expected '=' after name") ||
360 ParseToken(lltok::kw_type, "expected 'type' after '='"))
363 if (TypeID >= NumberedTypes.size())
364 NumberedTypes.resize(TypeID+1);
366 Type *Result = nullptr;
367 if (ParseStructDefinition(TypeLoc, "",
368 NumberedTypes[TypeID], Result)) return true;
370 if (!isa<StructType>(Result)) {
371 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
373 return Error(TypeLoc, "non-struct types may not be recursive");
374 Entry.first = Result;
375 Entry.second = SMLoc();
383 /// ::= LocalVar '=' 'type' type
384 bool LLParser::ParseNamedType() {
385 std::string Name = Lex.getStrVal();
386 LocTy NameLoc = Lex.getLoc();
387 Lex.Lex(); // eat LocalVar.
389 if (ParseToken(lltok::equal, "expected '=' after name") ||
390 ParseToken(lltok::kw_type, "expected 'type' after name"))
393 Type *Result = nullptr;
394 if (ParseStructDefinition(NameLoc, Name,
395 NamedTypes[Name], Result)) return true;
397 if (!isa<StructType>(Result)) {
398 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
400 return Error(NameLoc, "non-struct types may not be recursive");
401 Entry.first = Result;
402 Entry.second = SMLoc();
410 /// ::= 'declare' FunctionHeader
411 bool LLParser::ParseDeclare() {
412 assert(Lex.getKind() == lltok::kw_declare);
416 return ParseFunctionHeader(F, false);
420 /// ::= 'define' FunctionHeader '{' ...
421 bool LLParser::ParseDefine() {
422 assert(Lex.getKind() == lltok::kw_define);
426 return ParseFunctionHeader(F, true) ||
427 ParseFunctionBody(*F);
433 bool LLParser::ParseGlobalType(bool &IsConstant) {
434 if (Lex.getKind() == lltok::kw_constant)
436 else if (Lex.getKind() == lltok::kw_global)
440 return TokError("expected 'global' or 'constant'");
446 /// ParseUnnamedGlobal:
447 /// OptionalVisibility ALIAS ...
448 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
449 /// ... -> global variable
450 /// GlobalID '=' OptionalVisibility ALIAS ...
451 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
452 /// ... -> global variable
453 bool LLParser::ParseUnnamedGlobal() {
454 unsigned VarID = NumberedVals.size();
456 LocTy NameLoc = Lex.getLoc();
458 // Handle the GlobalID form.
459 if (Lex.getKind() == lltok::GlobalID) {
460 if (Lex.getUIntVal() != VarID)
461 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
463 Lex.Lex(); // eat GlobalID;
465 if (ParseToken(lltok::equal, "expected '=' after name"))
470 unsigned Linkage, Visibility, DLLStorageClass;
471 GlobalVariable::ThreadLocalMode TLM;
473 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
474 ParseOptionalVisibility(Visibility) ||
475 ParseOptionalDLLStorageClass(DLLStorageClass) ||
476 ParseOptionalThreadLocal(TLM) ||
477 parseOptionalUnnamedAddr(UnnamedAddr))
480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
482 DLLStorageClass, TLM, UnnamedAddr);
483 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
487 /// ParseNamedGlobal:
488 /// GlobalVar '=' OptionalVisibility ALIAS ...
489 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
490 /// ... -> global variable
491 bool LLParser::ParseNamedGlobal() {
492 assert(Lex.getKind() == lltok::GlobalVar);
493 LocTy NameLoc = Lex.getLoc();
494 std::string Name = Lex.getStrVal();
498 unsigned Linkage, Visibility, DLLStorageClass;
499 GlobalVariable::ThreadLocalMode TLM;
501 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
502 ParseOptionalLinkage(Linkage, HasLinkage) ||
503 ParseOptionalVisibility(Visibility) ||
504 ParseOptionalDLLStorageClass(DLLStorageClass) ||
505 ParseOptionalThreadLocal(TLM) ||
506 parseOptionalUnnamedAddr(UnnamedAddr))
509 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
510 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
511 DLLStorageClass, TLM, UnnamedAddr);
512 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
517 // ::= '!' STRINGCONSTANT
518 bool LLParser::ParseMDString(MDString *&Result) {
520 if (ParseStringConstant(Str)) return true;
521 llvm::UpgradeMDStringConstant(Str);
522 Result = MDString::get(Context, Str);
527 // ::= '!' MDNodeNumber
529 /// This version of ParseMDNodeID returns the slot number and null in the case
530 /// of a forward reference.
531 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
532 // !{ ..., !42, ... }
533 if (ParseUInt32(SlotNo)) return true;
535 // Check existing MDNode.
536 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
537 Result = NumberedMetadata[SlotNo];
543 bool LLParser::ParseMDNodeID(MDNode *&Result) {
544 // !{ ..., !42, ... }
546 if (ParseMDNodeID(Result, MID)) return true;
548 // If not a forward reference, just return it now.
549 if (Result) return false;
551 // Otherwise, create MDNode forward reference.
552 MDNode *FwdNode = MDNode::getTemporary(Context, None);
553 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
555 if (NumberedMetadata.size() <= MID)
556 NumberedMetadata.resize(MID+1);
557 NumberedMetadata[MID] = FwdNode;
562 /// ParseNamedMetadata:
563 /// !foo = !{ !1, !2 }
564 bool LLParser::ParseNamedMetadata() {
565 assert(Lex.getKind() == lltok::MetadataVar);
566 std::string Name = Lex.getStrVal();
569 if (ParseToken(lltok::equal, "expected '=' here") ||
570 ParseToken(lltok::exclaim, "Expected '!' here") ||
571 ParseToken(lltok::lbrace, "Expected '{' here"))
574 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
575 if (Lex.getKind() != lltok::rbrace)
577 if (ParseToken(lltok::exclaim, "Expected '!' here"))
581 if (ParseMDNodeID(N)) return true;
583 } while (EatIfPresent(lltok::comma));
585 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
591 /// ParseStandaloneMetadata:
593 bool LLParser::ParseStandaloneMetadata() {
594 assert(Lex.getKind() == lltok::exclaim);
596 unsigned MetadataID = 0;
600 SmallVector<Value *, 16> Elts;
601 if (ParseUInt32(MetadataID) ||
602 ParseToken(lltok::equal, "expected '=' here") ||
603 ParseType(Ty, TyLoc) ||
604 ParseToken(lltok::exclaim, "Expected '!' here") ||
605 ParseToken(lltok::lbrace, "Expected '{' here") ||
606 ParseMDNodeVector(Elts, nullptr) ||
607 ParseToken(lltok::rbrace, "expected end of metadata node"))
610 MDNode *Init = MDNode::get(Context, Elts);
612 // See if this was forward referenced, if so, handle it.
613 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
614 FI = ForwardRefMDNodes.find(MetadataID);
615 if (FI != ForwardRefMDNodes.end()) {
616 MDNode *Temp = FI->second.first;
617 Temp->replaceAllUsesWith(Init);
618 MDNode::deleteTemporary(Temp);
619 ForwardRefMDNodes.erase(FI);
621 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
623 if (MetadataID >= NumberedMetadata.size())
624 NumberedMetadata.resize(MetadataID+1);
626 if (NumberedMetadata[MetadataID] != nullptr)
627 return TokError("Metadata id is already used");
628 NumberedMetadata[MetadataID] = Init;
634 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
635 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
636 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
640 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass
641 /// OptionalThreadLocal OptionalUnNammedAddr 'alias'
642 /// OptionalLinkage Aliasee
647 /// Everything through OptionalUnNammedAddr has already been parsed.
649 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
650 unsigned Visibility, unsigned DLLStorageClass,
651 GlobalVariable::ThreadLocalMode TLM,
653 assert(Lex.getKind() == lltok::kw_alias);
655 LocTy LinkageLoc = Lex.getLoc();
657 if (ParseOptionalLinkage(L))
660 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
662 if(!GlobalAlias::isValidLinkage(Linkage))
663 return Error(LinkageLoc, "invalid linkage type for alias");
665 if (!isValidVisibilityForLinkage(Visibility, L))
666 return Error(LinkageLoc,
667 "symbol with local linkage must have default visibility");
670 LocTy AliaseeLoc = Lex.getLoc();
671 if (Lex.getKind() != lltok::kw_bitcast &&
672 Lex.getKind() != lltok::kw_getelementptr &&
673 Lex.getKind() != lltok::kw_addrspacecast &&
674 Lex.getKind() != lltok::kw_inttoptr) {
675 if (ParseGlobalTypeAndValue(Aliasee))
678 // The bitcast dest type is not present, it is implied by the dest type.
682 if (ID.Kind != ValID::t_Constant)
683 return Error(AliaseeLoc, "invalid aliasee");
684 Aliasee = ID.ConstantVal;
687 Type *AliaseeType = Aliasee->getType();
688 auto *PTy = dyn_cast<PointerType>(AliaseeType);
690 return Error(AliaseeLoc, "An alias must have pointer type");
691 Type *Ty = PTy->getElementType();
692 unsigned AddrSpace = PTy->getAddressSpace();
694 // Okay, create the alias but do not insert it into the module yet.
695 std::unique_ptr<GlobalAlias> GA(
696 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
697 Name, Aliasee, /*Parent*/ nullptr));
698 GA->setThreadLocalMode(TLM);
699 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
700 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
701 GA->setUnnamedAddr(UnnamedAddr);
703 // See if this value already exists in the symbol table. If so, it is either
704 // a redefinition or a definition of a forward reference.
705 if (GlobalValue *Val = M->getNamedValue(Name)) {
706 // See if this was a redefinition. If so, there is no entry in
708 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
709 I = ForwardRefVals.find(Name);
710 if (I == ForwardRefVals.end())
711 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
713 // Otherwise, this was a definition of forward ref. Verify that types
715 if (Val->getType() != GA->getType())
716 return Error(NameLoc,
717 "forward reference and definition of alias have different types");
719 // If they agree, just RAUW the old value with the alias and remove the
721 Val->replaceAllUsesWith(GA.get());
722 Val->eraseFromParent();
723 ForwardRefVals.erase(I);
726 // Insert into the module, we know its name won't collide now.
727 M->getAliasList().push_back(GA.get());
728 assert(GA->getName() == Name && "Should not be a name conflict!");
730 // The module owns this now
737 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
738 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
739 /// OptionalExternallyInitialized GlobalType Type Const
740 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
741 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
742 /// OptionalExternallyInitialized GlobalType Type Const
744 /// Everything up to and including OptionalUnNammedAddr has been parsed
747 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
748 unsigned Linkage, bool HasLinkage,
749 unsigned Visibility, unsigned DLLStorageClass,
750 GlobalVariable::ThreadLocalMode TLM,
752 if (!isValidVisibilityForLinkage(Visibility, Linkage))
753 return Error(NameLoc,
754 "symbol with local linkage must have default visibility");
757 bool IsConstant, IsExternallyInitialized;
758 LocTy IsExternallyInitializedLoc;
762 if (ParseOptionalAddrSpace(AddrSpace) ||
763 ParseOptionalToken(lltok::kw_externally_initialized,
764 IsExternallyInitialized,
765 &IsExternallyInitializedLoc) ||
766 ParseGlobalType(IsConstant) ||
767 ParseType(Ty, TyLoc))
770 // If the linkage is specified and is external, then no initializer is
772 Constant *Init = nullptr;
773 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
774 Linkage != GlobalValue::ExternalLinkage)) {
775 if (ParseGlobalValue(Ty, Init))
779 if (Ty->isFunctionTy() || Ty->isLabelTy())
780 return Error(TyLoc, "invalid type for global variable");
782 GlobalVariable *GV = nullptr;
784 // See if the global was forward referenced, if so, use the global.
786 if (GlobalValue *GVal = M->getNamedValue(Name)) {
787 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
788 return Error(NameLoc, "redefinition of global '@" + Name + "'");
789 GV = cast<GlobalVariable>(GVal);
792 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
793 I = ForwardRefValIDs.find(NumberedVals.size());
794 if (I != ForwardRefValIDs.end()) {
795 GV = cast<GlobalVariable>(I->second.first);
796 ForwardRefValIDs.erase(I);
801 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
802 Name, nullptr, GlobalVariable::NotThreadLocal,
805 if (GV->getType()->getElementType() != Ty)
807 "forward reference and definition of global have different types");
809 // Move the forward-reference to the correct spot in the module.
810 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
814 NumberedVals.push_back(GV);
816 // Set the parsed properties on the global.
818 GV->setInitializer(Init);
819 GV->setConstant(IsConstant);
820 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
821 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
822 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
823 GV->setExternallyInitialized(IsExternallyInitialized);
824 GV->setThreadLocalMode(TLM);
825 GV->setUnnamedAddr(UnnamedAddr);
827 // Parse attributes on the global.
828 while (Lex.getKind() == lltok::comma) {
831 if (Lex.getKind() == lltok::kw_section) {
833 GV->setSection(Lex.getStrVal());
834 if (ParseToken(lltok::StringConstant, "expected global section string"))
836 } else if (Lex.getKind() == lltok::kw_align) {
838 if (ParseOptionalAlignment(Alignment)) return true;
839 GV->setAlignment(Alignment);
841 TokError("unknown global variable property!");
848 /// ParseUnnamedAttrGrp
849 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
850 bool LLParser::ParseUnnamedAttrGrp() {
851 assert(Lex.getKind() == lltok::kw_attributes);
852 LocTy AttrGrpLoc = Lex.getLoc();
855 assert(Lex.getKind() == lltok::AttrGrpID);
856 unsigned VarID = Lex.getUIntVal();
857 std::vector<unsigned> unused;
861 if (ParseToken(lltok::equal, "expected '=' here") ||
862 ParseToken(lltok::lbrace, "expected '{' here") ||
863 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
865 ParseToken(lltok::rbrace, "expected end of attribute group"))
868 if (!NumberedAttrBuilders[VarID].hasAttributes())
869 return Error(AttrGrpLoc, "attribute group has no attributes");
874 /// ParseFnAttributeValuePairs
875 /// ::= <attr> | <attr> '=' <value>
876 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
877 std::vector<unsigned> &FwdRefAttrGrps,
878 bool inAttrGrp, LocTy &BuiltinLoc) {
879 bool HaveError = false;
884 lltok::Kind Token = Lex.getKind();
885 if (Token == lltok::kw_builtin)
886 BuiltinLoc = Lex.getLoc();
889 if (!inAttrGrp) return HaveError;
890 return Error(Lex.getLoc(), "unterminated attribute group");
895 case lltok::AttrGrpID: {
896 // Allow a function to reference an attribute group:
898 // define void @foo() #1 { ... }
902 "cannot have an attribute group reference in an attribute group");
904 unsigned AttrGrpNum = Lex.getUIntVal();
905 if (inAttrGrp) break;
907 // Save the reference to the attribute group. We'll fill it in later.
908 FwdRefAttrGrps.push_back(AttrGrpNum);
911 // Target-dependent attributes:
912 case lltok::StringConstant: {
913 std::string Attr = Lex.getStrVal();
916 if (EatIfPresent(lltok::equal) &&
917 ParseStringConstant(Val))
920 B.addAttribute(Attr, Val);
924 // Target-independent attributes:
925 case lltok::kw_align: {
926 // As a hack, we allow function alignment to be initially parsed as an
927 // attribute on a function declaration/definition or added to an attribute
928 // group and later moved to the alignment field.
932 if (ParseToken(lltok::equal, "expected '=' here") ||
933 ParseUInt32(Alignment))
936 if (ParseOptionalAlignment(Alignment))
939 B.addAlignmentAttr(Alignment);
942 case lltok::kw_alignstack: {
946 if (ParseToken(lltok::equal, "expected '=' here") ||
947 ParseUInt32(Alignment))
950 if (ParseOptionalStackAlignment(Alignment))
953 B.addStackAlignmentAttr(Alignment);
956 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
957 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
958 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
959 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
960 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
961 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
962 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
963 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
964 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
965 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
966 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
967 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
968 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
969 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
970 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
971 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
972 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
973 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
974 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
975 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
976 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
977 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
978 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
979 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
980 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
981 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
982 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
985 case lltok::kw_inreg:
986 case lltok::kw_signext:
987 case lltok::kw_zeroext:
990 "invalid use of attribute on a function");
992 case lltok::kw_byval:
993 case lltok::kw_inalloca:
995 case lltok::kw_noalias:
996 case lltok::kw_nocapture:
997 case lltok::kw_nonnull:
998 case lltok::kw_returned:
1002 "invalid use of parameter-only attribute on a function");
1010 //===----------------------------------------------------------------------===//
1011 // GlobalValue Reference/Resolution Routines.
1012 //===----------------------------------------------------------------------===//
1014 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1015 /// forward reference record if needed. This can return null if the value
1016 /// exists but does not have the right type.
1017 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1019 PointerType *PTy = dyn_cast<PointerType>(Ty);
1021 Error(Loc, "global variable reference must have pointer type");
1025 // Look this name up in the normal function symbol table.
1027 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1029 // If this is a forward reference for the value, see if we already created a
1030 // forward ref record.
1032 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1033 I = ForwardRefVals.find(Name);
1034 if (I != ForwardRefVals.end())
1035 Val = I->second.first;
1038 // If we have the value in the symbol table or fwd-ref table, return it.
1040 if (Val->getType() == Ty) return Val;
1041 Error(Loc, "'@" + Name + "' defined with type '" +
1042 getTypeString(Val->getType()) + "'");
1046 // Otherwise, create a new forward reference for this value and remember it.
1047 GlobalValue *FwdVal;
1048 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1049 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1051 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1052 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1053 nullptr, GlobalVariable::NotThreadLocal,
1054 PTy->getAddressSpace());
1056 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1060 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1061 PointerType *PTy = dyn_cast<PointerType>(Ty);
1063 Error(Loc, "global variable reference must have pointer type");
1067 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1069 // If this is a forward reference for the value, see if we already created a
1070 // forward ref record.
1072 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1073 I = ForwardRefValIDs.find(ID);
1074 if (I != ForwardRefValIDs.end())
1075 Val = I->second.first;
1078 // If we have the value in the symbol table or fwd-ref table, return it.
1080 if (Val->getType() == Ty) return Val;
1081 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1082 getTypeString(Val->getType()) + "'");
1086 // Otherwise, create a new forward reference for this value and remember it.
1087 GlobalValue *FwdVal;
1088 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1089 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1091 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1092 GlobalValue::ExternalWeakLinkage, nullptr, "");
1094 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1099 //===----------------------------------------------------------------------===//
1101 //===----------------------------------------------------------------------===//
1103 /// ParseToken - If the current token has the specified kind, eat it and return
1104 /// success. Otherwise, emit the specified error and return failure.
1105 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1106 if (Lex.getKind() != T)
1107 return TokError(ErrMsg);
1112 /// ParseStringConstant
1113 /// ::= StringConstant
1114 bool LLParser::ParseStringConstant(std::string &Result) {
1115 if (Lex.getKind() != lltok::StringConstant)
1116 return TokError("expected string constant");
1117 Result = Lex.getStrVal();
1124 bool LLParser::ParseUInt32(unsigned &Val) {
1125 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1126 return TokError("expected integer");
1127 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1128 if (Val64 != unsigned(Val64))
1129 return TokError("expected 32-bit integer (too large)");
1136 /// := 'localdynamic'
1137 /// := 'initialexec'
1139 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1140 switch (Lex.getKind()) {
1142 return TokError("expected localdynamic, initialexec or localexec");
1143 case lltok::kw_localdynamic:
1144 TLM = GlobalVariable::LocalDynamicTLSModel;
1146 case lltok::kw_initialexec:
1147 TLM = GlobalVariable::InitialExecTLSModel;
1149 case lltok::kw_localexec:
1150 TLM = GlobalVariable::LocalExecTLSModel;
1158 /// ParseOptionalThreadLocal
1160 /// := 'thread_local'
1161 /// := 'thread_local' '(' tlsmodel ')'
1162 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1163 TLM = GlobalVariable::NotThreadLocal;
1164 if (!EatIfPresent(lltok::kw_thread_local))
1167 TLM = GlobalVariable::GeneralDynamicTLSModel;
1168 if (Lex.getKind() == lltok::lparen) {
1170 return ParseTLSModel(TLM) ||
1171 ParseToken(lltok::rparen, "expected ')' after thread local model");
1176 /// ParseOptionalAddrSpace
1178 /// := 'addrspace' '(' uint32 ')'
1179 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1181 if (!EatIfPresent(lltok::kw_addrspace))
1183 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1184 ParseUInt32(AddrSpace) ||
1185 ParseToken(lltok::rparen, "expected ')' in address space");
1188 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1189 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1190 bool HaveError = false;
1195 lltok::Kind Token = Lex.getKind();
1197 default: // End of attributes.
1199 case lltok::kw_align: {
1201 if (ParseOptionalAlignment(Alignment))
1203 B.addAlignmentAttr(Alignment);
1206 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1207 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1208 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1209 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1210 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1211 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1212 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1213 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1214 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1215 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1216 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1217 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1218 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1220 case lltok::kw_alignstack:
1221 case lltok::kw_alwaysinline:
1222 case lltok::kw_builtin:
1223 case lltok::kw_inlinehint:
1224 case lltok::kw_jumptable:
1225 case lltok::kw_minsize:
1226 case lltok::kw_naked:
1227 case lltok::kw_nobuiltin:
1228 case lltok::kw_noduplicate:
1229 case lltok::kw_noimplicitfloat:
1230 case lltok::kw_noinline:
1231 case lltok::kw_nonlazybind:
1232 case lltok::kw_noredzone:
1233 case lltok::kw_noreturn:
1234 case lltok::kw_nounwind:
1235 case lltok::kw_optnone:
1236 case lltok::kw_optsize:
1237 case lltok::kw_returns_twice:
1238 case lltok::kw_sanitize_address:
1239 case lltok::kw_sanitize_memory:
1240 case lltok::kw_sanitize_thread:
1242 case lltok::kw_sspreq:
1243 case lltok::kw_sspstrong:
1244 case lltok::kw_uwtable:
1245 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1253 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1254 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1255 bool HaveError = false;
1260 lltok::Kind Token = Lex.getKind();
1262 default: // End of attributes.
1264 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1265 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1266 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1267 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1268 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1271 case lltok::kw_align:
1272 case lltok::kw_byval:
1273 case lltok::kw_inalloca:
1274 case lltok::kw_nest:
1275 case lltok::kw_nocapture:
1276 case lltok::kw_returned:
1277 case lltok::kw_sret:
1278 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1281 case lltok::kw_alignstack:
1282 case lltok::kw_alwaysinline:
1283 case lltok::kw_builtin:
1284 case lltok::kw_cold:
1285 case lltok::kw_inlinehint:
1286 case lltok::kw_jumptable:
1287 case lltok::kw_minsize:
1288 case lltok::kw_naked:
1289 case lltok::kw_nobuiltin:
1290 case lltok::kw_noduplicate:
1291 case lltok::kw_noimplicitfloat:
1292 case lltok::kw_noinline:
1293 case lltok::kw_nonlazybind:
1294 case lltok::kw_noredzone:
1295 case lltok::kw_noreturn:
1296 case lltok::kw_nounwind:
1297 case lltok::kw_optnone:
1298 case lltok::kw_optsize:
1299 case lltok::kw_returns_twice:
1300 case lltok::kw_sanitize_address:
1301 case lltok::kw_sanitize_memory:
1302 case lltok::kw_sanitize_thread:
1304 case lltok::kw_sspreq:
1305 case lltok::kw_sspstrong:
1306 case lltok::kw_uwtable:
1307 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1310 case lltok::kw_readnone:
1311 case lltok::kw_readonly:
1312 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1319 /// ParseOptionalLinkage
1326 /// ::= 'linkonce_odr'
1327 /// ::= 'available_externally'
1330 /// ::= 'extern_weak'
1333 /// Deprecated Values:
1334 /// ::= 'linker_private'
1335 /// ::= 'linker_private_weak'
1336 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1338 switch (Lex.getKind()) {
1339 default: Res=GlobalValue::ExternalLinkage; return false;
1340 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1341 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1342 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1343 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1344 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1345 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1346 case lltok::kw_available_externally:
1347 Res = GlobalValue::AvailableExternallyLinkage;
1349 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1350 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1351 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1352 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1354 case lltok::kw_linker_private:
1355 case lltok::kw_linker_private_weak:
1356 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1359 // treat linker_private and linker_private_weak as PrivateLinkage
1360 Res = GlobalValue::PrivateLinkage;
1368 /// ParseOptionalVisibility
1374 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1375 switch (Lex.getKind()) {
1376 default: Res = GlobalValue::DefaultVisibility; return false;
1377 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1378 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1379 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1385 /// ParseOptionalDLLStorageClass
1390 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1391 switch (Lex.getKind()) {
1392 default: Res = GlobalValue::DefaultStorageClass; return false;
1393 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1394 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1400 /// ParseOptionalCallingConv
1404 /// ::= 'kw_intel_ocl_bicc'
1406 /// ::= 'x86_stdcallcc'
1407 /// ::= 'x86_fastcallcc'
1408 /// ::= 'x86_thiscallcc'
1409 /// ::= 'arm_apcscc'
1410 /// ::= 'arm_aapcscc'
1411 /// ::= 'arm_aapcs_vfpcc'
1412 /// ::= 'msp430_intrcc'
1413 /// ::= 'ptx_kernel'
1414 /// ::= 'ptx_device'
1416 /// ::= 'spir_kernel'
1417 /// ::= 'x86_64_sysvcc'
1418 /// ::= 'x86_64_win64cc'
1419 /// ::= 'webkit_jscc'
1421 /// ::= 'preserve_mostcc'
1422 /// ::= 'preserve_allcc'
1425 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1426 switch (Lex.getKind()) {
1427 default: CC = CallingConv::C; return false;
1428 case lltok::kw_ccc: CC = CallingConv::C; break;
1429 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1430 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1431 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1432 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1433 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1434 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1435 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1436 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1437 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1438 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1439 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1440 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1441 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1442 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1443 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1444 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1445 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1446 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1447 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1448 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1449 case lltok::kw_cc: {
1450 unsigned ArbitraryCC;
1452 if (ParseUInt32(ArbitraryCC))
1454 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1463 /// ParseInstructionMetadata
1464 /// ::= !dbg !42 (',' !dbg !57)*
1465 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1466 PerFunctionState *PFS) {
1468 if (Lex.getKind() != lltok::MetadataVar)
1469 return TokError("expected metadata after comma");
1471 std::string Name = Lex.getStrVal();
1472 unsigned MDK = M->getMDKindID(Name);
1476 SMLoc Loc = Lex.getLoc();
1478 if (ParseToken(lltok::exclaim, "expected '!' here"))
1481 // This code is similar to that of ParseMetadataValue, however it needs to
1482 // have special-case code for a forward reference; see the comments on
1483 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1484 // at the top level here.
1485 if (Lex.getKind() == lltok::lbrace) {
1487 if (ParseMetadataListValue(ID, PFS))
1489 assert(ID.Kind == ValID::t_MDNode);
1490 Inst->setMetadata(MDK, ID.MDNodeVal);
1492 unsigned NodeID = 0;
1493 if (ParseMDNodeID(Node, NodeID))
1496 // If we got the node, add it to the instruction.
1497 Inst->setMetadata(MDK, Node);
1499 MDRef R = { Loc, MDK, NodeID };
1500 // Otherwise, remember that this should be resolved later.
1501 ForwardRefInstMetadata[Inst].push_back(R);
1505 if (MDK == LLVMContext::MD_tbaa)
1506 InstsWithTBAATag.push_back(Inst);
1508 // If this is the end of the list, we're done.
1509 } while (EatIfPresent(lltok::comma));
1513 /// ParseOptionalAlignment
1516 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1518 if (!EatIfPresent(lltok::kw_align))
1520 LocTy AlignLoc = Lex.getLoc();
1521 if (ParseUInt32(Alignment)) return true;
1522 if (!isPowerOf2_32(Alignment))
1523 return Error(AlignLoc, "alignment is not a power of two");
1524 if (Alignment > Value::MaximumAlignment)
1525 return Error(AlignLoc, "huge alignments are not supported yet");
1529 /// ParseOptionalCommaAlign
1533 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1535 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1536 bool &AteExtraComma) {
1537 AteExtraComma = false;
1538 while (EatIfPresent(lltok::comma)) {
1539 // Metadata at the end is an early exit.
1540 if (Lex.getKind() == lltok::MetadataVar) {
1541 AteExtraComma = true;
1545 if (Lex.getKind() != lltok::kw_align)
1546 return Error(Lex.getLoc(), "expected metadata or 'align'");
1548 if (ParseOptionalAlignment(Alignment)) return true;
1554 /// ParseScopeAndOrdering
1555 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1558 /// This sets Scope and Ordering to the parsed values.
1559 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1560 AtomicOrdering &Ordering) {
1564 Scope = CrossThread;
1565 if (EatIfPresent(lltok::kw_singlethread))
1566 Scope = SingleThread;
1568 return ParseOrdering(Ordering);
1572 /// ::= AtomicOrdering
1574 /// This sets Ordering to the parsed value.
1575 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1576 switch (Lex.getKind()) {
1577 default: return TokError("Expected ordering on atomic instruction");
1578 case lltok::kw_unordered: Ordering = Unordered; break;
1579 case lltok::kw_monotonic: Ordering = Monotonic; break;
1580 case lltok::kw_acquire: Ordering = Acquire; break;
1581 case lltok::kw_release: Ordering = Release; break;
1582 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1583 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1589 /// ParseOptionalStackAlignment
1591 /// ::= 'alignstack' '(' 4 ')'
1592 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1594 if (!EatIfPresent(lltok::kw_alignstack))
1596 LocTy ParenLoc = Lex.getLoc();
1597 if (!EatIfPresent(lltok::lparen))
1598 return Error(ParenLoc, "expected '('");
1599 LocTy AlignLoc = Lex.getLoc();
1600 if (ParseUInt32(Alignment)) return true;
1601 ParenLoc = Lex.getLoc();
1602 if (!EatIfPresent(lltok::rparen))
1603 return Error(ParenLoc, "expected ')'");
1604 if (!isPowerOf2_32(Alignment))
1605 return Error(AlignLoc, "stack alignment is not a power of two");
1609 /// ParseIndexList - This parses the index list for an insert/extractvalue
1610 /// instruction. This sets AteExtraComma in the case where we eat an extra
1611 /// comma at the end of the line and find that it is followed by metadata.
1612 /// Clients that don't allow metadata can call the version of this function that
1613 /// only takes one argument.
1616 /// ::= (',' uint32)+
1618 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1619 bool &AteExtraComma) {
1620 AteExtraComma = false;
1622 if (Lex.getKind() != lltok::comma)
1623 return TokError("expected ',' as start of index list");
1625 while (EatIfPresent(lltok::comma)) {
1626 if (Lex.getKind() == lltok::MetadataVar) {
1627 AteExtraComma = true;
1631 if (ParseUInt32(Idx)) return true;
1632 Indices.push_back(Idx);
1638 //===----------------------------------------------------------------------===//
1640 //===----------------------------------------------------------------------===//
1642 /// ParseType - Parse a type.
1643 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1644 SMLoc TypeLoc = Lex.getLoc();
1645 switch (Lex.getKind()) {
1647 return TokError("expected type");
1649 // Type ::= 'float' | 'void' (etc)
1650 Result = Lex.getTyVal();
1654 // Type ::= StructType
1655 if (ParseAnonStructType(Result, false))
1658 case lltok::lsquare:
1659 // Type ::= '[' ... ']'
1660 Lex.Lex(); // eat the lsquare.
1661 if (ParseArrayVectorType(Result, false))
1664 case lltok::less: // Either vector or packed struct.
1665 // Type ::= '<' ... '>'
1667 if (Lex.getKind() == lltok::lbrace) {
1668 if (ParseAnonStructType(Result, true) ||
1669 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1671 } else if (ParseArrayVectorType(Result, true))
1674 case lltok::LocalVar: {
1676 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1678 // If the type hasn't been defined yet, create a forward definition and
1679 // remember where that forward def'n was seen (in case it never is defined).
1681 Entry.first = StructType::create(Context, Lex.getStrVal());
1682 Entry.second = Lex.getLoc();
1684 Result = Entry.first;
1689 case lltok::LocalVarID: {
1691 if (Lex.getUIntVal() >= NumberedTypes.size())
1692 NumberedTypes.resize(Lex.getUIntVal()+1);
1693 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1695 // If the type hasn't been defined yet, create a forward definition and
1696 // remember where that forward def'n was seen (in case it never is defined).
1698 Entry.first = StructType::create(Context);
1699 Entry.second = Lex.getLoc();
1701 Result = Entry.first;
1707 // Parse the type suffixes.
1709 switch (Lex.getKind()) {
1712 if (!AllowVoid && Result->isVoidTy())
1713 return Error(TypeLoc, "void type only allowed for function results");
1716 // Type ::= Type '*'
1718 if (Result->isLabelTy())
1719 return TokError("basic block pointers are invalid");
1720 if (Result->isVoidTy())
1721 return TokError("pointers to void are invalid - use i8* instead");
1722 if (!PointerType::isValidElementType(Result))
1723 return TokError("pointer to this type is invalid");
1724 Result = PointerType::getUnqual(Result);
1728 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1729 case lltok::kw_addrspace: {
1730 if (Result->isLabelTy())
1731 return TokError("basic block pointers are invalid");
1732 if (Result->isVoidTy())
1733 return TokError("pointers to void are invalid; use i8* instead");
1734 if (!PointerType::isValidElementType(Result))
1735 return TokError("pointer to this type is invalid");
1737 if (ParseOptionalAddrSpace(AddrSpace) ||
1738 ParseToken(lltok::star, "expected '*' in address space"))
1741 Result = PointerType::get(Result, AddrSpace);
1745 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1747 if (ParseFunctionType(Result))
1754 /// ParseParameterList
1756 /// ::= '(' Arg (',' Arg)* ')'
1758 /// ::= Type OptionalAttributes Value OptionalAttributes
1759 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1760 PerFunctionState &PFS) {
1761 if (ParseToken(lltok::lparen, "expected '(' in call"))
1764 unsigned AttrIndex = 1;
1765 while (Lex.getKind() != lltok::rparen) {
1766 // If this isn't the first argument, we need a comma.
1767 if (!ArgList.empty() &&
1768 ParseToken(lltok::comma, "expected ',' in argument list"))
1771 // Parse the argument.
1773 Type *ArgTy = nullptr;
1774 AttrBuilder ArgAttrs;
1776 if (ParseType(ArgTy, ArgLoc))
1779 // Otherwise, handle normal operands.
1780 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1782 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1787 Lex.Lex(); // Lex the ')'.
1793 /// ParseArgumentList - Parse the argument list for a function type or function
1795 /// ::= '(' ArgTypeListI ')'
1799 /// ::= ArgTypeList ',' '...'
1800 /// ::= ArgType (',' ArgType)*
1802 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1805 assert(Lex.getKind() == lltok::lparen);
1806 Lex.Lex(); // eat the (.
1808 if (Lex.getKind() == lltok::rparen) {
1810 } else if (Lex.getKind() == lltok::dotdotdot) {
1814 LocTy TypeLoc = Lex.getLoc();
1815 Type *ArgTy = nullptr;
1819 if (ParseType(ArgTy) ||
1820 ParseOptionalParamAttrs(Attrs)) return true;
1822 if (ArgTy->isVoidTy())
1823 return Error(TypeLoc, "argument can not have void type");
1825 if (Lex.getKind() == lltok::LocalVar) {
1826 Name = Lex.getStrVal();
1830 if (!FunctionType::isValidArgumentType(ArgTy))
1831 return Error(TypeLoc, "invalid type for function argument");
1833 unsigned AttrIndex = 1;
1834 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1835 AttributeSet::get(ArgTy->getContext(),
1836 AttrIndex++, Attrs), Name));
1838 while (EatIfPresent(lltok::comma)) {
1839 // Handle ... at end of arg list.
1840 if (EatIfPresent(lltok::dotdotdot)) {
1845 // Otherwise must be an argument type.
1846 TypeLoc = Lex.getLoc();
1847 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1849 if (ArgTy->isVoidTy())
1850 return Error(TypeLoc, "argument can not have void type");
1852 if (Lex.getKind() == lltok::LocalVar) {
1853 Name = Lex.getStrVal();
1859 if (!ArgTy->isFirstClassType())
1860 return Error(TypeLoc, "invalid type for function argument");
1862 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1863 AttributeSet::get(ArgTy->getContext(),
1864 AttrIndex++, Attrs),
1869 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1872 /// ParseFunctionType
1873 /// ::= Type ArgumentList OptionalAttrs
1874 bool LLParser::ParseFunctionType(Type *&Result) {
1875 assert(Lex.getKind() == lltok::lparen);
1877 if (!FunctionType::isValidReturnType(Result))
1878 return TokError("invalid function return type");
1880 SmallVector<ArgInfo, 8> ArgList;
1882 if (ParseArgumentList(ArgList, isVarArg))
1885 // Reject names on the arguments lists.
1886 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1887 if (!ArgList[i].Name.empty())
1888 return Error(ArgList[i].Loc, "argument name invalid in function type");
1889 if (ArgList[i].Attrs.hasAttributes(i + 1))
1890 return Error(ArgList[i].Loc,
1891 "argument attributes invalid in function type");
1894 SmallVector<Type*, 16> ArgListTy;
1895 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1896 ArgListTy.push_back(ArgList[i].Ty);
1898 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1902 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1904 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1905 SmallVector<Type*, 8> Elts;
1906 if (ParseStructBody(Elts)) return true;
1908 Result = StructType::get(Context, Elts, Packed);
1912 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1913 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1914 std::pair<Type*, LocTy> &Entry,
1916 // If the type was already defined, diagnose the redefinition.
1917 if (Entry.first && !Entry.second.isValid())
1918 return Error(TypeLoc, "redefinition of type");
1920 // If we have opaque, just return without filling in the definition for the
1921 // struct. This counts as a definition as far as the .ll file goes.
1922 if (EatIfPresent(lltok::kw_opaque)) {
1923 // This type is being defined, so clear the location to indicate this.
1924 Entry.second = SMLoc();
1926 // If this type number has never been uttered, create it.
1928 Entry.first = StructType::create(Context, Name);
1929 ResultTy = Entry.first;
1933 // If the type starts with '<', then it is either a packed struct or a vector.
1934 bool isPacked = EatIfPresent(lltok::less);
1936 // If we don't have a struct, then we have a random type alias, which we
1937 // accept for compatibility with old files. These types are not allowed to be
1938 // forward referenced and not allowed to be recursive.
1939 if (Lex.getKind() != lltok::lbrace) {
1941 return Error(TypeLoc, "forward references to non-struct type");
1945 return ParseArrayVectorType(ResultTy, true);
1946 return ParseType(ResultTy);
1949 // This type is being defined, so clear the location to indicate this.
1950 Entry.second = SMLoc();
1952 // If this type number has never been uttered, create it.
1954 Entry.first = StructType::create(Context, Name);
1956 StructType *STy = cast<StructType>(Entry.first);
1958 SmallVector<Type*, 8> Body;
1959 if (ParseStructBody(Body) ||
1960 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1963 STy->setBody(Body, isPacked);
1969 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1972 /// ::= '{' Type (',' Type)* '}'
1973 /// ::= '<' '{' '}' '>'
1974 /// ::= '<' '{' Type (',' Type)* '}' '>'
1975 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1976 assert(Lex.getKind() == lltok::lbrace);
1977 Lex.Lex(); // Consume the '{'
1979 // Handle the empty struct.
1980 if (EatIfPresent(lltok::rbrace))
1983 LocTy EltTyLoc = Lex.getLoc();
1985 if (ParseType(Ty)) return true;
1988 if (!StructType::isValidElementType(Ty))
1989 return Error(EltTyLoc, "invalid element type for struct");
1991 while (EatIfPresent(lltok::comma)) {
1992 EltTyLoc = Lex.getLoc();
1993 if (ParseType(Ty)) return true;
1995 if (!StructType::isValidElementType(Ty))
1996 return Error(EltTyLoc, "invalid element type for struct");
2001 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2004 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2005 /// token has already been consumed.
2007 /// ::= '[' APSINTVAL 'x' Types ']'
2008 /// ::= '<' APSINTVAL 'x' Types '>'
2009 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2010 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2011 Lex.getAPSIntVal().getBitWidth() > 64)
2012 return TokError("expected number in address space");
2014 LocTy SizeLoc = Lex.getLoc();
2015 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2018 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2021 LocTy TypeLoc = Lex.getLoc();
2022 Type *EltTy = nullptr;
2023 if (ParseType(EltTy)) return true;
2025 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2026 "expected end of sequential type"))
2031 return Error(SizeLoc, "zero element vector is illegal");
2032 if ((unsigned)Size != Size)
2033 return Error(SizeLoc, "size too large for vector");
2034 if (!VectorType::isValidElementType(EltTy))
2035 return Error(TypeLoc, "invalid vector element type");
2036 Result = VectorType::get(EltTy, unsigned(Size));
2038 if (!ArrayType::isValidElementType(EltTy))
2039 return Error(TypeLoc, "invalid array element type");
2040 Result = ArrayType::get(EltTy, Size);
2045 //===----------------------------------------------------------------------===//
2046 // Function Semantic Analysis.
2047 //===----------------------------------------------------------------------===//
2049 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2051 : P(p), F(f), FunctionNumber(functionNumber) {
2053 // Insert unnamed arguments into the NumberedVals list.
2054 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2057 NumberedVals.push_back(AI);
2060 LLParser::PerFunctionState::~PerFunctionState() {
2061 // If there were any forward referenced non-basicblock values, delete them.
2062 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2063 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2064 if (!isa<BasicBlock>(I->second.first)) {
2065 I->second.first->replaceAllUsesWith(
2066 UndefValue::get(I->second.first->getType()));
2067 delete I->second.first;
2068 I->second.first = nullptr;
2071 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2072 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2073 if (!isa<BasicBlock>(I->second.first)) {
2074 I->second.first->replaceAllUsesWith(
2075 UndefValue::get(I->second.first->getType()));
2076 delete I->second.first;
2077 I->second.first = nullptr;
2081 bool LLParser::PerFunctionState::FinishFunction() {
2082 // Check to see if someone took the address of labels in this block.
2083 if (!P.ForwardRefBlockAddresses.empty()) {
2085 if (!F.getName().empty()) {
2086 FunctionID.Kind = ValID::t_GlobalName;
2087 FunctionID.StrVal = F.getName();
2089 FunctionID.Kind = ValID::t_GlobalID;
2090 FunctionID.UIntVal = FunctionNumber;
2093 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2094 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2095 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2096 // Resolve all these references.
2097 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2100 P.ForwardRefBlockAddresses.erase(FRBAI);
2104 if (!ForwardRefVals.empty())
2105 return P.Error(ForwardRefVals.begin()->second.second,
2106 "use of undefined value '%" + ForwardRefVals.begin()->first +
2108 if (!ForwardRefValIDs.empty())
2109 return P.Error(ForwardRefValIDs.begin()->second.second,
2110 "use of undefined value '%" +
2111 Twine(ForwardRefValIDs.begin()->first) + "'");
2116 /// GetVal - Get a value with the specified name or ID, creating a
2117 /// forward reference record if needed. This can return null if the value
2118 /// exists but does not have the right type.
2119 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2120 Type *Ty, LocTy Loc) {
2121 // Look this name up in the normal function symbol table.
2122 Value *Val = F.getValueSymbolTable().lookup(Name);
2124 // If this is a forward reference for the value, see if we already created a
2125 // forward ref record.
2127 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2128 I = ForwardRefVals.find(Name);
2129 if (I != ForwardRefVals.end())
2130 Val = I->second.first;
2133 // If we have the value in the symbol table or fwd-ref table, return it.
2135 if (Val->getType() == Ty) return Val;
2136 if (Ty->isLabelTy())
2137 P.Error(Loc, "'%" + Name + "' is not a basic block");
2139 P.Error(Loc, "'%" + Name + "' defined with type '" +
2140 getTypeString(Val->getType()) + "'");
2144 // Don't make placeholders with invalid type.
2145 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2146 P.Error(Loc, "invalid use of a non-first-class type");
2150 // Otherwise, create a new forward reference for this value and remember it.
2152 if (Ty->isLabelTy())
2153 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2155 FwdVal = new Argument(Ty, Name);
2157 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2161 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2163 // Look this name up in the normal function symbol table.
2164 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2166 // If this is a forward reference for the value, see if we already created a
2167 // forward ref record.
2169 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2170 I = ForwardRefValIDs.find(ID);
2171 if (I != ForwardRefValIDs.end())
2172 Val = I->second.first;
2175 // If we have the value in the symbol table or fwd-ref table, return it.
2177 if (Val->getType() == Ty) return Val;
2178 if (Ty->isLabelTy())
2179 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2181 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2182 getTypeString(Val->getType()) + "'");
2186 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2187 P.Error(Loc, "invalid use of a non-first-class type");
2191 // Otherwise, create a new forward reference for this value and remember it.
2193 if (Ty->isLabelTy())
2194 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2196 FwdVal = new Argument(Ty);
2198 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2202 /// SetInstName - After an instruction is parsed and inserted into its
2203 /// basic block, this installs its name.
2204 bool LLParser::PerFunctionState::SetInstName(int NameID,
2205 const std::string &NameStr,
2206 LocTy NameLoc, Instruction *Inst) {
2207 // If this instruction has void type, it cannot have a name or ID specified.
2208 if (Inst->getType()->isVoidTy()) {
2209 if (NameID != -1 || !NameStr.empty())
2210 return P.Error(NameLoc, "instructions returning void cannot have a name");
2214 // If this was a numbered instruction, verify that the instruction is the
2215 // expected value and resolve any forward references.
2216 if (NameStr.empty()) {
2217 // If neither a name nor an ID was specified, just use the next ID.
2219 NameID = NumberedVals.size();
2221 if (unsigned(NameID) != NumberedVals.size())
2222 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2223 Twine(NumberedVals.size()) + "'");
2225 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2226 ForwardRefValIDs.find(NameID);
2227 if (FI != ForwardRefValIDs.end()) {
2228 if (FI->second.first->getType() != Inst->getType())
2229 return P.Error(NameLoc, "instruction forward referenced with type '" +
2230 getTypeString(FI->second.first->getType()) + "'");
2231 FI->second.first->replaceAllUsesWith(Inst);
2232 delete FI->second.first;
2233 ForwardRefValIDs.erase(FI);
2236 NumberedVals.push_back(Inst);
2240 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2241 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2242 FI = ForwardRefVals.find(NameStr);
2243 if (FI != ForwardRefVals.end()) {
2244 if (FI->second.first->getType() != Inst->getType())
2245 return P.Error(NameLoc, "instruction forward referenced with type '" +
2246 getTypeString(FI->second.first->getType()) + "'");
2247 FI->second.first->replaceAllUsesWith(Inst);
2248 delete FI->second.first;
2249 ForwardRefVals.erase(FI);
2252 // Set the name on the instruction.
2253 Inst->setName(NameStr);
2255 if (Inst->getName() != NameStr)
2256 return P.Error(NameLoc, "multiple definition of local value named '" +
2261 /// GetBB - Get a basic block with the specified name or ID, creating a
2262 /// forward reference record if needed.
2263 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2265 return cast_or_null<BasicBlock>(GetVal(Name,
2266 Type::getLabelTy(F.getContext()), Loc));
2269 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2270 return cast_or_null<BasicBlock>(GetVal(ID,
2271 Type::getLabelTy(F.getContext()), Loc));
2274 /// DefineBB - Define the specified basic block, which is either named or
2275 /// unnamed. If there is an error, this returns null otherwise it returns
2276 /// the block being defined.
2277 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2281 BB = GetBB(NumberedVals.size(), Loc);
2283 BB = GetBB(Name, Loc);
2284 if (!BB) return nullptr; // Already diagnosed error.
2286 // Move the block to the end of the function. Forward ref'd blocks are
2287 // inserted wherever they happen to be referenced.
2288 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2290 // Remove the block from forward ref sets.
2292 ForwardRefValIDs.erase(NumberedVals.size());
2293 NumberedVals.push_back(BB);
2295 // BB forward references are already in the function symbol table.
2296 ForwardRefVals.erase(Name);
2302 //===----------------------------------------------------------------------===//
2304 //===----------------------------------------------------------------------===//
2306 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2307 /// type implied. For example, if we parse "4" we don't know what integer type
2308 /// it has. The value will later be combined with its type and checked for
2309 /// sanity. PFS is used to convert function-local operands of metadata (since
2310 /// metadata operands are not just parsed here but also converted to values).
2311 /// PFS can be null when we are not parsing metadata values inside a function.
2312 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2313 ID.Loc = Lex.getLoc();
2314 switch (Lex.getKind()) {
2315 default: return TokError("expected value token");
2316 case lltok::GlobalID: // @42
2317 ID.UIntVal = Lex.getUIntVal();
2318 ID.Kind = ValID::t_GlobalID;
2320 case lltok::GlobalVar: // @foo
2321 ID.StrVal = Lex.getStrVal();
2322 ID.Kind = ValID::t_GlobalName;
2324 case lltok::LocalVarID: // %42
2325 ID.UIntVal = Lex.getUIntVal();
2326 ID.Kind = ValID::t_LocalID;
2328 case lltok::LocalVar: // %foo
2329 ID.StrVal = Lex.getStrVal();
2330 ID.Kind = ValID::t_LocalName;
2332 case lltok::exclaim: // !42, !{...}, or !"foo"
2333 return ParseMetadataValue(ID, PFS);
2335 ID.APSIntVal = Lex.getAPSIntVal();
2336 ID.Kind = ValID::t_APSInt;
2338 case lltok::APFloat:
2339 ID.APFloatVal = Lex.getAPFloatVal();
2340 ID.Kind = ValID::t_APFloat;
2342 case lltok::kw_true:
2343 ID.ConstantVal = ConstantInt::getTrue(Context);
2344 ID.Kind = ValID::t_Constant;
2346 case lltok::kw_false:
2347 ID.ConstantVal = ConstantInt::getFalse(Context);
2348 ID.Kind = ValID::t_Constant;
2350 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2351 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2352 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2354 case lltok::lbrace: {
2355 // ValID ::= '{' ConstVector '}'
2357 SmallVector<Constant*, 16> Elts;
2358 if (ParseGlobalValueVector(Elts) ||
2359 ParseToken(lltok::rbrace, "expected end of struct constant"))
2362 ID.ConstantStructElts = new Constant*[Elts.size()];
2363 ID.UIntVal = Elts.size();
2364 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2365 ID.Kind = ValID::t_ConstantStruct;
2369 // ValID ::= '<' ConstVector '>' --> Vector.
2370 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2372 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2374 SmallVector<Constant*, 16> Elts;
2375 LocTy FirstEltLoc = Lex.getLoc();
2376 if (ParseGlobalValueVector(Elts) ||
2378 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2379 ParseToken(lltok::greater, "expected end of constant"))
2382 if (isPackedStruct) {
2383 ID.ConstantStructElts = new Constant*[Elts.size()];
2384 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2385 ID.UIntVal = Elts.size();
2386 ID.Kind = ValID::t_PackedConstantStruct;
2391 return Error(ID.Loc, "constant vector must not be empty");
2393 if (!Elts[0]->getType()->isIntegerTy() &&
2394 !Elts[0]->getType()->isFloatingPointTy() &&
2395 !Elts[0]->getType()->isPointerTy())
2396 return Error(FirstEltLoc,
2397 "vector elements must have integer, pointer or floating point type");
2399 // Verify that all the vector elements have the same type.
2400 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2401 if (Elts[i]->getType() != Elts[0]->getType())
2402 return Error(FirstEltLoc,
2403 "vector element #" + Twine(i) +
2404 " is not of type '" + getTypeString(Elts[0]->getType()));
2406 ID.ConstantVal = ConstantVector::get(Elts);
2407 ID.Kind = ValID::t_Constant;
2410 case lltok::lsquare: { // Array Constant
2412 SmallVector<Constant*, 16> Elts;
2413 LocTy FirstEltLoc = Lex.getLoc();
2414 if (ParseGlobalValueVector(Elts) ||
2415 ParseToken(lltok::rsquare, "expected end of array constant"))
2418 // Handle empty element.
2420 // Use undef instead of an array because it's inconvenient to determine
2421 // the element type at this point, there being no elements to examine.
2422 ID.Kind = ValID::t_EmptyArray;
2426 if (!Elts[0]->getType()->isFirstClassType())
2427 return Error(FirstEltLoc, "invalid array element type: " +
2428 getTypeString(Elts[0]->getType()));
2430 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2432 // Verify all elements are correct type!
2433 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2434 if (Elts[i]->getType() != Elts[0]->getType())
2435 return Error(FirstEltLoc,
2436 "array element #" + Twine(i) +
2437 " is not of type '" + getTypeString(Elts[0]->getType()));
2440 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2441 ID.Kind = ValID::t_Constant;
2444 case lltok::kw_c: // c "foo"
2446 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2448 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2449 ID.Kind = ValID::t_Constant;
2452 case lltok::kw_asm: {
2453 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2455 bool HasSideEffect, AlignStack, AsmDialect;
2457 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2458 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2459 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2460 ParseStringConstant(ID.StrVal) ||
2461 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2462 ParseToken(lltok::StringConstant, "expected constraint string"))
2464 ID.StrVal2 = Lex.getStrVal();
2465 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2466 (unsigned(AsmDialect)<<2);
2467 ID.Kind = ValID::t_InlineAsm;
2471 case lltok::kw_blockaddress: {
2472 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2477 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2479 ParseToken(lltok::comma, "expected comma in block address expression")||
2480 ParseValID(Label) ||
2481 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2484 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2485 return Error(Fn.Loc, "expected function name in blockaddress");
2486 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2487 return Error(Label.Loc, "expected basic block name in blockaddress");
2489 // Make a global variable as a placeholder for this reference.
2490 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2491 false, GlobalValue::InternalLinkage,
2493 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2494 ID.ConstantVal = FwdRef;
2495 ID.Kind = ValID::t_Constant;
2499 case lltok::kw_trunc:
2500 case lltok::kw_zext:
2501 case lltok::kw_sext:
2502 case lltok::kw_fptrunc:
2503 case lltok::kw_fpext:
2504 case lltok::kw_bitcast:
2505 case lltok::kw_addrspacecast:
2506 case lltok::kw_uitofp:
2507 case lltok::kw_sitofp:
2508 case lltok::kw_fptoui:
2509 case lltok::kw_fptosi:
2510 case lltok::kw_inttoptr:
2511 case lltok::kw_ptrtoint: {
2512 unsigned Opc = Lex.getUIntVal();
2513 Type *DestTy = nullptr;
2516 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2517 ParseGlobalTypeAndValue(SrcVal) ||
2518 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2519 ParseType(DestTy) ||
2520 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2522 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2523 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2524 getTypeString(SrcVal->getType()) + "' to '" +
2525 getTypeString(DestTy) + "'");
2526 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2528 ID.Kind = ValID::t_Constant;
2531 case lltok::kw_extractvalue: {
2534 SmallVector<unsigned, 4> Indices;
2535 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2536 ParseGlobalTypeAndValue(Val) ||
2537 ParseIndexList(Indices) ||
2538 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2541 if (!Val->getType()->isAggregateType())
2542 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2543 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2544 return Error(ID.Loc, "invalid indices for extractvalue");
2545 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2546 ID.Kind = ValID::t_Constant;
2549 case lltok::kw_insertvalue: {
2551 Constant *Val0, *Val1;
2552 SmallVector<unsigned, 4> Indices;
2553 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2554 ParseGlobalTypeAndValue(Val0) ||
2555 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2556 ParseGlobalTypeAndValue(Val1) ||
2557 ParseIndexList(Indices) ||
2558 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2560 if (!Val0->getType()->isAggregateType())
2561 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2562 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2563 return Error(ID.Loc, "invalid indices for insertvalue");
2564 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2565 ID.Kind = ValID::t_Constant;
2568 case lltok::kw_icmp:
2569 case lltok::kw_fcmp: {
2570 unsigned PredVal, Opc = Lex.getUIntVal();
2571 Constant *Val0, *Val1;
2573 if (ParseCmpPredicate(PredVal, Opc) ||
2574 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2575 ParseGlobalTypeAndValue(Val0) ||
2576 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2577 ParseGlobalTypeAndValue(Val1) ||
2578 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2581 if (Val0->getType() != Val1->getType())
2582 return Error(ID.Loc, "compare operands must have the same type");
2584 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2586 if (Opc == Instruction::FCmp) {
2587 if (!Val0->getType()->isFPOrFPVectorTy())
2588 return Error(ID.Loc, "fcmp requires floating point operands");
2589 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2591 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2592 if (!Val0->getType()->isIntOrIntVectorTy() &&
2593 !Val0->getType()->getScalarType()->isPointerTy())
2594 return Error(ID.Loc, "icmp requires pointer or integer operands");
2595 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2597 ID.Kind = ValID::t_Constant;
2601 // Binary Operators.
2603 case lltok::kw_fadd:
2605 case lltok::kw_fsub:
2607 case lltok::kw_fmul:
2608 case lltok::kw_udiv:
2609 case lltok::kw_sdiv:
2610 case lltok::kw_fdiv:
2611 case lltok::kw_urem:
2612 case lltok::kw_srem:
2613 case lltok::kw_frem:
2615 case lltok::kw_lshr:
2616 case lltok::kw_ashr: {
2620 unsigned Opc = Lex.getUIntVal();
2621 Constant *Val0, *Val1;
2623 LocTy ModifierLoc = Lex.getLoc();
2624 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2625 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2626 if (EatIfPresent(lltok::kw_nuw))
2628 if (EatIfPresent(lltok::kw_nsw)) {
2630 if (EatIfPresent(lltok::kw_nuw))
2633 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2634 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2635 if (EatIfPresent(lltok::kw_exact))
2638 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2639 ParseGlobalTypeAndValue(Val0) ||
2640 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2641 ParseGlobalTypeAndValue(Val1) ||
2642 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2644 if (Val0->getType() != Val1->getType())
2645 return Error(ID.Loc, "operands of constexpr must have same type");
2646 if (!Val0->getType()->isIntOrIntVectorTy()) {
2648 return Error(ModifierLoc, "nuw only applies to integer operations");
2650 return Error(ModifierLoc, "nsw only applies to integer operations");
2652 // Check that the type is valid for the operator.
2654 case Instruction::Add:
2655 case Instruction::Sub:
2656 case Instruction::Mul:
2657 case Instruction::UDiv:
2658 case Instruction::SDiv:
2659 case Instruction::URem:
2660 case Instruction::SRem:
2661 case Instruction::Shl:
2662 case Instruction::AShr:
2663 case Instruction::LShr:
2664 if (!Val0->getType()->isIntOrIntVectorTy())
2665 return Error(ID.Loc, "constexpr requires integer operands");
2667 case Instruction::FAdd:
2668 case Instruction::FSub:
2669 case Instruction::FMul:
2670 case Instruction::FDiv:
2671 case Instruction::FRem:
2672 if (!Val0->getType()->isFPOrFPVectorTy())
2673 return Error(ID.Loc, "constexpr requires fp operands");
2675 default: llvm_unreachable("Unknown binary operator!");
2678 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2679 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2680 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2681 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2683 ID.Kind = ValID::t_Constant;
2687 // Logical Operations
2690 case lltok::kw_xor: {
2691 unsigned Opc = Lex.getUIntVal();
2692 Constant *Val0, *Val1;
2694 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2695 ParseGlobalTypeAndValue(Val0) ||
2696 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2697 ParseGlobalTypeAndValue(Val1) ||
2698 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2700 if (Val0->getType() != Val1->getType())
2701 return Error(ID.Loc, "operands of constexpr must have same type");
2702 if (!Val0->getType()->isIntOrIntVectorTy())
2703 return Error(ID.Loc,
2704 "constexpr requires integer or integer vector operands");
2705 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2706 ID.Kind = ValID::t_Constant;
2710 case lltok::kw_getelementptr:
2711 case lltok::kw_shufflevector:
2712 case lltok::kw_insertelement:
2713 case lltok::kw_extractelement:
2714 case lltok::kw_select: {
2715 unsigned Opc = Lex.getUIntVal();
2716 SmallVector<Constant*, 16> Elts;
2717 bool InBounds = false;
2719 if (Opc == Instruction::GetElementPtr)
2720 InBounds = EatIfPresent(lltok::kw_inbounds);
2721 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2722 ParseGlobalValueVector(Elts) ||
2723 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2726 if (Opc == Instruction::GetElementPtr) {
2727 if (Elts.size() == 0 ||
2728 !Elts[0]->getType()->getScalarType()->isPointerTy())
2729 return Error(ID.Loc, "getelementptr requires pointer operand");
2731 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2732 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2733 return Error(ID.Loc, "invalid indices for getelementptr");
2734 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2736 } else if (Opc == Instruction::Select) {
2737 if (Elts.size() != 3)
2738 return Error(ID.Loc, "expected three operands to select");
2739 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2741 return Error(ID.Loc, Reason);
2742 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2743 } else if (Opc == Instruction::ShuffleVector) {
2744 if (Elts.size() != 3)
2745 return Error(ID.Loc, "expected three operands to shufflevector");
2746 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2747 return Error(ID.Loc, "invalid operands to shufflevector");
2749 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2750 } else if (Opc == Instruction::ExtractElement) {
2751 if (Elts.size() != 2)
2752 return Error(ID.Loc, "expected two operands to extractelement");
2753 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2754 return Error(ID.Loc, "invalid extractelement operands");
2755 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2757 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2758 if (Elts.size() != 3)
2759 return Error(ID.Loc, "expected three operands to insertelement");
2760 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2761 return Error(ID.Loc, "invalid insertelement operands");
2763 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2766 ID.Kind = ValID::t_Constant;
2775 /// ParseGlobalValue - Parse a global value with the specified type.
2776 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2780 bool Parsed = ParseValID(ID) ||
2781 ConvertValIDToValue(Ty, ID, V, nullptr);
2782 if (V && !(C = dyn_cast<Constant>(V)))
2783 return Error(ID.Loc, "global values must be constants");
2787 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2789 return ParseType(Ty) ||
2790 ParseGlobalValue(Ty, V);
2793 /// ParseGlobalValueVector
2795 /// ::= TypeAndValue (',' TypeAndValue)*
2796 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2798 if (Lex.getKind() == lltok::rbrace ||
2799 Lex.getKind() == lltok::rsquare ||
2800 Lex.getKind() == lltok::greater ||
2801 Lex.getKind() == lltok::rparen)
2805 if (ParseGlobalTypeAndValue(C)) return true;
2808 while (EatIfPresent(lltok::comma)) {
2809 if (ParseGlobalTypeAndValue(C)) return true;
2816 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2817 assert(Lex.getKind() == lltok::lbrace);
2820 SmallVector<Value*, 16> Elts;
2821 if (ParseMDNodeVector(Elts, PFS) ||
2822 ParseToken(lltok::rbrace, "expected end of metadata node"))
2825 ID.MDNodeVal = MDNode::get(Context, Elts);
2826 ID.Kind = ValID::t_MDNode;
2830 /// ParseMetadataValue
2834 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2835 assert(Lex.getKind() == lltok::exclaim);
2840 if (Lex.getKind() == lltok::lbrace)
2841 return ParseMetadataListValue(ID, PFS);
2843 // Standalone metadata reference
2845 if (Lex.getKind() == lltok::APSInt) {
2846 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2847 ID.Kind = ValID::t_MDNode;
2852 // ::= '!' STRINGCONSTANT
2853 if (ParseMDString(ID.MDStringVal)) return true;
2854 ID.Kind = ValID::t_MDString;
2859 //===----------------------------------------------------------------------===//
2860 // Function Parsing.
2861 //===----------------------------------------------------------------------===//
2863 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2864 PerFunctionState *PFS) {
2865 if (Ty->isFunctionTy())
2866 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2869 case ValID::t_LocalID:
2870 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2871 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2872 return V == nullptr;
2873 case ValID::t_LocalName:
2874 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2875 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2876 return V == nullptr;
2877 case ValID::t_InlineAsm: {
2878 PointerType *PTy = dyn_cast<PointerType>(Ty);
2880 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2881 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2882 return Error(ID.Loc, "invalid type for inline asm constraint string");
2883 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2884 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2887 case ValID::t_MDNode:
2888 if (!Ty->isMetadataTy())
2889 return Error(ID.Loc, "metadata value must have metadata type");
2892 case ValID::t_MDString:
2893 if (!Ty->isMetadataTy())
2894 return Error(ID.Loc, "metadata value must have metadata type");
2897 case ValID::t_GlobalName:
2898 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2899 return V == nullptr;
2900 case ValID::t_GlobalID:
2901 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2902 return V == nullptr;
2903 case ValID::t_APSInt:
2904 if (!Ty->isIntegerTy())
2905 return Error(ID.Loc, "integer constant must have integer type");
2906 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2907 V = ConstantInt::get(Context, ID.APSIntVal);
2909 case ValID::t_APFloat:
2910 if (!Ty->isFloatingPointTy() ||
2911 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2912 return Error(ID.Loc, "floating point constant invalid for type");
2914 // The lexer has no type info, so builds all half, float, and double FP
2915 // constants as double. Fix this here. Long double does not need this.
2916 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2919 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2921 else if (Ty->isFloatTy())
2922 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2925 V = ConstantFP::get(Context, ID.APFloatVal);
2927 if (V->getType() != Ty)
2928 return Error(ID.Loc, "floating point constant does not have type '" +
2929 getTypeString(Ty) + "'");
2933 if (!Ty->isPointerTy())
2934 return Error(ID.Loc, "null must be a pointer type");
2935 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2937 case ValID::t_Undef:
2938 // FIXME: LabelTy should not be a first-class type.
2939 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2940 return Error(ID.Loc, "invalid type for undef constant");
2941 V = UndefValue::get(Ty);
2943 case ValID::t_EmptyArray:
2944 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2945 return Error(ID.Loc, "invalid empty array initializer");
2946 V = UndefValue::get(Ty);
2949 // FIXME: LabelTy should not be a first-class type.
2950 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2951 return Error(ID.Loc, "invalid type for null constant");
2952 V = Constant::getNullValue(Ty);
2954 case ValID::t_Constant:
2955 if (ID.ConstantVal->getType() != Ty)
2956 return Error(ID.Loc, "constant expression type mismatch");
2960 case ValID::t_ConstantStruct:
2961 case ValID::t_PackedConstantStruct:
2962 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2963 if (ST->getNumElements() != ID.UIntVal)
2964 return Error(ID.Loc,
2965 "initializer with struct type has wrong # elements");
2966 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2967 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2969 // Verify that the elements are compatible with the structtype.
2970 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2971 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2972 return Error(ID.Loc, "element " + Twine(i) +
2973 " of struct initializer doesn't match struct element type");
2975 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2978 return Error(ID.Loc, "constant expression type mismatch");
2981 llvm_unreachable("Invalid ValID");
2984 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2987 return ParseValID(ID, PFS) ||
2988 ConvertValIDToValue(Ty, ID, V, PFS);
2991 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2993 return ParseType(Ty) ||
2994 ParseValue(Ty, V, PFS);
2997 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2998 PerFunctionState &PFS) {
3001 if (ParseTypeAndValue(V, PFS)) return true;
3002 if (!isa<BasicBlock>(V))
3003 return Error(Loc, "expected a basic block");
3004 BB = cast<BasicBlock>(V);
3010 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3011 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3012 /// OptionalAlign OptGC OptionalPrefix
3013 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3014 // Parse the linkage.
3015 LocTy LinkageLoc = Lex.getLoc();
3018 unsigned Visibility;
3019 unsigned DLLStorageClass;
3020 AttrBuilder RetAttrs;
3022 Type *RetType = nullptr;
3023 LocTy RetTypeLoc = Lex.getLoc();
3024 if (ParseOptionalLinkage(Linkage) ||
3025 ParseOptionalVisibility(Visibility) ||
3026 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3027 ParseOptionalCallingConv(CC) ||
3028 ParseOptionalReturnAttrs(RetAttrs) ||
3029 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3032 // Verify that the linkage is ok.
3033 switch ((GlobalValue::LinkageTypes)Linkage) {
3034 case GlobalValue::ExternalLinkage:
3035 break; // always ok.
3036 case GlobalValue::ExternalWeakLinkage:
3038 return Error(LinkageLoc, "invalid linkage for function definition");
3040 case GlobalValue::PrivateLinkage:
3041 case GlobalValue::InternalLinkage:
3042 case GlobalValue::AvailableExternallyLinkage:
3043 case GlobalValue::LinkOnceAnyLinkage:
3044 case GlobalValue::LinkOnceODRLinkage:
3045 case GlobalValue::WeakAnyLinkage:
3046 case GlobalValue::WeakODRLinkage:
3048 return Error(LinkageLoc, "invalid linkage for function declaration");
3050 case GlobalValue::AppendingLinkage:
3051 case GlobalValue::CommonLinkage:
3052 return Error(LinkageLoc, "invalid function linkage type");
3055 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3056 return Error(LinkageLoc,
3057 "symbol with local linkage must have default visibility");
3059 if (!FunctionType::isValidReturnType(RetType))
3060 return Error(RetTypeLoc, "invalid function return type");
3062 LocTy NameLoc = Lex.getLoc();
3064 std::string FunctionName;
3065 if (Lex.getKind() == lltok::GlobalVar) {
3066 FunctionName = Lex.getStrVal();
3067 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3068 unsigned NameID = Lex.getUIntVal();
3070 if (NameID != NumberedVals.size())
3071 return TokError("function expected to be numbered '%" +
3072 Twine(NumberedVals.size()) + "'");
3074 return TokError("expected function name");
3079 if (Lex.getKind() != lltok::lparen)
3080 return TokError("expected '(' in function argument list");
3082 SmallVector<ArgInfo, 8> ArgList;
3084 AttrBuilder FuncAttrs;
3085 std::vector<unsigned> FwdRefAttrGrps;
3087 std::string Section;
3091 LocTy UnnamedAddrLoc;
3092 Constant *Prefix = nullptr;
3094 if (ParseArgumentList(ArgList, isVarArg) ||
3095 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3097 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3099 (EatIfPresent(lltok::kw_section) &&
3100 ParseStringConstant(Section)) ||
3101 ParseOptionalAlignment(Alignment) ||
3102 (EatIfPresent(lltok::kw_gc) &&
3103 ParseStringConstant(GC)) ||
3104 (EatIfPresent(lltok::kw_prefix) &&
3105 ParseGlobalTypeAndValue(Prefix)))
3108 if (FuncAttrs.contains(Attribute::Builtin))
3109 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3111 // If the alignment was parsed as an attribute, move to the alignment field.
3112 if (FuncAttrs.hasAlignmentAttr()) {
3113 Alignment = FuncAttrs.getAlignment();
3114 FuncAttrs.removeAttribute(Attribute::Alignment);
3117 // Okay, if we got here, the function is syntactically valid. Convert types
3118 // and do semantic checks.
3119 std::vector<Type*> ParamTypeList;
3120 SmallVector<AttributeSet, 8> Attrs;
3122 if (RetAttrs.hasAttributes())
3123 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3124 AttributeSet::ReturnIndex,
3127 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3128 ParamTypeList.push_back(ArgList[i].Ty);
3129 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3130 AttrBuilder B(ArgList[i].Attrs, i + 1);
3131 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3135 if (FuncAttrs.hasAttributes())
3136 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3137 AttributeSet::FunctionIndex,
3140 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3142 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3143 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3146 FunctionType::get(RetType, ParamTypeList, isVarArg);
3147 PointerType *PFT = PointerType::getUnqual(FT);
3150 if (!FunctionName.empty()) {
3151 // If this was a definition of a forward reference, remove the definition
3152 // from the forward reference table and fill in the forward ref.
3153 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3154 ForwardRefVals.find(FunctionName);
3155 if (FRVI != ForwardRefVals.end()) {
3156 Fn = M->getFunction(FunctionName);
3158 return Error(FRVI->second.second, "invalid forward reference to "
3159 "function as global value!");
3160 if (Fn->getType() != PFT)
3161 return Error(FRVI->second.second, "invalid forward reference to "
3162 "function '" + FunctionName + "' with wrong type!");
3164 ForwardRefVals.erase(FRVI);
3165 } else if ((Fn = M->getFunction(FunctionName))) {
3166 // Reject redefinitions.
3167 return Error(NameLoc, "invalid redefinition of function '" +
3168 FunctionName + "'");
3169 } else if (M->getNamedValue(FunctionName)) {
3170 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3174 // If this is a definition of a forward referenced function, make sure the
3176 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3177 = ForwardRefValIDs.find(NumberedVals.size());
3178 if (I != ForwardRefValIDs.end()) {
3179 Fn = cast<Function>(I->second.first);
3180 if (Fn->getType() != PFT)
3181 return Error(NameLoc, "type of definition and forward reference of '@" +
3182 Twine(NumberedVals.size()) + "' disagree");
3183 ForwardRefValIDs.erase(I);
3188 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3189 else // Move the forward-reference to the correct spot in the module.
3190 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3192 if (FunctionName.empty())
3193 NumberedVals.push_back(Fn);
3195 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3196 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3197 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3198 Fn->setCallingConv(CC);
3199 Fn->setAttributes(PAL);
3200 Fn->setUnnamedAddr(UnnamedAddr);
3201 Fn->setAlignment(Alignment);
3202 Fn->setSection(Section);
3203 if (!GC.empty()) Fn->setGC(GC.c_str());
3204 Fn->setPrefixData(Prefix);
3205 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3207 // Add all of the arguments we parsed to the function.
3208 Function::arg_iterator ArgIt = Fn->arg_begin();
3209 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3210 // If the argument has a name, insert it into the argument symbol table.
3211 if (ArgList[i].Name.empty()) continue;
3213 // Set the name, if it conflicted, it will be auto-renamed.
3214 ArgIt->setName(ArgList[i].Name);
3216 if (ArgIt->getName() != ArgList[i].Name)
3217 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3218 ArgList[i].Name + "'");
3225 /// ParseFunctionBody
3226 /// ::= '{' BasicBlock+ '}'
3228 bool LLParser::ParseFunctionBody(Function &Fn) {
3229 if (Lex.getKind() != lltok::lbrace)
3230 return TokError("expected '{' in function body");
3231 Lex.Lex(); // eat the {.
3233 int FunctionNumber = -1;
3234 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3236 PerFunctionState PFS(*this, Fn, FunctionNumber);
3238 // We need at least one basic block.
3239 if (Lex.getKind() == lltok::rbrace)
3240 return TokError("function body requires at least one basic block");
3242 while (Lex.getKind() != lltok::rbrace)
3243 if (ParseBasicBlock(PFS)) return true;
3248 // Verify function is ok.
3249 return PFS.FinishFunction();
3253 /// ::= LabelStr? Instruction*
3254 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3255 // If this basic block starts out with a name, remember it.
3257 LocTy NameLoc = Lex.getLoc();
3258 if (Lex.getKind() == lltok::LabelStr) {
3259 Name = Lex.getStrVal();
3263 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3264 if (!BB) return true;
3266 std::string NameStr;
3268 // Parse the instructions in this block until we get a terminator.
3271 // This instruction may have three possibilities for a name: a) none
3272 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3273 LocTy NameLoc = Lex.getLoc();
3277 if (Lex.getKind() == lltok::LocalVarID) {
3278 NameID = Lex.getUIntVal();
3280 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3282 } else if (Lex.getKind() == lltok::LocalVar) {
3283 NameStr = Lex.getStrVal();
3285 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3289 switch (ParseInstruction(Inst, BB, PFS)) {
3290 default: llvm_unreachable("Unknown ParseInstruction result!");
3291 case InstError: return true;
3293 BB->getInstList().push_back(Inst);
3295 // With a normal result, we check to see if the instruction is followed by
3296 // a comma and metadata.
3297 if (EatIfPresent(lltok::comma))
3298 if (ParseInstructionMetadata(Inst, &PFS))
3301 case InstExtraComma:
3302 BB->getInstList().push_back(Inst);
3304 // If the instruction parser ate an extra comma at the end of it, it
3305 // *must* be followed by metadata.
3306 if (ParseInstructionMetadata(Inst, &PFS))
3311 // Set the name on the instruction.
3312 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3313 } while (!isa<TerminatorInst>(Inst));
3318 //===----------------------------------------------------------------------===//
3319 // Instruction Parsing.
3320 //===----------------------------------------------------------------------===//
3322 /// ParseInstruction - Parse one of the many different instructions.
3324 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3325 PerFunctionState &PFS) {
3326 lltok::Kind Token = Lex.getKind();
3327 if (Token == lltok::Eof)
3328 return TokError("found end of file when expecting more instructions");
3329 LocTy Loc = Lex.getLoc();
3330 unsigned KeywordVal = Lex.getUIntVal();
3331 Lex.Lex(); // Eat the keyword.
3334 default: return Error(Loc, "expected instruction opcode");
3335 // Terminator Instructions.
3336 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3337 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3338 case lltok::kw_br: return ParseBr(Inst, PFS);
3339 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3340 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3341 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3342 case lltok::kw_resume: return ParseResume(Inst, PFS);
3343 // Binary Operators.
3347 case lltok::kw_shl: {
3348 bool NUW = EatIfPresent(lltok::kw_nuw);
3349 bool NSW = EatIfPresent(lltok::kw_nsw);
3350 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3352 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3354 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3355 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3358 case lltok::kw_fadd:
3359 case lltok::kw_fsub:
3360 case lltok::kw_fmul:
3361 case lltok::kw_fdiv:
3362 case lltok::kw_frem: {
3363 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3364 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3368 Inst->setFastMathFlags(FMF);
3372 case lltok::kw_sdiv:
3373 case lltok::kw_udiv:
3374 case lltok::kw_lshr:
3375 case lltok::kw_ashr: {
3376 bool Exact = EatIfPresent(lltok::kw_exact);
3378 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3379 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3383 case lltok::kw_urem:
3384 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3387 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3388 case lltok::kw_icmp:
3389 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3391 case lltok::kw_trunc:
3392 case lltok::kw_zext:
3393 case lltok::kw_sext:
3394 case lltok::kw_fptrunc:
3395 case lltok::kw_fpext:
3396 case lltok::kw_bitcast:
3397 case lltok::kw_addrspacecast:
3398 case lltok::kw_uitofp:
3399 case lltok::kw_sitofp:
3400 case lltok::kw_fptoui:
3401 case lltok::kw_fptosi:
3402 case lltok::kw_inttoptr:
3403 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3405 case lltok::kw_select: return ParseSelect(Inst, PFS);
3406 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3407 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3408 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3409 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3410 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3411 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3413 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3414 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3415 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3417 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3418 case lltok::kw_load: return ParseLoad(Inst, PFS);
3419 case lltok::kw_store: return ParseStore(Inst, PFS);
3420 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3421 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3422 case lltok::kw_fence: return ParseFence(Inst, PFS);
3423 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3424 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3425 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3429 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3430 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3431 if (Opc == Instruction::FCmp) {
3432 switch (Lex.getKind()) {
3433 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3434 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3435 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3436 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3437 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3438 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3439 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3440 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3441 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3442 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3443 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3444 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3445 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3446 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3447 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3448 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3449 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3452 switch (Lex.getKind()) {
3453 default: return TokError("expected icmp predicate (e.g. 'eq')");
3454 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3455 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3456 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3457 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3458 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3459 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3460 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3461 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3462 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3463 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3470 //===----------------------------------------------------------------------===//
3471 // Terminator Instructions.
3472 //===----------------------------------------------------------------------===//
3474 /// ParseRet - Parse a return instruction.
3475 /// ::= 'ret' void (',' !dbg, !1)*
3476 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3477 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3478 PerFunctionState &PFS) {
3479 SMLoc TypeLoc = Lex.getLoc();
3481 if (ParseType(Ty, true /*void allowed*/)) return true;
3483 Type *ResType = PFS.getFunction().getReturnType();
3485 if (Ty->isVoidTy()) {
3486 if (!ResType->isVoidTy())
3487 return Error(TypeLoc, "value doesn't match function result type '" +
3488 getTypeString(ResType) + "'");
3490 Inst = ReturnInst::Create(Context);
3495 if (ParseValue(Ty, RV, PFS)) return true;
3497 if (ResType != RV->getType())
3498 return Error(TypeLoc, "value doesn't match function result type '" +
3499 getTypeString(ResType) + "'");
3501 Inst = ReturnInst::Create(Context, RV);
3507 /// ::= 'br' TypeAndValue
3508 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3509 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3512 BasicBlock *Op1, *Op2;
3513 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3515 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3516 Inst = BranchInst::Create(BB);
3520 if (Op0->getType() != Type::getInt1Ty(Context))
3521 return Error(Loc, "branch condition must have 'i1' type");
3523 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3524 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3525 ParseToken(lltok::comma, "expected ',' after true destination") ||
3526 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3529 Inst = BranchInst::Create(Op1, Op2, Op0);
3535 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3537 /// ::= (TypeAndValue ',' TypeAndValue)*
3538 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3539 LocTy CondLoc, BBLoc;
3541 BasicBlock *DefaultBB;
3542 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3543 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3544 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3545 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3548 if (!Cond->getType()->isIntegerTy())
3549 return Error(CondLoc, "switch condition must have integer type");
3551 // Parse the jump table pairs.
3552 SmallPtrSet<Value*, 32> SeenCases;
3553 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3554 while (Lex.getKind() != lltok::rsquare) {
3558 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3559 ParseToken(lltok::comma, "expected ',' after case value") ||
3560 ParseTypeAndBasicBlock(DestBB, PFS))
3563 if (!SeenCases.insert(Constant))
3564 return Error(CondLoc, "duplicate case value in switch");
3565 if (!isa<ConstantInt>(Constant))
3566 return Error(CondLoc, "case value is not a constant integer");
3568 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3571 Lex.Lex(); // Eat the ']'.
3573 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3574 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3575 SI->addCase(Table[i].first, Table[i].second);
3582 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3583 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3586 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3587 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3588 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3591 if (!Address->getType()->isPointerTy())
3592 return Error(AddrLoc, "indirectbr address must have pointer type");
3594 // Parse the destination list.
3595 SmallVector<BasicBlock*, 16> DestList;
3597 if (Lex.getKind() != lltok::rsquare) {
3599 if (ParseTypeAndBasicBlock(DestBB, PFS))
3601 DestList.push_back(DestBB);
3603 while (EatIfPresent(lltok::comma)) {
3604 if (ParseTypeAndBasicBlock(DestBB, PFS))
3606 DestList.push_back(DestBB);
3610 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3613 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3614 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3615 IBI->addDestination(DestList[i]);
3622 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3623 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3624 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3625 LocTy CallLoc = Lex.getLoc();
3626 AttrBuilder RetAttrs, FnAttrs;
3627 std::vector<unsigned> FwdRefAttrGrps;
3630 Type *RetType = nullptr;
3633 SmallVector<ParamInfo, 16> ArgList;
3635 BasicBlock *NormalBB, *UnwindBB;
3636 if (ParseOptionalCallingConv(CC) ||
3637 ParseOptionalReturnAttrs(RetAttrs) ||
3638 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3639 ParseValID(CalleeID) ||
3640 ParseParameterList(ArgList, PFS) ||
3641 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3643 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3644 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3645 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3646 ParseTypeAndBasicBlock(UnwindBB, PFS))
3649 // If RetType is a non-function pointer type, then this is the short syntax
3650 // for the call, which means that RetType is just the return type. Infer the
3651 // rest of the function argument types from the arguments that are present.
3652 PointerType *PFTy = nullptr;
3653 FunctionType *Ty = nullptr;
3654 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3655 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3656 // Pull out the types of all of the arguments...
3657 std::vector<Type*> ParamTypes;
3658 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3659 ParamTypes.push_back(ArgList[i].V->getType());
3661 if (!FunctionType::isValidReturnType(RetType))
3662 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3664 Ty = FunctionType::get(RetType, ParamTypes, false);
3665 PFTy = PointerType::getUnqual(Ty);
3668 // Look up the callee.
3670 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3672 // Set up the Attribute for the function.
3673 SmallVector<AttributeSet, 8> Attrs;
3674 if (RetAttrs.hasAttributes())
3675 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3676 AttributeSet::ReturnIndex,
3679 SmallVector<Value*, 8> Args;
3681 // Loop through FunctionType's arguments and ensure they are specified
3682 // correctly. Also, gather any parameter attributes.
3683 FunctionType::param_iterator I = Ty->param_begin();
3684 FunctionType::param_iterator E = Ty->param_end();
3685 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3686 Type *ExpectedTy = nullptr;
3689 } else if (!Ty->isVarArg()) {
3690 return Error(ArgList[i].Loc, "too many arguments specified");
3693 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3694 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3695 getTypeString(ExpectedTy) + "'");
3696 Args.push_back(ArgList[i].V);
3697 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3698 AttrBuilder B(ArgList[i].Attrs, i + 1);
3699 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3704 return Error(CallLoc, "not enough parameters specified for call");
3706 if (FnAttrs.hasAttributes())
3707 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3708 AttributeSet::FunctionIndex,
3711 // Finish off the Attribute and check them
3712 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3714 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3715 II->setCallingConv(CC);
3716 II->setAttributes(PAL);
3717 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3723 /// ::= 'resume' TypeAndValue
3724 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3725 Value *Exn; LocTy ExnLoc;
3726 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3729 ResumeInst *RI = ResumeInst::Create(Exn);
3734 //===----------------------------------------------------------------------===//
3735 // Binary Operators.
3736 //===----------------------------------------------------------------------===//
3739 /// ::= ArithmeticOps TypeAndValue ',' Value
3741 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3742 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3743 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3744 unsigned Opc, unsigned OperandType) {
3745 LocTy Loc; Value *LHS, *RHS;
3746 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3747 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3748 ParseValue(LHS->getType(), RHS, PFS))
3752 switch (OperandType) {
3753 default: llvm_unreachable("Unknown operand type!");
3754 case 0: // int or FP.
3755 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3756 LHS->getType()->isFPOrFPVectorTy();
3758 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3759 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3763 return Error(Loc, "invalid operand type for instruction");
3765 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3770 /// ::= ArithmeticOps TypeAndValue ',' Value {
3771 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3773 LocTy Loc; Value *LHS, *RHS;
3774 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3775 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3776 ParseValue(LHS->getType(), RHS, PFS))
3779 if (!LHS->getType()->isIntOrIntVectorTy())
3780 return Error(Loc,"instruction requires integer or integer vector operands");
3782 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3788 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3789 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3790 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3792 // Parse the integer/fp comparison predicate.
3796 if (ParseCmpPredicate(Pred, Opc) ||
3797 ParseTypeAndValue(LHS, Loc, PFS) ||
3798 ParseToken(lltok::comma, "expected ',' after compare value") ||
3799 ParseValue(LHS->getType(), RHS, PFS))
3802 if (Opc == Instruction::FCmp) {
3803 if (!LHS->getType()->isFPOrFPVectorTy())
3804 return Error(Loc, "fcmp requires floating point operands");
3805 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3807 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3808 if (!LHS->getType()->isIntOrIntVectorTy() &&
3809 !LHS->getType()->getScalarType()->isPointerTy())
3810 return Error(Loc, "icmp requires integer operands");
3811 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3816 //===----------------------------------------------------------------------===//
3817 // Other Instructions.
3818 //===----------------------------------------------------------------------===//
3822 /// ::= CastOpc TypeAndValue 'to' Type
3823 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3827 Type *DestTy = nullptr;
3828 if (ParseTypeAndValue(Op, Loc, PFS) ||
3829 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3833 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3834 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3835 return Error(Loc, "invalid cast opcode for cast from '" +
3836 getTypeString(Op->getType()) + "' to '" +
3837 getTypeString(DestTy) + "'");
3839 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3844 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3845 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3847 Value *Op0, *Op1, *Op2;
3848 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3849 ParseToken(lltok::comma, "expected ',' after select condition") ||
3850 ParseTypeAndValue(Op1, PFS) ||
3851 ParseToken(lltok::comma, "expected ',' after select value") ||
3852 ParseTypeAndValue(Op2, PFS))
3855 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3856 return Error(Loc, Reason);
3858 Inst = SelectInst::Create(Op0, Op1, Op2);
3863 /// ::= 'va_arg' TypeAndValue ',' Type
3864 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3866 Type *EltTy = nullptr;
3868 if (ParseTypeAndValue(Op, PFS) ||
3869 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3870 ParseType(EltTy, TypeLoc))
3873 if (!EltTy->isFirstClassType())
3874 return Error(TypeLoc, "va_arg requires operand with first class type");
3876 Inst = new VAArgInst(Op, EltTy);
3880 /// ParseExtractElement
3881 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3882 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3885 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3886 ParseToken(lltok::comma, "expected ',' after extract value") ||
3887 ParseTypeAndValue(Op1, PFS))
3890 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3891 return Error(Loc, "invalid extractelement operands");
3893 Inst = ExtractElementInst::Create(Op0, Op1);
3897 /// ParseInsertElement
3898 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3899 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3901 Value *Op0, *Op1, *Op2;
3902 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3903 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3904 ParseTypeAndValue(Op1, PFS) ||
3905 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3906 ParseTypeAndValue(Op2, PFS))
3909 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3910 return Error(Loc, "invalid insertelement operands");
3912 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3916 /// ParseShuffleVector
3917 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3918 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3920 Value *Op0, *Op1, *Op2;
3921 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3922 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3923 ParseTypeAndValue(Op1, PFS) ||
3924 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3925 ParseTypeAndValue(Op2, PFS))
3928 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3929 return Error(Loc, "invalid shufflevector operands");
3931 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3936 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3937 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3938 Type *Ty = nullptr; LocTy TypeLoc;
3941 if (ParseType(Ty, TypeLoc) ||
3942 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3943 ParseValue(Ty, Op0, PFS) ||
3944 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3945 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3946 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3949 bool AteExtraComma = false;
3950 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3952 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3954 if (!EatIfPresent(lltok::comma))
3957 if (Lex.getKind() == lltok::MetadataVar) {
3958 AteExtraComma = true;
3962 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3963 ParseValue(Ty, Op0, PFS) ||
3964 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3965 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3966 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3970 if (!Ty->isFirstClassType())
3971 return Error(TypeLoc, "phi node must have first class type");
3973 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3974 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3975 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3977 return AteExtraComma ? InstExtraComma : InstNormal;
3981 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3983 /// ::= 'catch' TypeAndValue
3985 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3986 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3987 Type *Ty = nullptr; LocTy TyLoc;
3988 Value *PersFn; LocTy PersFnLoc;
3990 if (ParseType(Ty, TyLoc) ||
3991 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3992 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3995 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3996 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3998 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3999 LandingPadInst::ClauseType CT;
4000 if (EatIfPresent(lltok::kw_catch))
4001 CT = LandingPadInst::Catch;
4002 else if (EatIfPresent(lltok::kw_filter))
4003 CT = LandingPadInst::Filter;
4005 return TokError("expected 'catch' or 'filter' clause type");
4009 if (ParseTypeAndValue(V, VLoc, PFS)) {
4014 // A 'catch' type expects a non-array constant. A filter clause expects an
4016 if (CT == LandingPadInst::Catch) {
4017 if (isa<ArrayType>(V->getType()))
4018 Error(VLoc, "'catch' clause has an invalid type");
4020 if (!isa<ArrayType>(V->getType()))
4021 Error(VLoc, "'filter' clause has an invalid type");
4024 LP->addClause(cast<Constant>(V));
4032 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4033 /// ParameterList OptionalAttrs
4034 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4035 /// ParameterList OptionalAttrs
4036 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4037 /// ParameterList OptionalAttrs
4038 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4039 CallInst::TailCallKind TCK) {
4040 AttrBuilder RetAttrs, FnAttrs;
4041 std::vector<unsigned> FwdRefAttrGrps;
4044 Type *RetType = nullptr;
4047 SmallVector<ParamInfo, 16> ArgList;
4048 LocTy CallLoc = Lex.getLoc();
4050 if ((TCK != CallInst::TCK_None &&
4051 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4052 ParseOptionalCallingConv(CC) ||
4053 ParseOptionalReturnAttrs(RetAttrs) ||
4054 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4055 ParseValID(CalleeID) ||
4056 ParseParameterList(ArgList, PFS) ||
4057 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4061 // If RetType is a non-function pointer type, then this is the short syntax
4062 // for the call, which means that RetType is just the return type. Infer the
4063 // rest of the function argument types from the arguments that are present.
4064 PointerType *PFTy = nullptr;
4065 FunctionType *Ty = nullptr;
4066 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4067 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4068 // Pull out the types of all of the arguments...
4069 std::vector<Type*> ParamTypes;
4070 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4071 ParamTypes.push_back(ArgList[i].V->getType());
4073 if (!FunctionType::isValidReturnType(RetType))
4074 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4076 Ty = FunctionType::get(RetType, ParamTypes, false);
4077 PFTy = PointerType::getUnqual(Ty);
4080 // Look up the callee.
4082 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4084 // Set up the Attribute for the function.
4085 SmallVector<AttributeSet, 8> Attrs;
4086 if (RetAttrs.hasAttributes())
4087 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4088 AttributeSet::ReturnIndex,
4091 SmallVector<Value*, 8> Args;
4093 // Loop through FunctionType's arguments and ensure they are specified
4094 // correctly. Also, gather any parameter attributes.
4095 FunctionType::param_iterator I = Ty->param_begin();
4096 FunctionType::param_iterator E = Ty->param_end();
4097 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4098 Type *ExpectedTy = nullptr;
4101 } else if (!Ty->isVarArg()) {
4102 return Error(ArgList[i].Loc, "too many arguments specified");
4105 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4106 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4107 getTypeString(ExpectedTy) + "'");
4108 Args.push_back(ArgList[i].V);
4109 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4110 AttrBuilder B(ArgList[i].Attrs, i + 1);
4111 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4116 return Error(CallLoc, "not enough parameters specified for call");
4118 if (FnAttrs.hasAttributes())
4119 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4120 AttributeSet::FunctionIndex,
4123 // Finish off the Attribute and check them
4124 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4126 CallInst *CI = CallInst::Create(Callee, Args);
4127 CI->setTailCallKind(TCK);
4128 CI->setCallingConv(CC);
4129 CI->setAttributes(PAL);
4130 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4135 //===----------------------------------------------------------------------===//
4136 // Memory Instructions.
4137 //===----------------------------------------------------------------------===//
4140 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4141 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4142 Value *Size = nullptr;
4144 unsigned Alignment = 0;
4147 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4149 if (ParseType(Ty)) return true;
4151 bool AteExtraComma = false;
4152 if (EatIfPresent(lltok::comma)) {
4153 if (Lex.getKind() == lltok::kw_align) {
4154 if (ParseOptionalAlignment(Alignment)) return true;
4155 } else if (Lex.getKind() == lltok::MetadataVar) {
4156 AteExtraComma = true;
4158 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4159 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4164 if (Size && !Size->getType()->isIntegerTy())
4165 return Error(SizeLoc, "element count must have integer type");
4167 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4168 AI->setUsedWithInAlloca(IsInAlloca);
4170 return AteExtraComma ? InstExtraComma : InstNormal;
4174 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4175 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4176 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4177 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4178 Value *Val; LocTy Loc;
4179 unsigned Alignment = 0;
4180 bool AteExtraComma = false;
4181 bool isAtomic = false;
4182 AtomicOrdering Ordering = NotAtomic;
4183 SynchronizationScope Scope = CrossThread;
4185 if (Lex.getKind() == lltok::kw_atomic) {
4190 bool isVolatile = false;
4191 if (Lex.getKind() == lltok::kw_volatile) {
4196 if (ParseTypeAndValue(Val, Loc, PFS) ||
4197 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4198 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4201 if (!Val->getType()->isPointerTy() ||
4202 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4203 return Error(Loc, "load operand must be a pointer to a first class type");
4204 if (isAtomic && !Alignment)
4205 return Error(Loc, "atomic load must have explicit non-zero alignment");
4206 if (Ordering == Release || Ordering == AcquireRelease)
4207 return Error(Loc, "atomic load cannot use Release ordering");
4209 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4210 return AteExtraComma ? InstExtraComma : InstNormal;
4215 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4216 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4217 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4218 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4219 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4220 unsigned Alignment = 0;
4221 bool AteExtraComma = false;
4222 bool isAtomic = false;
4223 AtomicOrdering Ordering = NotAtomic;
4224 SynchronizationScope Scope = CrossThread;
4226 if (Lex.getKind() == lltok::kw_atomic) {
4231 bool isVolatile = false;
4232 if (Lex.getKind() == lltok::kw_volatile) {
4237 if (ParseTypeAndValue(Val, Loc, PFS) ||
4238 ParseToken(lltok::comma, "expected ',' after store operand") ||
4239 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4240 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4241 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4244 if (!Ptr->getType()->isPointerTy())
4245 return Error(PtrLoc, "store operand must be a pointer");
4246 if (!Val->getType()->isFirstClassType())
4247 return Error(Loc, "store operand must be a first class value");
4248 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4249 return Error(Loc, "stored value and pointer type do not match");
4250 if (isAtomic && !Alignment)
4251 return Error(Loc, "atomic store must have explicit non-zero alignment");
4252 if (Ordering == Acquire || Ordering == AcquireRelease)
4253 return Error(Loc, "atomic store cannot use Acquire ordering");
4255 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4256 return AteExtraComma ? InstExtraComma : InstNormal;
4260 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4261 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4262 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4263 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4264 bool AteExtraComma = false;
4265 AtomicOrdering SuccessOrdering = NotAtomic;
4266 AtomicOrdering FailureOrdering = NotAtomic;
4267 SynchronizationScope Scope = CrossThread;
4268 bool isVolatile = false;
4269 bool isWeak = false;
4271 if (EatIfPresent(lltok::kw_weak))
4274 if (EatIfPresent(lltok::kw_volatile))
4277 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4278 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4279 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4280 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4281 ParseTypeAndValue(New, NewLoc, PFS) ||
4282 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4283 ParseOrdering(FailureOrdering))
4286 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4287 return TokError("cmpxchg cannot be unordered");
4288 if (SuccessOrdering < FailureOrdering)
4289 return TokError("cmpxchg must be at least as ordered on success as failure");
4290 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4291 return TokError("cmpxchg failure ordering cannot include release semantics");
4292 if (!Ptr->getType()->isPointerTy())
4293 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4294 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4295 return Error(CmpLoc, "compare value and pointer type do not match");
4296 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4297 return Error(NewLoc, "new value and pointer type do not match");
4298 if (!New->getType()->isIntegerTy())
4299 return Error(NewLoc, "cmpxchg operand must be an integer");
4300 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4301 if (Size < 8 || (Size & (Size - 1)))
4302 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4305 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4306 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4307 CXI->setVolatile(isVolatile);
4308 CXI->setWeak(isWeak);
4310 return AteExtraComma ? InstExtraComma : InstNormal;
4314 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4315 /// 'singlethread'? AtomicOrdering
4316 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4317 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4318 bool AteExtraComma = false;
4319 AtomicOrdering Ordering = NotAtomic;
4320 SynchronizationScope Scope = CrossThread;
4321 bool isVolatile = false;
4322 AtomicRMWInst::BinOp Operation;
4324 if (EatIfPresent(lltok::kw_volatile))
4327 switch (Lex.getKind()) {
4328 default: return TokError("expected binary operation in atomicrmw");
4329 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4330 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4331 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4332 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4333 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4334 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4335 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4336 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4337 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4338 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4339 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4341 Lex.Lex(); // Eat the operation.
4343 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4344 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4345 ParseTypeAndValue(Val, ValLoc, PFS) ||
4346 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4349 if (Ordering == Unordered)
4350 return TokError("atomicrmw cannot be unordered");
4351 if (!Ptr->getType()->isPointerTy())
4352 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4353 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4354 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4355 if (!Val->getType()->isIntegerTy())
4356 return Error(ValLoc, "atomicrmw operand must be an integer");
4357 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4358 if (Size < 8 || (Size & (Size - 1)))
4359 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4362 AtomicRMWInst *RMWI =
4363 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4364 RMWI->setVolatile(isVolatile);
4366 return AteExtraComma ? InstExtraComma : InstNormal;
4370 /// ::= 'fence' 'singlethread'? AtomicOrdering
4371 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4372 AtomicOrdering Ordering = NotAtomic;
4373 SynchronizationScope Scope = CrossThread;
4374 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4377 if (Ordering == Unordered)
4378 return TokError("fence cannot be unordered");
4379 if (Ordering == Monotonic)
4380 return TokError("fence cannot be monotonic");
4382 Inst = new FenceInst(Context, Ordering, Scope);
4386 /// ParseGetElementPtr
4387 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4388 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4389 Value *Ptr = nullptr;
4390 Value *Val = nullptr;
4393 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4395 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4397 Type *BaseType = Ptr->getType();
4398 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4399 if (!BasePointerType)
4400 return Error(Loc, "base of getelementptr must be a pointer");
4402 SmallVector<Value*, 16> Indices;
4403 bool AteExtraComma = false;
4404 while (EatIfPresent(lltok::comma)) {
4405 if (Lex.getKind() == lltok::MetadataVar) {
4406 AteExtraComma = true;
4409 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4410 if (!Val->getType()->getScalarType()->isIntegerTy())
4411 return Error(EltLoc, "getelementptr index must be an integer");
4412 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4413 return Error(EltLoc, "getelementptr index type missmatch");
4414 if (Val->getType()->isVectorTy()) {
4415 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4416 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4417 if (ValNumEl != PtrNumEl)
4418 return Error(EltLoc,
4419 "getelementptr vector index has a wrong number of elements");
4421 Indices.push_back(Val);
4424 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4425 return Error(Loc, "base element of getelementptr must be sized");
4427 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4428 return Error(Loc, "invalid getelementptr indices");
4429 Inst = GetElementPtrInst::Create(Ptr, Indices);
4431 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4432 return AteExtraComma ? InstExtraComma : InstNormal;
4435 /// ParseExtractValue
4436 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4437 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4438 Value *Val; LocTy Loc;
4439 SmallVector<unsigned, 4> Indices;
4441 if (ParseTypeAndValue(Val, Loc, PFS) ||
4442 ParseIndexList(Indices, AteExtraComma))
4445 if (!Val->getType()->isAggregateType())
4446 return Error(Loc, "extractvalue operand must be aggregate type");
4448 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4449 return Error(Loc, "invalid indices for extractvalue");
4450 Inst = ExtractValueInst::Create(Val, Indices);
4451 return AteExtraComma ? InstExtraComma : InstNormal;
4454 /// ParseInsertValue
4455 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4456 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4457 Value *Val0, *Val1; LocTy Loc0, Loc1;
4458 SmallVector<unsigned, 4> Indices;
4460 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4461 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4462 ParseTypeAndValue(Val1, Loc1, PFS) ||
4463 ParseIndexList(Indices, AteExtraComma))
4466 if (!Val0->getType()->isAggregateType())
4467 return Error(Loc0, "insertvalue operand must be aggregate type");
4469 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4470 return Error(Loc0, "invalid indices for insertvalue");
4471 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4472 return AteExtraComma ? InstExtraComma : InstNormal;
4475 //===----------------------------------------------------------------------===//
4476 // Embedded metadata.
4477 //===----------------------------------------------------------------------===//
4479 /// ParseMDNodeVector
4480 /// ::= Element (',' Element)*
4482 /// ::= 'null' | TypeAndValue
4483 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4484 PerFunctionState *PFS) {
4485 // Check for an empty list.
4486 if (Lex.getKind() == lltok::rbrace)
4490 // Null is a special case since it is typeless.
4491 if (EatIfPresent(lltok::kw_null)) {
4492 Elts.push_back(nullptr);
4497 if (ParseTypeAndValue(V, PFS)) return true;
4499 } while (EatIfPresent(lltok::comma));