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(const 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());
93 if (!ForwardRefTypes.empty())
94 return Error(ForwardRefTypes.begin()->second.second,
95 "use of undefined type named '" +
96 ForwardRefTypes.begin()->first + "'");
97 if (!ForwardRefTypeIDs.empty())
98 return Error(ForwardRefTypeIDs.begin()->second.second,
99 "use of undefined type '%" +
100 Twine(ForwardRefTypeIDs.begin()->first) + "'");
102 if (!ForwardRefVals.empty())
103 return Error(ForwardRefVals.begin()->second.second,
104 "use of undefined value '@" + ForwardRefVals.begin()->first +
107 if (!ForwardRefValIDs.empty())
108 return Error(ForwardRefValIDs.begin()->second.second,
109 "use of undefined value '@" +
110 Twine(ForwardRefValIDs.begin()->first) + "'");
112 if (!ForwardRefMDNodes.empty())
113 return Error(ForwardRefMDNodes.begin()->second.second,
114 "use of undefined metadata '!" +
115 Twine(ForwardRefMDNodes.begin()->first) + "'");
118 // Look for intrinsic functions and CallInst that need to be upgraded
119 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
120 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
122 // Check debug info intrinsics.
123 CheckDebugInfoIntrinsics(M);
127 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
128 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
129 PerFunctionState *PFS) {
130 // Loop over all the references, resolving them.
131 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
134 if (Refs[i].first.Kind == ValID::t_LocalName)
135 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
137 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
138 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
139 return Error(Refs[i].first.Loc,
140 "cannot take address of numeric label after the function is defined");
142 Res = dyn_cast_or_null<BasicBlock>(
143 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
147 return Error(Refs[i].first.Loc,
148 "referenced value is not a basic block");
150 // Get the BlockAddress for this and update references to use it.
151 BlockAddress *BA = BlockAddress::get(TheFn, Res);
152 Refs[i].second->replaceAllUsesWith(BA);
153 Refs[i].second->eraseFromParent();
159 //===----------------------------------------------------------------------===//
160 // Top-Level Entities
161 //===----------------------------------------------------------------------===//
163 bool LLParser::ParseTopLevelEntities() {
165 switch (Lex.getKind()) {
166 default: return TokError("expected top-level entity");
167 case lltok::Eof: return false;
168 case lltok::kw_declare: if (ParseDeclare()) return true; break;
169 case lltok::kw_define: if (ParseDefine()) return true; break;
170 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
171 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
172 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
173 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
174 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
175 case lltok::LocalVar: if (ParseNamedType()) return true; break;
176 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
177 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
178 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
179 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
181 // The Global variable production with no name can have many different
182 // optional leading prefixes, the production is:
183 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
184 // OptionalAddrSpace OptionalUnNammedAddr
185 // ('constant'|'global') ...
186 case lltok::kw_private: // OptionalLinkage
187 case lltok::kw_linker_private: // OptionalLinkage
188 case lltok::kw_linker_private_weak: // OptionalLinkage
189 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
190 case lltok::kw_internal: // OptionalLinkage
191 case lltok::kw_weak: // OptionalLinkage
192 case lltok::kw_weak_odr: // OptionalLinkage
193 case lltok::kw_linkonce: // OptionalLinkage
194 case lltok::kw_linkonce_odr: // OptionalLinkage
195 case lltok::kw_appending: // OptionalLinkage
196 case lltok::kw_dllexport: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_dllimport: // OptionalLinkage
199 case lltok::kw_extern_weak: // OptionalLinkage
200 case lltok::kw_external: { // OptionalLinkage
201 unsigned Linkage, Visibility;
202 if (ParseOptionalLinkage(Linkage) ||
203 ParseOptionalVisibility(Visibility) ||
204 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
208 case lltok::kw_default: // OptionalVisibility
209 case lltok::kw_hidden: // OptionalVisibility
210 case lltok::kw_protected: { // OptionalVisibility
212 if (ParseOptionalVisibility(Visibility) ||
213 ParseGlobal("", SMLoc(), 0, false, Visibility))
218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: // GlobalType
222 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
230 /// ::= 'module' 'asm' STRINGCONSTANT
231 bool LLParser::ParseModuleAsm() {
232 assert(Lex.getKind() == lltok::kw_module);
236 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
237 ParseStringConstant(AsmStr)) return true;
239 M->appendModuleInlineAsm(AsmStr);
244 /// ::= 'target' 'triple' '=' STRINGCONSTANT
245 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
246 bool LLParser::ParseTargetDefinition() {
247 assert(Lex.getKind() == lltok::kw_target);
250 default: return TokError("unknown target property");
251 case lltok::kw_triple:
253 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
254 ParseStringConstant(Str))
256 M->setTargetTriple(Str);
258 case lltok::kw_datalayout:
260 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
261 ParseStringConstant(Str))
263 M->setDataLayout(Str);
269 /// ::= 'deplibs' '=' '[' ']'
270 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
271 bool LLParser::ParseDepLibs() {
272 assert(Lex.getKind() == lltok::kw_deplibs);
274 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
275 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
278 if (EatIfPresent(lltok::rsquare))
282 if (ParseStringConstant(Str)) return true;
285 while (EatIfPresent(lltok::comma)) {
286 if (ParseStringConstant(Str)) return true;
290 return ParseToken(lltok::rsquare, "expected ']' at end of list");
293 /// ParseUnnamedType:
295 /// ::= LocalVarID '=' 'type' type
296 bool LLParser::ParseUnnamedType() {
297 unsigned TypeID = NumberedTypes.size();
299 // Handle the LocalVarID form.
300 if (Lex.getKind() == lltok::LocalVarID) {
301 if (Lex.getUIntVal() != TypeID)
302 return Error(Lex.getLoc(), "type expected to be numbered '%" +
303 Twine(TypeID) + "'");
304 Lex.Lex(); // eat LocalVarID;
306 if (ParseToken(lltok::equal, "expected '=' after name"))
310 LocTy TypeLoc = Lex.getLoc();
311 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
313 PATypeHolder Ty(Type::getVoidTy(Context));
314 if (ParseType(Ty)) return true;
316 // See if this type was previously referenced.
317 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
318 FI = ForwardRefTypeIDs.find(TypeID);
319 if (FI != ForwardRefTypeIDs.end()) {
320 if (FI->second.first.get() == Ty)
321 return Error(TypeLoc, "self referential type is invalid");
323 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
324 Ty = FI->second.first.get();
325 ForwardRefTypeIDs.erase(FI);
328 NumberedTypes.push_back(Ty);
334 /// ::= LocalVar '=' 'type' type
335 bool LLParser::ParseNamedType() {
336 std::string Name = Lex.getStrVal();
337 LocTy NameLoc = Lex.getLoc();
338 Lex.Lex(); // eat LocalVar.
340 PATypeHolder Ty(Type::getVoidTy(Context));
342 if (ParseToken(lltok::equal, "expected '=' after name") ||
343 ParseToken(lltok::kw_type, "expected 'type' after name") ||
347 // Set the type name, checking for conflicts as we do so.
348 bool AlreadyExists = M->addTypeName(Name, Ty);
349 if (!AlreadyExists) return false;
351 // See if this type is a forward reference. We need to eagerly resolve
352 // types to allow recursive type redefinitions below.
353 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
354 FI = ForwardRefTypes.find(Name);
355 if (FI != ForwardRefTypes.end()) {
356 if (FI->second.first.get() == Ty)
357 return Error(NameLoc, "self referential type is invalid");
359 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
360 Ty = FI->second.first.get();
361 ForwardRefTypes.erase(FI);
365 // Inserting a name that is already defined, get the existing name.
366 assert(M->getTypeByName(Name) && "Conflict but no matching type?!");
368 // Otherwise, this is an attempt to redefine a type, report the error.
369 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
370 getTypeString(Ty) + "'");
375 /// ::= 'declare' FunctionHeader
376 bool LLParser::ParseDeclare() {
377 assert(Lex.getKind() == lltok::kw_declare);
381 return ParseFunctionHeader(F, false);
385 /// ::= 'define' FunctionHeader '{' ...
386 bool LLParser::ParseDefine() {
387 assert(Lex.getKind() == lltok::kw_define);
391 return ParseFunctionHeader(F, true) ||
392 ParseFunctionBody(*F);
398 bool LLParser::ParseGlobalType(bool &IsConstant) {
399 if (Lex.getKind() == lltok::kw_constant)
401 else if (Lex.getKind() == lltok::kw_global)
405 return TokError("expected 'global' or 'constant'");
411 /// ParseUnnamedGlobal:
412 /// OptionalVisibility ALIAS ...
413 /// OptionalLinkage OptionalVisibility ... -> global variable
414 /// GlobalID '=' OptionalVisibility ALIAS ...
415 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
416 bool LLParser::ParseUnnamedGlobal() {
417 unsigned VarID = NumberedVals.size();
419 LocTy NameLoc = Lex.getLoc();
421 // Handle the GlobalID form.
422 if (Lex.getKind() == lltok::GlobalID) {
423 if (Lex.getUIntVal() != VarID)
424 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
426 Lex.Lex(); // eat GlobalID;
428 if (ParseToken(lltok::equal, "expected '=' after name"))
433 unsigned Linkage, Visibility;
434 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
435 ParseOptionalVisibility(Visibility))
438 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
439 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
440 return ParseAlias(Name, NameLoc, Visibility);
443 /// ParseNamedGlobal:
444 /// GlobalVar '=' OptionalVisibility ALIAS ...
445 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
446 bool LLParser::ParseNamedGlobal() {
447 assert(Lex.getKind() == lltok::GlobalVar);
448 LocTy NameLoc = Lex.getLoc();
449 std::string Name = Lex.getStrVal();
453 unsigned Linkage, Visibility;
454 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
455 ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
465 // ::= '!' STRINGCONSTANT
466 bool LLParser::ParseMDString(MDString *&Result) {
468 if (ParseStringConstant(Str)) return true;
469 Result = MDString::get(Context, Str);
474 // ::= '!' MDNodeNumber
476 /// This version of ParseMDNodeID returns the slot number and null in the case
477 /// of a forward reference.
478 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
479 // !{ ..., !42, ... }
480 if (ParseUInt32(SlotNo)) return true;
482 // Check existing MDNode.
483 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
484 Result = NumberedMetadata[SlotNo];
490 bool LLParser::ParseMDNodeID(MDNode *&Result) {
491 // !{ ..., !42, ... }
493 if (ParseMDNodeID(Result, MID)) return true;
495 // If not a forward reference, just return it now.
496 if (Result) return false;
498 // Otherwise, create MDNode forward reference.
499 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
500 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
502 if (NumberedMetadata.size() <= MID)
503 NumberedMetadata.resize(MID+1);
504 NumberedMetadata[MID] = FwdNode;
509 /// ParseNamedMetadata:
510 /// !foo = !{ !1, !2 }
511 bool LLParser::ParseNamedMetadata() {
512 assert(Lex.getKind() == lltok::MetadataVar);
513 std::string Name = Lex.getStrVal();
516 if (ParseToken(lltok::equal, "expected '=' here") ||
517 ParseToken(lltok::exclaim, "Expected '!' here") ||
518 ParseToken(lltok::lbrace, "Expected '{' here"))
521 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
522 if (Lex.getKind() != lltok::rbrace)
524 if (ParseToken(lltok::exclaim, "Expected '!' here"))
528 if (ParseMDNodeID(N)) return true;
530 } while (EatIfPresent(lltok::comma));
532 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
538 /// ParseStandaloneMetadata:
540 bool LLParser::ParseStandaloneMetadata() {
541 assert(Lex.getKind() == lltok::exclaim);
543 unsigned MetadataID = 0;
546 PATypeHolder Ty(Type::getVoidTy(Context));
547 SmallVector<Value *, 16> Elts;
548 if (ParseUInt32(MetadataID) ||
549 ParseToken(lltok::equal, "expected '=' here") ||
550 ParseType(Ty, TyLoc) ||
551 ParseToken(lltok::exclaim, "Expected '!' here") ||
552 ParseToken(lltok::lbrace, "Expected '{' here") ||
553 ParseMDNodeVector(Elts, NULL) ||
554 ParseToken(lltok::rbrace, "expected end of metadata node"))
557 MDNode *Init = MDNode::get(Context, Elts);
559 // See if this was forward referenced, if so, handle it.
560 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
561 FI = ForwardRefMDNodes.find(MetadataID);
562 if (FI != ForwardRefMDNodes.end()) {
563 MDNode *Temp = FI->second.first;
564 Temp->replaceAllUsesWith(Init);
565 MDNode::deleteTemporary(Temp);
566 ForwardRefMDNodes.erase(FI);
568 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
570 if (MetadataID >= NumberedMetadata.size())
571 NumberedMetadata.resize(MetadataID+1);
573 if (NumberedMetadata[MetadataID] != 0)
574 return TokError("Metadata id is already used");
575 NumberedMetadata[MetadataID] = Init;
582 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
585 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
586 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
588 /// Everything through visibility has already been parsed.
590 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
591 unsigned Visibility) {
592 assert(Lex.getKind() == lltok::kw_alias);
595 LocTy LinkageLoc = Lex.getLoc();
596 if (ParseOptionalLinkage(Linkage))
599 if (Linkage != GlobalValue::ExternalLinkage &&
600 Linkage != GlobalValue::WeakAnyLinkage &&
601 Linkage != GlobalValue::WeakODRLinkage &&
602 Linkage != GlobalValue::InternalLinkage &&
603 Linkage != GlobalValue::PrivateLinkage &&
604 Linkage != GlobalValue::LinkerPrivateLinkage &&
605 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
606 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
607 return Error(LinkageLoc, "invalid linkage type for alias");
610 LocTy AliaseeLoc = Lex.getLoc();
611 if (Lex.getKind() != lltok::kw_bitcast &&
612 Lex.getKind() != lltok::kw_getelementptr) {
613 if (ParseGlobalTypeAndValue(Aliasee)) return true;
615 // The bitcast dest type is not present, it is implied by the dest type.
617 if (ParseValID(ID)) return true;
618 if (ID.Kind != ValID::t_Constant)
619 return Error(AliaseeLoc, "invalid aliasee");
620 Aliasee = ID.ConstantVal;
623 if (!Aliasee->getType()->isPointerTy())
624 return Error(AliaseeLoc, "alias must have pointer type");
626 // Okay, create the alias but do not insert it into the module yet.
627 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
628 (GlobalValue::LinkageTypes)Linkage, Name,
630 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
632 // See if this value already exists in the symbol table. If so, it is either
633 // a redefinition or a definition of a forward reference.
634 if (GlobalValue *Val = M->getNamedValue(Name)) {
635 // See if this was a redefinition. If so, there is no entry in
637 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
638 I = ForwardRefVals.find(Name);
639 if (I == ForwardRefVals.end())
640 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
642 // Otherwise, this was a definition of forward ref. Verify that types
644 if (Val->getType() != GA->getType())
645 return Error(NameLoc,
646 "forward reference and definition of alias have different types");
648 // If they agree, just RAUW the old value with the alias and remove the
650 Val->replaceAllUsesWith(GA);
651 Val->eraseFromParent();
652 ForwardRefVals.erase(I);
655 // Insert into the module, we know its name won't collide now.
656 M->getAliasList().push_back(GA);
657 assert(GA->getName() == Name && "Should not be a name conflict!");
663 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
664 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
665 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
666 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
668 /// Everything through visibility has been parsed already.
670 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
671 unsigned Linkage, bool HasLinkage,
672 unsigned Visibility) {
674 bool ThreadLocal, IsConstant, UnnamedAddr;
675 LocTy UnnamedAddrLoc;
678 PATypeHolder Ty(Type::getVoidTy(Context));
679 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
680 ParseOptionalAddrSpace(AddrSpace) ||
681 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
683 ParseGlobalType(IsConstant) ||
684 ParseType(Ty, TyLoc))
687 // If the linkage is specified and is external, then no initializer is
690 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
691 Linkage != GlobalValue::ExternalWeakLinkage &&
692 Linkage != GlobalValue::ExternalLinkage)) {
693 if (ParseGlobalValue(Ty, Init))
697 if (Ty->isFunctionTy() || Ty->isLabelTy())
698 return Error(TyLoc, "invalid type for global variable");
700 GlobalVariable *GV = 0;
702 // See if the global was forward referenced, if so, use the global.
704 if (GlobalValue *GVal = M->getNamedValue(Name)) {
705 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
706 return Error(NameLoc, "redefinition of global '@" + Name + "'");
707 GV = cast<GlobalVariable>(GVal);
710 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
711 I = ForwardRefValIDs.find(NumberedVals.size());
712 if (I != ForwardRefValIDs.end()) {
713 GV = cast<GlobalVariable>(I->second.first);
714 ForwardRefValIDs.erase(I);
719 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
720 Name, 0, false, AddrSpace);
722 if (GV->getType()->getElementType() != Ty)
724 "forward reference and definition of global have different types");
726 // Move the forward-reference to the correct spot in the module.
727 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
731 NumberedVals.push_back(GV);
733 // Set the parsed properties on the global.
735 GV->setInitializer(Init);
736 GV->setConstant(IsConstant);
737 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
738 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
739 GV->setThreadLocal(ThreadLocal);
740 GV->setUnnamedAddr(UnnamedAddr);
742 // Parse attributes on the global.
743 while (Lex.getKind() == lltok::comma) {
746 if (Lex.getKind() == lltok::kw_section) {
748 GV->setSection(Lex.getStrVal());
749 if (ParseToken(lltok::StringConstant, "expected global section string"))
751 } else if (Lex.getKind() == lltok::kw_align) {
753 if (ParseOptionalAlignment(Alignment)) return true;
754 GV->setAlignment(Alignment);
756 TokError("unknown global variable property!");
764 //===----------------------------------------------------------------------===//
765 // GlobalValue Reference/Resolution Routines.
766 //===----------------------------------------------------------------------===//
768 /// GetGlobalVal - Get a value with the specified name or ID, creating a
769 /// forward reference record if needed. This can return null if the value
770 /// exists but does not have the right type.
771 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
773 const PointerType *PTy = dyn_cast<PointerType>(Ty);
775 Error(Loc, "global variable reference must have pointer type");
779 // Look this name up in the normal function symbol table.
781 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
783 // If this is a forward reference for the value, see if we already created a
784 // forward ref record.
786 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
787 I = ForwardRefVals.find(Name);
788 if (I != ForwardRefVals.end())
789 Val = I->second.first;
792 // If we have the value in the symbol table or fwd-ref table, return it.
794 if (Val->getType() == Ty) return Val;
795 Error(Loc, "'@" + Name + "' defined with type '" +
796 getTypeString(Val->getType()) + "'");
800 // Otherwise, create a new forward reference for this value and remember it.
802 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
803 // Function types can return opaque but functions can't.
804 if (FT->getReturnType()->isOpaqueTy()) {
805 Error(Loc, "function may not return opaque type");
809 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
811 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
812 GlobalValue::ExternalWeakLinkage, 0, Name);
815 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
819 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
820 const PointerType *PTy = dyn_cast<PointerType>(Ty);
822 Error(Loc, "global variable reference must have pointer type");
826 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
828 // If this is a forward reference for the value, see if we already created a
829 // forward ref record.
831 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
832 I = ForwardRefValIDs.find(ID);
833 if (I != ForwardRefValIDs.end())
834 Val = I->second.first;
837 // If we have the value in the symbol table or fwd-ref table, return it.
839 if (Val->getType() == Ty) return Val;
840 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
841 getTypeString(Val->getType()) + "'");
845 // Otherwise, create a new forward reference for this value and remember it.
847 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
848 // Function types can return opaque but functions can't.
849 if (FT->getReturnType()->isOpaqueTy()) {
850 Error(Loc, "function may not return opaque type");
853 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
855 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
856 GlobalValue::ExternalWeakLinkage, 0, "");
859 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
864 //===----------------------------------------------------------------------===//
866 //===----------------------------------------------------------------------===//
868 /// ParseToken - If the current token has the specified kind, eat it and return
869 /// success. Otherwise, emit the specified error and return failure.
870 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
871 if (Lex.getKind() != T)
872 return TokError(ErrMsg);
877 /// ParseStringConstant
878 /// ::= StringConstant
879 bool LLParser::ParseStringConstant(std::string &Result) {
880 if (Lex.getKind() != lltok::StringConstant)
881 return TokError("expected string constant");
882 Result = Lex.getStrVal();
889 bool LLParser::ParseUInt32(unsigned &Val) {
890 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
891 return TokError("expected integer");
892 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
893 if (Val64 != unsigned(Val64))
894 return TokError("expected 32-bit integer (too large)");
901 /// ParseOptionalAddrSpace
903 /// := 'addrspace' '(' uint32 ')'
904 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
906 if (!EatIfPresent(lltok::kw_addrspace))
908 return ParseToken(lltok::lparen, "expected '(' in address space") ||
909 ParseUInt32(AddrSpace) ||
910 ParseToken(lltok::rparen, "expected ')' in address space");
913 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
914 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
915 /// 2: function attr.
916 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
917 Attrs = Attribute::None;
918 LocTy AttrLoc = Lex.getLoc();
921 switch (Lex.getKind()) {
922 default: // End of attributes.
923 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
924 return Error(AttrLoc, "invalid use of function-only attribute");
926 // As a hack, we allow "align 2" on functions as a synonym for
929 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
930 return Error(AttrLoc, "invalid use of attribute on a function");
932 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
933 return Error(AttrLoc, "invalid use of parameter-only attribute");
936 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
937 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
938 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
939 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
940 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
941 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
942 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
943 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
945 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
946 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
947 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
948 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
949 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
950 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
951 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
952 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
953 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
954 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
955 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
956 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
957 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
958 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
959 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
960 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
962 case lltok::kw_alignstack: {
964 if (ParseOptionalStackAlignment(Alignment))
966 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
970 case lltok::kw_align: {
972 if (ParseOptionalAlignment(Alignment))
974 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
983 /// ParseOptionalLinkage
986 /// ::= 'linker_private'
987 /// ::= 'linker_private_weak'
988 /// ::= 'linker_private_weak_def_auto'
993 /// ::= 'linkonce_odr'
994 /// ::= 'available_externally'
999 /// ::= 'extern_weak'
1001 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1003 switch (Lex.getKind()) {
1004 default: Res=GlobalValue::ExternalLinkage; return false;
1005 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1006 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1007 case lltok::kw_linker_private_weak:
1008 Res = GlobalValue::LinkerPrivateWeakLinkage;
1010 case lltok::kw_linker_private_weak_def_auto:
1011 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1013 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1014 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1015 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1016 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1017 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1018 case lltok::kw_available_externally:
1019 Res = GlobalValue::AvailableExternallyLinkage;
1021 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1022 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1023 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1024 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1025 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1026 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1033 /// ParseOptionalVisibility
1039 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1040 switch (Lex.getKind()) {
1041 default: Res = GlobalValue::DefaultVisibility; return false;
1042 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1043 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1044 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1050 /// ParseOptionalCallingConv
1055 /// ::= 'x86_stdcallcc'
1056 /// ::= 'x86_fastcallcc'
1057 /// ::= 'x86_thiscallcc'
1058 /// ::= 'arm_apcscc'
1059 /// ::= 'arm_aapcscc'
1060 /// ::= 'arm_aapcs_vfpcc'
1061 /// ::= 'msp430_intrcc'
1062 /// ::= 'ptx_kernel'
1063 /// ::= 'ptx_device'
1066 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1067 switch (Lex.getKind()) {
1068 default: CC = CallingConv::C; return false;
1069 case lltok::kw_ccc: CC = CallingConv::C; break;
1070 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1071 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1072 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1073 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1074 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1075 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1076 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1077 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1078 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1079 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1080 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1081 case lltok::kw_cc: {
1082 unsigned ArbitraryCC;
1084 if (ParseUInt32(ArbitraryCC)) {
1087 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1097 /// ParseInstructionMetadata
1098 /// ::= !dbg !42 (',' !dbg !57)*
1099 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1100 PerFunctionState *PFS) {
1102 if (Lex.getKind() != lltok::MetadataVar)
1103 return TokError("expected metadata after comma");
1105 std::string Name = Lex.getStrVal();
1106 unsigned MDK = M->getMDKindID(Name.c_str());
1110 SMLoc Loc = Lex.getLoc();
1112 if (ParseToken(lltok::exclaim, "expected '!' here"))
1115 // This code is similar to that of ParseMetadataValue, however it needs to
1116 // have special-case code for a forward reference; see the comments on
1117 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1118 // at the top level here.
1119 if (Lex.getKind() == lltok::lbrace) {
1121 if (ParseMetadataListValue(ID, PFS))
1123 assert(ID.Kind == ValID::t_MDNode);
1124 Inst->setMetadata(MDK, ID.MDNodeVal);
1126 unsigned NodeID = 0;
1127 if (ParseMDNodeID(Node, NodeID))
1130 // If we got the node, add it to the instruction.
1131 Inst->setMetadata(MDK, Node);
1133 MDRef R = { Loc, MDK, NodeID };
1134 // Otherwise, remember that this should be resolved later.
1135 ForwardRefInstMetadata[Inst].push_back(R);
1139 // If this is the end of the list, we're done.
1140 } while (EatIfPresent(lltok::comma));
1144 /// ParseOptionalAlignment
1147 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1149 if (!EatIfPresent(lltok::kw_align))
1151 LocTy AlignLoc = Lex.getLoc();
1152 if (ParseUInt32(Alignment)) return true;
1153 if (!isPowerOf2_32(Alignment))
1154 return Error(AlignLoc, "alignment is not a power of two");
1155 if (Alignment > Value::MaximumAlignment)
1156 return Error(AlignLoc, "huge alignments are not supported yet");
1160 /// ParseOptionalCommaAlign
1164 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1166 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1167 bool &AteExtraComma) {
1168 AteExtraComma = false;
1169 while (EatIfPresent(lltok::comma)) {
1170 // Metadata at the end is an early exit.
1171 if (Lex.getKind() == lltok::MetadataVar) {
1172 AteExtraComma = true;
1176 if (Lex.getKind() != lltok::kw_align)
1177 return Error(Lex.getLoc(), "expected metadata or 'align'");
1179 if (ParseOptionalAlignment(Alignment)) return true;
1185 /// ParseOptionalStackAlignment
1187 /// ::= 'alignstack' '(' 4 ')'
1188 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1190 if (!EatIfPresent(lltok::kw_alignstack))
1192 LocTy ParenLoc = Lex.getLoc();
1193 if (!EatIfPresent(lltok::lparen))
1194 return Error(ParenLoc, "expected '('");
1195 LocTy AlignLoc = Lex.getLoc();
1196 if (ParseUInt32(Alignment)) return true;
1197 ParenLoc = Lex.getLoc();
1198 if (!EatIfPresent(lltok::rparen))
1199 return Error(ParenLoc, "expected ')'");
1200 if (!isPowerOf2_32(Alignment))
1201 return Error(AlignLoc, "stack alignment is not a power of two");
1205 /// ParseIndexList - This parses the index list for an insert/extractvalue
1206 /// instruction. This sets AteExtraComma in the case where we eat an extra
1207 /// comma at the end of the line and find that it is followed by metadata.
1208 /// Clients that don't allow metadata can call the version of this function that
1209 /// only takes one argument.
1212 /// ::= (',' uint32)+
1214 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1215 bool &AteExtraComma) {
1216 AteExtraComma = false;
1218 if (Lex.getKind() != lltok::comma)
1219 return TokError("expected ',' as start of index list");
1221 while (EatIfPresent(lltok::comma)) {
1222 if (Lex.getKind() == lltok::MetadataVar) {
1223 AteExtraComma = true;
1227 if (ParseUInt32(Idx)) return true;
1228 Indices.push_back(Idx);
1234 //===----------------------------------------------------------------------===//
1236 //===----------------------------------------------------------------------===//
1238 /// ParseType - Parse and resolve a full type.
1239 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1240 LocTy TypeLoc = Lex.getLoc();
1241 if (ParseTypeRec(Result)) return true;
1243 // Verify no unresolved uprefs.
1244 if (!UpRefs.empty())
1245 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1247 if (!AllowVoid && Result.get()->isVoidTy())
1248 return Error(TypeLoc, "void type only allowed for function results");
1253 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1254 /// called. It loops through the UpRefs vector, which is a list of the
1255 /// currently active types. For each type, if the up-reference is contained in
1256 /// the newly completed type, we decrement the level count. When the level
1257 /// count reaches zero, the up-referenced type is the type that is passed in:
1258 /// thus we can complete the cycle.
1260 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1261 // If Ty isn't abstract, or if there are no up-references in it, then there is
1262 // nothing to resolve here.
1263 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1265 PATypeHolder Ty(ty);
1267 dbgs() << "Type '" << *Ty
1268 << "' newly formed. Resolving upreferences.\n"
1269 << UpRefs.size() << " upreferences active!\n";
1272 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1273 // to zero), we resolve them all together before we resolve them to Ty. At
1274 // the end of the loop, if there is anything to resolve to Ty, it will be in
1276 OpaqueType *TypeToResolve = 0;
1278 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1279 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1281 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1282 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1285 dbgs() << " UR#" << i << " - TypeContains(" << *Ty << ", "
1286 << *UpRefs[i].LastContainedTy << ") = "
1287 << (ContainsType ? "true" : "false")
1288 << " level=" << UpRefs[i].NestingLevel << "\n";
1293 // Decrement level of upreference
1294 unsigned Level = --UpRefs[i].NestingLevel;
1295 UpRefs[i].LastContainedTy = Ty;
1297 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1302 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1305 TypeToResolve = UpRefs[i].UpRefTy;
1307 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1308 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1309 --i; // Do not skip the next element.
1313 TypeToResolve->refineAbstractTypeTo(Ty);
1319 /// ParseTypeRec - The recursive function used to process the internal
1320 /// implementation details of types.
1321 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1322 switch (Lex.getKind()) {
1324 return TokError("expected type");
1326 // TypeRec ::= 'float' | 'void' (etc)
1327 Result = Lex.getTyVal();
1330 case lltok::kw_opaque:
1331 // TypeRec ::= 'opaque'
1332 Result = OpaqueType::get(Context);
1336 // TypeRec ::= '{' ... '}'
1337 if (ParseStructType(Result, false))
1340 case lltok::lsquare:
1341 // TypeRec ::= '[' ... ']'
1342 Lex.Lex(); // eat the lsquare.
1343 if (ParseArrayVectorType(Result, false))
1346 case lltok::less: // Either vector or packed struct.
1347 // TypeRec ::= '<' ... '>'
1349 if (Lex.getKind() == lltok::lbrace) {
1350 if (ParseStructType(Result, true) ||
1351 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1353 } else if (ParseArrayVectorType(Result, true))
1356 case lltok::LocalVar:
1358 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1361 Result = OpaqueType::get(Context);
1362 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1363 std::make_pair(Result,
1365 M->addTypeName(Lex.getStrVal(), Result.get());
1370 case lltok::LocalVarID:
1372 if (Lex.getUIntVal() < NumberedTypes.size())
1373 Result = NumberedTypes[Lex.getUIntVal()];
1375 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1376 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1377 if (I != ForwardRefTypeIDs.end())
1378 Result = I->second.first;
1380 Result = OpaqueType::get(Context);
1381 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1382 std::make_pair(Result,
1388 case lltok::backslash: {
1389 // TypeRec ::= '\' 4
1392 if (ParseUInt32(Val)) return true;
1393 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1394 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1400 // Parse the type suffixes.
1402 switch (Lex.getKind()) {
1404 default: return false;
1406 // TypeRec ::= TypeRec '*'
1408 if (Result.get()->isLabelTy())
1409 return TokError("basic block pointers are invalid");
1410 if (Result.get()->isVoidTy())
1411 return TokError("pointers to void are invalid; use i8* instead");
1412 if (!PointerType::isValidElementType(Result.get()))
1413 return TokError("pointer to this type is invalid");
1414 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1418 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1419 case lltok::kw_addrspace: {
1420 if (Result.get()->isLabelTy())
1421 return TokError("basic block pointers are invalid");
1422 if (Result.get()->isVoidTy())
1423 return TokError("pointers to void are invalid; use i8* instead");
1424 if (!PointerType::isValidElementType(Result.get()))
1425 return TokError("pointer to this type is invalid");
1427 if (ParseOptionalAddrSpace(AddrSpace) ||
1428 ParseToken(lltok::star, "expected '*' in address space"))
1431 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1435 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1437 if (ParseFunctionType(Result))
1444 /// ParseParameterList
1446 /// ::= '(' Arg (',' Arg)* ')'
1448 /// ::= Type OptionalAttributes Value OptionalAttributes
1449 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1450 PerFunctionState &PFS) {
1451 if (ParseToken(lltok::lparen, "expected '(' in call"))
1454 while (Lex.getKind() != lltok::rparen) {
1455 // If this isn't the first argument, we need a comma.
1456 if (!ArgList.empty() &&
1457 ParseToken(lltok::comma, "expected ',' in argument list"))
1460 // Parse the argument.
1462 PATypeHolder ArgTy(Type::getVoidTy(Context));
1463 unsigned ArgAttrs1 = Attribute::None;
1464 unsigned ArgAttrs2 = Attribute::None;
1466 if (ParseType(ArgTy, ArgLoc))
1469 // Otherwise, handle normal operands.
1470 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1472 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1475 Lex.Lex(); // Lex the ')'.
1481 /// ParseArgumentList - Parse the argument list for a function type or function
1482 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1483 /// ::= '(' ArgTypeListI ')'
1487 /// ::= ArgTypeList ',' '...'
1488 /// ::= ArgType (',' ArgType)*
1490 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1491 bool &isVarArg, bool inType) {
1493 assert(Lex.getKind() == lltok::lparen);
1494 Lex.Lex(); // eat the (.
1496 if (Lex.getKind() == lltok::rparen) {
1498 } else if (Lex.getKind() == lltok::dotdotdot) {
1502 LocTy TypeLoc = Lex.getLoc();
1503 PATypeHolder ArgTy(Type::getVoidTy(Context));
1507 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1508 // types (such as a function returning a pointer to itself). If parsing a
1509 // function prototype, we require fully resolved types.
1510 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1511 ParseOptionalAttrs(Attrs, 0)) return true;
1513 if (ArgTy->isVoidTy())
1514 return Error(TypeLoc, "argument can not have void type");
1516 if (Lex.getKind() == lltok::LocalVar) {
1517 Name = Lex.getStrVal();
1521 if (!FunctionType::isValidArgumentType(ArgTy))
1522 return Error(TypeLoc, "invalid type for function argument");
1524 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1526 while (EatIfPresent(lltok::comma)) {
1527 // Handle ... at end of arg list.
1528 if (EatIfPresent(lltok::dotdotdot)) {
1533 // Otherwise must be an argument type.
1534 TypeLoc = Lex.getLoc();
1535 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1536 ParseOptionalAttrs(Attrs, 0)) return true;
1538 if (ArgTy->isVoidTy())
1539 return Error(TypeLoc, "argument can not have void type");
1541 if (Lex.getKind() == lltok::LocalVar) {
1542 Name = Lex.getStrVal();
1548 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1549 return Error(TypeLoc, "invalid type for function argument");
1551 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1555 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1558 /// ParseFunctionType
1559 /// ::= Type ArgumentList OptionalAttrs
1560 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1561 assert(Lex.getKind() == lltok::lparen);
1563 if (!FunctionType::isValidReturnType(Result))
1564 return TokError("invalid function return type");
1566 std::vector<ArgInfo> ArgList;
1568 if (ParseArgumentList(ArgList, isVarArg, true))
1571 // Reject names on the arguments lists.
1572 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1573 if (!ArgList[i].Name.empty())
1574 return Error(ArgList[i].Loc, "argument name invalid in function type");
1575 if (ArgList[i].Attrs != 0)
1576 return Error(ArgList[i].Loc,
1577 "argument attributes invalid in function type");
1580 std::vector<const Type*> ArgListTy;
1581 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1582 ArgListTy.push_back(ArgList[i].Type);
1584 Result = HandleUpRefs(FunctionType::get(Result.get(),
1585 ArgListTy, isVarArg));
1589 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1592 /// ::= '{' TypeRec (',' TypeRec)* '}'
1593 /// ::= '<' '{' '}' '>'
1594 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1595 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1596 assert(Lex.getKind() == lltok::lbrace);
1597 Lex.Lex(); // Consume the '{'
1599 if (EatIfPresent(lltok::rbrace)) {
1600 Result = StructType::get(Context, Packed);
1604 std::vector<PATypeHolder> ParamsList;
1605 LocTy EltTyLoc = Lex.getLoc();
1606 if (ParseTypeRec(Result)) return true;
1607 ParamsList.push_back(Result);
1609 if (Result->isVoidTy())
1610 return Error(EltTyLoc, "struct element can not have void type");
1611 if (!StructType::isValidElementType(Result))
1612 return Error(EltTyLoc, "invalid element type for struct");
1614 while (EatIfPresent(lltok::comma)) {
1615 EltTyLoc = Lex.getLoc();
1616 if (ParseTypeRec(Result)) return true;
1618 if (Result->isVoidTy())
1619 return Error(EltTyLoc, "struct element can not have void type");
1620 if (!StructType::isValidElementType(Result))
1621 return Error(EltTyLoc, "invalid element type for struct");
1623 ParamsList.push_back(Result);
1626 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1629 std::vector<const Type*> ParamsListTy;
1630 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1631 ParamsListTy.push_back(ParamsList[i].get());
1632 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1636 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1637 /// token has already been consumed.
1639 /// ::= '[' APSINTVAL 'x' Types ']'
1640 /// ::= '<' APSINTVAL 'x' Types '>'
1641 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1642 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1643 Lex.getAPSIntVal().getBitWidth() > 64)
1644 return TokError("expected number in address space");
1646 LocTy SizeLoc = Lex.getLoc();
1647 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1650 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1653 LocTy TypeLoc = Lex.getLoc();
1654 PATypeHolder EltTy(Type::getVoidTy(Context));
1655 if (ParseTypeRec(EltTy)) return true;
1657 if (EltTy->isVoidTy())
1658 return Error(TypeLoc, "array and vector element type cannot be void");
1660 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1661 "expected end of sequential type"))
1666 return Error(SizeLoc, "zero element vector is illegal");
1667 if ((unsigned)Size != Size)
1668 return Error(SizeLoc, "size too large for vector");
1669 if (!VectorType::isValidElementType(EltTy))
1670 return Error(TypeLoc, "vector element type must be fp or integer");
1671 Result = VectorType::get(EltTy, unsigned(Size));
1673 if (!ArrayType::isValidElementType(EltTy))
1674 return Error(TypeLoc, "invalid array element type");
1675 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1680 //===----------------------------------------------------------------------===//
1681 // Function Semantic Analysis.
1682 //===----------------------------------------------------------------------===//
1684 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1686 : P(p), F(f), FunctionNumber(functionNumber) {
1688 // Insert unnamed arguments into the NumberedVals list.
1689 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1692 NumberedVals.push_back(AI);
1695 LLParser::PerFunctionState::~PerFunctionState() {
1696 // If there were any forward referenced non-basicblock values, delete them.
1697 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1698 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1699 if (!isa<BasicBlock>(I->second.first)) {
1700 I->second.first->replaceAllUsesWith(
1701 UndefValue::get(I->second.first->getType()));
1702 delete I->second.first;
1703 I->second.first = 0;
1706 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1707 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1708 if (!isa<BasicBlock>(I->second.first)) {
1709 I->second.first->replaceAllUsesWith(
1710 UndefValue::get(I->second.first->getType()));
1711 delete I->second.first;
1712 I->second.first = 0;
1716 bool LLParser::PerFunctionState::FinishFunction() {
1717 // Check to see if someone took the address of labels in this block.
1718 if (!P.ForwardRefBlockAddresses.empty()) {
1720 if (!F.getName().empty()) {
1721 FunctionID.Kind = ValID::t_GlobalName;
1722 FunctionID.StrVal = F.getName();
1724 FunctionID.Kind = ValID::t_GlobalID;
1725 FunctionID.UIntVal = FunctionNumber;
1728 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1729 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1730 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1731 // Resolve all these references.
1732 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1735 P.ForwardRefBlockAddresses.erase(FRBAI);
1739 if (!ForwardRefVals.empty())
1740 return P.Error(ForwardRefVals.begin()->second.second,
1741 "use of undefined value '%" + ForwardRefVals.begin()->first +
1743 if (!ForwardRefValIDs.empty())
1744 return P.Error(ForwardRefValIDs.begin()->second.second,
1745 "use of undefined value '%" +
1746 Twine(ForwardRefValIDs.begin()->first) + "'");
1751 /// GetVal - Get a value with the specified name or ID, creating a
1752 /// forward reference record if needed. This can return null if the value
1753 /// exists but does not have the right type.
1754 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1755 const Type *Ty, LocTy Loc) {
1756 // Look this name up in the normal function symbol table.
1757 Value *Val = F.getValueSymbolTable().lookup(Name);
1759 // If this is a forward reference for the value, see if we already created a
1760 // forward ref record.
1762 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1763 I = ForwardRefVals.find(Name);
1764 if (I != ForwardRefVals.end())
1765 Val = I->second.first;
1768 // If we have the value in the symbol table or fwd-ref table, return it.
1770 if (Val->getType() == Ty) return Val;
1771 if (Ty->isLabelTy())
1772 P.Error(Loc, "'%" + Name + "' is not a basic block");
1774 P.Error(Loc, "'%" + Name + "' defined with type '" +
1775 getTypeString(Val->getType()) + "'");
1779 // Don't make placeholders with invalid type.
1780 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1781 P.Error(Loc, "invalid use of a non-first-class type");
1785 // Otherwise, create a new forward reference for this value and remember it.
1787 if (Ty->isLabelTy())
1788 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1790 FwdVal = new Argument(Ty, Name);
1792 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1796 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1798 // Look this name up in the normal function symbol table.
1799 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1801 // If this is a forward reference for the value, see if we already created a
1802 // forward ref record.
1804 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1805 I = ForwardRefValIDs.find(ID);
1806 if (I != ForwardRefValIDs.end())
1807 Val = I->second.first;
1810 // If we have the value in the symbol table or fwd-ref table, return it.
1812 if (Val->getType() == Ty) return Val;
1813 if (Ty->isLabelTy())
1814 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1816 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1817 getTypeString(Val->getType()) + "'");
1821 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1822 P.Error(Loc, "invalid use of a non-first-class type");
1826 // Otherwise, create a new forward reference for this value and remember it.
1828 if (Ty->isLabelTy())
1829 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1831 FwdVal = new Argument(Ty);
1833 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1837 /// SetInstName - After an instruction is parsed and inserted into its
1838 /// basic block, this installs its name.
1839 bool LLParser::PerFunctionState::SetInstName(int NameID,
1840 const std::string &NameStr,
1841 LocTy NameLoc, Instruction *Inst) {
1842 // If this instruction has void type, it cannot have a name or ID specified.
1843 if (Inst->getType()->isVoidTy()) {
1844 if (NameID != -1 || !NameStr.empty())
1845 return P.Error(NameLoc, "instructions returning void cannot have a name");
1849 // If this was a numbered instruction, verify that the instruction is the
1850 // expected value and resolve any forward references.
1851 if (NameStr.empty()) {
1852 // If neither a name nor an ID was specified, just use the next ID.
1854 NameID = NumberedVals.size();
1856 if (unsigned(NameID) != NumberedVals.size())
1857 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1858 Twine(NumberedVals.size()) + "'");
1860 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1861 ForwardRefValIDs.find(NameID);
1862 if (FI != ForwardRefValIDs.end()) {
1863 if (FI->second.first->getType() != Inst->getType())
1864 return P.Error(NameLoc, "instruction forward referenced with type '" +
1865 getTypeString(FI->second.first->getType()) + "'");
1866 FI->second.first->replaceAllUsesWith(Inst);
1867 delete FI->second.first;
1868 ForwardRefValIDs.erase(FI);
1871 NumberedVals.push_back(Inst);
1875 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1876 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1877 FI = ForwardRefVals.find(NameStr);
1878 if (FI != ForwardRefVals.end()) {
1879 if (FI->second.first->getType() != Inst->getType())
1880 return P.Error(NameLoc, "instruction forward referenced with type '" +
1881 getTypeString(FI->second.first->getType()) + "'");
1882 FI->second.first->replaceAllUsesWith(Inst);
1883 delete FI->second.first;
1884 ForwardRefVals.erase(FI);
1887 // Set the name on the instruction.
1888 Inst->setName(NameStr);
1890 if (Inst->getName() != NameStr)
1891 return P.Error(NameLoc, "multiple definition of local value named '" +
1896 /// GetBB - Get a basic block with the specified name or ID, creating a
1897 /// forward reference record if needed.
1898 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1900 return cast_or_null<BasicBlock>(GetVal(Name,
1901 Type::getLabelTy(F.getContext()), Loc));
1904 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1905 return cast_or_null<BasicBlock>(GetVal(ID,
1906 Type::getLabelTy(F.getContext()), Loc));
1909 /// DefineBB - Define the specified basic block, which is either named or
1910 /// unnamed. If there is an error, this returns null otherwise it returns
1911 /// the block being defined.
1912 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1916 BB = GetBB(NumberedVals.size(), Loc);
1918 BB = GetBB(Name, Loc);
1919 if (BB == 0) return 0; // Already diagnosed error.
1921 // Move the block to the end of the function. Forward ref'd blocks are
1922 // inserted wherever they happen to be referenced.
1923 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1925 // Remove the block from forward ref sets.
1927 ForwardRefValIDs.erase(NumberedVals.size());
1928 NumberedVals.push_back(BB);
1930 // BB forward references are already in the function symbol table.
1931 ForwardRefVals.erase(Name);
1937 //===----------------------------------------------------------------------===//
1939 //===----------------------------------------------------------------------===//
1941 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1942 /// type implied. For example, if we parse "4" we don't know what integer type
1943 /// it has. The value will later be combined with its type and checked for
1944 /// sanity. PFS is used to convert function-local operands of metadata (since
1945 /// metadata operands are not just parsed here but also converted to values).
1946 /// PFS can be null when we are not parsing metadata values inside a function.
1947 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1948 ID.Loc = Lex.getLoc();
1949 switch (Lex.getKind()) {
1950 default: return TokError("expected value token");
1951 case lltok::GlobalID: // @42
1952 ID.UIntVal = Lex.getUIntVal();
1953 ID.Kind = ValID::t_GlobalID;
1955 case lltok::GlobalVar: // @foo
1956 ID.StrVal = Lex.getStrVal();
1957 ID.Kind = ValID::t_GlobalName;
1959 case lltok::LocalVarID: // %42
1960 ID.UIntVal = Lex.getUIntVal();
1961 ID.Kind = ValID::t_LocalID;
1963 case lltok::LocalVar: // %foo
1964 ID.StrVal = Lex.getStrVal();
1965 ID.Kind = ValID::t_LocalName;
1967 case lltok::exclaim: // !42, !{...}, or !"foo"
1968 return ParseMetadataValue(ID, PFS);
1970 ID.APSIntVal = Lex.getAPSIntVal();
1971 ID.Kind = ValID::t_APSInt;
1973 case lltok::APFloat:
1974 ID.APFloatVal = Lex.getAPFloatVal();
1975 ID.Kind = ValID::t_APFloat;
1977 case lltok::kw_true:
1978 ID.ConstantVal = ConstantInt::getTrue(Context);
1979 ID.Kind = ValID::t_Constant;
1981 case lltok::kw_false:
1982 ID.ConstantVal = ConstantInt::getFalse(Context);
1983 ID.Kind = ValID::t_Constant;
1985 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1986 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1987 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1989 case lltok::lbrace: {
1990 // ValID ::= '{' ConstVector '}'
1992 SmallVector<Constant*, 16> Elts;
1993 if (ParseGlobalValueVector(Elts) ||
1994 ParseToken(lltok::rbrace, "expected end of struct constant"))
1997 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1998 Elts.size(), false);
1999 ID.Kind = ValID::t_Constant;
2003 // ValID ::= '<' ConstVector '>' --> Vector.
2004 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2006 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2008 SmallVector<Constant*, 16> Elts;
2009 LocTy FirstEltLoc = Lex.getLoc();
2010 if (ParseGlobalValueVector(Elts) ||
2012 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2013 ParseToken(lltok::greater, "expected end of constant"))
2016 if (isPackedStruct) {
2018 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2019 ID.Kind = ValID::t_Constant;
2024 return Error(ID.Loc, "constant vector must not be empty");
2026 if (!Elts[0]->getType()->isIntegerTy() &&
2027 !Elts[0]->getType()->isFloatingPointTy())
2028 return Error(FirstEltLoc,
2029 "vector elements must have integer or floating point type");
2031 // Verify that all the vector elements have the same type.
2032 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2033 if (Elts[i]->getType() != Elts[0]->getType())
2034 return Error(FirstEltLoc,
2035 "vector element #" + Twine(i) +
2036 " is not of type '" + getTypeString(Elts[0]->getType()));
2038 ID.ConstantVal = ConstantVector::get(Elts);
2039 ID.Kind = ValID::t_Constant;
2042 case lltok::lsquare: { // Array Constant
2044 SmallVector<Constant*, 16> Elts;
2045 LocTy FirstEltLoc = Lex.getLoc();
2046 if (ParseGlobalValueVector(Elts) ||
2047 ParseToken(lltok::rsquare, "expected end of array constant"))
2050 // Handle empty element.
2052 // Use undef instead of an array because it's inconvenient to determine
2053 // the element type at this point, there being no elements to examine.
2054 ID.Kind = ValID::t_EmptyArray;
2058 if (!Elts[0]->getType()->isFirstClassType())
2059 return Error(FirstEltLoc, "invalid array element type: " +
2060 getTypeString(Elts[0]->getType()));
2062 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2064 // Verify all elements are correct type!
2065 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2066 if (Elts[i]->getType() != Elts[0]->getType())
2067 return Error(FirstEltLoc,
2068 "array element #" + Twine(i) +
2069 " is not of type '" + getTypeString(Elts[0]->getType()));
2072 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2073 ID.Kind = ValID::t_Constant;
2076 case lltok::kw_c: // c "foo"
2078 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2079 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2080 ID.Kind = ValID::t_Constant;
2083 case lltok::kw_asm: {
2084 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2085 bool HasSideEffect, AlignStack;
2087 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2088 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2089 ParseStringConstant(ID.StrVal) ||
2090 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2091 ParseToken(lltok::StringConstant, "expected constraint string"))
2093 ID.StrVal2 = Lex.getStrVal();
2094 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2095 ID.Kind = ValID::t_InlineAsm;
2099 case lltok::kw_blockaddress: {
2100 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2104 LocTy FnLoc, LabelLoc;
2106 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2108 ParseToken(lltok::comma, "expected comma in block address expression")||
2109 ParseValID(Label) ||
2110 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2113 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2114 return Error(Fn.Loc, "expected function name in blockaddress");
2115 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2116 return Error(Label.Loc, "expected basic block name in blockaddress");
2118 // Make a global variable as a placeholder for this reference.
2119 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2120 false, GlobalValue::InternalLinkage,
2122 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2123 ID.ConstantVal = FwdRef;
2124 ID.Kind = ValID::t_Constant;
2128 case lltok::kw_trunc:
2129 case lltok::kw_zext:
2130 case lltok::kw_sext:
2131 case lltok::kw_fptrunc:
2132 case lltok::kw_fpext:
2133 case lltok::kw_bitcast:
2134 case lltok::kw_uitofp:
2135 case lltok::kw_sitofp:
2136 case lltok::kw_fptoui:
2137 case lltok::kw_fptosi:
2138 case lltok::kw_inttoptr:
2139 case lltok::kw_ptrtoint: {
2140 unsigned Opc = Lex.getUIntVal();
2141 PATypeHolder DestTy(Type::getVoidTy(Context));
2144 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2145 ParseGlobalTypeAndValue(SrcVal) ||
2146 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2147 ParseType(DestTy) ||
2148 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2150 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2151 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2152 getTypeString(SrcVal->getType()) + "' to '" +
2153 getTypeString(DestTy) + "'");
2154 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2156 ID.Kind = ValID::t_Constant;
2159 case lltok::kw_extractvalue: {
2162 SmallVector<unsigned, 4> Indices;
2163 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2164 ParseGlobalTypeAndValue(Val) ||
2165 ParseIndexList(Indices) ||
2166 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2169 if (!Val->getType()->isAggregateType())
2170 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2171 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2173 return Error(ID.Loc, "invalid indices for extractvalue");
2175 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2176 ID.Kind = ValID::t_Constant;
2179 case lltok::kw_insertvalue: {
2181 Constant *Val0, *Val1;
2182 SmallVector<unsigned, 4> Indices;
2183 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2184 ParseGlobalTypeAndValue(Val0) ||
2185 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2186 ParseGlobalTypeAndValue(Val1) ||
2187 ParseIndexList(Indices) ||
2188 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2190 if (!Val0->getType()->isAggregateType())
2191 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2192 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2194 return Error(ID.Loc, "invalid indices for insertvalue");
2195 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2196 Indices.data(), Indices.size());
2197 ID.Kind = ValID::t_Constant;
2200 case lltok::kw_icmp:
2201 case lltok::kw_fcmp: {
2202 unsigned PredVal, Opc = Lex.getUIntVal();
2203 Constant *Val0, *Val1;
2205 if (ParseCmpPredicate(PredVal, Opc) ||
2206 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2207 ParseGlobalTypeAndValue(Val0) ||
2208 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2209 ParseGlobalTypeAndValue(Val1) ||
2210 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2213 if (Val0->getType() != Val1->getType())
2214 return Error(ID.Loc, "compare operands must have the same type");
2216 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2218 if (Opc == Instruction::FCmp) {
2219 if (!Val0->getType()->isFPOrFPVectorTy())
2220 return Error(ID.Loc, "fcmp requires floating point operands");
2221 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2223 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2224 if (!Val0->getType()->isIntOrIntVectorTy() &&
2225 !Val0->getType()->isPointerTy())
2226 return Error(ID.Loc, "icmp requires pointer or integer operands");
2227 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2229 ID.Kind = ValID::t_Constant;
2233 // Binary Operators.
2235 case lltok::kw_fadd:
2237 case lltok::kw_fsub:
2239 case lltok::kw_fmul:
2240 case lltok::kw_udiv:
2241 case lltok::kw_sdiv:
2242 case lltok::kw_fdiv:
2243 case lltok::kw_urem:
2244 case lltok::kw_srem:
2245 case lltok::kw_frem:
2247 case lltok::kw_lshr:
2248 case lltok::kw_ashr: {
2252 unsigned Opc = Lex.getUIntVal();
2253 Constant *Val0, *Val1;
2255 LocTy ModifierLoc = Lex.getLoc();
2256 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2257 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2258 if (EatIfPresent(lltok::kw_nuw))
2260 if (EatIfPresent(lltok::kw_nsw)) {
2262 if (EatIfPresent(lltok::kw_nuw))
2265 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2266 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2267 if (EatIfPresent(lltok::kw_exact))
2270 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2271 ParseGlobalTypeAndValue(Val0) ||
2272 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2273 ParseGlobalTypeAndValue(Val1) ||
2274 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2276 if (Val0->getType() != Val1->getType())
2277 return Error(ID.Loc, "operands of constexpr must have same type");
2278 if (!Val0->getType()->isIntOrIntVectorTy()) {
2280 return Error(ModifierLoc, "nuw only applies to integer operations");
2282 return Error(ModifierLoc, "nsw only applies to integer operations");
2284 // Check that the type is valid for the operator.
2286 case Instruction::Add:
2287 case Instruction::Sub:
2288 case Instruction::Mul:
2289 case Instruction::UDiv:
2290 case Instruction::SDiv:
2291 case Instruction::URem:
2292 case Instruction::SRem:
2293 case Instruction::Shl:
2294 case Instruction::AShr:
2295 case Instruction::LShr:
2296 if (!Val0->getType()->isIntOrIntVectorTy())
2297 return Error(ID.Loc, "constexpr requires integer operands");
2299 case Instruction::FAdd:
2300 case Instruction::FSub:
2301 case Instruction::FMul:
2302 case Instruction::FDiv:
2303 case Instruction::FRem:
2304 if (!Val0->getType()->isFPOrFPVectorTy())
2305 return Error(ID.Loc, "constexpr requires fp operands");
2307 default: llvm_unreachable("Unknown binary operator!");
2310 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2311 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2312 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2313 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2315 ID.Kind = ValID::t_Constant;
2319 // Logical Operations
2322 case lltok::kw_xor: {
2323 unsigned Opc = Lex.getUIntVal();
2324 Constant *Val0, *Val1;
2326 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2327 ParseGlobalTypeAndValue(Val0) ||
2328 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2329 ParseGlobalTypeAndValue(Val1) ||
2330 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2332 if (Val0->getType() != Val1->getType())
2333 return Error(ID.Loc, "operands of constexpr must have same type");
2334 if (!Val0->getType()->isIntOrIntVectorTy())
2335 return Error(ID.Loc,
2336 "constexpr requires integer or integer vector operands");
2337 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2338 ID.Kind = ValID::t_Constant;
2342 case lltok::kw_getelementptr:
2343 case lltok::kw_shufflevector:
2344 case lltok::kw_insertelement:
2345 case lltok::kw_extractelement:
2346 case lltok::kw_select: {
2347 unsigned Opc = Lex.getUIntVal();
2348 SmallVector<Constant*, 16> Elts;
2349 bool InBounds = false;
2351 if (Opc == Instruction::GetElementPtr)
2352 InBounds = EatIfPresent(lltok::kw_inbounds);
2353 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2354 ParseGlobalValueVector(Elts) ||
2355 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2358 if (Opc == Instruction::GetElementPtr) {
2359 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2360 return Error(ID.Loc, "getelementptr requires pointer operand");
2362 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2363 (Value**)(Elts.data() + 1),
2365 return Error(ID.Loc, "invalid indices for getelementptr");
2366 ID.ConstantVal = InBounds ?
2367 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2370 ConstantExpr::getGetElementPtr(Elts[0],
2371 Elts.data() + 1, Elts.size() - 1);
2372 } else if (Opc == Instruction::Select) {
2373 if (Elts.size() != 3)
2374 return Error(ID.Loc, "expected three operands to select");
2375 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2377 return Error(ID.Loc, Reason);
2378 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2379 } else if (Opc == Instruction::ShuffleVector) {
2380 if (Elts.size() != 3)
2381 return Error(ID.Loc, "expected three operands to shufflevector");
2382 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2383 return Error(ID.Loc, "invalid operands to shufflevector");
2385 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2386 } else if (Opc == Instruction::ExtractElement) {
2387 if (Elts.size() != 2)
2388 return Error(ID.Loc, "expected two operands to extractelement");
2389 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2390 return Error(ID.Loc, "invalid extractelement operands");
2391 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2393 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2394 if (Elts.size() != 3)
2395 return Error(ID.Loc, "expected three operands to insertelement");
2396 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2397 return Error(ID.Loc, "invalid insertelement operands");
2399 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2402 ID.Kind = ValID::t_Constant;
2411 /// ParseGlobalValue - Parse a global value with the specified type.
2412 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2416 bool Parsed = ParseValID(ID) ||
2417 ConvertValIDToValue(Ty, ID, V, NULL);
2418 if (V && !(C = dyn_cast<Constant>(V)))
2419 return Error(ID.Loc, "global values must be constants");
2423 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2424 PATypeHolder Type(Type::getVoidTy(Context));
2425 return ParseType(Type) ||
2426 ParseGlobalValue(Type, V);
2429 /// ParseGlobalValueVector
2431 /// ::= TypeAndValue (',' TypeAndValue)*
2432 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2434 if (Lex.getKind() == lltok::rbrace ||
2435 Lex.getKind() == lltok::rsquare ||
2436 Lex.getKind() == lltok::greater ||
2437 Lex.getKind() == lltok::rparen)
2441 if (ParseGlobalTypeAndValue(C)) return true;
2444 while (EatIfPresent(lltok::comma)) {
2445 if (ParseGlobalTypeAndValue(C)) return true;
2452 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2453 assert(Lex.getKind() == lltok::lbrace);
2456 SmallVector<Value*, 16> Elts;
2457 if (ParseMDNodeVector(Elts, PFS) ||
2458 ParseToken(lltok::rbrace, "expected end of metadata node"))
2461 ID.MDNodeVal = MDNode::get(Context, Elts);
2462 ID.Kind = ValID::t_MDNode;
2466 /// ParseMetadataValue
2470 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2471 assert(Lex.getKind() == lltok::exclaim);
2476 if (Lex.getKind() == lltok::lbrace)
2477 return ParseMetadataListValue(ID, PFS);
2479 // Standalone metadata reference
2481 if (Lex.getKind() == lltok::APSInt) {
2482 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2483 ID.Kind = ValID::t_MDNode;
2488 // ::= '!' STRINGCONSTANT
2489 if (ParseMDString(ID.MDStringVal)) return true;
2490 ID.Kind = ValID::t_MDString;
2495 //===----------------------------------------------------------------------===//
2496 // Function Parsing.
2497 //===----------------------------------------------------------------------===//
2499 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2500 PerFunctionState *PFS) {
2501 if (Ty->isFunctionTy())
2502 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2505 default: llvm_unreachable("Unknown ValID!");
2506 case ValID::t_LocalID:
2507 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2508 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2510 case ValID::t_LocalName:
2511 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2512 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2514 case ValID::t_InlineAsm: {
2515 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2516 const FunctionType *FTy =
2517 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2518 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2519 return Error(ID.Loc, "invalid type for inline asm constraint string");
2520 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2523 case ValID::t_MDNode:
2524 if (!Ty->isMetadataTy())
2525 return Error(ID.Loc, "metadata value must have metadata type");
2528 case ValID::t_MDString:
2529 if (!Ty->isMetadataTy())
2530 return Error(ID.Loc, "metadata value must have metadata type");
2533 case ValID::t_GlobalName:
2534 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2536 case ValID::t_GlobalID:
2537 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2539 case ValID::t_APSInt:
2540 if (!Ty->isIntegerTy())
2541 return Error(ID.Loc, "integer constant must have integer type");
2542 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2543 V = ConstantInt::get(Context, ID.APSIntVal);
2545 case ValID::t_APFloat:
2546 if (!Ty->isFloatingPointTy() ||
2547 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2548 return Error(ID.Loc, "floating point constant invalid for type");
2550 // The lexer has no type info, so builds all float and double FP constants
2551 // as double. Fix this here. Long double does not need this.
2552 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2555 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2558 V = ConstantFP::get(Context, ID.APFloatVal);
2560 if (V->getType() != Ty)
2561 return Error(ID.Loc, "floating point constant does not have type '" +
2562 getTypeString(Ty) + "'");
2566 if (!Ty->isPointerTy())
2567 return Error(ID.Loc, "null must be a pointer type");
2568 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2570 case ValID::t_Undef:
2571 // FIXME: LabelTy should not be a first-class type.
2572 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2574 return Error(ID.Loc, "invalid type for undef constant");
2575 V = UndefValue::get(Ty);
2577 case ValID::t_EmptyArray:
2578 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2579 return Error(ID.Loc, "invalid empty array initializer");
2580 V = UndefValue::get(Ty);
2583 // FIXME: LabelTy should not be a first-class type.
2584 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2585 return Error(ID.Loc, "invalid type for null constant");
2586 V = Constant::getNullValue(Ty);
2588 case ValID::t_Constant:
2589 if (ID.ConstantVal->getType() != Ty)
2590 return Error(ID.Loc, "constant expression type mismatch");
2597 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2600 return ParseValID(ID, &PFS) ||
2601 ConvertValIDToValue(Ty, ID, V, &PFS);
2604 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2605 PATypeHolder T(Type::getVoidTy(Context));
2606 return ParseType(T) ||
2607 ParseValue(T, V, PFS);
2610 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2611 PerFunctionState &PFS) {
2614 if (ParseTypeAndValue(V, PFS)) return true;
2615 if (!isa<BasicBlock>(V))
2616 return Error(Loc, "expected a basic block");
2617 BB = cast<BasicBlock>(V);
2623 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2624 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2625 /// OptionalAlign OptGC
2626 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2627 // Parse the linkage.
2628 LocTy LinkageLoc = Lex.getLoc();
2631 unsigned Visibility, RetAttrs;
2633 PATypeHolder RetType(Type::getVoidTy(Context));
2634 LocTy RetTypeLoc = Lex.getLoc();
2635 if (ParseOptionalLinkage(Linkage) ||
2636 ParseOptionalVisibility(Visibility) ||
2637 ParseOptionalCallingConv(CC) ||
2638 ParseOptionalAttrs(RetAttrs, 1) ||
2639 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2642 // Verify that the linkage is ok.
2643 switch ((GlobalValue::LinkageTypes)Linkage) {
2644 case GlobalValue::ExternalLinkage:
2645 break; // always ok.
2646 case GlobalValue::DLLImportLinkage:
2647 case GlobalValue::ExternalWeakLinkage:
2649 return Error(LinkageLoc, "invalid linkage for function definition");
2651 case GlobalValue::PrivateLinkage:
2652 case GlobalValue::LinkerPrivateLinkage:
2653 case GlobalValue::LinkerPrivateWeakLinkage:
2654 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2655 case GlobalValue::InternalLinkage:
2656 case GlobalValue::AvailableExternallyLinkage:
2657 case GlobalValue::LinkOnceAnyLinkage:
2658 case GlobalValue::LinkOnceODRLinkage:
2659 case GlobalValue::WeakAnyLinkage:
2660 case GlobalValue::WeakODRLinkage:
2661 case GlobalValue::DLLExportLinkage:
2663 return Error(LinkageLoc, "invalid linkage for function declaration");
2665 case GlobalValue::AppendingLinkage:
2666 case GlobalValue::CommonLinkage:
2667 return Error(LinkageLoc, "invalid function linkage type");
2670 if (!FunctionType::isValidReturnType(RetType) ||
2671 RetType->isOpaqueTy())
2672 return Error(RetTypeLoc, "invalid function return type");
2674 LocTy NameLoc = Lex.getLoc();
2676 std::string FunctionName;
2677 if (Lex.getKind() == lltok::GlobalVar) {
2678 FunctionName = Lex.getStrVal();
2679 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2680 unsigned NameID = Lex.getUIntVal();
2682 if (NameID != NumberedVals.size())
2683 return TokError("function expected to be numbered '%" +
2684 Twine(NumberedVals.size()) + "'");
2686 return TokError("expected function name");
2691 if (Lex.getKind() != lltok::lparen)
2692 return TokError("expected '(' in function argument list");
2694 std::vector<ArgInfo> ArgList;
2697 std::string Section;
2701 LocTy UnnamedAddrLoc;
2703 if (ParseArgumentList(ArgList, isVarArg, false) ||
2704 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2706 ParseOptionalAttrs(FuncAttrs, 2) ||
2707 (EatIfPresent(lltok::kw_section) &&
2708 ParseStringConstant(Section)) ||
2709 ParseOptionalAlignment(Alignment) ||
2710 (EatIfPresent(lltok::kw_gc) &&
2711 ParseStringConstant(GC)))
2714 // If the alignment was parsed as an attribute, move to the alignment field.
2715 if (FuncAttrs & Attribute::Alignment) {
2716 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2717 FuncAttrs &= ~Attribute::Alignment;
2720 // Okay, if we got here, the function is syntactically valid. Convert types
2721 // and do semantic checks.
2722 std::vector<const Type*> ParamTypeList;
2723 SmallVector<AttributeWithIndex, 8> Attrs;
2725 if (RetAttrs != Attribute::None)
2726 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2728 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2729 ParamTypeList.push_back(ArgList[i].Type);
2730 if (ArgList[i].Attrs != Attribute::None)
2731 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2734 if (FuncAttrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2737 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2739 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2740 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2742 const FunctionType *FT =
2743 FunctionType::get(RetType, ParamTypeList, isVarArg);
2744 const PointerType *PFT = PointerType::getUnqual(FT);
2747 if (!FunctionName.empty()) {
2748 // If this was a definition of a forward reference, remove the definition
2749 // from the forward reference table and fill in the forward ref.
2750 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2751 ForwardRefVals.find(FunctionName);
2752 if (FRVI != ForwardRefVals.end()) {
2753 Fn = M->getFunction(FunctionName);
2754 if (Fn->getType() != PFT)
2755 return Error(FRVI->second.second, "invalid forward reference to "
2756 "function '" + FunctionName + "' with wrong type!");
2758 ForwardRefVals.erase(FRVI);
2759 } else if ((Fn = M->getFunction(FunctionName))) {
2760 // Reject redefinitions.
2761 return Error(NameLoc, "invalid redefinition of function '" +
2762 FunctionName + "'");
2763 } else if (M->getNamedValue(FunctionName)) {
2764 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2768 // If this is a definition of a forward referenced function, make sure the
2770 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2771 = ForwardRefValIDs.find(NumberedVals.size());
2772 if (I != ForwardRefValIDs.end()) {
2773 Fn = cast<Function>(I->second.first);
2774 if (Fn->getType() != PFT)
2775 return Error(NameLoc, "type of definition and forward reference of '@" +
2776 Twine(NumberedVals.size()) + "' disagree");
2777 ForwardRefValIDs.erase(I);
2782 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2783 else // Move the forward-reference to the correct spot in the module.
2784 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2786 if (FunctionName.empty())
2787 NumberedVals.push_back(Fn);
2789 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2790 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2791 Fn->setCallingConv(CC);
2792 Fn->setAttributes(PAL);
2793 Fn->setUnnamedAddr(UnnamedAddr);
2794 Fn->setAlignment(Alignment);
2795 Fn->setSection(Section);
2796 if (!GC.empty()) Fn->setGC(GC.c_str());
2798 // Add all of the arguments we parsed to the function.
2799 Function::arg_iterator ArgIt = Fn->arg_begin();
2800 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2801 // If the argument has a name, insert it into the argument symbol table.
2802 if (ArgList[i].Name.empty()) continue;
2804 // Set the name, if it conflicted, it will be auto-renamed.
2805 ArgIt->setName(ArgList[i].Name);
2807 if (ArgIt->getName() != ArgList[i].Name)
2808 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2809 ArgList[i].Name + "'");
2816 /// ParseFunctionBody
2817 /// ::= '{' BasicBlock+ '}'
2819 bool LLParser::ParseFunctionBody(Function &Fn) {
2820 if (Lex.getKind() != lltok::lbrace)
2821 return TokError("expected '{' in function body");
2822 Lex.Lex(); // eat the {.
2824 int FunctionNumber = -1;
2825 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2827 PerFunctionState PFS(*this, Fn, FunctionNumber);
2829 // We need at least one basic block.
2830 if (Lex.getKind() == lltok::rbrace)
2831 return TokError("function body requires at least one basic block");
2833 while (Lex.getKind() != lltok::rbrace)
2834 if (ParseBasicBlock(PFS)) return true;
2839 // Verify function is ok.
2840 return PFS.FinishFunction();
2844 /// ::= LabelStr? Instruction*
2845 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2846 // If this basic block starts out with a name, remember it.
2848 LocTy NameLoc = Lex.getLoc();
2849 if (Lex.getKind() == lltok::LabelStr) {
2850 Name = Lex.getStrVal();
2854 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2855 if (BB == 0) return true;
2857 std::string NameStr;
2859 // Parse the instructions in this block until we get a terminator.
2861 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2863 // This instruction may have three possibilities for a name: a) none
2864 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2865 LocTy NameLoc = Lex.getLoc();
2869 if (Lex.getKind() == lltok::LocalVarID) {
2870 NameID = Lex.getUIntVal();
2872 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2874 } else if (Lex.getKind() == lltok::LocalVar) {
2875 NameStr = Lex.getStrVal();
2877 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2881 switch (ParseInstruction(Inst, BB, PFS)) {
2882 default: assert(0 && "Unknown ParseInstruction result!");
2883 case InstError: return true;
2885 BB->getInstList().push_back(Inst);
2887 // With a normal result, we check to see if the instruction is followed by
2888 // a comma and metadata.
2889 if (EatIfPresent(lltok::comma))
2890 if (ParseInstructionMetadata(Inst, &PFS))
2893 case InstExtraComma:
2894 BB->getInstList().push_back(Inst);
2896 // If the instruction parser ate an extra comma at the end of it, it
2897 // *must* be followed by metadata.
2898 if (ParseInstructionMetadata(Inst, &PFS))
2903 // Set the name on the instruction.
2904 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2905 } while (!isa<TerminatorInst>(Inst));
2910 //===----------------------------------------------------------------------===//
2911 // Instruction Parsing.
2912 //===----------------------------------------------------------------------===//
2914 /// ParseInstruction - Parse one of the many different instructions.
2916 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2917 PerFunctionState &PFS) {
2918 lltok::Kind Token = Lex.getKind();
2919 if (Token == lltok::Eof)
2920 return TokError("found end of file when expecting more instructions");
2921 LocTy Loc = Lex.getLoc();
2922 unsigned KeywordVal = Lex.getUIntVal();
2923 Lex.Lex(); // Eat the keyword.
2926 default: return Error(Loc, "expected instruction opcode");
2927 // Terminator Instructions.
2928 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2929 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2930 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2931 case lltok::kw_br: return ParseBr(Inst, PFS);
2932 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2933 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2934 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2935 // Binary Operators.
2939 case lltok::kw_shl: {
2940 bool NUW = EatIfPresent(lltok::kw_nuw);
2941 bool NSW = EatIfPresent(lltok::kw_nsw);
2942 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2944 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2946 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2947 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2950 case lltok::kw_fadd:
2951 case lltok::kw_fsub:
2952 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2954 case lltok::kw_sdiv:
2955 case lltok::kw_udiv:
2956 case lltok::kw_lshr:
2957 case lltok::kw_ashr: {
2958 bool Exact = EatIfPresent(lltok::kw_exact);
2960 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2961 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2965 case lltok::kw_urem:
2966 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2967 case lltok::kw_fdiv:
2968 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2971 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2972 case lltok::kw_icmp:
2973 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2975 case lltok::kw_trunc:
2976 case lltok::kw_zext:
2977 case lltok::kw_sext:
2978 case lltok::kw_fptrunc:
2979 case lltok::kw_fpext:
2980 case lltok::kw_bitcast:
2981 case lltok::kw_uitofp:
2982 case lltok::kw_sitofp:
2983 case lltok::kw_fptoui:
2984 case lltok::kw_fptosi:
2985 case lltok::kw_inttoptr:
2986 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2988 case lltok::kw_select: return ParseSelect(Inst, PFS);
2989 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2990 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2991 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2992 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2993 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2994 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2995 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2997 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2998 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2999 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3000 case lltok::kw_volatile:
3001 if (EatIfPresent(lltok::kw_load))
3002 return ParseLoad(Inst, PFS, true);
3003 else if (EatIfPresent(lltok::kw_store))
3004 return ParseStore(Inst, PFS, true);
3006 return TokError("expected 'load' or 'store'");
3007 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3008 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3009 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3013 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3014 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3015 if (Opc == Instruction::FCmp) {
3016 switch (Lex.getKind()) {
3017 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3018 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3019 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3020 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3021 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3022 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3023 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3024 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3025 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3026 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3027 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3028 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3029 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3030 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3031 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3032 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3033 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3036 switch (Lex.getKind()) {
3037 default: TokError("expected icmp predicate (e.g. 'eq')");
3038 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3039 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3040 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3041 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3042 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3043 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3044 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3045 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3046 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3047 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3054 //===----------------------------------------------------------------------===//
3055 // Terminator Instructions.
3056 //===----------------------------------------------------------------------===//
3058 /// ParseRet - Parse a return instruction.
3059 /// ::= 'ret' void (',' !dbg, !1)*
3060 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3061 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3062 PerFunctionState &PFS) {
3063 PATypeHolder Ty(Type::getVoidTy(Context));
3064 if (ParseType(Ty, true /*void allowed*/)) return true;
3066 if (Ty->isVoidTy()) {
3067 Inst = ReturnInst::Create(Context);
3072 if (ParseValue(Ty, RV, PFS)) return true;
3074 Inst = ReturnInst::Create(Context, RV);
3080 /// ::= 'br' TypeAndValue
3081 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3082 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3085 BasicBlock *Op1, *Op2;
3086 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3088 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3089 Inst = BranchInst::Create(BB);
3093 if (Op0->getType() != Type::getInt1Ty(Context))
3094 return Error(Loc, "branch condition must have 'i1' type");
3096 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3097 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3098 ParseToken(lltok::comma, "expected ',' after true destination") ||
3099 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3102 Inst = BranchInst::Create(Op1, Op2, Op0);
3108 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3110 /// ::= (TypeAndValue ',' TypeAndValue)*
3111 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3112 LocTy CondLoc, BBLoc;
3114 BasicBlock *DefaultBB;
3115 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3116 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3117 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3118 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3121 if (!Cond->getType()->isIntegerTy())
3122 return Error(CondLoc, "switch condition must have integer type");
3124 // Parse the jump table pairs.
3125 SmallPtrSet<Value*, 32> SeenCases;
3126 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3127 while (Lex.getKind() != lltok::rsquare) {
3131 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3132 ParseToken(lltok::comma, "expected ',' after case value") ||
3133 ParseTypeAndBasicBlock(DestBB, PFS))
3136 if (!SeenCases.insert(Constant))
3137 return Error(CondLoc, "duplicate case value in switch");
3138 if (!isa<ConstantInt>(Constant))
3139 return Error(CondLoc, "case value is not a constant integer");
3141 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3144 Lex.Lex(); // Eat the ']'.
3146 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3147 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3148 SI->addCase(Table[i].first, Table[i].second);
3155 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3156 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3159 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3160 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3161 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3164 if (!Address->getType()->isPointerTy())
3165 return Error(AddrLoc, "indirectbr address must have pointer type");
3167 // Parse the destination list.
3168 SmallVector<BasicBlock*, 16> DestList;
3170 if (Lex.getKind() != lltok::rsquare) {
3172 if (ParseTypeAndBasicBlock(DestBB, PFS))
3174 DestList.push_back(DestBB);
3176 while (EatIfPresent(lltok::comma)) {
3177 if (ParseTypeAndBasicBlock(DestBB, PFS))
3179 DestList.push_back(DestBB);
3183 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3186 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3187 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3188 IBI->addDestination(DestList[i]);
3195 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3196 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3197 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3198 LocTy CallLoc = Lex.getLoc();
3199 unsigned RetAttrs, FnAttrs;
3201 PATypeHolder RetType(Type::getVoidTy(Context));
3204 SmallVector<ParamInfo, 16> ArgList;
3206 BasicBlock *NormalBB, *UnwindBB;
3207 if (ParseOptionalCallingConv(CC) ||
3208 ParseOptionalAttrs(RetAttrs, 1) ||
3209 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3210 ParseValID(CalleeID) ||
3211 ParseParameterList(ArgList, PFS) ||
3212 ParseOptionalAttrs(FnAttrs, 2) ||
3213 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3214 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3215 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3216 ParseTypeAndBasicBlock(UnwindBB, PFS))
3219 // If RetType is a non-function pointer type, then this is the short syntax
3220 // for the call, which means that RetType is just the return type. Infer the
3221 // rest of the function argument types from the arguments that are present.
3222 const PointerType *PFTy = 0;
3223 const FunctionType *Ty = 0;
3224 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3225 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3226 // Pull out the types of all of the arguments...
3227 std::vector<const Type*> ParamTypes;
3228 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3229 ParamTypes.push_back(ArgList[i].V->getType());
3231 if (!FunctionType::isValidReturnType(RetType))
3232 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3234 Ty = FunctionType::get(RetType, ParamTypes, false);
3235 PFTy = PointerType::getUnqual(Ty);
3238 // Look up the callee.
3240 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3242 // Set up the Attributes for the function.
3243 SmallVector<AttributeWithIndex, 8> Attrs;
3244 if (RetAttrs != Attribute::None)
3245 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3247 SmallVector<Value*, 8> Args;
3249 // Loop through FunctionType's arguments and ensure they are specified
3250 // correctly. Also, gather any parameter attributes.
3251 FunctionType::param_iterator I = Ty->param_begin();
3252 FunctionType::param_iterator E = Ty->param_end();
3253 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3254 const Type *ExpectedTy = 0;
3257 } else if (!Ty->isVarArg()) {
3258 return Error(ArgList[i].Loc, "too many arguments specified");
3261 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3262 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3263 getTypeString(ExpectedTy) + "'");
3264 Args.push_back(ArgList[i].V);
3265 if (ArgList[i].Attrs != Attribute::None)
3266 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3270 return Error(CallLoc, "not enough parameters specified for call");
3272 if (FnAttrs != Attribute::None)
3273 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3275 // Finish off the Attributes and check them
3276 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3278 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3279 Args.begin(), Args.end());
3280 II->setCallingConv(CC);
3281 II->setAttributes(PAL);
3288 //===----------------------------------------------------------------------===//
3289 // Binary Operators.
3290 //===----------------------------------------------------------------------===//
3293 /// ::= ArithmeticOps TypeAndValue ',' Value
3295 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3296 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3297 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3298 unsigned Opc, unsigned OperandType) {
3299 LocTy Loc; Value *LHS, *RHS;
3300 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3301 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3302 ParseValue(LHS->getType(), RHS, PFS))
3306 switch (OperandType) {
3307 default: llvm_unreachable("Unknown operand type!");
3308 case 0: // int or FP.
3309 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3310 LHS->getType()->isFPOrFPVectorTy();
3312 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3313 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3317 return Error(Loc, "invalid operand type for instruction");
3319 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3324 /// ::= ArithmeticOps TypeAndValue ',' Value {
3325 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3327 LocTy Loc; Value *LHS, *RHS;
3328 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3329 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3330 ParseValue(LHS->getType(), RHS, PFS))
3333 if (!LHS->getType()->isIntOrIntVectorTy())
3334 return Error(Loc,"instruction requires integer or integer vector operands");
3336 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3342 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3343 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3344 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3346 // Parse the integer/fp comparison predicate.
3350 if (ParseCmpPredicate(Pred, Opc) ||
3351 ParseTypeAndValue(LHS, Loc, PFS) ||
3352 ParseToken(lltok::comma, "expected ',' after compare value") ||
3353 ParseValue(LHS->getType(), RHS, PFS))
3356 if (Opc == Instruction::FCmp) {
3357 if (!LHS->getType()->isFPOrFPVectorTy())
3358 return Error(Loc, "fcmp requires floating point operands");
3359 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3361 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3362 if (!LHS->getType()->isIntOrIntVectorTy() &&
3363 !LHS->getType()->isPointerTy())
3364 return Error(Loc, "icmp requires integer operands");
3365 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3370 //===----------------------------------------------------------------------===//
3371 // Other Instructions.
3372 //===----------------------------------------------------------------------===//
3376 /// ::= CastOpc TypeAndValue 'to' Type
3377 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3379 LocTy Loc; Value *Op;
3380 PATypeHolder DestTy(Type::getVoidTy(Context));
3381 if (ParseTypeAndValue(Op, Loc, PFS) ||
3382 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3386 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3387 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3388 return Error(Loc, "invalid cast opcode for cast from '" +
3389 getTypeString(Op->getType()) + "' to '" +
3390 getTypeString(DestTy) + "'");
3392 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3397 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3398 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3400 Value *Op0, *Op1, *Op2;
3401 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3402 ParseToken(lltok::comma, "expected ',' after select condition") ||
3403 ParseTypeAndValue(Op1, PFS) ||
3404 ParseToken(lltok::comma, "expected ',' after select value") ||
3405 ParseTypeAndValue(Op2, PFS))
3408 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3409 return Error(Loc, Reason);
3411 Inst = SelectInst::Create(Op0, Op1, Op2);
3416 /// ::= 'va_arg' TypeAndValue ',' Type
3417 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3419 PATypeHolder EltTy(Type::getVoidTy(Context));
3421 if (ParseTypeAndValue(Op, PFS) ||
3422 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3423 ParseType(EltTy, TypeLoc))
3426 if (!EltTy->isFirstClassType())
3427 return Error(TypeLoc, "va_arg requires operand with first class type");
3429 Inst = new VAArgInst(Op, EltTy);
3433 /// ParseExtractElement
3434 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3435 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3438 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3439 ParseToken(lltok::comma, "expected ',' after extract value") ||
3440 ParseTypeAndValue(Op1, PFS))
3443 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3444 return Error(Loc, "invalid extractelement operands");
3446 Inst = ExtractElementInst::Create(Op0, Op1);
3450 /// ParseInsertElement
3451 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3452 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3454 Value *Op0, *Op1, *Op2;
3455 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3456 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3457 ParseTypeAndValue(Op1, PFS) ||
3458 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3459 ParseTypeAndValue(Op2, PFS))
3462 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3463 return Error(Loc, "invalid insertelement operands");
3465 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3469 /// ParseShuffleVector
3470 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3471 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3473 Value *Op0, *Op1, *Op2;
3474 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3475 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3476 ParseTypeAndValue(Op1, PFS) ||
3477 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3478 ParseTypeAndValue(Op2, PFS))
3481 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3482 return Error(Loc, "invalid extractelement operands");
3484 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3489 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3490 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3491 PATypeHolder Ty(Type::getVoidTy(Context));
3493 LocTy TypeLoc = Lex.getLoc();
3495 if (ParseType(Ty) ||
3496 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3497 ParseValue(Ty, Op0, PFS) ||
3498 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3499 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3500 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3503 bool AteExtraComma = false;
3504 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3506 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3508 if (!EatIfPresent(lltok::comma))
3511 if (Lex.getKind() == lltok::MetadataVar) {
3512 AteExtraComma = true;
3516 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3517 ParseValue(Ty, Op0, PFS) ||
3518 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3519 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3520 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3524 if (!Ty->isFirstClassType())
3525 return Error(TypeLoc, "phi node must have first class type");
3527 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3528 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3529 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3531 return AteExtraComma ? InstExtraComma : InstNormal;
3535 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3536 /// ParameterList OptionalAttrs
3537 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3539 unsigned RetAttrs, FnAttrs;
3541 PATypeHolder RetType(Type::getVoidTy(Context));
3544 SmallVector<ParamInfo, 16> ArgList;
3545 LocTy CallLoc = Lex.getLoc();
3547 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3548 ParseOptionalCallingConv(CC) ||
3549 ParseOptionalAttrs(RetAttrs, 1) ||
3550 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3551 ParseValID(CalleeID) ||
3552 ParseParameterList(ArgList, PFS) ||
3553 ParseOptionalAttrs(FnAttrs, 2))
3556 // If RetType is a non-function pointer type, then this is the short syntax
3557 // for the call, which means that RetType is just the return type. Infer the
3558 // rest of the function argument types from the arguments that are present.
3559 const PointerType *PFTy = 0;
3560 const FunctionType *Ty = 0;
3561 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3562 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3563 // Pull out the types of all of the arguments...
3564 std::vector<const Type*> ParamTypes;
3565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3566 ParamTypes.push_back(ArgList[i].V->getType());
3568 if (!FunctionType::isValidReturnType(RetType))
3569 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3571 Ty = FunctionType::get(RetType, ParamTypes, false);
3572 PFTy = PointerType::getUnqual(Ty);
3575 // Look up the callee.
3577 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3579 // Set up the Attributes for the function.
3580 SmallVector<AttributeWithIndex, 8> Attrs;
3581 if (RetAttrs != Attribute::None)
3582 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3584 SmallVector<Value*, 8> Args;
3586 // Loop through FunctionType's arguments and ensure they are specified
3587 // correctly. Also, gather any parameter attributes.
3588 FunctionType::param_iterator I = Ty->param_begin();
3589 FunctionType::param_iterator E = Ty->param_end();
3590 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3591 const Type *ExpectedTy = 0;
3594 } else if (!Ty->isVarArg()) {
3595 return Error(ArgList[i].Loc, "too many arguments specified");
3598 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3599 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3600 getTypeString(ExpectedTy) + "'");
3601 Args.push_back(ArgList[i].V);
3602 if (ArgList[i].Attrs != Attribute::None)
3603 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3607 return Error(CallLoc, "not enough parameters specified for call");
3609 if (FnAttrs != Attribute::None)
3610 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3612 // Finish off the Attributes and check them
3613 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3615 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3616 CI->setTailCall(isTail);
3617 CI->setCallingConv(CC);
3618 CI->setAttributes(PAL);
3623 //===----------------------------------------------------------------------===//
3624 // Memory Instructions.
3625 //===----------------------------------------------------------------------===//
3628 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3629 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3630 PATypeHolder Ty(Type::getVoidTy(Context));
3633 unsigned Alignment = 0;
3634 if (ParseType(Ty)) return true;
3636 bool AteExtraComma = false;
3637 if (EatIfPresent(lltok::comma)) {
3638 if (Lex.getKind() == lltok::kw_align) {
3639 if (ParseOptionalAlignment(Alignment)) return true;
3640 } else if (Lex.getKind() == lltok::MetadataVar) {
3641 AteExtraComma = true;
3643 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3644 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3649 if (Size && !Size->getType()->isIntegerTy())
3650 return Error(SizeLoc, "element count must have integer type");
3652 Inst = new AllocaInst(Ty, Size, Alignment);
3653 return AteExtraComma ? InstExtraComma : InstNormal;
3657 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3658 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3660 Value *Val; LocTy Loc;
3661 unsigned Alignment = 0;
3662 bool AteExtraComma = false;
3663 if (ParseTypeAndValue(Val, Loc, PFS) ||
3664 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3667 if (!Val->getType()->isPointerTy() ||
3668 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3669 return Error(Loc, "load operand must be a pointer to a first class type");
3671 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3672 return AteExtraComma ? InstExtraComma : InstNormal;
3676 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3677 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3679 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3680 unsigned Alignment = 0;
3681 bool AteExtraComma = false;
3682 if (ParseTypeAndValue(Val, Loc, PFS) ||
3683 ParseToken(lltok::comma, "expected ',' after store operand") ||
3684 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3685 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3688 if (!Ptr->getType()->isPointerTy())
3689 return Error(PtrLoc, "store operand must be a pointer");
3690 if (!Val->getType()->isFirstClassType())
3691 return Error(Loc, "store operand must be a first class value");
3692 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3693 return Error(Loc, "stored value and pointer type do not match");
3695 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3696 return AteExtraComma ? InstExtraComma : InstNormal;
3699 /// ParseGetElementPtr
3700 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3701 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3702 Value *Ptr, *Val; LocTy Loc, EltLoc;
3704 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3706 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3708 if (!Ptr->getType()->isPointerTy())
3709 return Error(Loc, "base of getelementptr must be a pointer");
3711 SmallVector<Value*, 16> Indices;
3712 bool AteExtraComma = false;
3713 while (EatIfPresent(lltok::comma)) {
3714 if (Lex.getKind() == lltok::MetadataVar) {
3715 AteExtraComma = true;
3718 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3719 if (!Val->getType()->isIntegerTy())
3720 return Error(EltLoc, "getelementptr index must be an integer");
3721 Indices.push_back(Val);
3724 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3725 Indices.begin(), Indices.end()))
3726 return Error(Loc, "invalid getelementptr indices");
3727 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3729 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3730 return AteExtraComma ? InstExtraComma : InstNormal;
3733 /// ParseExtractValue
3734 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3735 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3736 Value *Val; LocTy Loc;
3737 SmallVector<unsigned, 4> Indices;
3739 if (ParseTypeAndValue(Val, Loc, PFS) ||
3740 ParseIndexList(Indices, AteExtraComma))
3743 if (!Val->getType()->isAggregateType())
3744 return Error(Loc, "extractvalue operand must be aggregate type");
3746 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3748 return Error(Loc, "invalid indices for extractvalue");
3749 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3750 return AteExtraComma ? InstExtraComma : InstNormal;
3753 /// ParseInsertValue
3754 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3755 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3756 Value *Val0, *Val1; LocTy Loc0, Loc1;
3757 SmallVector<unsigned, 4> Indices;
3759 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3760 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3761 ParseTypeAndValue(Val1, Loc1, PFS) ||
3762 ParseIndexList(Indices, AteExtraComma))
3765 if (!Val0->getType()->isAggregateType())
3766 return Error(Loc0, "insertvalue operand must be aggregate type");
3768 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3770 return Error(Loc0, "invalid indices for insertvalue");
3771 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3772 return AteExtraComma ? InstExtraComma : InstNormal;
3775 //===----------------------------------------------------------------------===//
3776 // Embedded metadata.
3777 //===----------------------------------------------------------------------===//
3779 /// ParseMDNodeVector
3780 /// ::= Element (',' Element)*
3782 /// ::= 'null' | TypeAndValue
3783 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3784 PerFunctionState *PFS) {
3785 // Check for an empty list.
3786 if (Lex.getKind() == lltok::rbrace)
3790 // Null is a special case since it is typeless.
3791 if (EatIfPresent(lltok::kw_null)) {
3797 PATypeHolder Ty(Type::getVoidTy(Context));
3799 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3800 ConvertValIDToValue(Ty, ID, V, PFS))
3804 } while (EatIfPresent(lltok::comma));