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/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
126 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
139 "cannot take address of numeric label after the function is defined");
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
158 //===----------------------------------------------------------------------===//
159 // Top-Level Entities
160 //===----------------------------------------------------------------------===//
162 bool LLParser::ParseTopLevelEntities() {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
187 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
188 case lltok::kw_internal: // OptionalLinkage
189 case lltok::kw_weak: // OptionalLinkage
190 case lltok::kw_weak_odr: // OptionalLinkage
191 case lltok::kw_linkonce: // OptionalLinkage
192 case lltok::kw_linkonce_odr: // OptionalLinkage
193 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
194 case lltok::kw_appending: // OptionalLinkage
195 case lltok::kw_dllexport: // OptionalLinkage
196 case lltok::kw_common: // OptionalLinkage
197 case lltok::kw_dllimport: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: { // OptionalLinkage
200 unsigned Linkage, Visibility;
201 if (ParseOptionalLinkage(Linkage) ||
202 ParseOptionalVisibility(Visibility) ||
203 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
207 case lltok::kw_default: // OptionalVisibility
208 case lltok::kw_hidden: // OptionalVisibility
209 case lltok::kw_protected: { // OptionalVisibility
211 if (ParseOptionalVisibility(Visibility) ||
212 ParseGlobal("", SMLoc(), 0, false, Visibility))
217 case lltok::kw_thread_local: // OptionalThreadLocal
218 case lltok::kw_addrspace: // OptionalAddrSpace
219 case lltok::kw_constant: // GlobalType
220 case lltok::kw_global: // GlobalType
221 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
229 /// ::= 'module' 'asm' STRINGCONSTANT
230 bool LLParser::ParseModuleAsm() {
231 assert(Lex.getKind() == lltok::kw_module);
235 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
236 ParseStringConstant(AsmStr)) return true;
238 M->appendModuleInlineAsm(AsmStr);
243 /// ::= 'target' 'triple' '=' STRINGCONSTANT
244 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
245 bool LLParser::ParseTargetDefinition() {
246 assert(Lex.getKind() == lltok::kw_target);
249 default: return TokError("unknown target property");
250 case lltok::kw_triple:
252 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
253 ParseStringConstant(Str))
255 M->setTargetTriple(Str);
257 case lltok::kw_datalayout:
259 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
260 ParseStringConstant(Str))
262 M->setDataLayout(Str);
268 /// ::= 'deplibs' '=' '[' ']'
269 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
270 bool LLParser::ParseDepLibs() {
271 assert(Lex.getKind() == lltok::kw_deplibs);
273 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
274 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
277 if (EatIfPresent(lltok::rsquare))
281 if (ParseStringConstant(Str)) return true;
284 while (EatIfPresent(lltok::comma)) {
285 if (ParseStringConstant(Str)) return true;
289 return ParseToken(lltok::rsquare, "expected ']' at end of list");
292 /// ParseUnnamedType:
293 /// ::= LocalVarID '=' 'type' type
294 bool LLParser::ParseUnnamedType() {
295 LocTy TypeLoc = Lex.getLoc();
296 unsigned TypeID = Lex.getUIntVal();
297 Lex.Lex(); // eat LocalVarID;
299 if (ParseToken(lltok::equal, "expected '=' after name") ||
300 ParseToken(lltok::kw_type, "expected 'type' after '='"))
303 if (TypeID >= NumberedTypes.size())
304 NumberedTypes.resize(TypeID+1);
307 if (ParseStructDefinition(TypeLoc, "",
308 NumberedTypes[TypeID], Result)) return true;
310 if (!isa<StructType>(Result)) {
311 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
313 return Error(TypeLoc, "non-struct types may not be recursive");
314 Entry.first = Result;
315 Entry.second = SMLoc();
323 /// ::= LocalVar '=' 'type' type
324 bool LLParser::ParseNamedType() {
325 std::string Name = Lex.getStrVal();
326 LocTy NameLoc = Lex.getLoc();
327 Lex.Lex(); // eat LocalVar.
329 if (ParseToken(lltok::equal, "expected '=' after name") ||
330 ParseToken(lltok::kw_type, "expected 'type' after name"))
334 if (ParseStructDefinition(NameLoc, Name,
335 NamedTypes[Name], Result)) return true;
337 if (!isa<StructType>(Result)) {
338 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
340 return Error(NameLoc, "non-struct types may not be recursive");
341 Entry.first = Result;
342 Entry.second = SMLoc();
350 /// ::= 'declare' FunctionHeader
351 bool LLParser::ParseDeclare() {
352 assert(Lex.getKind() == lltok::kw_declare);
356 return ParseFunctionHeader(F, false);
360 /// ::= 'define' FunctionHeader '{' ...
361 bool LLParser::ParseDefine() {
362 assert(Lex.getKind() == lltok::kw_define);
366 return ParseFunctionHeader(F, true) ||
367 ParseFunctionBody(*F);
373 bool LLParser::ParseGlobalType(bool &IsConstant) {
374 if (Lex.getKind() == lltok::kw_constant)
376 else if (Lex.getKind() == lltok::kw_global)
380 return TokError("expected 'global' or 'constant'");
386 /// ParseUnnamedGlobal:
387 /// OptionalVisibility ALIAS ...
388 /// OptionalLinkage OptionalVisibility ... -> global variable
389 /// GlobalID '=' OptionalVisibility ALIAS ...
390 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
391 bool LLParser::ParseUnnamedGlobal() {
392 unsigned VarID = NumberedVals.size();
394 LocTy NameLoc = Lex.getLoc();
396 // Handle the GlobalID form.
397 if (Lex.getKind() == lltok::GlobalID) {
398 if (Lex.getUIntVal() != VarID)
399 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
401 Lex.Lex(); // eat GlobalID;
403 if (ParseToken(lltok::equal, "expected '=' after name"))
408 unsigned Linkage, Visibility;
409 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
410 ParseOptionalVisibility(Visibility))
413 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
414 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
415 return ParseAlias(Name, NameLoc, Visibility);
418 /// ParseNamedGlobal:
419 /// GlobalVar '=' OptionalVisibility ALIAS ...
420 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
421 bool LLParser::ParseNamedGlobal() {
422 assert(Lex.getKind() == lltok::GlobalVar);
423 LocTy NameLoc = Lex.getLoc();
424 std::string Name = Lex.getStrVal();
428 unsigned Linkage, Visibility;
429 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
430 ParseOptionalLinkage(Linkage, HasLinkage) ||
431 ParseOptionalVisibility(Visibility))
434 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
435 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
436 return ParseAlias(Name, NameLoc, Visibility);
440 // ::= '!' STRINGCONSTANT
441 bool LLParser::ParseMDString(MDString *&Result) {
443 if (ParseStringConstant(Str)) return true;
444 Result = MDString::get(Context, Str);
449 // ::= '!' MDNodeNumber
451 /// This version of ParseMDNodeID returns the slot number and null in the case
452 /// of a forward reference.
453 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
454 // !{ ..., !42, ... }
455 if (ParseUInt32(SlotNo)) return true;
457 // Check existing MDNode.
458 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
459 Result = NumberedMetadata[SlotNo];
465 bool LLParser::ParseMDNodeID(MDNode *&Result) {
466 // !{ ..., !42, ... }
468 if (ParseMDNodeID(Result, MID)) return true;
470 // If not a forward reference, just return it now.
471 if (Result) return false;
473 // Otherwise, create MDNode forward reference.
474 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
475 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
477 if (NumberedMetadata.size() <= MID)
478 NumberedMetadata.resize(MID+1);
479 NumberedMetadata[MID] = FwdNode;
484 /// ParseNamedMetadata:
485 /// !foo = !{ !1, !2 }
486 bool LLParser::ParseNamedMetadata() {
487 assert(Lex.getKind() == lltok::MetadataVar);
488 std::string Name = Lex.getStrVal();
491 if (ParseToken(lltok::equal, "expected '=' here") ||
492 ParseToken(lltok::exclaim, "Expected '!' here") ||
493 ParseToken(lltok::lbrace, "Expected '{' here"))
496 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
497 if (Lex.getKind() != lltok::rbrace)
499 if (ParseToken(lltok::exclaim, "Expected '!' here"))
503 if (ParseMDNodeID(N)) return true;
505 } while (EatIfPresent(lltok::comma));
507 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
513 /// ParseStandaloneMetadata:
515 bool LLParser::ParseStandaloneMetadata() {
516 assert(Lex.getKind() == lltok::exclaim);
518 unsigned MetadataID = 0;
522 SmallVector<Value *, 16> Elts;
523 if (ParseUInt32(MetadataID) ||
524 ParseToken(lltok::equal, "expected '=' here") ||
525 ParseType(Ty, TyLoc) ||
526 ParseToken(lltok::exclaim, "Expected '!' here") ||
527 ParseToken(lltok::lbrace, "Expected '{' here") ||
528 ParseMDNodeVector(Elts, NULL) ||
529 ParseToken(lltok::rbrace, "expected end of metadata node"))
532 MDNode *Init = MDNode::get(Context, Elts);
534 // See if this was forward referenced, if so, handle it.
535 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
536 FI = ForwardRefMDNodes.find(MetadataID);
537 if (FI != ForwardRefMDNodes.end()) {
538 MDNode *Temp = FI->second.first;
539 Temp->replaceAllUsesWith(Init);
540 MDNode::deleteTemporary(Temp);
541 ForwardRefMDNodes.erase(FI);
543 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
545 if (MetadataID >= NumberedMetadata.size())
546 NumberedMetadata.resize(MetadataID+1);
548 if (NumberedMetadata[MetadataID] != 0)
549 return TokError("Metadata id is already used");
550 NumberedMetadata[MetadataID] = Init;
557 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
560 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
561 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
563 /// Everything through visibility has already been parsed.
565 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
566 unsigned Visibility) {
567 assert(Lex.getKind() == lltok::kw_alias);
570 LocTy LinkageLoc = Lex.getLoc();
571 if (ParseOptionalLinkage(Linkage))
574 if (Linkage != GlobalValue::ExternalLinkage &&
575 Linkage != GlobalValue::WeakAnyLinkage &&
576 Linkage != GlobalValue::WeakODRLinkage &&
577 Linkage != GlobalValue::InternalLinkage &&
578 Linkage != GlobalValue::PrivateLinkage &&
579 Linkage != GlobalValue::LinkerPrivateLinkage &&
580 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
581 return Error(LinkageLoc, "invalid linkage type for alias");
584 LocTy AliaseeLoc = Lex.getLoc();
585 if (Lex.getKind() != lltok::kw_bitcast &&
586 Lex.getKind() != lltok::kw_getelementptr) {
587 if (ParseGlobalTypeAndValue(Aliasee)) return true;
589 // The bitcast dest type is not present, it is implied by the dest type.
591 if (ParseValID(ID)) return true;
592 if (ID.Kind != ValID::t_Constant)
593 return Error(AliaseeLoc, "invalid aliasee");
594 Aliasee = ID.ConstantVal;
597 if (!Aliasee->getType()->isPointerTy())
598 return Error(AliaseeLoc, "alias must have pointer type");
600 // Okay, create the alias but do not insert it into the module yet.
601 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
602 (GlobalValue::LinkageTypes)Linkage, Name,
604 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
606 // See if this value already exists in the symbol table. If so, it is either
607 // a redefinition or a definition of a forward reference.
608 if (GlobalValue *Val = M->getNamedValue(Name)) {
609 // See if this was a redefinition. If so, there is no entry in
611 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
612 I = ForwardRefVals.find(Name);
613 if (I == ForwardRefVals.end())
614 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
616 // Otherwise, this was a definition of forward ref. Verify that types
618 if (Val->getType() != GA->getType())
619 return Error(NameLoc,
620 "forward reference and definition of alias have different types");
622 // If they agree, just RAUW the old value with the alias and remove the
624 Val->replaceAllUsesWith(GA);
625 Val->eraseFromParent();
626 ForwardRefVals.erase(I);
629 // Insert into the module, we know its name won't collide now.
630 M->getAliasList().push_back(GA);
631 assert(GA->getName() == Name && "Should not be a name conflict!");
637 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
638 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
639 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
640 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
642 /// Everything through visibility has been parsed already.
644 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
645 unsigned Linkage, bool HasLinkage,
646 unsigned Visibility) {
648 bool IsConstant, UnnamedAddr;
649 GlobalVariable::ThreadLocalMode TLM;
650 LocTy UnnamedAddrLoc;
654 if (ParseOptionalThreadLocal(TLM) ||
655 ParseOptionalAddrSpace(AddrSpace) ||
656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
658 ParseGlobalType(IsConstant) ||
659 ParseType(Ty, TyLoc))
662 // If the linkage is specified and is external, then no initializer is
665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
666 Linkage != GlobalValue::ExternalWeakLinkage &&
667 Linkage != GlobalValue::ExternalLinkage)) {
668 if (ParseGlobalValue(Ty, Init))
672 if (Ty->isFunctionTy() || Ty->isLabelTy())
673 return Error(TyLoc, "invalid type for global variable");
675 GlobalVariable *GV = 0;
677 // See if the global was forward referenced, if so, use the global.
679 if (GlobalValue *GVal = M->getNamedValue(Name)) {
680 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
681 return Error(NameLoc, "redefinition of global '@" + Name + "'");
682 GV = cast<GlobalVariable>(GVal);
685 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
686 I = ForwardRefValIDs.find(NumberedVals.size());
687 if (I != ForwardRefValIDs.end()) {
688 GV = cast<GlobalVariable>(I->second.first);
689 ForwardRefValIDs.erase(I);
694 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
695 Name, 0, GlobalVariable::NotThreadLocal,
698 if (GV->getType()->getElementType() != Ty)
700 "forward reference and definition of global have different types");
702 // Move the forward-reference to the correct spot in the module.
703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
707 NumberedVals.push_back(GV);
709 // Set the parsed properties on the global.
711 GV->setInitializer(Init);
712 GV->setConstant(IsConstant);
713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
715 GV->setThreadLocalMode(TLM);
716 GV->setUnnamedAddr(UnnamedAddr);
718 // Parse attributes on the global.
719 while (Lex.getKind() == lltok::comma) {
722 if (Lex.getKind() == lltok::kw_section) {
724 GV->setSection(Lex.getStrVal());
725 if (ParseToken(lltok::StringConstant, "expected global section string"))
727 } else if (Lex.getKind() == lltok::kw_align) {
729 if (ParseOptionalAlignment(Alignment)) return true;
730 GV->setAlignment(Alignment);
732 TokError("unknown global variable property!");
740 //===----------------------------------------------------------------------===//
741 // GlobalValue Reference/Resolution Routines.
742 //===----------------------------------------------------------------------===//
744 /// GetGlobalVal - Get a value with the specified name or ID, creating a
745 /// forward reference record if needed. This can return null if the value
746 /// exists but does not have the right type.
747 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
749 PointerType *PTy = dyn_cast<PointerType>(Ty);
751 Error(Loc, "global variable reference must have pointer type");
755 // Look this name up in the normal function symbol table.
757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
759 // If this is a forward reference for the value, see if we already created a
760 // forward ref record.
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I != ForwardRefVals.end())
765 Val = I->second.first;
768 // If we have the value in the symbol table or fwd-ref table, return it.
770 if (Val->getType() == Ty) return Val;
771 Error(Loc, "'@" + Name + "' defined with type '" +
772 getTypeString(Val->getType()) + "'");
776 // Otherwise, create a new forward reference for this value and remember it.
778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
782 GlobalValue::ExternalWeakLinkage, 0, Name,
783 0, GlobalVariable::NotThreadLocal,
784 PTy->getAddressSpace());
786 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
790 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
791 PointerType *PTy = dyn_cast<PointerType>(Ty);
793 Error(Loc, "global variable reference must have pointer type");
797 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
799 // If this is a forward reference for the value, see if we already created a
800 // forward ref record.
802 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
803 I = ForwardRefValIDs.find(ID);
804 if (I != ForwardRefValIDs.end())
805 Val = I->second.first;
808 // If we have the value in the symbol table or fwd-ref table, return it.
810 if (Val->getType() == Ty) return Val;
811 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
812 getTypeString(Val->getType()) + "'");
816 // Otherwise, create a new forward reference for this value and remember it.
818 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
819 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
821 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
822 GlobalValue::ExternalWeakLinkage, 0, "");
824 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
829 //===----------------------------------------------------------------------===//
831 //===----------------------------------------------------------------------===//
833 /// ParseToken - If the current token has the specified kind, eat it and return
834 /// success. Otherwise, emit the specified error and return failure.
835 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
836 if (Lex.getKind() != T)
837 return TokError(ErrMsg);
842 /// ParseStringConstant
843 /// ::= StringConstant
844 bool LLParser::ParseStringConstant(std::string &Result) {
845 if (Lex.getKind() != lltok::StringConstant)
846 return TokError("expected string constant");
847 Result = Lex.getStrVal();
854 bool LLParser::ParseUInt32(unsigned &Val) {
855 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
856 return TokError("expected integer");
857 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
858 if (Val64 != unsigned(Val64))
859 return TokError("expected 32-bit integer (too large)");
866 /// := 'localdynamic'
869 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
870 switch (Lex.getKind()) {
872 return TokError("expected localdynamic, initialexec or localexec");
873 case lltok::kw_localdynamic:
874 TLM = GlobalVariable::LocalDynamicTLSModel;
876 case lltok::kw_initialexec:
877 TLM = GlobalVariable::InitialExecTLSModel;
879 case lltok::kw_localexec:
880 TLM = GlobalVariable::LocalExecTLSModel;
888 /// ParseOptionalThreadLocal
890 /// := 'thread_local'
891 /// := 'thread_local' '(' tlsmodel ')'
892 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
893 TLM = GlobalVariable::NotThreadLocal;
894 if (!EatIfPresent(lltok::kw_thread_local))
897 TLM = GlobalVariable::GeneralDynamicTLSModel;
898 if (Lex.getKind() == lltok::lparen) {
900 return ParseTLSModel(TLM) ||
901 ParseToken(lltok::rparen, "expected ')' after thread local model");
906 /// ParseOptionalAddrSpace
908 /// := 'addrspace' '(' uint32 ')'
909 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
911 if (!EatIfPresent(lltok::kw_addrspace))
913 return ParseToken(lltok::lparen, "expected '(' in address space") ||
914 ParseUInt32(AddrSpace) ||
915 ParseToken(lltok::rparen, "expected ')' in address space");
918 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
919 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
920 /// 2: function attr.
921 bool LLParser::ParseOptionalAttrs(AttrBuilder &B, unsigned AttrKind) {
922 LocTy AttrLoc = Lex.getLoc();
923 bool HaveError = false;
928 lltok::Kind Token = Lex.getKind();
930 default: // End of attributes.
932 case lltok::kw_zeroext: B.addAttribute(Attributes::ZExt); break;
933 case lltok::kw_signext: B.addAttribute(Attributes::SExt); break;
934 case lltok::kw_inreg: B.addAttribute(Attributes::InReg); break;
935 case lltok::kw_sret: B.addAttribute(Attributes::StructRet); break;
936 case lltok::kw_noalias: B.addAttribute(Attributes::NoAlias); break;
937 case lltok::kw_nocapture: B.addAttribute(Attributes::NoCapture); break;
938 case lltok::kw_byval: B.addAttribute(Attributes::ByVal); break;
939 case lltok::kw_nest: B.addAttribute(Attributes::Nest); break;
941 case lltok::kw_noreturn: B.addAttribute(Attributes::NoReturn); break;
942 case lltok::kw_nounwind: B.addAttribute(Attributes::NoUnwind); break;
943 case lltok::kw_uwtable: B.addAttribute(Attributes::UWTable); break;
944 case lltok::kw_returns_twice: B.addAttribute(Attributes::ReturnsTwice); break;
945 case lltok::kw_noinline: B.addAttribute(Attributes::NoInline); break;
946 case lltok::kw_readnone: B.addAttribute(Attributes::ReadNone); break;
947 case lltok::kw_readonly: B.addAttribute(Attributes::ReadOnly); break;
948 case lltok::kw_inlinehint: B.addAttribute(Attributes::InlineHint); break;
949 case lltok::kw_alwaysinline: B.addAttribute(Attributes::AlwaysInline); break;
950 case lltok::kw_optsize: B.addAttribute(Attributes::OptimizeForSize); break;
951 case lltok::kw_ssp: B.addAttribute(Attributes::StackProtect); break;
952 case lltok::kw_sspreq: B.addAttribute(Attributes::StackProtectReq); break;
953 case lltok::kw_noredzone: B.addAttribute(Attributes::NoRedZone); break;
954 case lltok::kw_noimplicitfloat: B.addAttribute(Attributes::NoImplicitFloat); break;
955 case lltok::kw_naked: B.addAttribute(Attributes::Naked); break;
956 case lltok::kw_nonlazybind: B.addAttribute(Attributes::NonLazyBind); break;
957 case lltok::kw_address_safety: B.addAttribute(Attributes::AddressSafety); break;
958 case lltok::kw_minsize: B.addAttribute(Attributes::MinSize); break;
960 case lltok::kw_alignstack: {
962 if (ParseOptionalStackAlignment(Alignment))
964 B.addStackAlignmentAttr(Alignment);
968 case lltok::kw_align: {
970 if (ParseOptionalAlignment(Alignment))
972 B.addAlignmentAttr(Alignment);
978 // Perform some error checking.
982 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
984 case lltok::kw_align:
985 // As a hack, we allow "align 2" on functions as a synonym for
991 case lltok::kw_nocapture:
992 case lltok::kw_byval:
995 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
999 case lltok::kw_noreturn:
1000 case lltok::kw_nounwind:
1001 case lltok::kw_readnone:
1002 case lltok::kw_readonly:
1003 case lltok::kw_noinline:
1004 case lltok::kw_alwaysinline:
1005 case lltok::kw_optsize:
1007 case lltok::kw_sspreq:
1008 case lltok::kw_noredzone:
1009 case lltok::kw_noimplicitfloat:
1010 case lltok::kw_naked:
1011 case lltok::kw_inlinehint:
1012 case lltok::kw_alignstack:
1013 case lltok::kw_uwtable:
1014 case lltok::kw_nonlazybind:
1015 case lltok::kw_returns_twice:
1016 case lltok::kw_address_safety:
1017 case lltok::kw_minsize:
1019 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
1027 /// ParseOptionalLinkage
1030 /// ::= 'linker_private'
1031 /// ::= 'linker_private_weak'
1036 /// ::= 'linkonce_odr'
1037 /// ::= 'linkonce_odr_auto_hide'
1038 /// ::= 'available_externally'
1043 /// ::= 'extern_weak'
1045 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1047 switch (Lex.getKind()) {
1048 default: Res=GlobalValue::ExternalLinkage; return false;
1049 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1050 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1051 case lltok::kw_linker_private_weak:
1052 Res = GlobalValue::LinkerPrivateWeakLinkage;
1054 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1055 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1056 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1057 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1058 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1059 case lltok::kw_linkonce_odr_auto_hide:
1060 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1061 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1063 case lltok::kw_available_externally:
1064 Res = GlobalValue::AvailableExternallyLinkage;
1066 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1067 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1068 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1069 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1070 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1071 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1078 /// ParseOptionalVisibility
1084 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1085 switch (Lex.getKind()) {
1086 default: Res = GlobalValue::DefaultVisibility; return false;
1087 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1088 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1089 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1095 /// ParseOptionalCallingConv
1099 /// ::= 'kw_intel_ocl_bicc'
1101 /// ::= 'x86_stdcallcc'
1102 /// ::= 'x86_fastcallcc'
1103 /// ::= 'x86_thiscallcc'
1104 /// ::= 'arm_apcscc'
1105 /// ::= 'arm_aapcscc'
1106 /// ::= 'arm_aapcs_vfpcc'
1107 /// ::= 'msp430_intrcc'
1108 /// ::= 'ptx_kernel'
1109 /// ::= 'ptx_device'
1111 /// ::= 'spir_kernel'
1114 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1115 switch (Lex.getKind()) {
1116 default: CC = CallingConv::C; return false;
1117 case lltok::kw_ccc: CC = CallingConv::C; break;
1118 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1119 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1120 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1121 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1122 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1123 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1124 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1125 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1126 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1127 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1128 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1129 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1130 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1131 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1132 case lltok::kw_cc: {
1133 unsigned ArbitraryCC;
1135 if (ParseUInt32(ArbitraryCC))
1137 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1146 /// ParseInstructionMetadata
1147 /// ::= !dbg !42 (',' !dbg !57)*
1148 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1149 PerFunctionState *PFS) {
1151 if (Lex.getKind() != lltok::MetadataVar)
1152 return TokError("expected metadata after comma");
1154 std::string Name = Lex.getStrVal();
1155 unsigned MDK = M->getMDKindID(Name);
1159 SMLoc Loc = Lex.getLoc();
1161 if (ParseToken(lltok::exclaim, "expected '!' here"))
1164 // This code is similar to that of ParseMetadataValue, however it needs to
1165 // have special-case code for a forward reference; see the comments on
1166 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1167 // at the top level here.
1168 if (Lex.getKind() == lltok::lbrace) {
1170 if (ParseMetadataListValue(ID, PFS))
1172 assert(ID.Kind == ValID::t_MDNode);
1173 Inst->setMetadata(MDK, ID.MDNodeVal);
1175 unsigned NodeID = 0;
1176 if (ParseMDNodeID(Node, NodeID))
1179 // If we got the node, add it to the instruction.
1180 Inst->setMetadata(MDK, Node);
1182 MDRef R = { Loc, MDK, NodeID };
1183 // Otherwise, remember that this should be resolved later.
1184 ForwardRefInstMetadata[Inst].push_back(R);
1188 // If this is the end of the list, we're done.
1189 } while (EatIfPresent(lltok::comma));
1193 /// ParseOptionalAlignment
1196 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1198 if (!EatIfPresent(lltok::kw_align))
1200 LocTy AlignLoc = Lex.getLoc();
1201 if (ParseUInt32(Alignment)) return true;
1202 if (!isPowerOf2_32(Alignment))
1203 return Error(AlignLoc, "alignment is not a power of two");
1204 if (Alignment > Value::MaximumAlignment)
1205 return Error(AlignLoc, "huge alignments are not supported yet");
1209 /// ParseOptionalCommaAlign
1213 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1215 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1216 bool &AteExtraComma) {
1217 AteExtraComma = false;
1218 while (EatIfPresent(lltok::comma)) {
1219 // Metadata at the end is an early exit.
1220 if (Lex.getKind() == lltok::MetadataVar) {
1221 AteExtraComma = true;
1225 if (Lex.getKind() != lltok::kw_align)
1226 return Error(Lex.getLoc(), "expected metadata or 'align'");
1228 if (ParseOptionalAlignment(Alignment)) return true;
1234 /// ParseScopeAndOrdering
1235 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1238 /// This sets Scope and Ordering to the parsed values.
1239 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1240 AtomicOrdering &Ordering) {
1244 Scope = CrossThread;
1245 if (EatIfPresent(lltok::kw_singlethread))
1246 Scope = SingleThread;
1247 switch (Lex.getKind()) {
1248 default: return TokError("Expected ordering on atomic instruction");
1249 case lltok::kw_unordered: Ordering = Unordered; break;
1250 case lltok::kw_monotonic: Ordering = Monotonic; break;
1251 case lltok::kw_acquire: Ordering = Acquire; break;
1252 case lltok::kw_release: Ordering = Release; break;
1253 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1254 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1260 /// ParseOptionalStackAlignment
1262 /// ::= 'alignstack' '(' 4 ')'
1263 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1265 if (!EatIfPresent(lltok::kw_alignstack))
1267 LocTy ParenLoc = Lex.getLoc();
1268 if (!EatIfPresent(lltok::lparen))
1269 return Error(ParenLoc, "expected '('");
1270 LocTy AlignLoc = Lex.getLoc();
1271 if (ParseUInt32(Alignment)) return true;
1272 ParenLoc = Lex.getLoc();
1273 if (!EatIfPresent(lltok::rparen))
1274 return Error(ParenLoc, "expected ')'");
1275 if (!isPowerOf2_32(Alignment))
1276 return Error(AlignLoc, "stack alignment is not a power of two");
1280 /// ParseIndexList - This parses the index list for an insert/extractvalue
1281 /// instruction. This sets AteExtraComma in the case where we eat an extra
1282 /// comma at the end of the line and find that it is followed by metadata.
1283 /// Clients that don't allow metadata can call the version of this function that
1284 /// only takes one argument.
1287 /// ::= (',' uint32)+
1289 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1290 bool &AteExtraComma) {
1291 AteExtraComma = false;
1293 if (Lex.getKind() != lltok::comma)
1294 return TokError("expected ',' as start of index list");
1296 while (EatIfPresent(lltok::comma)) {
1297 if (Lex.getKind() == lltok::MetadataVar) {
1298 AteExtraComma = true;
1302 if (ParseUInt32(Idx)) return true;
1303 Indices.push_back(Idx);
1309 //===----------------------------------------------------------------------===//
1311 //===----------------------------------------------------------------------===//
1313 /// ParseType - Parse a type.
1314 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1315 SMLoc TypeLoc = Lex.getLoc();
1316 switch (Lex.getKind()) {
1318 return TokError("expected type");
1320 // Type ::= 'float' | 'void' (etc)
1321 Result = Lex.getTyVal();
1325 // Type ::= StructType
1326 if (ParseAnonStructType(Result, false))
1329 case lltok::lsquare:
1330 // Type ::= '[' ... ']'
1331 Lex.Lex(); // eat the lsquare.
1332 if (ParseArrayVectorType(Result, false))
1335 case lltok::less: // Either vector or packed struct.
1336 // Type ::= '<' ... '>'
1338 if (Lex.getKind() == lltok::lbrace) {
1339 if (ParseAnonStructType(Result, true) ||
1340 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1342 } else if (ParseArrayVectorType(Result, true))
1345 case lltok::LocalVar: {
1347 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1349 // If the type hasn't been defined yet, create a forward definition and
1350 // remember where that forward def'n was seen (in case it never is defined).
1351 if (Entry.first == 0) {
1352 Entry.first = StructType::create(Context, Lex.getStrVal());
1353 Entry.second = Lex.getLoc();
1355 Result = Entry.first;
1360 case lltok::LocalVarID: {
1362 if (Lex.getUIntVal() >= NumberedTypes.size())
1363 NumberedTypes.resize(Lex.getUIntVal()+1);
1364 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1366 // If the type hasn't been defined yet, create a forward definition and
1367 // remember where that forward def'n was seen (in case it never is defined).
1368 if (Entry.first == 0) {
1369 Entry.first = StructType::create(Context);
1370 Entry.second = Lex.getLoc();
1372 Result = Entry.first;
1378 // Parse the type suffixes.
1380 switch (Lex.getKind()) {
1383 if (!AllowVoid && Result->isVoidTy())
1384 return Error(TypeLoc, "void type only allowed for function results");
1387 // Type ::= Type '*'
1389 if (Result->isLabelTy())
1390 return TokError("basic block pointers are invalid");
1391 if (Result->isVoidTy())
1392 return TokError("pointers to void are invalid - use i8* instead");
1393 if (!PointerType::isValidElementType(Result))
1394 return TokError("pointer to this type is invalid");
1395 Result = PointerType::getUnqual(Result);
1399 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1400 case lltok::kw_addrspace: {
1401 if (Result->isLabelTy())
1402 return TokError("basic block pointers are invalid");
1403 if (Result->isVoidTy())
1404 return TokError("pointers to void are invalid; use i8* instead");
1405 if (!PointerType::isValidElementType(Result))
1406 return TokError("pointer to this type is invalid");
1408 if (ParseOptionalAddrSpace(AddrSpace) ||
1409 ParseToken(lltok::star, "expected '*' in address space"))
1412 Result = PointerType::get(Result, AddrSpace);
1416 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1418 if (ParseFunctionType(Result))
1425 /// ParseParameterList
1427 /// ::= '(' Arg (',' Arg)* ')'
1429 /// ::= Type OptionalAttributes Value OptionalAttributes
1430 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1431 PerFunctionState &PFS) {
1432 if (ParseToken(lltok::lparen, "expected '(' in call"))
1435 while (Lex.getKind() != lltok::rparen) {
1436 // If this isn't the first argument, we need a comma.
1437 if (!ArgList.empty() &&
1438 ParseToken(lltok::comma, "expected ',' in argument list"))
1441 // Parse the argument.
1444 AttrBuilder ArgAttrs;
1446 if (ParseType(ArgTy, ArgLoc))
1449 // Otherwise, handle normal operands.
1450 if (ParseOptionalAttrs(ArgAttrs, 0) || ParseValue(ArgTy, V, PFS))
1452 ArgList.push_back(ParamInfo(ArgLoc, V, Attributes::get(V->getContext(),
1456 Lex.Lex(); // Lex the ')'.
1462 /// ParseArgumentList - Parse the argument list for a function type or function
1464 /// ::= '(' ArgTypeListI ')'
1468 /// ::= ArgTypeList ',' '...'
1469 /// ::= ArgType (',' ArgType)*
1471 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1474 assert(Lex.getKind() == lltok::lparen);
1475 Lex.Lex(); // eat the (.
1477 if (Lex.getKind() == lltok::rparen) {
1479 } else if (Lex.getKind() == lltok::dotdotdot) {
1483 LocTy TypeLoc = Lex.getLoc();
1488 if (ParseType(ArgTy) ||
1489 ParseOptionalAttrs(Attrs, 0)) return true;
1491 if (ArgTy->isVoidTy())
1492 return Error(TypeLoc, "argument can not have void type");
1494 if (Lex.getKind() == lltok::LocalVar) {
1495 Name = Lex.getStrVal();
1499 if (!FunctionType::isValidArgumentType(ArgTy))
1500 return Error(TypeLoc, "invalid type for function argument");
1502 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1503 Attributes::get(ArgTy->getContext(),
1506 while (EatIfPresent(lltok::comma)) {
1507 // Handle ... at end of arg list.
1508 if (EatIfPresent(lltok::dotdotdot)) {
1513 // Otherwise must be an argument type.
1514 TypeLoc = Lex.getLoc();
1515 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1517 if (ArgTy->isVoidTy())
1518 return Error(TypeLoc, "argument can not have void type");
1520 if (Lex.getKind() == lltok::LocalVar) {
1521 Name = Lex.getStrVal();
1527 if (!ArgTy->isFirstClassType())
1528 return Error(TypeLoc, "invalid type for function argument");
1530 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1531 Attributes::get(ArgTy->getContext(), Attrs),
1536 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1539 /// ParseFunctionType
1540 /// ::= Type ArgumentList OptionalAttrs
1541 bool LLParser::ParseFunctionType(Type *&Result) {
1542 assert(Lex.getKind() == lltok::lparen);
1544 if (!FunctionType::isValidReturnType(Result))
1545 return TokError("invalid function return type");
1547 SmallVector<ArgInfo, 8> ArgList;
1549 if (ParseArgumentList(ArgList, isVarArg))
1552 // Reject names on the arguments lists.
1553 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1554 if (!ArgList[i].Name.empty())
1555 return Error(ArgList[i].Loc, "argument name invalid in function type");
1556 if (ArgList[i].Attrs.hasAttributes())
1557 return Error(ArgList[i].Loc,
1558 "argument attributes invalid in function type");
1561 SmallVector<Type*, 16> ArgListTy;
1562 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1563 ArgListTy.push_back(ArgList[i].Ty);
1565 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1569 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1571 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1572 SmallVector<Type*, 8> Elts;
1573 if (ParseStructBody(Elts)) return true;
1575 Result = StructType::get(Context, Elts, Packed);
1579 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1580 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1581 std::pair<Type*, LocTy> &Entry,
1583 // If the type was already defined, diagnose the redefinition.
1584 if (Entry.first && !Entry.second.isValid())
1585 return Error(TypeLoc, "redefinition of type");
1587 // If we have opaque, just return without filling in the definition for the
1588 // struct. This counts as a definition as far as the .ll file goes.
1589 if (EatIfPresent(lltok::kw_opaque)) {
1590 // This type is being defined, so clear the location to indicate this.
1591 Entry.second = SMLoc();
1593 // If this type number has never been uttered, create it.
1594 if (Entry.first == 0)
1595 Entry.first = StructType::create(Context, Name);
1596 ResultTy = Entry.first;
1600 // If the type starts with '<', then it is either a packed struct or a vector.
1601 bool isPacked = EatIfPresent(lltok::less);
1603 // If we don't have a struct, then we have a random type alias, which we
1604 // accept for compatibility with old files. These types are not allowed to be
1605 // forward referenced and not allowed to be recursive.
1606 if (Lex.getKind() != lltok::lbrace) {
1608 return Error(TypeLoc, "forward references to non-struct type");
1612 return ParseArrayVectorType(ResultTy, true);
1613 return ParseType(ResultTy);
1616 // This type is being defined, so clear the location to indicate this.
1617 Entry.second = SMLoc();
1619 // If this type number has never been uttered, create it.
1620 if (Entry.first == 0)
1621 Entry.first = StructType::create(Context, Name);
1623 StructType *STy = cast<StructType>(Entry.first);
1625 SmallVector<Type*, 8> Body;
1626 if (ParseStructBody(Body) ||
1627 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1630 STy->setBody(Body, isPacked);
1636 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1639 /// ::= '{' Type (',' Type)* '}'
1640 /// ::= '<' '{' '}' '>'
1641 /// ::= '<' '{' Type (',' Type)* '}' '>'
1642 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1643 assert(Lex.getKind() == lltok::lbrace);
1644 Lex.Lex(); // Consume the '{'
1646 // Handle the empty struct.
1647 if (EatIfPresent(lltok::rbrace))
1650 LocTy EltTyLoc = Lex.getLoc();
1652 if (ParseType(Ty)) return true;
1655 if (!StructType::isValidElementType(Ty))
1656 return Error(EltTyLoc, "invalid element type for struct");
1658 while (EatIfPresent(lltok::comma)) {
1659 EltTyLoc = Lex.getLoc();
1660 if (ParseType(Ty)) return true;
1662 if (!StructType::isValidElementType(Ty))
1663 return Error(EltTyLoc, "invalid element type for struct");
1668 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1671 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1672 /// token has already been consumed.
1674 /// ::= '[' APSINTVAL 'x' Types ']'
1675 /// ::= '<' APSINTVAL 'x' Types '>'
1676 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1677 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1678 Lex.getAPSIntVal().getBitWidth() > 64)
1679 return TokError("expected number in address space");
1681 LocTy SizeLoc = Lex.getLoc();
1682 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1685 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1688 LocTy TypeLoc = Lex.getLoc();
1690 if (ParseType(EltTy)) return true;
1692 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1693 "expected end of sequential type"))
1698 return Error(SizeLoc, "zero element vector is illegal");
1699 if ((unsigned)Size != Size)
1700 return Error(SizeLoc, "size too large for vector");
1701 if (!VectorType::isValidElementType(EltTy))
1702 return Error(TypeLoc, "invalid vector element type");
1703 Result = VectorType::get(EltTy, unsigned(Size));
1705 if (!ArrayType::isValidElementType(EltTy))
1706 return Error(TypeLoc, "invalid array element type");
1707 Result = ArrayType::get(EltTy, Size);
1712 //===----------------------------------------------------------------------===//
1713 // Function Semantic Analysis.
1714 //===----------------------------------------------------------------------===//
1716 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1718 : P(p), F(f), FunctionNumber(functionNumber) {
1720 // Insert unnamed arguments into the NumberedVals list.
1721 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1724 NumberedVals.push_back(AI);
1727 LLParser::PerFunctionState::~PerFunctionState() {
1728 // If there were any forward referenced non-basicblock values, delete them.
1729 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1730 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1731 if (!isa<BasicBlock>(I->second.first)) {
1732 I->second.first->replaceAllUsesWith(
1733 UndefValue::get(I->second.first->getType()));
1734 delete I->second.first;
1735 I->second.first = 0;
1738 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1739 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1740 if (!isa<BasicBlock>(I->second.first)) {
1741 I->second.first->replaceAllUsesWith(
1742 UndefValue::get(I->second.first->getType()));
1743 delete I->second.first;
1744 I->second.first = 0;
1748 bool LLParser::PerFunctionState::FinishFunction() {
1749 // Check to see if someone took the address of labels in this block.
1750 if (!P.ForwardRefBlockAddresses.empty()) {
1752 if (!F.getName().empty()) {
1753 FunctionID.Kind = ValID::t_GlobalName;
1754 FunctionID.StrVal = F.getName();
1756 FunctionID.Kind = ValID::t_GlobalID;
1757 FunctionID.UIntVal = FunctionNumber;
1760 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1761 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1762 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1763 // Resolve all these references.
1764 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1767 P.ForwardRefBlockAddresses.erase(FRBAI);
1771 if (!ForwardRefVals.empty())
1772 return P.Error(ForwardRefVals.begin()->second.second,
1773 "use of undefined value '%" + ForwardRefVals.begin()->first +
1775 if (!ForwardRefValIDs.empty())
1776 return P.Error(ForwardRefValIDs.begin()->second.second,
1777 "use of undefined value '%" +
1778 Twine(ForwardRefValIDs.begin()->first) + "'");
1783 /// GetVal - Get a value with the specified name or ID, creating a
1784 /// forward reference record if needed. This can return null if the value
1785 /// exists but does not have the right type.
1786 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1787 Type *Ty, LocTy Loc) {
1788 // Look this name up in the normal function symbol table.
1789 Value *Val = F.getValueSymbolTable().lookup(Name);
1791 // If this is a forward reference for the value, see if we already created a
1792 // forward ref record.
1794 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1795 I = ForwardRefVals.find(Name);
1796 if (I != ForwardRefVals.end())
1797 Val = I->second.first;
1800 // If we have the value in the symbol table or fwd-ref table, return it.
1802 if (Val->getType() == Ty) return Val;
1803 if (Ty->isLabelTy())
1804 P.Error(Loc, "'%" + Name + "' is not a basic block");
1806 P.Error(Loc, "'%" + Name + "' defined with type '" +
1807 getTypeString(Val->getType()) + "'");
1811 // Don't make placeholders with invalid type.
1812 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1813 P.Error(Loc, "invalid use of a non-first-class type");
1817 // Otherwise, create a new forward reference for this value and remember it.
1819 if (Ty->isLabelTy())
1820 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1822 FwdVal = new Argument(Ty, Name);
1824 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1828 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1830 // Look this name up in the normal function symbol table.
1831 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1833 // If this is a forward reference for the value, see if we already created a
1834 // forward ref record.
1836 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1837 I = ForwardRefValIDs.find(ID);
1838 if (I != ForwardRefValIDs.end())
1839 Val = I->second.first;
1842 // If we have the value in the symbol table or fwd-ref table, return it.
1844 if (Val->getType() == Ty) return Val;
1845 if (Ty->isLabelTy())
1846 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1848 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1849 getTypeString(Val->getType()) + "'");
1853 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1854 P.Error(Loc, "invalid use of a non-first-class type");
1858 // Otherwise, create a new forward reference for this value and remember it.
1860 if (Ty->isLabelTy())
1861 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1863 FwdVal = new Argument(Ty);
1865 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1869 /// SetInstName - After an instruction is parsed and inserted into its
1870 /// basic block, this installs its name.
1871 bool LLParser::PerFunctionState::SetInstName(int NameID,
1872 const std::string &NameStr,
1873 LocTy NameLoc, Instruction *Inst) {
1874 // If this instruction has void type, it cannot have a name or ID specified.
1875 if (Inst->getType()->isVoidTy()) {
1876 if (NameID != -1 || !NameStr.empty())
1877 return P.Error(NameLoc, "instructions returning void cannot have a name");
1881 // If this was a numbered instruction, verify that the instruction is the
1882 // expected value and resolve any forward references.
1883 if (NameStr.empty()) {
1884 // If neither a name nor an ID was specified, just use the next ID.
1886 NameID = NumberedVals.size();
1888 if (unsigned(NameID) != NumberedVals.size())
1889 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1890 Twine(NumberedVals.size()) + "'");
1892 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1893 ForwardRefValIDs.find(NameID);
1894 if (FI != ForwardRefValIDs.end()) {
1895 if (FI->second.first->getType() != Inst->getType())
1896 return P.Error(NameLoc, "instruction forward referenced with type '" +
1897 getTypeString(FI->second.first->getType()) + "'");
1898 FI->second.first->replaceAllUsesWith(Inst);
1899 delete FI->second.first;
1900 ForwardRefValIDs.erase(FI);
1903 NumberedVals.push_back(Inst);
1907 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1908 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1909 FI = ForwardRefVals.find(NameStr);
1910 if (FI != ForwardRefVals.end()) {
1911 if (FI->second.first->getType() != Inst->getType())
1912 return P.Error(NameLoc, "instruction forward referenced with type '" +
1913 getTypeString(FI->second.first->getType()) + "'");
1914 FI->second.first->replaceAllUsesWith(Inst);
1915 delete FI->second.first;
1916 ForwardRefVals.erase(FI);
1919 // Set the name on the instruction.
1920 Inst->setName(NameStr);
1922 if (Inst->getName() != NameStr)
1923 return P.Error(NameLoc, "multiple definition of local value named '" +
1928 /// GetBB - Get a basic block with the specified name or ID, creating a
1929 /// forward reference record if needed.
1930 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1932 return cast_or_null<BasicBlock>(GetVal(Name,
1933 Type::getLabelTy(F.getContext()), Loc));
1936 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1937 return cast_or_null<BasicBlock>(GetVal(ID,
1938 Type::getLabelTy(F.getContext()), Loc));
1941 /// DefineBB - Define the specified basic block, which is either named or
1942 /// unnamed. If there is an error, this returns null otherwise it returns
1943 /// the block being defined.
1944 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1948 BB = GetBB(NumberedVals.size(), Loc);
1950 BB = GetBB(Name, Loc);
1951 if (BB == 0) return 0; // Already diagnosed error.
1953 // Move the block to the end of the function. Forward ref'd blocks are
1954 // inserted wherever they happen to be referenced.
1955 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1957 // Remove the block from forward ref sets.
1959 ForwardRefValIDs.erase(NumberedVals.size());
1960 NumberedVals.push_back(BB);
1962 // BB forward references are already in the function symbol table.
1963 ForwardRefVals.erase(Name);
1969 //===----------------------------------------------------------------------===//
1971 //===----------------------------------------------------------------------===//
1973 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1974 /// type implied. For example, if we parse "4" we don't know what integer type
1975 /// it has. The value will later be combined with its type and checked for
1976 /// sanity. PFS is used to convert function-local operands of metadata (since
1977 /// metadata operands are not just parsed here but also converted to values).
1978 /// PFS can be null when we are not parsing metadata values inside a function.
1979 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1980 ID.Loc = Lex.getLoc();
1981 switch (Lex.getKind()) {
1982 default: return TokError("expected value token");
1983 case lltok::GlobalID: // @42
1984 ID.UIntVal = Lex.getUIntVal();
1985 ID.Kind = ValID::t_GlobalID;
1987 case lltok::GlobalVar: // @foo
1988 ID.StrVal = Lex.getStrVal();
1989 ID.Kind = ValID::t_GlobalName;
1991 case lltok::LocalVarID: // %42
1992 ID.UIntVal = Lex.getUIntVal();
1993 ID.Kind = ValID::t_LocalID;
1995 case lltok::LocalVar: // %foo
1996 ID.StrVal = Lex.getStrVal();
1997 ID.Kind = ValID::t_LocalName;
1999 case lltok::exclaim: // !42, !{...}, or !"foo"
2000 return ParseMetadataValue(ID, PFS);
2002 ID.APSIntVal = Lex.getAPSIntVal();
2003 ID.Kind = ValID::t_APSInt;
2005 case lltok::APFloat:
2006 ID.APFloatVal = Lex.getAPFloatVal();
2007 ID.Kind = ValID::t_APFloat;
2009 case lltok::kw_true:
2010 ID.ConstantVal = ConstantInt::getTrue(Context);
2011 ID.Kind = ValID::t_Constant;
2013 case lltok::kw_false:
2014 ID.ConstantVal = ConstantInt::getFalse(Context);
2015 ID.Kind = ValID::t_Constant;
2017 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2018 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2019 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2021 case lltok::lbrace: {
2022 // ValID ::= '{' ConstVector '}'
2024 SmallVector<Constant*, 16> Elts;
2025 if (ParseGlobalValueVector(Elts) ||
2026 ParseToken(lltok::rbrace, "expected end of struct constant"))
2029 ID.ConstantStructElts = new Constant*[Elts.size()];
2030 ID.UIntVal = Elts.size();
2031 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2032 ID.Kind = ValID::t_ConstantStruct;
2036 // ValID ::= '<' ConstVector '>' --> Vector.
2037 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2039 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2041 SmallVector<Constant*, 16> Elts;
2042 LocTy FirstEltLoc = Lex.getLoc();
2043 if (ParseGlobalValueVector(Elts) ||
2045 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2046 ParseToken(lltok::greater, "expected end of constant"))
2049 if (isPackedStruct) {
2050 ID.ConstantStructElts = new Constant*[Elts.size()];
2051 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2052 ID.UIntVal = Elts.size();
2053 ID.Kind = ValID::t_PackedConstantStruct;
2058 return Error(ID.Loc, "constant vector must not be empty");
2060 if (!Elts[0]->getType()->isIntegerTy() &&
2061 !Elts[0]->getType()->isFloatingPointTy() &&
2062 !Elts[0]->getType()->isPointerTy())
2063 return Error(FirstEltLoc,
2064 "vector elements must have integer, pointer or floating point type");
2066 // Verify that all the vector elements have the same type.
2067 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2068 if (Elts[i]->getType() != Elts[0]->getType())
2069 return Error(FirstEltLoc,
2070 "vector element #" + Twine(i) +
2071 " is not of type '" + getTypeString(Elts[0]->getType()));
2073 ID.ConstantVal = ConstantVector::get(Elts);
2074 ID.Kind = ValID::t_Constant;
2077 case lltok::lsquare: { // Array Constant
2079 SmallVector<Constant*, 16> Elts;
2080 LocTy FirstEltLoc = Lex.getLoc();
2081 if (ParseGlobalValueVector(Elts) ||
2082 ParseToken(lltok::rsquare, "expected end of array constant"))
2085 // Handle empty element.
2087 // Use undef instead of an array because it's inconvenient to determine
2088 // the element type at this point, there being no elements to examine.
2089 ID.Kind = ValID::t_EmptyArray;
2093 if (!Elts[0]->getType()->isFirstClassType())
2094 return Error(FirstEltLoc, "invalid array element type: " +
2095 getTypeString(Elts[0]->getType()));
2097 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2099 // Verify all elements are correct type!
2100 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2101 if (Elts[i]->getType() != Elts[0]->getType())
2102 return Error(FirstEltLoc,
2103 "array element #" + Twine(i) +
2104 " is not of type '" + getTypeString(Elts[0]->getType()));
2107 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2108 ID.Kind = ValID::t_Constant;
2111 case lltok::kw_c: // c "foo"
2113 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2115 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2116 ID.Kind = ValID::t_Constant;
2119 case lltok::kw_asm: {
2120 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2121 bool HasSideEffect, AlignStack, AsmDialect;
2123 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2124 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2125 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2126 ParseStringConstant(ID.StrVal) ||
2127 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2128 ParseToken(lltok::StringConstant, "expected constraint string"))
2130 ID.StrVal2 = Lex.getStrVal();
2131 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2132 (unsigned(AsmDialect)<<2);
2133 ID.Kind = ValID::t_InlineAsm;
2137 case lltok::kw_blockaddress: {
2138 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2142 LocTy FnLoc, LabelLoc;
2144 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2146 ParseToken(lltok::comma, "expected comma in block address expression")||
2147 ParseValID(Label) ||
2148 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2151 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2152 return Error(Fn.Loc, "expected function name in blockaddress");
2153 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2154 return Error(Label.Loc, "expected basic block name in blockaddress");
2156 // Make a global variable as a placeholder for this reference.
2157 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2158 false, GlobalValue::InternalLinkage,
2160 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2161 ID.ConstantVal = FwdRef;
2162 ID.Kind = ValID::t_Constant;
2166 case lltok::kw_trunc:
2167 case lltok::kw_zext:
2168 case lltok::kw_sext:
2169 case lltok::kw_fptrunc:
2170 case lltok::kw_fpext:
2171 case lltok::kw_bitcast:
2172 case lltok::kw_uitofp:
2173 case lltok::kw_sitofp:
2174 case lltok::kw_fptoui:
2175 case lltok::kw_fptosi:
2176 case lltok::kw_inttoptr:
2177 case lltok::kw_ptrtoint: {
2178 unsigned Opc = Lex.getUIntVal();
2182 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2183 ParseGlobalTypeAndValue(SrcVal) ||
2184 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2185 ParseType(DestTy) ||
2186 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2188 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2189 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2190 getTypeString(SrcVal->getType()) + "' to '" +
2191 getTypeString(DestTy) + "'");
2192 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2194 ID.Kind = ValID::t_Constant;
2197 case lltok::kw_extractvalue: {
2200 SmallVector<unsigned, 4> Indices;
2201 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2202 ParseGlobalTypeAndValue(Val) ||
2203 ParseIndexList(Indices) ||
2204 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2207 if (!Val->getType()->isAggregateType())
2208 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2209 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2210 return Error(ID.Loc, "invalid indices for extractvalue");
2211 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2212 ID.Kind = ValID::t_Constant;
2215 case lltok::kw_insertvalue: {
2217 Constant *Val0, *Val1;
2218 SmallVector<unsigned, 4> Indices;
2219 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2220 ParseGlobalTypeAndValue(Val0) ||
2221 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2222 ParseGlobalTypeAndValue(Val1) ||
2223 ParseIndexList(Indices) ||
2224 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2226 if (!Val0->getType()->isAggregateType())
2227 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2228 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2229 return Error(ID.Loc, "invalid indices for insertvalue");
2230 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2231 ID.Kind = ValID::t_Constant;
2234 case lltok::kw_icmp:
2235 case lltok::kw_fcmp: {
2236 unsigned PredVal, Opc = Lex.getUIntVal();
2237 Constant *Val0, *Val1;
2239 if (ParseCmpPredicate(PredVal, Opc) ||
2240 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2241 ParseGlobalTypeAndValue(Val0) ||
2242 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2243 ParseGlobalTypeAndValue(Val1) ||
2244 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2247 if (Val0->getType() != Val1->getType())
2248 return Error(ID.Loc, "compare operands must have the same type");
2250 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2252 if (Opc == Instruction::FCmp) {
2253 if (!Val0->getType()->isFPOrFPVectorTy())
2254 return Error(ID.Loc, "fcmp requires floating point operands");
2255 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2257 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2258 if (!Val0->getType()->isIntOrIntVectorTy() &&
2259 !Val0->getType()->getScalarType()->isPointerTy())
2260 return Error(ID.Loc, "icmp requires pointer or integer operands");
2261 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2263 ID.Kind = ValID::t_Constant;
2267 // Binary Operators.
2269 case lltok::kw_fadd:
2271 case lltok::kw_fsub:
2273 case lltok::kw_fmul:
2274 case lltok::kw_udiv:
2275 case lltok::kw_sdiv:
2276 case lltok::kw_fdiv:
2277 case lltok::kw_urem:
2278 case lltok::kw_srem:
2279 case lltok::kw_frem:
2281 case lltok::kw_lshr:
2282 case lltok::kw_ashr: {
2286 unsigned Opc = Lex.getUIntVal();
2287 Constant *Val0, *Val1;
2289 LocTy ModifierLoc = Lex.getLoc();
2290 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2291 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2292 if (EatIfPresent(lltok::kw_nuw))
2294 if (EatIfPresent(lltok::kw_nsw)) {
2296 if (EatIfPresent(lltok::kw_nuw))
2299 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2300 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2301 if (EatIfPresent(lltok::kw_exact))
2304 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2305 ParseGlobalTypeAndValue(Val0) ||
2306 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2307 ParseGlobalTypeAndValue(Val1) ||
2308 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2310 if (Val0->getType() != Val1->getType())
2311 return Error(ID.Loc, "operands of constexpr must have same type");
2312 if (!Val0->getType()->isIntOrIntVectorTy()) {
2314 return Error(ModifierLoc, "nuw only applies to integer operations");
2316 return Error(ModifierLoc, "nsw only applies to integer operations");
2318 // Check that the type is valid for the operator.
2320 case Instruction::Add:
2321 case Instruction::Sub:
2322 case Instruction::Mul:
2323 case Instruction::UDiv:
2324 case Instruction::SDiv:
2325 case Instruction::URem:
2326 case Instruction::SRem:
2327 case Instruction::Shl:
2328 case Instruction::AShr:
2329 case Instruction::LShr:
2330 if (!Val0->getType()->isIntOrIntVectorTy())
2331 return Error(ID.Loc, "constexpr requires integer operands");
2333 case Instruction::FAdd:
2334 case Instruction::FSub:
2335 case Instruction::FMul:
2336 case Instruction::FDiv:
2337 case Instruction::FRem:
2338 if (!Val0->getType()->isFPOrFPVectorTy())
2339 return Error(ID.Loc, "constexpr requires fp operands");
2341 default: llvm_unreachable("Unknown binary operator!");
2344 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2345 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2346 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2347 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2349 ID.Kind = ValID::t_Constant;
2353 // Logical Operations
2356 case lltok::kw_xor: {
2357 unsigned Opc = Lex.getUIntVal();
2358 Constant *Val0, *Val1;
2360 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2361 ParseGlobalTypeAndValue(Val0) ||
2362 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2363 ParseGlobalTypeAndValue(Val1) ||
2364 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2366 if (Val0->getType() != Val1->getType())
2367 return Error(ID.Loc, "operands of constexpr must have same type");
2368 if (!Val0->getType()->isIntOrIntVectorTy())
2369 return Error(ID.Loc,
2370 "constexpr requires integer or integer vector operands");
2371 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2372 ID.Kind = ValID::t_Constant;
2376 case lltok::kw_getelementptr:
2377 case lltok::kw_shufflevector:
2378 case lltok::kw_insertelement:
2379 case lltok::kw_extractelement:
2380 case lltok::kw_select: {
2381 unsigned Opc = Lex.getUIntVal();
2382 SmallVector<Constant*, 16> Elts;
2383 bool InBounds = false;
2385 if (Opc == Instruction::GetElementPtr)
2386 InBounds = EatIfPresent(lltok::kw_inbounds);
2387 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2388 ParseGlobalValueVector(Elts) ||
2389 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2392 if (Opc == Instruction::GetElementPtr) {
2393 if (Elts.size() == 0 ||
2394 !Elts[0]->getType()->getScalarType()->isPointerTy())
2395 return Error(ID.Loc, "getelementptr requires pointer operand");
2397 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2398 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2399 return Error(ID.Loc, "invalid indices for getelementptr");
2400 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2402 } else if (Opc == Instruction::Select) {
2403 if (Elts.size() != 3)
2404 return Error(ID.Loc, "expected three operands to select");
2405 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2407 return Error(ID.Loc, Reason);
2408 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2409 } else if (Opc == Instruction::ShuffleVector) {
2410 if (Elts.size() != 3)
2411 return Error(ID.Loc, "expected three operands to shufflevector");
2412 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2413 return Error(ID.Loc, "invalid operands to shufflevector");
2415 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2416 } else if (Opc == Instruction::ExtractElement) {
2417 if (Elts.size() != 2)
2418 return Error(ID.Loc, "expected two operands to extractelement");
2419 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2420 return Error(ID.Loc, "invalid extractelement operands");
2421 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2423 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2424 if (Elts.size() != 3)
2425 return Error(ID.Loc, "expected three operands to insertelement");
2426 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2427 return Error(ID.Loc, "invalid insertelement operands");
2429 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2432 ID.Kind = ValID::t_Constant;
2441 /// ParseGlobalValue - Parse a global value with the specified type.
2442 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2446 bool Parsed = ParseValID(ID) ||
2447 ConvertValIDToValue(Ty, ID, V, NULL);
2448 if (V && !(C = dyn_cast<Constant>(V)))
2449 return Error(ID.Loc, "global values must be constants");
2453 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2455 return ParseType(Ty) ||
2456 ParseGlobalValue(Ty, V);
2459 /// ParseGlobalValueVector
2461 /// ::= TypeAndValue (',' TypeAndValue)*
2462 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2464 if (Lex.getKind() == lltok::rbrace ||
2465 Lex.getKind() == lltok::rsquare ||
2466 Lex.getKind() == lltok::greater ||
2467 Lex.getKind() == lltok::rparen)
2471 if (ParseGlobalTypeAndValue(C)) return true;
2474 while (EatIfPresent(lltok::comma)) {
2475 if (ParseGlobalTypeAndValue(C)) return true;
2482 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2483 assert(Lex.getKind() == lltok::lbrace);
2486 SmallVector<Value*, 16> Elts;
2487 if (ParseMDNodeVector(Elts, PFS) ||
2488 ParseToken(lltok::rbrace, "expected end of metadata node"))
2491 ID.MDNodeVal = MDNode::get(Context, Elts);
2492 ID.Kind = ValID::t_MDNode;
2496 /// ParseMetadataValue
2500 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2501 assert(Lex.getKind() == lltok::exclaim);
2506 if (Lex.getKind() == lltok::lbrace)
2507 return ParseMetadataListValue(ID, PFS);
2509 // Standalone metadata reference
2511 if (Lex.getKind() == lltok::APSInt) {
2512 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2513 ID.Kind = ValID::t_MDNode;
2518 // ::= '!' STRINGCONSTANT
2519 if (ParseMDString(ID.MDStringVal)) return true;
2520 ID.Kind = ValID::t_MDString;
2525 //===----------------------------------------------------------------------===//
2526 // Function Parsing.
2527 //===----------------------------------------------------------------------===//
2529 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2530 PerFunctionState *PFS) {
2531 if (Ty->isFunctionTy())
2532 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2535 case ValID::t_LocalID:
2536 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2537 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2539 case ValID::t_LocalName:
2540 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2541 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2543 case ValID::t_InlineAsm: {
2544 PointerType *PTy = dyn_cast<PointerType>(Ty);
2546 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2547 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2548 return Error(ID.Loc, "invalid type for inline asm constraint string");
2549 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2550 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2553 case ValID::t_MDNode:
2554 if (!Ty->isMetadataTy())
2555 return Error(ID.Loc, "metadata value must have metadata type");
2558 case ValID::t_MDString:
2559 if (!Ty->isMetadataTy())
2560 return Error(ID.Loc, "metadata value must have metadata type");
2563 case ValID::t_GlobalName:
2564 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2566 case ValID::t_GlobalID:
2567 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2569 case ValID::t_APSInt:
2570 if (!Ty->isIntegerTy())
2571 return Error(ID.Loc, "integer constant must have integer type");
2572 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2573 V = ConstantInt::get(Context, ID.APSIntVal);
2575 case ValID::t_APFloat:
2576 if (!Ty->isFloatingPointTy() ||
2577 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2578 return Error(ID.Loc, "floating point constant invalid for type");
2580 // The lexer has no type info, so builds all half, float, and double FP
2581 // constants as double. Fix this here. Long double does not need this.
2582 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2585 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2587 else if (Ty->isFloatTy())
2588 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2591 V = ConstantFP::get(Context, ID.APFloatVal);
2593 if (V->getType() != Ty)
2594 return Error(ID.Loc, "floating point constant does not have type '" +
2595 getTypeString(Ty) + "'");
2599 if (!Ty->isPointerTy())
2600 return Error(ID.Loc, "null must be a pointer type");
2601 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2603 case ValID::t_Undef:
2604 // FIXME: LabelTy should not be a first-class type.
2605 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2606 return Error(ID.Loc, "invalid type for undef constant");
2607 V = UndefValue::get(Ty);
2609 case ValID::t_EmptyArray:
2610 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2611 return Error(ID.Loc, "invalid empty array initializer");
2612 V = UndefValue::get(Ty);
2615 // FIXME: LabelTy should not be a first-class type.
2616 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2617 return Error(ID.Loc, "invalid type for null constant");
2618 V = Constant::getNullValue(Ty);
2620 case ValID::t_Constant:
2621 if (ID.ConstantVal->getType() != Ty)
2622 return Error(ID.Loc, "constant expression type mismatch");
2626 case ValID::t_ConstantStruct:
2627 case ValID::t_PackedConstantStruct:
2628 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2629 if (ST->getNumElements() != ID.UIntVal)
2630 return Error(ID.Loc,
2631 "initializer with struct type has wrong # elements");
2632 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2633 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2635 // Verify that the elements are compatible with the structtype.
2636 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2637 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2638 return Error(ID.Loc, "element " + Twine(i) +
2639 " of struct initializer doesn't match struct element type");
2641 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2644 return Error(ID.Loc, "constant expression type mismatch");
2647 llvm_unreachable("Invalid ValID");
2650 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2653 return ParseValID(ID, PFS) ||
2654 ConvertValIDToValue(Ty, ID, V, PFS);
2657 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2659 return ParseType(Ty) ||
2660 ParseValue(Ty, V, PFS);
2663 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2664 PerFunctionState &PFS) {
2667 if (ParseTypeAndValue(V, PFS)) return true;
2668 if (!isa<BasicBlock>(V))
2669 return Error(Loc, "expected a basic block");
2670 BB = cast<BasicBlock>(V);
2676 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2677 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2678 /// OptionalAlign OptGC
2679 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2680 // Parse the linkage.
2681 LocTy LinkageLoc = Lex.getLoc();
2684 unsigned Visibility;
2685 AttrBuilder RetAttrs;
2688 LocTy RetTypeLoc = Lex.getLoc();
2689 if (ParseOptionalLinkage(Linkage) ||
2690 ParseOptionalVisibility(Visibility) ||
2691 ParseOptionalCallingConv(CC) ||
2692 ParseOptionalAttrs(RetAttrs, 1) ||
2693 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2696 // Verify that the linkage is ok.
2697 switch ((GlobalValue::LinkageTypes)Linkage) {
2698 case GlobalValue::ExternalLinkage:
2699 break; // always ok.
2700 case GlobalValue::DLLImportLinkage:
2701 case GlobalValue::ExternalWeakLinkage:
2703 return Error(LinkageLoc, "invalid linkage for function definition");
2705 case GlobalValue::PrivateLinkage:
2706 case GlobalValue::LinkerPrivateLinkage:
2707 case GlobalValue::LinkerPrivateWeakLinkage:
2708 case GlobalValue::InternalLinkage:
2709 case GlobalValue::AvailableExternallyLinkage:
2710 case GlobalValue::LinkOnceAnyLinkage:
2711 case GlobalValue::LinkOnceODRLinkage:
2712 case GlobalValue::LinkOnceODRAutoHideLinkage:
2713 case GlobalValue::WeakAnyLinkage:
2714 case GlobalValue::WeakODRLinkage:
2715 case GlobalValue::DLLExportLinkage:
2717 return Error(LinkageLoc, "invalid linkage for function declaration");
2719 case GlobalValue::AppendingLinkage:
2720 case GlobalValue::CommonLinkage:
2721 return Error(LinkageLoc, "invalid function linkage type");
2724 if (!FunctionType::isValidReturnType(RetType))
2725 return Error(RetTypeLoc, "invalid function return type");
2727 LocTy NameLoc = Lex.getLoc();
2729 std::string FunctionName;
2730 if (Lex.getKind() == lltok::GlobalVar) {
2731 FunctionName = Lex.getStrVal();
2732 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2733 unsigned NameID = Lex.getUIntVal();
2735 if (NameID != NumberedVals.size())
2736 return TokError("function expected to be numbered '%" +
2737 Twine(NumberedVals.size()) + "'");
2739 return TokError("expected function name");
2744 if (Lex.getKind() != lltok::lparen)
2745 return TokError("expected '(' in function argument list");
2747 SmallVector<ArgInfo, 8> ArgList;
2749 AttrBuilder FuncAttrs;
2750 std::string Section;
2754 LocTy UnnamedAddrLoc;
2756 if (ParseArgumentList(ArgList, isVarArg) ||
2757 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2759 ParseOptionalAttrs(FuncAttrs, 2) ||
2760 (EatIfPresent(lltok::kw_section) &&
2761 ParseStringConstant(Section)) ||
2762 ParseOptionalAlignment(Alignment) ||
2763 (EatIfPresent(lltok::kw_gc) &&
2764 ParseStringConstant(GC)))
2767 // If the alignment was parsed as an attribute, move to the alignment field.
2768 if (FuncAttrs.hasAlignmentAttr()) {
2769 Alignment = FuncAttrs.getAlignment();
2770 FuncAttrs.removeAttribute(Attributes::Alignment);
2773 // Okay, if we got here, the function is syntactically valid. Convert types
2774 // and do semantic checks.
2775 std::vector<Type*> ParamTypeList;
2776 SmallVector<AttributeWithIndex, 8> Attrs;
2778 if (RetAttrs.hasAttributes())
2780 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
2781 Attributes::get(RetType->getContext(),
2784 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2785 ParamTypeList.push_back(ArgList[i].Ty);
2786 if (ArgList[i].Attrs.hasAttributes())
2787 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2790 if (FuncAttrs.hasAttributes())
2792 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
2793 Attributes::get(RetType->getContext(),
2796 AttrListPtr PAL = AttrListPtr::get(Attrs);
2798 if (PAL.getParamAttributes(1).hasAttribute(Attributes::StructRet) &&
2799 !RetType->isVoidTy())
2800 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2803 FunctionType::get(RetType, ParamTypeList, isVarArg);
2804 PointerType *PFT = PointerType::getUnqual(FT);
2807 if (!FunctionName.empty()) {
2808 // If this was a definition of a forward reference, remove the definition
2809 // from the forward reference table and fill in the forward ref.
2810 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2811 ForwardRefVals.find(FunctionName);
2812 if (FRVI != ForwardRefVals.end()) {
2813 Fn = M->getFunction(FunctionName);
2815 return Error(FRVI->second.second, "invalid forward reference to "
2816 "function as global value!");
2817 if (Fn->getType() != PFT)
2818 return Error(FRVI->second.second, "invalid forward reference to "
2819 "function '" + FunctionName + "' with wrong type!");
2821 ForwardRefVals.erase(FRVI);
2822 } else if ((Fn = M->getFunction(FunctionName))) {
2823 // Reject redefinitions.
2824 return Error(NameLoc, "invalid redefinition of function '" +
2825 FunctionName + "'");
2826 } else if (M->getNamedValue(FunctionName)) {
2827 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2831 // If this is a definition of a forward referenced function, make sure the
2833 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2834 = ForwardRefValIDs.find(NumberedVals.size());
2835 if (I != ForwardRefValIDs.end()) {
2836 Fn = cast<Function>(I->second.first);
2837 if (Fn->getType() != PFT)
2838 return Error(NameLoc, "type of definition and forward reference of '@" +
2839 Twine(NumberedVals.size()) + "' disagree");
2840 ForwardRefValIDs.erase(I);
2845 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2846 else // Move the forward-reference to the correct spot in the module.
2847 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2849 if (FunctionName.empty())
2850 NumberedVals.push_back(Fn);
2852 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2853 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2854 Fn->setCallingConv(CC);
2855 Fn->setAttributes(PAL);
2856 Fn->setUnnamedAddr(UnnamedAddr);
2857 Fn->setAlignment(Alignment);
2858 Fn->setSection(Section);
2859 if (!GC.empty()) Fn->setGC(GC.c_str());
2861 // Add all of the arguments we parsed to the function.
2862 Function::arg_iterator ArgIt = Fn->arg_begin();
2863 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2864 // If the argument has a name, insert it into the argument symbol table.
2865 if (ArgList[i].Name.empty()) continue;
2867 // Set the name, if it conflicted, it will be auto-renamed.
2868 ArgIt->setName(ArgList[i].Name);
2870 if (ArgIt->getName() != ArgList[i].Name)
2871 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2872 ArgList[i].Name + "'");
2879 /// ParseFunctionBody
2880 /// ::= '{' BasicBlock+ '}'
2882 bool LLParser::ParseFunctionBody(Function &Fn) {
2883 if (Lex.getKind() != lltok::lbrace)
2884 return TokError("expected '{' in function body");
2885 Lex.Lex(); // eat the {.
2887 int FunctionNumber = -1;
2888 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2890 PerFunctionState PFS(*this, Fn, FunctionNumber);
2892 // We need at least one basic block.
2893 if (Lex.getKind() == lltok::rbrace)
2894 return TokError("function body requires at least one basic block");
2896 while (Lex.getKind() != lltok::rbrace)
2897 if (ParseBasicBlock(PFS)) return true;
2902 // Verify function is ok.
2903 return PFS.FinishFunction();
2907 /// ::= LabelStr? Instruction*
2908 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2909 // If this basic block starts out with a name, remember it.
2911 LocTy NameLoc = Lex.getLoc();
2912 if (Lex.getKind() == lltok::LabelStr) {
2913 Name = Lex.getStrVal();
2917 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2918 if (BB == 0) return true;
2920 std::string NameStr;
2922 // Parse the instructions in this block until we get a terminator.
2924 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2926 // This instruction may have three possibilities for a name: a) none
2927 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2928 LocTy NameLoc = Lex.getLoc();
2932 if (Lex.getKind() == lltok::LocalVarID) {
2933 NameID = Lex.getUIntVal();
2935 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2937 } else if (Lex.getKind() == lltok::LocalVar) {
2938 NameStr = Lex.getStrVal();
2940 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2944 switch (ParseInstruction(Inst, BB, PFS)) {
2945 default: llvm_unreachable("Unknown ParseInstruction result!");
2946 case InstError: return true;
2948 BB->getInstList().push_back(Inst);
2950 // With a normal result, we check to see if the instruction is followed by
2951 // a comma and metadata.
2952 if (EatIfPresent(lltok::comma))
2953 if (ParseInstructionMetadata(Inst, &PFS))
2956 case InstExtraComma:
2957 BB->getInstList().push_back(Inst);
2959 // If the instruction parser ate an extra comma at the end of it, it
2960 // *must* be followed by metadata.
2961 if (ParseInstructionMetadata(Inst, &PFS))
2966 // Set the name on the instruction.
2967 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2968 } while (!isa<TerminatorInst>(Inst));
2973 //===----------------------------------------------------------------------===//
2974 // Instruction Parsing.
2975 //===----------------------------------------------------------------------===//
2977 /// ParseInstruction - Parse one of the many different instructions.
2979 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2980 PerFunctionState &PFS) {
2981 lltok::Kind Token = Lex.getKind();
2982 if (Token == lltok::Eof)
2983 return TokError("found end of file when expecting more instructions");
2984 LocTy Loc = Lex.getLoc();
2985 unsigned KeywordVal = Lex.getUIntVal();
2986 Lex.Lex(); // Eat the keyword.
2989 default: return Error(Loc, "expected instruction opcode");
2990 // Terminator Instructions.
2991 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2992 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2993 case lltok::kw_br: return ParseBr(Inst, PFS);
2994 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2995 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2996 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2997 case lltok::kw_resume: return ParseResume(Inst, PFS);
2998 // Binary Operators.
3002 case lltok::kw_shl: {
3003 bool NUW = EatIfPresent(lltok::kw_nuw);
3004 bool NSW = EatIfPresent(lltok::kw_nsw);
3005 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3007 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3009 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3010 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3013 case lltok::kw_fadd:
3014 case lltok::kw_fsub:
3015 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3017 case lltok::kw_sdiv:
3018 case lltok::kw_udiv:
3019 case lltok::kw_lshr:
3020 case lltok::kw_ashr: {
3021 bool Exact = EatIfPresent(lltok::kw_exact);
3023 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3024 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3028 case lltok::kw_urem:
3029 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3030 case lltok::kw_fdiv:
3031 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3034 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3035 case lltok::kw_icmp:
3036 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3038 case lltok::kw_trunc:
3039 case lltok::kw_zext:
3040 case lltok::kw_sext:
3041 case lltok::kw_fptrunc:
3042 case lltok::kw_fpext:
3043 case lltok::kw_bitcast:
3044 case lltok::kw_uitofp:
3045 case lltok::kw_sitofp:
3046 case lltok::kw_fptoui:
3047 case lltok::kw_fptosi:
3048 case lltok::kw_inttoptr:
3049 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3051 case lltok::kw_select: return ParseSelect(Inst, PFS);
3052 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3053 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3054 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3055 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3056 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3057 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3058 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3059 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3061 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3062 case lltok::kw_load: return ParseLoad(Inst, PFS);
3063 case lltok::kw_store: return ParseStore(Inst, PFS);
3064 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3065 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3066 case lltok::kw_fence: return ParseFence(Inst, PFS);
3067 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3068 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3069 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3073 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3074 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3075 if (Opc == Instruction::FCmp) {
3076 switch (Lex.getKind()) {
3077 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3078 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3079 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3080 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3081 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3082 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3083 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3084 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3085 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3086 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3087 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3088 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3089 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3090 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3091 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3092 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3093 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3096 switch (Lex.getKind()) {
3097 default: TokError("expected icmp predicate (e.g. 'eq')");
3098 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3099 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3100 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3101 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3102 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3103 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3104 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3105 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3106 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3107 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3114 //===----------------------------------------------------------------------===//
3115 // Terminator Instructions.
3116 //===----------------------------------------------------------------------===//
3118 /// ParseRet - Parse a return instruction.
3119 /// ::= 'ret' void (',' !dbg, !1)*
3120 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3121 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3122 PerFunctionState &PFS) {
3123 SMLoc TypeLoc = Lex.getLoc();
3125 if (ParseType(Ty, true /*void allowed*/)) return true;
3127 Type *ResType = PFS.getFunction().getReturnType();
3129 if (Ty->isVoidTy()) {
3130 if (!ResType->isVoidTy())
3131 return Error(TypeLoc, "value doesn't match function result type '" +
3132 getTypeString(ResType) + "'");
3134 Inst = ReturnInst::Create(Context);
3139 if (ParseValue(Ty, RV, PFS)) return true;
3141 if (ResType != RV->getType())
3142 return Error(TypeLoc, "value doesn't match function result type '" +
3143 getTypeString(ResType) + "'");
3145 Inst = ReturnInst::Create(Context, RV);
3151 /// ::= 'br' TypeAndValue
3152 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3153 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3156 BasicBlock *Op1, *Op2;
3157 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3159 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3160 Inst = BranchInst::Create(BB);
3164 if (Op0->getType() != Type::getInt1Ty(Context))
3165 return Error(Loc, "branch condition must have 'i1' type");
3167 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3168 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3169 ParseToken(lltok::comma, "expected ',' after true destination") ||
3170 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3173 Inst = BranchInst::Create(Op1, Op2, Op0);
3179 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3181 /// ::= (TypeAndValue ',' TypeAndValue)*
3182 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3183 LocTy CondLoc, BBLoc;
3185 BasicBlock *DefaultBB;
3186 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3187 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3188 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3189 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3192 if (!Cond->getType()->isIntegerTy())
3193 return Error(CondLoc, "switch condition must have integer type");
3195 // Parse the jump table pairs.
3196 SmallPtrSet<Value*, 32> SeenCases;
3197 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3198 while (Lex.getKind() != lltok::rsquare) {
3202 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3203 ParseToken(lltok::comma, "expected ',' after case value") ||
3204 ParseTypeAndBasicBlock(DestBB, PFS))
3207 if (!SeenCases.insert(Constant))
3208 return Error(CondLoc, "duplicate case value in switch");
3209 if (!isa<ConstantInt>(Constant))
3210 return Error(CondLoc, "case value is not a constant integer");
3212 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3215 Lex.Lex(); // Eat the ']'.
3217 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3218 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3219 SI->addCase(Table[i].first, Table[i].second);
3226 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3227 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3230 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3231 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3232 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3235 if (!Address->getType()->isPointerTy())
3236 return Error(AddrLoc, "indirectbr address must have pointer type");
3238 // Parse the destination list.
3239 SmallVector<BasicBlock*, 16> DestList;
3241 if (Lex.getKind() != lltok::rsquare) {
3243 if (ParseTypeAndBasicBlock(DestBB, PFS))
3245 DestList.push_back(DestBB);
3247 while (EatIfPresent(lltok::comma)) {
3248 if (ParseTypeAndBasicBlock(DestBB, PFS))
3250 DestList.push_back(DestBB);
3254 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3257 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3258 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3259 IBI->addDestination(DestList[i]);
3266 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3267 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3268 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3269 LocTy CallLoc = Lex.getLoc();
3270 AttrBuilder RetAttrs, FnAttrs;
3275 SmallVector<ParamInfo, 16> ArgList;
3277 BasicBlock *NormalBB, *UnwindBB;
3278 if (ParseOptionalCallingConv(CC) ||
3279 ParseOptionalAttrs(RetAttrs, 1) ||
3280 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3281 ParseValID(CalleeID) ||
3282 ParseParameterList(ArgList, PFS) ||
3283 ParseOptionalAttrs(FnAttrs, 2) ||
3284 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3285 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3286 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3287 ParseTypeAndBasicBlock(UnwindBB, PFS))
3290 // If RetType is a non-function pointer type, then this is the short syntax
3291 // for the call, which means that RetType is just the return type. Infer the
3292 // rest of the function argument types from the arguments that are present.
3293 PointerType *PFTy = 0;
3294 FunctionType *Ty = 0;
3295 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3296 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3297 // Pull out the types of all of the arguments...
3298 std::vector<Type*> ParamTypes;
3299 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3300 ParamTypes.push_back(ArgList[i].V->getType());
3302 if (!FunctionType::isValidReturnType(RetType))
3303 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3305 Ty = FunctionType::get(RetType, ParamTypes, false);
3306 PFTy = PointerType::getUnqual(Ty);
3309 // Look up the callee.
3311 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3313 // Set up the Attributes for the function.
3314 SmallVector<AttributeWithIndex, 8> Attrs;
3315 if (RetAttrs.hasAttributes())
3317 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3318 Attributes::get(Callee->getContext(),
3321 SmallVector<Value*, 8> Args;
3323 // Loop through FunctionType's arguments and ensure they are specified
3324 // correctly. Also, gather any parameter attributes.
3325 FunctionType::param_iterator I = Ty->param_begin();
3326 FunctionType::param_iterator E = Ty->param_end();
3327 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3328 Type *ExpectedTy = 0;
3331 } else if (!Ty->isVarArg()) {
3332 return Error(ArgList[i].Loc, "too many arguments specified");
3335 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3336 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3337 getTypeString(ExpectedTy) + "'");
3338 Args.push_back(ArgList[i].V);
3339 if (ArgList[i].Attrs.hasAttributes())
3340 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3344 return Error(CallLoc, "not enough parameters specified for call");
3346 if (FnAttrs.hasAttributes())
3348 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3349 Attributes::get(Callee->getContext(),
3352 // Finish off the Attributes and check them
3353 AttrListPtr PAL = AttrListPtr::get(Attrs);
3355 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3356 II->setCallingConv(CC);
3357 II->setAttributes(PAL);
3363 /// ::= 'resume' TypeAndValue
3364 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3365 Value *Exn; LocTy ExnLoc;
3366 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3369 ResumeInst *RI = ResumeInst::Create(Exn);
3374 //===----------------------------------------------------------------------===//
3375 // Binary Operators.
3376 //===----------------------------------------------------------------------===//
3379 /// ::= ArithmeticOps TypeAndValue ',' Value
3381 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3382 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3383 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3384 unsigned Opc, unsigned OperandType) {
3385 LocTy Loc; Value *LHS, *RHS;
3386 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3387 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3388 ParseValue(LHS->getType(), RHS, PFS))
3392 switch (OperandType) {
3393 default: llvm_unreachable("Unknown operand type!");
3394 case 0: // int or FP.
3395 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3396 LHS->getType()->isFPOrFPVectorTy();
3398 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3399 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3403 return Error(Loc, "invalid operand type for instruction");
3405 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3410 /// ::= ArithmeticOps TypeAndValue ',' Value {
3411 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3413 LocTy Loc; Value *LHS, *RHS;
3414 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3415 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3416 ParseValue(LHS->getType(), RHS, PFS))
3419 if (!LHS->getType()->isIntOrIntVectorTy())
3420 return Error(Loc,"instruction requires integer or integer vector operands");
3422 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3428 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3429 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3430 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3432 // Parse the integer/fp comparison predicate.
3436 if (ParseCmpPredicate(Pred, Opc) ||
3437 ParseTypeAndValue(LHS, Loc, PFS) ||
3438 ParseToken(lltok::comma, "expected ',' after compare value") ||
3439 ParseValue(LHS->getType(), RHS, PFS))
3442 if (Opc == Instruction::FCmp) {
3443 if (!LHS->getType()->isFPOrFPVectorTy())
3444 return Error(Loc, "fcmp requires floating point operands");
3445 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3447 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3448 if (!LHS->getType()->isIntOrIntVectorTy() &&
3449 !LHS->getType()->getScalarType()->isPointerTy())
3450 return Error(Loc, "icmp requires integer operands");
3451 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3456 //===----------------------------------------------------------------------===//
3457 // Other Instructions.
3458 //===----------------------------------------------------------------------===//
3462 /// ::= CastOpc TypeAndValue 'to' Type
3463 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3468 if (ParseTypeAndValue(Op, Loc, PFS) ||
3469 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3473 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3474 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3475 return Error(Loc, "invalid cast opcode for cast from '" +
3476 getTypeString(Op->getType()) + "' to '" +
3477 getTypeString(DestTy) + "'");
3479 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3484 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3485 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3487 Value *Op0, *Op1, *Op2;
3488 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3489 ParseToken(lltok::comma, "expected ',' after select condition") ||
3490 ParseTypeAndValue(Op1, PFS) ||
3491 ParseToken(lltok::comma, "expected ',' after select value") ||
3492 ParseTypeAndValue(Op2, PFS))
3495 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3496 return Error(Loc, Reason);
3498 Inst = SelectInst::Create(Op0, Op1, Op2);
3503 /// ::= 'va_arg' TypeAndValue ',' Type
3504 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3508 if (ParseTypeAndValue(Op, PFS) ||
3509 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3510 ParseType(EltTy, TypeLoc))
3513 if (!EltTy->isFirstClassType())
3514 return Error(TypeLoc, "va_arg requires operand with first class type");
3516 Inst = new VAArgInst(Op, EltTy);
3520 /// ParseExtractElement
3521 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3522 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3525 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3526 ParseToken(lltok::comma, "expected ',' after extract value") ||
3527 ParseTypeAndValue(Op1, PFS))
3530 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3531 return Error(Loc, "invalid extractelement operands");
3533 Inst = ExtractElementInst::Create(Op0, Op1);
3537 /// ParseInsertElement
3538 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3539 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3541 Value *Op0, *Op1, *Op2;
3542 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3543 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3544 ParseTypeAndValue(Op1, PFS) ||
3545 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3546 ParseTypeAndValue(Op2, PFS))
3549 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3550 return Error(Loc, "invalid insertelement operands");
3552 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3556 /// ParseShuffleVector
3557 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3558 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3560 Value *Op0, *Op1, *Op2;
3561 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3562 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3563 ParseTypeAndValue(Op1, PFS) ||
3564 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3565 ParseTypeAndValue(Op2, PFS))
3568 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3569 return Error(Loc, "invalid shufflevector operands");
3571 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3576 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3577 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3578 Type *Ty = 0; LocTy TypeLoc;
3581 if (ParseType(Ty, TypeLoc) ||
3582 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3583 ParseValue(Ty, Op0, PFS) ||
3584 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3585 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3586 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3589 bool AteExtraComma = false;
3590 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3592 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3594 if (!EatIfPresent(lltok::comma))
3597 if (Lex.getKind() == lltok::MetadataVar) {
3598 AteExtraComma = true;
3602 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3603 ParseValue(Ty, Op0, PFS) ||
3604 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3605 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3606 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3610 if (!Ty->isFirstClassType())
3611 return Error(TypeLoc, "phi node must have first class type");
3613 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3614 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3615 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3617 return AteExtraComma ? InstExtraComma : InstNormal;
3621 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3623 /// ::= 'catch' TypeAndValue
3625 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3626 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3627 Type *Ty = 0; LocTy TyLoc;
3628 Value *PersFn; LocTy PersFnLoc;
3630 if (ParseType(Ty, TyLoc) ||
3631 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3632 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3635 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3636 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3638 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3639 LandingPadInst::ClauseType CT;
3640 if (EatIfPresent(lltok::kw_catch))
3641 CT = LandingPadInst::Catch;
3642 else if (EatIfPresent(lltok::kw_filter))
3643 CT = LandingPadInst::Filter;
3645 return TokError("expected 'catch' or 'filter' clause type");
3647 Value *V; LocTy VLoc;
3648 if (ParseTypeAndValue(V, VLoc, PFS)) {
3653 // A 'catch' type expects a non-array constant. A filter clause expects an
3655 if (CT == LandingPadInst::Catch) {
3656 if (isa<ArrayType>(V->getType()))
3657 Error(VLoc, "'catch' clause has an invalid type");
3659 if (!isa<ArrayType>(V->getType()))
3660 Error(VLoc, "'filter' clause has an invalid type");
3671 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3672 /// ParameterList OptionalAttrs
3673 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3675 AttrBuilder RetAttrs, FnAttrs;
3680 SmallVector<ParamInfo, 16> ArgList;
3681 LocTy CallLoc = Lex.getLoc();
3683 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3684 ParseOptionalCallingConv(CC) ||
3685 ParseOptionalAttrs(RetAttrs, 1) ||
3686 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3687 ParseValID(CalleeID) ||
3688 ParseParameterList(ArgList, PFS) ||
3689 ParseOptionalAttrs(FnAttrs, 2))
3692 // If RetType is a non-function pointer type, then this is the short syntax
3693 // for the call, which means that RetType is just the return type. Infer the
3694 // rest of the function argument types from the arguments that are present.
3695 PointerType *PFTy = 0;
3696 FunctionType *Ty = 0;
3697 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3698 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3699 // Pull out the types of all of the arguments...
3700 std::vector<Type*> ParamTypes;
3701 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3702 ParamTypes.push_back(ArgList[i].V->getType());
3704 if (!FunctionType::isValidReturnType(RetType))
3705 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3707 Ty = FunctionType::get(RetType, ParamTypes, false);
3708 PFTy = PointerType::getUnqual(Ty);
3711 // Look up the callee.
3713 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3715 // Set up the Attributes for the function.
3716 SmallVector<AttributeWithIndex, 8> Attrs;
3717 if (RetAttrs.hasAttributes())
3719 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3720 Attributes::get(Callee->getContext(),
3723 SmallVector<Value*, 8> Args;
3725 // Loop through FunctionType's arguments and ensure they are specified
3726 // correctly. Also, gather any parameter attributes.
3727 FunctionType::param_iterator I = Ty->param_begin();
3728 FunctionType::param_iterator E = Ty->param_end();
3729 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3730 Type *ExpectedTy = 0;
3733 } else if (!Ty->isVarArg()) {
3734 return Error(ArgList[i].Loc, "too many arguments specified");
3737 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3738 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3739 getTypeString(ExpectedTy) + "'");
3740 Args.push_back(ArgList[i].V);
3741 if (ArgList[i].Attrs.hasAttributes())
3742 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3746 return Error(CallLoc, "not enough parameters specified for call");
3748 if (FnAttrs.hasAttributes())
3750 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3751 Attributes::get(Callee->getContext(),
3754 // Finish off the Attributes and check them
3755 AttrListPtr PAL = AttrListPtr::get(Attrs);
3757 CallInst *CI = CallInst::Create(Callee, Args);
3758 CI->setTailCall(isTail);
3759 CI->setCallingConv(CC);
3760 CI->setAttributes(PAL);
3765 //===----------------------------------------------------------------------===//
3766 // Memory Instructions.
3767 //===----------------------------------------------------------------------===//
3770 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3771 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3774 unsigned Alignment = 0;
3776 if (ParseType(Ty)) return true;
3778 bool AteExtraComma = false;
3779 if (EatIfPresent(lltok::comma)) {
3780 if (Lex.getKind() == lltok::kw_align) {
3781 if (ParseOptionalAlignment(Alignment)) return true;
3782 } else if (Lex.getKind() == lltok::MetadataVar) {
3783 AteExtraComma = true;
3785 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3786 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3791 if (Size && !Size->getType()->isIntegerTy())
3792 return Error(SizeLoc, "element count must have integer type");
3794 Inst = new AllocaInst(Ty, Size, Alignment);
3795 return AteExtraComma ? InstExtraComma : InstNormal;
3799 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3800 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3801 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3802 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3803 Value *Val; LocTy Loc;
3804 unsigned Alignment = 0;
3805 bool AteExtraComma = false;
3806 bool isAtomic = false;
3807 AtomicOrdering Ordering = NotAtomic;
3808 SynchronizationScope Scope = CrossThread;
3810 if (Lex.getKind() == lltok::kw_atomic) {
3815 bool isVolatile = false;
3816 if (Lex.getKind() == lltok::kw_volatile) {
3821 if (ParseTypeAndValue(Val, Loc, PFS) ||
3822 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3823 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3826 if (!Val->getType()->isPointerTy() ||
3827 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3828 return Error(Loc, "load operand must be a pointer to a first class type");
3829 if (isAtomic && !Alignment)
3830 return Error(Loc, "atomic load must have explicit non-zero alignment");
3831 if (Ordering == Release || Ordering == AcquireRelease)
3832 return Error(Loc, "atomic load cannot use Release ordering");
3834 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3835 return AteExtraComma ? InstExtraComma : InstNormal;
3840 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3841 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3842 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3843 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3844 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3845 unsigned Alignment = 0;
3846 bool AteExtraComma = false;
3847 bool isAtomic = false;
3848 AtomicOrdering Ordering = NotAtomic;
3849 SynchronizationScope Scope = CrossThread;
3851 if (Lex.getKind() == lltok::kw_atomic) {
3856 bool isVolatile = false;
3857 if (Lex.getKind() == lltok::kw_volatile) {
3862 if (ParseTypeAndValue(Val, Loc, PFS) ||
3863 ParseToken(lltok::comma, "expected ',' after store operand") ||
3864 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3865 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3866 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3869 if (!Ptr->getType()->isPointerTy())
3870 return Error(PtrLoc, "store operand must be a pointer");
3871 if (!Val->getType()->isFirstClassType())
3872 return Error(Loc, "store operand must be a first class value");
3873 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3874 return Error(Loc, "stored value and pointer type do not match");
3875 if (isAtomic && !Alignment)
3876 return Error(Loc, "atomic store must have explicit non-zero alignment");
3877 if (Ordering == Acquire || Ordering == AcquireRelease)
3878 return Error(Loc, "atomic store cannot use Acquire ordering");
3880 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3881 return AteExtraComma ? InstExtraComma : InstNormal;
3885 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3886 /// 'singlethread'? AtomicOrdering
3887 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3888 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3889 bool AteExtraComma = false;
3890 AtomicOrdering Ordering = NotAtomic;
3891 SynchronizationScope Scope = CrossThread;
3892 bool isVolatile = false;
3894 if (EatIfPresent(lltok::kw_volatile))
3897 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3898 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3899 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3900 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3901 ParseTypeAndValue(New, NewLoc, PFS) ||
3902 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3905 if (Ordering == Unordered)
3906 return TokError("cmpxchg cannot be unordered");
3907 if (!Ptr->getType()->isPointerTy())
3908 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3909 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3910 return Error(CmpLoc, "compare value and pointer type do not match");
3911 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3912 return Error(NewLoc, "new value and pointer type do not match");
3913 if (!New->getType()->isIntegerTy())
3914 return Error(NewLoc, "cmpxchg operand must be an integer");
3915 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3916 if (Size < 8 || (Size & (Size - 1)))
3917 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3920 AtomicCmpXchgInst *CXI =
3921 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3922 CXI->setVolatile(isVolatile);
3924 return AteExtraComma ? InstExtraComma : InstNormal;
3928 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3929 /// 'singlethread'? AtomicOrdering
3930 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3931 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3932 bool AteExtraComma = false;
3933 AtomicOrdering Ordering = NotAtomic;
3934 SynchronizationScope Scope = CrossThread;
3935 bool isVolatile = false;
3936 AtomicRMWInst::BinOp Operation;
3938 if (EatIfPresent(lltok::kw_volatile))
3941 switch (Lex.getKind()) {
3942 default: return TokError("expected binary operation in atomicrmw");
3943 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3944 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3945 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3946 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3947 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3948 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3949 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3950 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3951 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3952 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3953 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3955 Lex.Lex(); // Eat the operation.
3957 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3958 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3959 ParseTypeAndValue(Val, ValLoc, PFS) ||
3960 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3963 if (Ordering == Unordered)
3964 return TokError("atomicrmw cannot be unordered");
3965 if (!Ptr->getType()->isPointerTy())
3966 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3967 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3968 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3969 if (!Val->getType()->isIntegerTy())
3970 return Error(ValLoc, "atomicrmw operand must be an integer");
3971 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3972 if (Size < 8 || (Size & (Size - 1)))
3973 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3976 AtomicRMWInst *RMWI =
3977 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3978 RMWI->setVolatile(isVolatile);
3980 return AteExtraComma ? InstExtraComma : InstNormal;
3984 /// ::= 'fence' 'singlethread'? AtomicOrdering
3985 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3986 AtomicOrdering Ordering = NotAtomic;
3987 SynchronizationScope Scope = CrossThread;
3988 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3991 if (Ordering == Unordered)
3992 return TokError("fence cannot be unordered");
3993 if (Ordering == Monotonic)
3994 return TokError("fence cannot be monotonic");
3996 Inst = new FenceInst(Context, Ordering, Scope);
4000 /// ParseGetElementPtr
4001 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4002 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4007 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4009 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4011 if (!Ptr->getType()->getScalarType()->isPointerTy())
4012 return Error(Loc, "base of getelementptr must be a pointer");
4014 SmallVector<Value*, 16> Indices;
4015 bool AteExtraComma = false;
4016 while (EatIfPresent(lltok::comma)) {
4017 if (Lex.getKind() == lltok::MetadataVar) {
4018 AteExtraComma = true;
4021 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4022 if (!Val->getType()->getScalarType()->isIntegerTy())
4023 return Error(EltLoc, "getelementptr index must be an integer");
4024 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4025 return Error(EltLoc, "getelementptr index type missmatch");
4026 if (Val->getType()->isVectorTy()) {
4027 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4028 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4029 if (ValNumEl != PtrNumEl)
4030 return Error(EltLoc,
4031 "getelementptr vector index has a wrong number of elements");
4033 Indices.push_back(Val);
4036 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4037 return Error(Loc, "invalid getelementptr indices");
4038 Inst = GetElementPtrInst::Create(Ptr, Indices);
4040 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4041 return AteExtraComma ? InstExtraComma : InstNormal;
4044 /// ParseExtractValue
4045 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4046 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4047 Value *Val; LocTy Loc;
4048 SmallVector<unsigned, 4> Indices;
4050 if (ParseTypeAndValue(Val, Loc, PFS) ||
4051 ParseIndexList(Indices, AteExtraComma))
4054 if (!Val->getType()->isAggregateType())
4055 return Error(Loc, "extractvalue operand must be aggregate type");
4057 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4058 return Error(Loc, "invalid indices for extractvalue");
4059 Inst = ExtractValueInst::Create(Val, Indices);
4060 return AteExtraComma ? InstExtraComma : InstNormal;
4063 /// ParseInsertValue
4064 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4065 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4066 Value *Val0, *Val1; LocTy Loc0, Loc1;
4067 SmallVector<unsigned, 4> Indices;
4069 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4070 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4071 ParseTypeAndValue(Val1, Loc1, PFS) ||
4072 ParseIndexList(Indices, AteExtraComma))
4075 if (!Val0->getType()->isAggregateType())
4076 return Error(Loc0, "insertvalue operand must be aggregate type");
4078 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4079 return Error(Loc0, "invalid indices for insertvalue");
4080 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4081 return AteExtraComma ? InstExtraComma : InstNormal;
4084 //===----------------------------------------------------------------------===//
4085 // Embedded metadata.
4086 //===----------------------------------------------------------------------===//
4088 /// ParseMDNodeVector
4089 /// ::= Element (',' Element)*
4091 /// ::= 'null' | TypeAndValue
4092 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4093 PerFunctionState *PFS) {
4094 // Check for an empty list.
4095 if (Lex.getKind() == lltok::rbrace)
4099 // Null is a special case since it is typeless.
4100 if (EatIfPresent(lltok::kw_null)) {
4106 if (ParseTypeAndValue(V, PFS)) return true;
4108 } while (EatIfPresent(lltok::comma));