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/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
33 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
39 t_LocalID
, t_GlobalID
, // ID in UIntVal.
40 t_LocalName
, t_GlobalName
, // Name in StrVal.
41 t_APSInt
, t_APFloat
, // Value in APSIntVal/APFloatVal.
42 t_Null
, t_Undef
, t_Zero
, // No value.
43 t_EmptyArray
, // No value: []
44 t_Constant
, // Value in ConstantVal.
45 t_InlineAsm
, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata
// Value in MetadataVal.
51 std::string StrVal
, StrVal2
;
54 Constant
*ConstantVal
;
55 MetadataBase
*MetadataVal
;
56 ValID() : APFloatVal(0.0) {}
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
65 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
71 bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes
.empty())
73 return Error(ForwardRefTypes
.begin()->second
.second
,
74 "use of undefined type named '" +
75 ForwardRefTypes
.begin()->first
+ "'");
76 if (!ForwardRefTypeIDs
.empty())
77 return Error(ForwardRefTypeIDs
.begin()->second
.second
,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs
.begin()->first
) + "'");
81 if (!ForwardRefVals
.empty())
82 return Error(ForwardRefVals
.begin()->second
.second
,
83 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
86 if (!ForwardRefValIDs
.empty())
87 return Error(ForwardRefValIDs
.begin()->second
.second
,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs
.begin()->first
) + "'");
91 if (!ForwardRefMDNodes
.empty())
92 return Error(ForwardRefMDNodes
.begin()->second
.second
,
93 "use of undefined metadata '!" +
94 utostr(ForwardRefMDNodes
.begin()->first
) + "'");
97 // Look for intrinsic functions and CallInst that need to be upgraded
98 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
99 UpgradeCallsToIntrinsic(FI
++); // must be post-increment, as we remove
101 // Check debug info intrinsics.
102 CheckDebugInfoIntrinsics(M
);
106 //===----------------------------------------------------------------------===//
107 // Top-Level Entities
108 //===----------------------------------------------------------------------===//
110 bool LLParser::ParseTopLevelEntities() {
112 switch (Lex
.getKind()) {
113 default: return TokError("expected top-level entity");
114 case lltok::Eof
: return false;
115 //case lltok::kw_define:
116 case lltok::kw_declare
: if (ParseDeclare()) return true; break;
117 case lltok::kw_define
: if (ParseDefine()) return true; break;
118 case lltok::kw_module
: if (ParseModuleAsm()) return true; break;
119 case lltok::kw_target
: if (ParseTargetDefinition()) return true; break;
120 case lltok::kw_deplibs
: if (ParseDepLibs()) return true; break;
121 case lltok::kw_type
: if (ParseUnnamedType()) return true; break;
122 case lltok::LocalVarID
: if (ParseUnnamedType()) return true; break;
123 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
124 case lltok::LocalVar
: if (ParseNamedType()) return true; break;
125 case lltok::GlobalID
: if (ParseUnnamedGlobal()) return true; break;
126 case lltok::GlobalVar
: if (ParseNamedGlobal()) return true; break;
127 case lltok::Metadata
: if (ParseStandaloneMetadata()) return true; break;
128 case lltok::NamedMD
: if (ParseNamedMetadata()) return true; break;
130 // The Global variable production with no name can have many different
131 // optional leading prefixes, the production is:
132 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
133 // OptionalAddrSpace ('constant'|'global') ...
134 case lltok::kw_private
: // OptionalLinkage
135 case lltok::kw_linker_private
: // OptionalLinkage
136 case lltok::kw_internal
: // OptionalLinkage
137 case lltok::kw_weak
: // OptionalLinkage
138 case lltok::kw_weak_odr
: // OptionalLinkage
139 case lltok::kw_linkonce
: // OptionalLinkage
140 case lltok::kw_linkonce_odr
: // OptionalLinkage
141 case lltok::kw_appending
: // OptionalLinkage
142 case lltok::kw_dllexport
: // OptionalLinkage
143 case lltok::kw_common
: // OptionalLinkage
144 case lltok::kw_dllimport
: // OptionalLinkage
145 case lltok::kw_extern_weak
: // OptionalLinkage
146 case lltok::kw_external
: { // OptionalLinkage
147 unsigned Linkage
, Visibility
;
148 if (ParseOptionalLinkage(Linkage
) ||
149 ParseOptionalVisibility(Visibility
) ||
150 ParseGlobal("", SMLoc(), Linkage
, true, Visibility
))
154 case lltok::kw_default
: // OptionalVisibility
155 case lltok::kw_hidden
: // OptionalVisibility
156 case lltok::kw_protected
: { // OptionalVisibility
158 if (ParseOptionalVisibility(Visibility
) ||
159 ParseGlobal("", SMLoc(), 0, false, Visibility
))
164 case lltok::kw_thread_local
: // OptionalThreadLocal
165 case lltok::kw_addrspace
: // OptionalAddrSpace
166 case lltok::kw_constant
: // GlobalType
167 case lltok::kw_global
: // GlobalType
168 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
176 /// ::= 'module' 'asm' STRINGCONSTANT
177 bool LLParser::ParseModuleAsm() {
178 assert(Lex
.getKind() == lltok::kw_module
);
182 if (ParseToken(lltok::kw_asm
, "expected 'module asm'") ||
183 ParseStringConstant(AsmStr
)) return true;
185 const std::string
&AsmSoFar
= M
->getModuleInlineAsm();
186 if (AsmSoFar
.empty())
187 M
->setModuleInlineAsm(AsmStr
);
189 M
->setModuleInlineAsm(AsmSoFar
+"\n"+AsmStr
);
194 /// ::= 'target' 'triple' '=' STRINGCONSTANT
195 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
196 bool LLParser::ParseTargetDefinition() {
197 assert(Lex
.getKind() == lltok::kw_target
);
200 default: return TokError("unknown target property");
201 case lltok::kw_triple
:
203 if (ParseToken(lltok::equal
, "expected '=' after target triple") ||
204 ParseStringConstant(Str
))
206 M
->setTargetTriple(Str
);
208 case lltok::kw_datalayout
:
210 if (ParseToken(lltok::equal
, "expected '=' after target datalayout") ||
211 ParseStringConstant(Str
))
213 M
->setDataLayout(Str
);
219 /// ::= 'deplibs' '=' '[' ']'
220 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
221 bool LLParser::ParseDepLibs() {
222 assert(Lex
.getKind() == lltok::kw_deplibs
);
224 if (ParseToken(lltok::equal
, "expected '=' after deplibs") ||
225 ParseToken(lltok::lsquare
, "expected '=' after deplibs"))
228 if (EatIfPresent(lltok::rsquare
))
232 if (ParseStringConstant(Str
)) return true;
235 while (EatIfPresent(lltok::comma
)) {
236 if (ParseStringConstant(Str
)) return true;
240 return ParseToken(lltok::rsquare
, "expected ']' at end of list");
243 /// ParseUnnamedType:
245 /// ::= LocalVarID '=' 'type' type
246 bool LLParser::ParseUnnamedType() {
247 unsigned TypeID
= NumberedTypes
.size();
249 // Handle the LocalVarID form.
250 if (Lex
.getKind() == lltok::LocalVarID
) {
251 if (Lex
.getUIntVal() != TypeID
)
252 return Error(Lex
.getLoc(), "type expected to be numbered '%" +
253 utostr(TypeID
) + "'");
254 Lex
.Lex(); // eat LocalVarID;
256 if (ParseToken(lltok::equal
, "expected '=' after name"))
260 assert(Lex
.getKind() == lltok::kw_type
);
261 LocTy TypeLoc
= Lex
.getLoc();
262 Lex
.Lex(); // eat kw_type
264 PATypeHolder
Ty(Type::getVoidTy(Context
));
265 if (ParseType(Ty
)) return true;
267 // See if this type was previously referenced.
268 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
269 FI
= ForwardRefTypeIDs
.find(TypeID
);
270 if (FI
!= ForwardRefTypeIDs
.end()) {
271 if (FI
->second
.first
.get() == Ty
)
272 return Error(TypeLoc
, "self referential type is invalid");
274 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
275 Ty
= FI
->second
.first
.get();
276 ForwardRefTypeIDs
.erase(FI
);
279 NumberedTypes
.push_back(Ty
);
285 /// ::= LocalVar '=' 'type' type
286 bool LLParser::ParseNamedType() {
287 std::string Name
= Lex
.getStrVal();
288 LocTy NameLoc
= Lex
.getLoc();
289 Lex
.Lex(); // eat LocalVar.
291 PATypeHolder
Ty(Type::getVoidTy(Context
));
293 if (ParseToken(lltok::equal
, "expected '=' after name") ||
294 ParseToken(lltok::kw_type
, "expected 'type' after name") ||
298 // Set the type name, checking for conflicts as we do so.
299 bool AlreadyExists
= M
->addTypeName(Name
, Ty
);
300 if (!AlreadyExists
) return false;
302 // See if this type is a forward reference. We need to eagerly resolve
303 // types to allow recursive type redefinitions below.
304 std::map
<std::string
, std::pair
<PATypeHolder
, LocTy
> >::iterator
305 FI
= ForwardRefTypes
.find(Name
);
306 if (FI
!= ForwardRefTypes
.end()) {
307 if (FI
->second
.first
.get() == Ty
)
308 return Error(NameLoc
, "self referential type is invalid");
310 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
311 Ty
= FI
->second
.first
.get();
312 ForwardRefTypes
.erase(FI
);
315 // Inserting a name that is already defined, get the existing name.
316 const Type
*Existing
= M
->getTypeByName(Name
);
317 assert(Existing
&& "Conflict but no matching type?!");
319 // Otherwise, this is an attempt to redefine a type. That's okay if
320 // the redefinition is identical to the original.
321 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
322 if (Existing
== Ty
) return false;
324 // Any other kind of (non-equivalent) redefinition is an error.
325 return Error(NameLoc
, "redefinition of type named '" + Name
+ "' of type '" +
326 Ty
->getDescription() + "'");
331 /// ::= 'declare' FunctionHeader
332 bool LLParser::ParseDeclare() {
333 assert(Lex
.getKind() == lltok::kw_declare
);
337 return ParseFunctionHeader(F
, false);
341 /// ::= 'define' FunctionHeader '{' ...
342 bool LLParser::ParseDefine() {
343 assert(Lex
.getKind() == lltok::kw_define
);
347 return ParseFunctionHeader(F
, true) ||
348 ParseFunctionBody(*F
);
354 bool LLParser::ParseGlobalType(bool &IsConstant
) {
355 if (Lex
.getKind() == lltok::kw_constant
)
357 else if (Lex
.getKind() == lltok::kw_global
)
361 return TokError("expected 'global' or 'constant'");
367 /// ParseUnnamedGlobal:
368 /// OptionalVisibility ALIAS ...
369 /// OptionalLinkage OptionalVisibility ... -> global variable
370 /// GlobalID '=' OptionalVisibility ALIAS ...
371 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
372 bool LLParser::ParseUnnamedGlobal() {
373 unsigned VarID
= NumberedVals
.size();
375 LocTy NameLoc
= Lex
.getLoc();
377 // Handle the GlobalID form.
378 if (Lex
.getKind() == lltok::GlobalID
) {
379 if (Lex
.getUIntVal() != VarID
)
380 return Error(Lex
.getLoc(), "variable expected to be numbered '%" +
381 utostr(VarID
) + "'");
382 Lex
.Lex(); // eat GlobalID;
384 if (ParseToken(lltok::equal
, "expected '=' after name"))
389 unsigned Linkage
, Visibility
;
390 if (ParseOptionalLinkage(Linkage
, HasLinkage
) ||
391 ParseOptionalVisibility(Visibility
))
394 if (HasLinkage
|| Lex
.getKind() != lltok::kw_alias
)
395 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
);
396 return ParseAlias(Name
, NameLoc
, Visibility
);
399 /// ParseNamedGlobal:
400 /// GlobalVar '=' OptionalVisibility ALIAS ...
401 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
402 bool LLParser::ParseNamedGlobal() {
403 assert(Lex
.getKind() == lltok::GlobalVar
);
404 LocTy NameLoc
= Lex
.getLoc();
405 std::string Name
= Lex
.getStrVal();
409 unsigned Linkage
, Visibility
;
410 if (ParseToken(lltok::equal
, "expected '=' in global variable") ||
411 ParseOptionalLinkage(Linkage
, HasLinkage
) ||
412 ParseOptionalVisibility(Visibility
))
415 if (HasLinkage
|| Lex
.getKind() != lltok::kw_alias
)
416 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
);
417 return ParseAlias(Name
, NameLoc
, Visibility
);
421 // ::= '!' STRINGCONSTANT
422 bool LLParser::ParseMDString(MetadataBase
*&MDS
) {
424 if (ParseStringConstant(Str
)) return true;
425 MDS
= MDString::get(Context
, Str
);
430 // ::= '!' MDNodeNumber
431 bool LLParser::ParseMDNode(MetadataBase
*&Node
) {
432 // !{ ..., !42, ... }
434 if (ParseUInt32(MID
)) return true;
436 // Check existing MDNode.
437 std::map
<unsigned, MetadataBase
*>::iterator I
= MetadataCache
.find(MID
);
438 if (I
!= MetadataCache
.end()) {
443 // Check known forward references.
444 std::map
<unsigned, std::pair
<MetadataBase
*, LocTy
> >::iterator
445 FI
= ForwardRefMDNodes
.find(MID
);
446 if (FI
!= ForwardRefMDNodes
.end()) {
447 Node
= FI
->second
.first
;
451 // Create MDNode forward reference
452 SmallVector
<Value
*, 1> Elts
;
453 std::string FwdRefName
= "llvm.mdnode.fwdref." + utostr(MID
);
454 Elts
.push_back(MDString::get(Context
, FwdRefName
));
455 MDNode
*FwdNode
= MDNode::get(Context
, Elts
.data(), Elts
.size());
456 ForwardRefMDNodes
[MID
] = std::make_pair(FwdNode
, Lex
.getLoc());
461 ///ParseNamedMetadata:
462 /// !foo = !{ !1, !2 }
463 bool LLParser::ParseNamedMetadata() {
464 assert(Lex
.getKind() == lltok::NamedMD
);
466 std::string Name
= Lex
.getStrVal();
468 if (ParseToken(lltok::equal
, "expected '=' here"))
471 if (Lex
.getKind() != lltok::Metadata
)
472 return TokError("Expected '!' here");
475 if (Lex
.getKind() != lltok::lbrace
)
476 return TokError("Expected '{' here");
478 SmallVector
<MetadataBase
*, 8> Elts
;
480 if (Lex
.getKind() != lltok::Metadata
)
481 return TokError("Expected '!' here");
484 if (ParseMDNode(N
)) return true;
486 } while (EatIfPresent(lltok::comma
));
488 if (ParseToken(lltok::rbrace
, "expected end of metadata node"))
491 NamedMDNode::Create(Context
, Name
, Elts
.data(), Elts
.size(), M
);
495 /// ParseStandaloneMetadata:
497 bool LLParser::ParseStandaloneMetadata() {
498 assert(Lex
.getKind() == lltok::Metadata
);
500 unsigned MetadataID
= 0;
501 if (ParseUInt32(MetadataID
))
503 if (MetadataCache
.find(MetadataID
) != MetadataCache
.end())
504 return TokError("Metadata id is already used");
505 if (ParseToken(lltok::equal
, "expected '=' here"))
509 PATypeHolder
Ty(Type::getVoidTy(Context
));
510 if (ParseType(Ty
, TyLoc
))
513 if (Lex
.getKind() != lltok::Metadata
)
514 return TokError("Expected metadata here");
517 if (Lex
.getKind() != lltok::lbrace
)
518 return TokError("Expected '{' here");
520 SmallVector
<Value
*, 16> Elts
;
521 if (ParseMDNodeVector(Elts
)
522 || ParseToken(lltok::rbrace
, "expected end of metadata node"))
525 MDNode
*Init
= MDNode::get(Context
, Elts
.data(), Elts
.size());
526 MetadataCache
[MetadataID
] = Init
;
527 std::map
<unsigned, std::pair
<MetadataBase
*, LocTy
> >::iterator
528 FI
= ForwardRefMDNodes
.find(MetadataID
);
529 if (FI
!= ForwardRefMDNodes
.end()) {
530 MDNode
*FwdNode
= cast
<MDNode
>(FI
->second
.first
);
531 FwdNode
->replaceAllUsesWith(Init
);
532 ForwardRefMDNodes
.erase(FI
);
539 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
542 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
543 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
545 /// Everything through visibility has already been parsed.
547 bool LLParser::ParseAlias(const std::string
&Name
, LocTy NameLoc
,
548 unsigned Visibility
) {
549 assert(Lex
.getKind() == lltok::kw_alias
);
552 LocTy LinkageLoc
= Lex
.getLoc();
553 if (ParseOptionalLinkage(Linkage
))
556 if (Linkage
!= GlobalValue::ExternalLinkage
&&
557 Linkage
!= GlobalValue::WeakAnyLinkage
&&
558 Linkage
!= GlobalValue::WeakODRLinkage
&&
559 Linkage
!= GlobalValue::InternalLinkage
&&
560 Linkage
!= GlobalValue::PrivateLinkage
&&
561 Linkage
!= GlobalValue::LinkerPrivateLinkage
)
562 return Error(LinkageLoc
, "invalid linkage type for alias");
565 LocTy AliaseeLoc
= Lex
.getLoc();
566 if (Lex
.getKind() != lltok::kw_bitcast
&&
567 Lex
.getKind() != lltok::kw_getelementptr
) {
568 if (ParseGlobalTypeAndValue(Aliasee
)) return true;
570 // The bitcast dest type is not present, it is implied by the dest type.
572 if (ParseValID(ID
)) return true;
573 if (ID
.Kind
!= ValID::t_Constant
)
574 return Error(AliaseeLoc
, "invalid aliasee");
575 Aliasee
= ID
.ConstantVal
;
578 if (!isa
<PointerType
>(Aliasee
->getType()))
579 return Error(AliaseeLoc
, "alias must have pointer type");
581 // Okay, create the alias but do not insert it into the module yet.
582 GlobalAlias
* GA
= new GlobalAlias(Aliasee
->getType(),
583 (GlobalValue::LinkageTypes
)Linkage
, Name
,
585 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
587 // See if this value already exists in the symbol table. If so, it is either
588 // a redefinition or a definition of a forward reference.
589 if (GlobalValue
*Val
=
590 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
))) {
591 // See if this was a redefinition. If so, there is no entry in
593 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
594 I
= ForwardRefVals
.find(Name
);
595 if (I
== ForwardRefVals
.end())
596 return Error(NameLoc
, "redefinition of global named '@" + Name
+ "'");
598 // Otherwise, this was a definition of forward ref. Verify that types
600 if (Val
->getType() != GA
->getType())
601 return Error(NameLoc
,
602 "forward reference and definition of alias have different types");
604 // If they agree, just RAUW the old value with the alias and remove the
606 Val
->replaceAllUsesWith(GA
);
607 Val
->eraseFromParent();
608 ForwardRefVals
.erase(I
);
611 // Insert into the module, we know its name won't collide now.
612 M
->getAliasList().push_back(GA
);
613 assert(GA
->getNameStr() == Name
&& "Should not be a name conflict!");
619 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
620 /// OptionalAddrSpace GlobalType Type Const
621 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
622 /// OptionalAddrSpace GlobalType Type Const
624 /// Everything through visibility has been parsed already.
626 bool LLParser::ParseGlobal(const std::string
&Name
, LocTy NameLoc
,
627 unsigned Linkage
, bool HasLinkage
,
628 unsigned Visibility
) {
630 bool ThreadLocal
, IsConstant
;
633 PATypeHolder
Ty(Type::getVoidTy(Context
));
634 if (ParseOptionalToken(lltok::kw_thread_local
, ThreadLocal
) ||
635 ParseOptionalAddrSpace(AddrSpace
) ||
636 ParseGlobalType(IsConstant
) ||
637 ParseType(Ty
, TyLoc
))
640 // If the linkage is specified and is external, then no initializer is
643 if (!HasLinkage
|| (Linkage
!= GlobalValue::DLLImportLinkage
&&
644 Linkage
!= GlobalValue::ExternalWeakLinkage
&&
645 Linkage
!= GlobalValue::ExternalLinkage
)) {
646 if (ParseGlobalValue(Ty
, Init
))
650 if (isa
<FunctionType
>(Ty
) || Ty
== Type::getLabelTy(Context
))
651 return Error(TyLoc
, "invalid type for global variable");
653 GlobalVariable
*GV
= 0;
655 // See if the global was forward referenced, if so, use the global.
657 if ((GV
= M
->getGlobalVariable(Name
, true)) &&
658 !ForwardRefVals
.erase(Name
))
659 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
661 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
662 I
= ForwardRefValIDs
.find(NumberedVals
.size());
663 if (I
!= ForwardRefValIDs
.end()) {
664 GV
= cast
<GlobalVariable
>(I
->second
.first
);
665 ForwardRefValIDs
.erase(I
);
670 GV
= new GlobalVariable(*M
, Ty
, false, GlobalValue::ExternalLinkage
, 0,
671 Name
, 0, false, AddrSpace
);
673 if (GV
->getType()->getElementType() != Ty
)
675 "forward reference and definition of global have different types");
677 // Move the forward-reference to the correct spot in the module.
678 M
->getGlobalList().splice(M
->global_end(), M
->getGlobalList(), GV
);
682 NumberedVals
.push_back(GV
);
684 // Set the parsed properties on the global.
686 GV
->setInitializer(Init
);
687 GV
->setConstant(IsConstant
);
688 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
689 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
690 GV
->setThreadLocal(ThreadLocal
);
692 // Parse attributes on the global.
693 while (Lex
.getKind() == lltok::comma
) {
696 if (Lex
.getKind() == lltok::kw_section
) {
698 GV
->setSection(Lex
.getStrVal());
699 if (ParseToken(lltok::StringConstant
, "expected global section string"))
701 } else if (Lex
.getKind() == lltok::kw_align
) {
703 if (ParseOptionalAlignment(Alignment
)) return true;
704 GV
->setAlignment(Alignment
);
706 TokError("unknown global variable property!");
714 //===----------------------------------------------------------------------===//
715 // GlobalValue Reference/Resolution Routines.
716 //===----------------------------------------------------------------------===//
718 /// GetGlobalVal - Get a value with the specified name or ID, creating a
719 /// forward reference record if needed. This can return null if the value
720 /// exists but does not have the right type.
721 GlobalValue
*LLParser::GetGlobalVal(const std::string
&Name
, const Type
*Ty
,
723 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
725 Error(Loc
, "global variable reference must have pointer type");
729 // Look this name up in the normal function symbol table.
731 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
733 // If this is a forward reference for the value, see if we already created a
734 // forward ref record.
736 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
737 I
= ForwardRefVals
.find(Name
);
738 if (I
!= ForwardRefVals
.end())
739 Val
= I
->second
.first
;
742 // If we have the value in the symbol table or fwd-ref table, return it.
744 if (Val
->getType() == Ty
) return Val
;
745 Error(Loc
, "'@" + Name
+ "' defined with type '" +
746 Val
->getType()->getDescription() + "'");
750 // Otherwise, create a new forward reference for this value and remember it.
752 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
753 // Function types can return opaque but functions can't.
754 if (isa
<OpaqueType
>(FT
->getReturnType())) {
755 Error(Loc
, "function may not return opaque type");
759 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, Name
, M
);
761 FwdVal
= new GlobalVariable(*M
, PTy
->getElementType(), false,
762 GlobalValue::ExternalWeakLinkage
, 0, Name
);
765 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
769 GlobalValue
*LLParser::GetGlobalVal(unsigned ID
, const Type
*Ty
, LocTy Loc
) {
770 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
772 Error(Loc
, "global variable reference must have pointer type");
776 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
778 // If this is a forward reference for the value, see if we already created a
779 // forward ref record.
781 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
782 I
= ForwardRefValIDs
.find(ID
);
783 if (I
!= ForwardRefValIDs
.end())
784 Val
= I
->second
.first
;
787 // If we have the value in the symbol table or fwd-ref table, return it.
789 if (Val
->getType() == Ty
) return Val
;
790 Error(Loc
, "'@" + utostr(ID
) + "' defined with type '" +
791 Val
->getType()->getDescription() + "'");
795 // Otherwise, create a new forward reference for this value and remember it.
797 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
798 // Function types can return opaque but functions can't.
799 if (isa
<OpaqueType
>(FT
->getReturnType())) {
800 Error(Loc
, "function may not return opaque type");
803 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, "", M
);
805 FwdVal
= new GlobalVariable(*M
, PTy
->getElementType(), false,
806 GlobalValue::ExternalWeakLinkage
, 0, "");
809 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
814 //===----------------------------------------------------------------------===//
816 //===----------------------------------------------------------------------===//
818 /// ParseToken - If the current token has the specified kind, eat it and return
819 /// success. Otherwise, emit the specified error and return failure.
820 bool LLParser::ParseToken(lltok::Kind T
, const char *ErrMsg
) {
821 if (Lex
.getKind() != T
)
822 return TokError(ErrMsg
);
827 /// ParseStringConstant
828 /// ::= StringConstant
829 bool LLParser::ParseStringConstant(std::string
&Result
) {
830 if (Lex
.getKind() != lltok::StringConstant
)
831 return TokError("expected string constant");
832 Result
= Lex
.getStrVal();
839 bool LLParser::ParseUInt32(unsigned &Val
) {
840 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
841 return TokError("expected integer");
842 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
843 if (Val64
!= unsigned(Val64
))
844 return TokError("expected 32-bit integer (too large)");
851 /// ParseOptionalAddrSpace
853 /// := 'addrspace' '(' uint32 ')'
854 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace
) {
856 if (!EatIfPresent(lltok::kw_addrspace
))
858 return ParseToken(lltok::lparen
, "expected '(' in address space") ||
859 ParseUInt32(AddrSpace
) ||
860 ParseToken(lltok::rparen
, "expected ')' in address space");
863 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
864 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
865 /// 2: function attr.
866 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
867 bool LLParser::ParseOptionalAttrs(unsigned &Attrs
, unsigned AttrKind
) {
868 Attrs
= Attribute::None
;
869 LocTy AttrLoc
= Lex
.getLoc();
872 switch (Lex
.getKind()) {
875 // Treat these as signext/zeroext if they occur in the argument list after
876 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
877 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
879 // FIXME: REMOVE THIS IN LLVM 3.0
881 if (Lex
.getKind() == lltok::kw_sext
)
882 Attrs
|= Attribute::SExt
;
884 Attrs
|= Attribute::ZExt
;
888 default: // End of attributes.
889 if (AttrKind
!= 2 && (Attrs
& Attribute::FunctionOnly
))
890 return Error(AttrLoc
, "invalid use of function-only attribute");
892 if (AttrKind
!= 0 && AttrKind
!= 3 && (Attrs
& Attribute::ParameterOnly
))
893 return Error(AttrLoc
, "invalid use of parameter-only attribute");
896 case lltok::kw_zeroext
: Attrs
|= Attribute::ZExt
; break;
897 case lltok::kw_signext
: Attrs
|= Attribute::SExt
; break;
898 case lltok::kw_inreg
: Attrs
|= Attribute::InReg
; break;
899 case lltok::kw_sret
: Attrs
|= Attribute::StructRet
; break;
900 case lltok::kw_noalias
: Attrs
|= Attribute::NoAlias
; break;
901 case lltok::kw_nocapture
: Attrs
|= Attribute::NoCapture
; break;
902 case lltok::kw_byval
: Attrs
|= Attribute::ByVal
; break;
903 case lltok::kw_nest
: Attrs
|= Attribute::Nest
; break;
905 case lltok::kw_noreturn
: Attrs
|= Attribute::NoReturn
; break;
906 case lltok::kw_nounwind
: Attrs
|= Attribute::NoUnwind
; break;
907 case lltok::kw_noinline
: Attrs
|= Attribute::NoInline
; break;
908 case lltok::kw_readnone
: Attrs
|= Attribute::ReadNone
; break;
909 case lltok::kw_readonly
: Attrs
|= Attribute::ReadOnly
; break;
910 case lltok::kw_inlinehint
: Attrs
|= Attribute::InlineHint
; break;
911 case lltok::kw_alwaysinline
: Attrs
|= Attribute::AlwaysInline
; break;
912 case lltok::kw_optsize
: Attrs
|= Attribute::OptimizeForSize
; break;
913 case lltok::kw_ssp
: Attrs
|= Attribute::StackProtect
; break;
914 case lltok::kw_sspreq
: Attrs
|= Attribute::StackProtectReq
; break;
915 case lltok::kw_noredzone
: Attrs
|= Attribute::NoRedZone
; break;
916 case lltok::kw_noimplicitfloat
: Attrs
|= Attribute::NoImplicitFloat
; break;
917 case lltok::kw_naked
: Attrs
|= Attribute::Naked
; break;
919 case lltok::kw_align
: {
921 if (ParseOptionalAlignment(Alignment
))
923 Attrs
|= Attribute::constructAlignmentFromInt(Alignment
);
931 /// ParseOptionalLinkage
934 /// ::= 'linker_private'
939 /// ::= 'linkonce_odr'
944 /// ::= 'extern_weak'
946 bool LLParser::ParseOptionalLinkage(unsigned &Res
, bool &HasLinkage
) {
948 switch (Lex
.getKind()) {
949 default: Res
=GlobalValue::ExternalLinkage
; return false;
950 case lltok::kw_private
: Res
= GlobalValue::PrivateLinkage
; break;
951 case lltok::kw_linker_private
: Res
= GlobalValue::LinkerPrivateLinkage
; break;
952 case lltok::kw_internal
: Res
= GlobalValue::InternalLinkage
; break;
953 case lltok::kw_weak
: Res
= GlobalValue::WeakAnyLinkage
; break;
954 case lltok::kw_weak_odr
: Res
= GlobalValue::WeakODRLinkage
; break;
955 case lltok::kw_linkonce
: Res
= GlobalValue::LinkOnceAnyLinkage
; break;
956 case lltok::kw_linkonce_odr
: Res
= GlobalValue::LinkOnceODRLinkage
; break;
957 case lltok::kw_available_externally
:
958 Res
= GlobalValue::AvailableExternallyLinkage
;
960 case lltok::kw_appending
: Res
= GlobalValue::AppendingLinkage
; break;
961 case lltok::kw_dllexport
: Res
= GlobalValue::DLLExportLinkage
; break;
962 case lltok::kw_common
: Res
= GlobalValue::CommonLinkage
; break;
963 case lltok::kw_dllimport
: Res
= GlobalValue::DLLImportLinkage
; break;
964 case lltok::kw_extern_weak
: Res
= GlobalValue::ExternalWeakLinkage
; break;
965 case lltok::kw_external
: Res
= GlobalValue::ExternalLinkage
; break;
972 /// ParseOptionalVisibility
978 bool LLParser::ParseOptionalVisibility(unsigned &Res
) {
979 switch (Lex
.getKind()) {
980 default: Res
= GlobalValue::DefaultVisibility
; return false;
981 case lltok::kw_default
: Res
= GlobalValue::DefaultVisibility
; break;
982 case lltok::kw_hidden
: Res
= GlobalValue::HiddenVisibility
; break;
983 case lltok::kw_protected
: Res
= GlobalValue::ProtectedVisibility
; break;
989 /// ParseOptionalCallingConv
994 /// ::= 'x86_stdcallcc'
995 /// ::= 'x86_fastcallcc'
997 /// ::= 'arm_aapcscc'
998 /// ::= 'arm_aapcs_vfpcc'
1001 bool LLParser::ParseOptionalCallingConv(CallingConv::ID
&CC
) {
1002 switch (Lex
.getKind()) {
1003 default: CC
= CallingConv::C
; return false;
1004 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
1005 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
1006 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
1007 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
1008 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
1009 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
1010 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
1011 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
1012 case lltok::kw_cc
: {
1013 unsigned ArbitraryCC
;
1015 if (ParseUInt32(ArbitraryCC
)) {
1018 CC
= static_cast<CallingConv::ID
>(ArbitraryCC
);
1028 /// ParseOptionalAlignment
1031 bool LLParser::ParseOptionalAlignment(unsigned &Alignment
) {
1033 if (!EatIfPresent(lltok::kw_align
))
1035 LocTy AlignLoc
= Lex
.getLoc();
1036 if (ParseUInt32(Alignment
)) return true;
1037 if (!isPowerOf2_32(Alignment
))
1038 return Error(AlignLoc
, "alignment is not a power of two");
1042 /// ParseOptionalCommaAlignment
1044 /// ::= ',' 'align' 4
1045 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment
) {
1047 if (!EatIfPresent(lltok::comma
))
1049 return ParseToken(lltok::kw_align
, "expected 'align'") ||
1050 ParseUInt32(Alignment
);
1054 /// ::= (',' uint32)+
1055 bool LLParser::ParseIndexList(SmallVectorImpl
<unsigned> &Indices
) {
1056 if (Lex
.getKind() != lltok::comma
)
1057 return TokError("expected ',' as start of index list");
1059 while (EatIfPresent(lltok::comma
)) {
1061 if (ParseUInt32(Idx
)) return true;
1062 Indices
.push_back(Idx
);
1068 //===----------------------------------------------------------------------===//
1070 //===----------------------------------------------------------------------===//
1072 /// ParseType - Parse and resolve a full type.
1073 bool LLParser::ParseType(PATypeHolder
&Result
, bool AllowVoid
) {
1074 LocTy TypeLoc
= Lex
.getLoc();
1075 if (ParseTypeRec(Result
)) return true;
1077 // Verify no unresolved uprefs.
1078 if (!UpRefs
.empty())
1079 return Error(UpRefs
.back().Loc
, "invalid unresolved type up reference");
1081 if (!AllowVoid
&& Result
.get() == Type::getVoidTy(Context
))
1082 return Error(TypeLoc
, "void type only allowed for function results");
1087 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1088 /// called. It loops through the UpRefs vector, which is a list of the
1089 /// currently active types. For each type, if the up-reference is contained in
1090 /// the newly completed type, we decrement the level count. When the level
1091 /// count reaches zero, the up-referenced type is the type that is passed in:
1092 /// thus we can complete the cycle.
1094 PATypeHolder
LLParser::HandleUpRefs(const Type
*ty
) {
1095 // If Ty isn't abstract, or if there are no up-references in it, then there is
1096 // nothing to resolve here.
1097 if (!ty
->isAbstract() || UpRefs
.empty()) return ty
;
1099 PATypeHolder
Ty(ty
);
1101 errs() << "Type '" << Ty
->getDescription()
1102 << "' newly formed. Resolving upreferences.\n"
1103 << UpRefs
.size() << " upreferences active!\n";
1106 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1107 // to zero), we resolve them all together before we resolve them to Ty. At
1108 // the end of the loop, if there is anything to resolve to Ty, it will be in
1110 OpaqueType
*TypeToResolve
= 0;
1112 for (unsigned i
= 0; i
!= UpRefs
.size(); ++i
) {
1113 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1115 std::find(Ty
->subtype_begin(), Ty
->subtype_end(),
1116 UpRefs
[i
].LastContainedTy
) != Ty
->subtype_end();
1119 errs() << " UR#" << i
<< " - TypeContains(" << Ty
->getDescription() << ", "
1120 << UpRefs
[i
].LastContainedTy
->getDescription() << ") = "
1121 << (ContainsType
? "true" : "false")
1122 << " level=" << UpRefs
[i
].NestingLevel
<< "\n";
1127 // Decrement level of upreference
1128 unsigned Level
= --UpRefs
[i
].NestingLevel
;
1129 UpRefs
[i
].LastContainedTy
= Ty
;
1131 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1136 errs() << " * Resolving upreference for " << UpRefs
[i
].UpRefTy
<< "\n";
1139 TypeToResolve
= UpRefs
[i
].UpRefTy
;
1141 UpRefs
[i
].UpRefTy
->refineAbstractTypeTo(TypeToResolve
);
1142 UpRefs
.erase(UpRefs
.begin()+i
); // Remove from upreference list.
1143 --i
; // Do not skip the next element.
1147 TypeToResolve
->refineAbstractTypeTo(Ty
);
1153 /// ParseTypeRec - The recursive function used to process the internal
1154 /// implementation details of types.
1155 bool LLParser::ParseTypeRec(PATypeHolder
&Result
) {
1156 switch (Lex
.getKind()) {
1158 return TokError("expected type");
1160 // TypeRec ::= 'float' | 'void' (etc)
1161 Result
= Lex
.getTyVal();
1164 case lltok::kw_opaque
:
1165 // TypeRec ::= 'opaque'
1166 Result
= OpaqueType::get(Context
);
1170 // TypeRec ::= '{' ... '}'
1171 if (ParseStructType(Result
, false))
1174 case lltok::lsquare
:
1175 // TypeRec ::= '[' ... ']'
1176 Lex
.Lex(); // eat the lsquare.
1177 if (ParseArrayVectorType(Result
, false))
1180 case lltok::less
: // Either vector or packed struct.
1181 // TypeRec ::= '<' ... '>'
1183 if (Lex
.getKind() == lltok::lbrace
) {
1184 if (ParseStructType(Result
, true) ||
1185 ParseToken(lltok::greater
, "expected '>' at end of packed struct"))
1187 } else if (ParseArrayVectorType(Result
, true))
1190 case lltok::LocalVar
:
1191 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
1193 if (const Type
*T
= M
->getTypeByName(Lex
.getStrVal())) {
1196 Result
= OpaqueType::get(Context
);
1197 ForwardRefTypes
.insert(std::make_pair(Lex
.getStrVal(),
1198 std::make_pair(Result
,
1200 M
->addTypeName(Lex
.getStrVal(), Result
.get());
1205 case lltok::LocalVarID
:
1207 if (Lex
.getUIntVal() < NumberedTypes
.size())
1208 Result
= NumberedTypes
[Lex
.getUIntVal()];
1210 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
1211 I
= ForwardRefTypeIDs
.find(Lex
.getUIntVal());
1212 if (I
!= ForwardRefTypeIDs
.end())
1213 Result
= I
->second
.first
;
1215 Result
= OpaqueType::get(Context
);
1216 ForwardRefTypeIDs
.insert(std::make_pair(Lex
.getUIntVal(),
1217 std::make_pair(Result
,
1223 case lltok::backslash
: {
1224 // TypeRec ::= '\' 4
1227 if (ParseUInt32(Val
)) return true;
1228 OpaqueType
*OT
= OpaqueType::get(Context
); //Use temporary placeholder.
1229 UpRefs
.push_back(UpRefRecord(Lex
.getLoc(), Val
, OT
));
1235 // Parse the type suffixes.
1237 switch (Lex
.getKind()) {
1239 default: return false;
1241 // TypeRec ::= TypeRec '*'
1243 if (Result
.get() == Type::getLabelTy(Context
))
1244 return TokError("basic block pointers are invalid");
1245 if (Result
.get() == Type::getVoidTy(Context
))
1246 return TokError("pointers to void are invalid; use i8* instead");
1247 if (!PointerType::isValidElementType(Result
.get()))
1248 return TokError("pointer to this type is invalid");
1249 Result
= HandleUpRefs(PointerType::getUnqual(Result
.get()));
1253 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1254 case lltok::kw_addrspace
: {
1255 if (Result
.get() == Type::getLabelTy(Context
))
1256 return TokError("basic block pointers are invalid");
1257 if (Result
.get() == Type::getVoidTy(Context
))
1258 return TokError("pointers to void are invalid; use i8* instead");
1259 if (!PointerType::isValidElementType(Result
.get()))
1260 return TokError("pointer to this type is invalid");
1262 if (ParseOptionalAddrSpace(AddrSpace
) ||
1263 ParseToken(lltok::star
, "expected '*' in address space"))
1266 Result
= HandleUpRefs(PointerType::get(Result
.get(), AddrSpace
));
1270 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1272 if (ParseFunctionType(Result
))
1279 /// ParseParameterList
1281 /// ::= '(' Arg (',' Arg)* ')'
1283 /// ::= Type OptionalAttributes Value OptionalAttributes
1284 bool LLParser::ParseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
1285 PerFunctionState
&PFS
) {
1286 if (ParseToken(lltok::lparen
, "expected '(' in call"))
1289 while (Lex
.getKind() != lltok::rparen
) {
1290 // If this isn't the first argument, we need a comma.
1291 if (!ArgList
.empty() &&
1292 ParseToken(lltok::comma
, "expected ',' in argument list"))
1295 // Parse the argument.
1297 PATypeHolder
ArgTy(Type::getVoidTy(Context
));
1298 unsigned ArgAttrs1
, ArgAttrs2
;
1300 if (ParseType(ArgTy
, ArgLoc
) ||
1301 ParseOptionalAttrs(ArgAttrs1
, 0) ||
1302 ParseValue(ArgTy
, V
, PFS
) ||
1303 // FIXME: Should not allow attributes after the argument, remove this in
1305 ParseOptionalAttrs(ArgAttrs2
, 3))
1307 ArgList
.push_back(ParamInfo(ArgLoc
, V
, ArgAttrs1
|ArgAttrs2
));
1310 Lex
.Lex(); // Lex the ')'.
1316 /// ParseArgumentList - Parse the argument list for a function type or function
1317 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1318 /// ::= '(' ArgTypeListI ')'
1322 /// ::= ArgTypeList ',' '...'
1323 /// ::= ArgType (',' ArgType)*
1325 bool LLParser::ParseArgumentList(std::vector
<ArgInfo
> &ArgList
,
1326 bool &isVarArg
, bool inType
) {
1328 assert(Lex
.getKind() == lltok::lparen
);
1329 Lex
.Lex(); // eat the (.
1331 if (Lex
.getKind() == lltok::rparen
) {
1333 } else if (Lex
.getKind() == lltok::dotdotdot
) {
1337 LocTy TypeLoc
= Lex
.getLoc();
1338 PATypeHolder
ArgTy(Type::getVoidTy(Context
));
1342 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1343 // types (such as a function returning a pointer to itself). If parsing a
1344 // function prototype, we require fully resolved types.
1345 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1346 ParseOptionalAttrs(Attrs
, 0)) return true;
1348 if (ArgTy
== Type::getVoidTy(Context
))
1349 return Error(TypeLoc
, "argument can not have void type");
1351 if (Lex
.getKind() == lltok::LocalVar
||
1352 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1353 Name
= Lex
.getStrVal();
1357 if (!FunctionType::isValidArgumentType(ArgTy
))
1358 return Error(TypeLoc
, "invalid type for function argument");
1360 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1362 while (EatIfPresent(lltok::comma
)) {
1363 // Handle ... at end of arg list.
1364 if (EatIfPresent(lltok::dotdotdot
)) {
1369 // Otherwise must be an argument type.
1370 TypeLoc
= Lex
.getLoc();
1371 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1372 ParseOptionalAttrs(Attrs
, 0)) return true;
1374 if (ArgTy
== Type::getVoidTy(Context
))
1375 return Error(TypeLoc
, "argument can not have void type");
1377 if (Lex
.getKind() == lltok::LocalVar
||
1378 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1379 Name
= Lex
.getStrVal();
1385 if (!ArgTy
->isFirstClassType() && !isa
<OpaqueType
>(ArgTy
))
1386 return Error(TypeLoc
, "invalid type for function argument");
1388 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1392 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
1395 /// ParseFunctionType
1396 /// ::= Type ArgumentList OptionalAttrs
1397 bool LLParser::ParseFunctionType(PATypeHolder
&Result
) {
1398 assert(Lex
.getKind() == lltok::lparen
);
1400 if (!FunctionType::isValidReturnType(Result
))
1401 return TokError("invalid function return type");
1403 std::vector
<ArgInfo
> ArgList
;
1406 if (ParseArgumentList(ArgList
, isVarArg
, true) ||
1407 // FIXME: Allow, but ignore attributes on function types!
1408 // FIXME: Remove in LLVM 3.0
1409 ParseOptionalAttrs(Attrs
, 2))
1412 // Reject names on the arguments lists.
1413 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
1414 if (!ArgList
[i
].Name
.empty())
1415 return Error(ArgList
[i
].Loc
, "argument name invalid in function type");
1416 if (!ArgList
[i
].Attrs
!= 0) {
1417 // Allow but ignore attributes on function types; this permits
1419 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1423 std::vector
<const Type
*> ArgListTy
;
1424 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
1425 ArgListTy
.push_back(ArgList
[i
].Type
);
1427 Result
= HandleUpRefs(FunctionType::get(Result
.get(),
1428 ArgListTy
, isVarArg
));
1432 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1435 /// ::= '{' TypeRec (',' TypeRec)* '}'
1436 /// ::= '<' '{' '}' '>'
1437 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1438 bool LLParser::ParseStructType(PATypeHolder
&Result
, bool Packed
) {
1439 assert(Lex
.getKind() == lltok::lbrace
);
1440 Lex
.Lex(); // Consume the '{'
1442 if (EatIfPresent(lltok::rbrace
)) {
1443 Result
= StructType::get(Context
, Packed
);
1447 std::vector
<PATypeHolder
> ParamsList
;
1448 LocTy EltTyLoc
= Lex
.getLoc();
1449 if (ParseTypeRec(Result
)) return true;
1450 ParamsList
.push_back(Result
);
1452 if (Result
== Type::getVoidTy(Context
))
1453 return Error(EltTyLoc
, "struct element can not have void type");
1454 if (!StructType::isValidElementType(Result
))
1455 return Error(EltTyLoc
, "invalid element type for struct");
1457 while (EatIfPresent(lltok::comma
)) {
1458 EltTyLoc
= Lex
.getLoc();
1459 if (ParseTypeRec(Result
)) return true;
1461 if (Result
== Type::getVoidTy(Context
))
1462 return Error(EltTyLoc
, "struct element can not have void type");
1463 if (!StructType::isValidElementType(Result
))
1464 return Error(EltTyLoc
, "invalid element type for struct");
1466 ParamsList
.push_back(Result
);
1469 if (ParseToken(lltok::rbrace
, "expected '}' at end of struct"))
1472 std::vector
<const Type
*> ParamsListTy
;
1473 for (unsigned i
= 0, e
= ParamsList
.size(); i
!= e
; ++i
)
1474 ParamsListTy
.push_back(ParamsList
[i
].get());
1475 Result
= HandleUpRefs(StructType::get(Context
, ParamsListTy
, Packed
));
1479 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1480 /// token has already been consumed.
1482 /// ::= '[' APSINTVAL 'x' Types ']'
1483 /// ::= '<' APSINTVAL 'x' Types '>'
1484 bool LLParser::ParseArrayVectorType(PATypeHolder
&Result
, bool isVector
) {
1485 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
1486 Lex
.getAPSIntVal().getBitWidth() > 64)
1487 return TokError("expected number in address space");
1489 LocTy SizeLoc
= Lex
.getLoc();
1490 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
1493 if (ParseToken(lltok::kw_x
, "expected 'x' after element count"))
1496 LocTy TypeLoc
= Lex
.getLoc();
1497 PATypeHolder
EltTy(Type::getVoidTy(Context
));
1498 if (ParseTypeRec(EltTy
)) return true;
1500 if (EltTy
== Type::getVoidTy(Context
))
1501 return Error(TypeLoc
, "array and vector element type cannot be void");
1503 if (ParseToken(isVector
? lltok::greater
: lltok::rsquare
,
1504 "expected end of sequential type"))
1509 return Error(SizeLoc
, "zero element vector is illegal");
1510 if ((unsigned)Size
!= Size
)
1511 return Error(SizeLoc
, "size too large for vector");
1512 if (!VectorType::isValidElementType(EltTy
))
1513 return Error(TypeLoc
, "vector element type must be fp or integer");
1514 Result
= VectorType::get(EltTy
, unsigned(Size
));
1516 if (!ArrayType::isValidElementType(EltTy
))
1517 return Error(TypeLoc
, "invalid array element type");
1518 Result
= HandleUpRefs(ArrayType::get(EltTy
, Size
));
1523 //===----------------------------------------------------------------------===//
1524 // Function Semantic Analysis.
1525 //===----------------------------------------------------------------------===//
1527 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
)
1530 // Insert unnamed arguments into the NumberedVals list.
1531 for (Function::arg_iterator AI
= F
.arg_begin(), E
= F
.arg_end();
1534 NumberedVals
.push_back(AI
);
1537 LLParser::PerFunctionState::~PerFunctionState() {
1538 // If there were any forward referenced non-basicblock values, delete them.
1539 for (std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1540 I
= ForwardRefVals
.begin(), E
= ForwardRefVals
.end(); I
!= E
; ++I
)
1541 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1542 I
->second
.first
->replaceAllUsesWith(
1543 UndefValue::get(I
->second
.first
->getType()));
1544 delete I
->second
.first
;
1545 I
->second
.first
= 0;
1548 for (std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1549 I
= ForwardRefValIDs
.begin(), E
= ForwardRefValIDs
.end(); I
!= E
; ++I
)
1550 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1551 I
->second
.first
->replaceAllUsesWith(
1552 UndefValue::get(I
->second
.first
->getType()));
1553 delete I
->second
.first
;
1554 I
->second
.first
= 0;
1558 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1559 if (!ForwardRefVals
.empty())
1560 return P
.Error(ForwardRefVals
.begin()->second
.second
,
1561 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
1563 if (!ForwardRefValIDs
.empty())
1564 return P
.Error(ForwardRefValIDs
.begin()->second
.second
,
1565 "use of undefined value '%" +
1566 utostr(ForwardRefValIDs
.begin()->first
) + "'");
1571 /// GetVal - Get a value with the specified name or ID, creating a
1572 /// forward reference record if needed. This can return null if the value
1573 /// exists but does not have the right type.
1574 Value
*LLParser::PerFunctionState::GetVal(const std::string
&Name
,
1575 const Type
*Ty
, LocTy Loc
) {
1576 // Look this name up in the normal function symbol table.
1577 Value
*Val
= F
.getValueSymbolTable().lookup(Name
);
1579 // If this is a forward reference for the value, see if we already created a
1580 // forward ref record.
1582 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1583 I
= ForwardRefVals
.find(Name
);
1584 if (I
!= ForwardRefVals
.end())
1585 Val
= I
->second
.first
;
1588 // If we have the value in the symbol table or fwd-ref table, return it.
1590 if (Val
->getType() == Ty
) return Val
;
1591 if (Ty
== Type::getLabelTy(F
.getContext()))
1592 P
.Error(Loc
, "'%" + Name
+ "' is not a basic block");
1594 P
.Error(Loc
, "'%" + Name
+ "' defined with type '" +
1595 Val
->getType()->getDescription() + "'");
1599 // Don't make placeholders with invalid type.
1600 if (!Ty
->isFirstClassType() && !isa
<OpaqueType
>(Ty
) &&
1601 Ty
!= Type::getLabelTy(F
.getContext())) {
1602 P
.Error(Loc
, "invalid use of a non-first-class type");
1606 // Otherwise, create a new forward reference for this value and remember it.
1608 if (Ty
== Type::getLabelTy(F
.getContext()))
1609 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
1611 FwdVal
= new Argument(Ty
, Name
);
1613 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1617 Value
*LLParser::PerFunctionState::GetVal(unsigned ID
, const Type
*Ty
,
1619 // Look this name up in the normal function symbol table.
1620 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
1622 // If this is a forward reference for the value, see if we already created a
1623 // forward ref record.
1625 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1626 I
= ForwardRefValIDs
.find(ID
);
1627 if (I
!= ForwardRefValIDs
.end())
1628 Val
= I
->second
.first
;
1631 // If we have the value in the symbol table or fwd-ref table, return it.
1633 if (Val
->getType() == Ty
) return Val
;
1634 if (Ty
== Type::getLabelTy(F
.getContext()))
1635 P
.Error(Loc
, "'%" + utostr(ID
) + "' is not a basic block");
1637 P
.Error(Loc
, "'%" + utostr(ID
) + "' defined with type '" +
1638 Val
->getType()->getDescription() + "'");
1642 if (!Ty
->isFirstClassType() && !isa
<OpaqueType
>(Ty
) &&
1643 Ty
!= Type::getLabelTy(F
.getContext())) {
1644 P
.Error(Loc
, "invalid use of a non-first-class type");
1648 // Otherwise, create a new forward reference for this value and remember it.
1650 if (Ty
== Type::getLabelTy(F
.getContext()))
1651 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
1653 FwdVal
= new Argument(Ty
);
1655 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1659 /// SetInstName - After an instruction is parsed and inserted into its
1660 /// basic block, this installs its name.
1661 bool LLParser::PerFunctionState::SetInstName(int NameID
,
1662 const std::string
&NameStr
,
1663 LocTy NameLoc
, Instruction
*Inst
) {
1664 // If this instruction has void type, it cannot have a name or ID specified.
1665 if (Inst
->getType() == Type::getVoidTy(F
.getContext())) {
1666 if (NameID
!= -1 || !NameStr
.empty())
1667 return P
.Error(NameLoc
, "instructions returning void cannot have a name");
1671 // If this was a numbered instruction, verify that the instruction is the
1672 // expected value and resolve any forward references.
1673 if (NameStr
.empty()) {
1674 // If neither a name nor an ID was specified, just use the next ID.
1676 NameID
= NumberedVals
.size();
1678 if (unsigned(NameID
) != NumberedVals
.size())
1679 return P
.Error(NameLoc
, "instruction expected to be numbered '%" +
1680 utostr(NumberedVals
.size()) + "'");
1682 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator FI
=
1683 ForwardRefValIDs
.find(NameID
);
1684 if (FI
!= ForwardRefValIDs
.end()) {
1685 if (FI
->second
.first
->getType() != Inst
->getType())
1686 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1687 FI
->second
.first
->getType()->getDescription() + "'");
1688 FI
->second
.first
->replaceAllUsesWith(Inst
);
1689 delete FI
->second
.first
;
1690 ForwardRefValIDs
.erase(FI
);
1693 NumberedVals
.push_back(Inst
);
1697 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1698 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1699 FI
= ForwardRefVals
.find(NameStr
);
1700 if (FI
!= ForwardRefVals
.end()) {
1701 if (FI
->second
.first
->getType() != Inst
->getType())
1702 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1703 FI
->second
.first
->getType()->getDescription() + "'");
1704 FI
->second
.first
->replaceAllUsesWith(Inst
);
1705 delete FI
->second
.first
;
1706 ForwardRefVals
.erase(FI
);
1709 // Set the name on the instruction.
1710 Inst
->setName(NameStr
);
1712 if (Inst
->getNameStr() != NameStr
)
1713 return P
.Error(NameLoc
, "multiple definition of local value named '" +
1718 /// GetBB - Get a basic block with the specified name or ID, creating a
1719 /// forward reference record if needed.
1720 BasicBlock
*LLParser::PerFunctionState::GetBB(const std::string
&Name
,
1722 return cast_or_null
<BasicBlock
>(GetVal(Name
,
1723 Type::getLabelTy(F
.getContext()), Loc
));
1726 BasicBlock
*LLParser::PerFunctionState::GetBB(unsigned ID
, LocTy Loc
) {
1727 return cast_or_null
<BasicBlock
>(GetVal(ID
,
1728 Type::getLabelTy(F
.getContext()), Loc
));
1731 /// DefineBB - Define the specified basic block, which is either named or
1732 /// unnamed. If there is an error, this returns null otherwise it returns
1733 /// the block being defined.
1734 BasicBlock
*LLParser::PerFunctionState::DefineBB(const std::string
&Name
,
1738 BB
= GetBB(NumberedVals
.size(), Loc
);
1740 BB
= GetBB(Name
, Loc
);
1741 if (BB
== 0) return 0; // Already diagnosed error.
1743 // Move the block to the end of the function. Forward ref'd blocks are
1744 // inserted wherever they happen to be referenced.
1745 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
1747 // Remove the block from forward ref sets.
1749 ForwardRefValIDs
.erase(NumberedVals
.size());
1750 NumberedVals
.push_back(BB
);
1752 // BB forward references are already in the function symbol table.
1753 ForwardRefVals
.erase(Name
);
1759 //===----------------------------------------------------------------------===//
1761 //===----------------------------------------------------------------------===//
1763 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1764 /// type implied. For example, if we parse "4" we don't know what integer type
1765 /// it has. The value will later be combined with its type and checked for
1767 bool LLParser::ParseValID(ValID
&ID
) {
1768 ID
.Loc
= Lex
.getLoc();
1769 switch (Lex
.getKind()) {
1770 default: return TokError("expected value token");
1771 case lltok::GlobalID
: // @42
1772 ID
.UIntVal
= Lex
.getUIntVal();
1773 ID
.Kind
= ValID::t_GlobalID
;
1775 case lltok::GlobalVar
: // @foo
1776 ID
.StrVal
= Lex
.getStrVal();
1777 ID
.Kind
= ValID::t_GlobalName
;
1779 case lltok::LocalVarID
: // %42
1780 ID
.UIntVal
= Lex
.getUIntVal();
1781 ID
.Kind
= ValID::t_LocalID
;
1783 case lltok::LocalVar
: // %foo
1784 case lltok::StringConstant
: // "foo" - FIXME: REMOVE IN LLVM 3.0
1785 ID
.StrVal
= Lex
.getStrVal();
1786 ID
.Kind
= ValID::t_LocalName
;
1788 case lltok::Metadata
: { // !{...} MDNode, !"foo" MDString
1789 ID
.Kind
= ValID::t_Metadata
;
1791 if (Lex
.getKind() == lltok::lbrace
) {
1792 SmallVector
<Value
*, 16> Elts
;
1793 if (ParseMDNodeVector(Elts
) ||
1794 ParseToken(lltok::rbrace
, "expected end of metadata node"))
1797 ID
.MetadataVal
= MDNode::get(Context
, Elts
.data(), Elts
.size());
1801 // Standalone metadata reference
1802 // !{ ..., !42, ... }
1803 if (!ParseMDNode(ID
.MetadataVal
))
1807 // ::= '!' STRINGCONSTANT
1808 if (ParseMDString(ID
.MetadataVal
)) return true;
1809 ID
.Kind
= ValID::t_Metadata
;
1813 ID
.APSIntVal
= Lex
.getAPSIntVal();
1814 ID
.Kind
= ValID::t_APSInt
;
1816 case lltok::APFloat
:
1817 ID
.APFloatVal
= Lex
.getAPFloatVal();
1818 ID
.Kind
= ValID::t_APFloat
;
1820 case lltok::kw_true
:
1821 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
1822 ID
.Kind
= ValID::t_Constant
;
1824 case lltok::kw_false
:
1825 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
1826 ID
.Kind
= ValID::t_Constant
;
1828 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
1829 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
1830 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
1832 case lltok::lbrace
: {
1833 // ValID ::= '{' ConstVector '}'
1835 SmallVector
<Constant
*, 16> Elts
;
1836 if (ParseGlobalValueVector(Elts
) ||
1837 ParseToken(lltok::rbrace
, "expected end of struct constant"))
1840 ID
.ConstantVal
= ConstantStruct::get(Context
, Elts
.data(),
1841 Elts
.size(), false);
1842 ID
.Kind
= ValID::t_Constant
;
1846 // ValID ::= '<' ConstVector '>' --> Vector.
1847 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1849 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
1851 SmallVector
<Constant
*, 16> Elts
;
1852 LocTy FirstEltLoc
= Lex
.getLoc();
1853 if (ParseGlobalValueVector(Elts
) ||
1855 ParseToken(lltok::rbrace
, "expected end of packed struct")) ||
1856 ParseToken(lltok::greater
, "expected end of constant"))
1859 if (isPackedStruct
) {
1861 ConstantStruct::get(Context
, Elts
.data(), Elts
.size(), true);
1862 ID
.Kind
= ValID::t_Constant
;
1867 return Error(ID
.Loc
, "constant vector must not be empty");
1869 if (!Elts
[0]->getType()->isInteger() &&
1870 !Elts
[0]->getType()->isFloatingPoint())
1871 return Error(FirstEltLoc
,
1872 "vector elements must have integer or floating point type");
1874 // Verify that all the vector elements have the same type.
1875 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
1876 if (Elts
[i
]->getType() != Elts
[0]->getType())
1877 return Error(FirstEltLoc
,
1878 "vector element #" + utostr(i
) +
1879 " is not of type '" + Elts
[0]->getType()->getDescription());
1881 ID
.ConstantVal
= ConstantVector::get(Elts
.data(), Elts
.size());
1882 ID
.Kind
= ValID::t_Constant
;
1885 case lltok::lsquare
: { // Array Constant
1887 SmallVector
<Constant
*, 16> Elts
;
1888 LocTy FirstEltLoc
= Lex
.getLoc();
1889 if (ParseGlobalValueVector(Elts
) ||
1890 ParseToken(lltok::rsquare
, "expected end of array constant"))
1893 // Handle empty element.
1895 // Use undef instead of an array because it's inconvenient to determine
1896 // the element type at this point, there being no elements to examine.
1897 ID
.Kind
= ValID::t_EmptyArray
;
1901 if (!Elts
[0]->getType()->isFirstClassType())
1902 return Error(FirstEltLoc
, "invalid array element type: " +
1903 Elts
[0]->getType()->getDescription());
1905 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
1907 // Verify all elements are correct type!
1908 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
1909 if (Elts
[i
]->getType() != Elts
[0]->getType())
1910 return Error(FirstEltLoc
,
1911 "array element #" + utostr(i
) +
1912 " is not of type '" +Elts
[0]->getType()->getDescription());
1915 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
.data(), Elts
.size());
1916 ID
.Kind
= ValID::t_Constant
;
1919 case lltok::kw_c
: // c "foo"
1921 ID
.ConstantVal
= ConstantArray::get(Context
, Lex
.getStrVal(), false);
1922 if (ParseToken(lltok::StringConstant
, "expected string")) return true;
1923 ID
.Kind
= ValID::t_Constant
;
1926 case lltok::kw_asm
: {
1927 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1930 if (ParseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
1931 ParseStringConstant(ID
.StrVal
) ||
1932 ParseToken(lltok::comma
, "expected comma in inline asm expression") ||
1933 ParseToken(lltok::StringConstant
, "expected constraint string"))
1935 ID
.StrVal2
= Lex
.getStrVal();
1936 ID
.UIntVal
= HasSideEffect
;
1937 ID
.Kind
= ValID::t_InlineAsm
;
1941 case lltok::kw_trunc
:
1942 case lltok::kw_zext
:
1943 case lltok::kw_sext
:
1944 case lltok::kw_fptrunc
:
1945 case lltok::kw_fpext
:
1946 case lltok::kw_bitcast
:
1947 case lltok::kw_uitofp
:
1948 case lltok::kw_sitofp
:
1949 case lltok::kw_fptoui
:
1950 case lltok::kw_fptosi
:
1951 case lltok::kw_inttoptr
:
1952 case lltok::kw_ptrtoint
: {
1953 unsigned Opc
= Lex
.getUIntVal();
1954 PATypeHolder
DestTy(Type::getVoidTy(Context
));
1957 if (ParseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
1958 ParseGlobalTypeAndValue(SrcVal
) ||
1959 ParseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
1960 ParseType(DestTy
) ||
1961 ParseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
1963 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
1964 return Error(ID
.Loc
, "invalid cast opcode for cast from '" +
1965 SrcVal
->getType()->getDescription() + "' to '" +
1966 DestTy
->getDescription() + "'");
1967 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
1969 ID
.Kind
= ValID::t_Constant
;
1972 case lltok::kw_extractvalue
: {
1975 SmallVector
<unsigned, 4> Indices
;
1976 if (ParseToken(lltok::lparen
, "expected '(' in extractvalue constantexpr")||
1977 ParseGlobalTypeAndValue(Val
) ||
1978 ParseIndexList(Indices
) ||
1979 ParseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
1981 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
1982 return Error(ID
.Loc
, "extractvalue operand must be array or struct");
1983 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
1985 return Error(ID
.Loc
, "invalid indices for extractvalue");
1987 ConstantExpr::getExtractValue(Val
, Indices
.data(), Indices
.size());
1988 ID
.Kind
= ValID::t_Constant
;
1991 case lltok::kw_insertvalue
: {
1993 Constant
*Val0
, *Val1
;
1994 SmallVector
<unsigned, 4> Indices
;
1995 if (ParseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr")||
1996 ParseGlobalTypeAndValue(Val0
) ||
1997 ParseToken(lltok::comma
, "expected comma in insertvalue constantexpr")||
1998 ParseGlobalTypeAndValue(Val1
) ||
1999 ParseIndexList(Indices
) ||
2000 ParseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
2002 if (!isa
<StructType
>(Val0
->getType()) && !isa
<ArrayType
>(Val0
->getType()))
2003 return Error(ID
.Loc
, "extractvalue operand must be array or struct");
2004 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
2006 return Error(ID
.Loc
, "invalid indices for insertvalue");
2007 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
,
2008 Indices
.data(), Indices
.size());
2009 ID
.Kind
= ValID::t_Constant
;
2012 case lltok::kw_icmp
:
2013 case lltok::kw_fcmp
: {
2014 unsigned PredVal
, Opc
= Lex
.getUIntVal();
2015 Constant
*Val0
, *Val1
;
2017 if (ParseCmpPredicate(PredVal
, Opc
) ||
2018 ParseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
2019 ParseGlobalTypeAndValue(Val0
) ||
2020 ParseToken(lltok::comma
, "expected comma in compare constantexpr") ||
2021 ParseGlobalTypeAndValue(Val1
) ||
2022 ParseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
2025 if (Val0
->getType() != Val1
->getType())
2026 return Error(ID
.Loc
, "compare operands must have the same type");
2028 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
2030 if (Opc
== Instruction::FCmp
) {
2031 if (!Val0
->getType()->isFPOrFPVector())
2032 return Error(ID
.Loc
, "fcmp requires floating point operands");
2033 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
2035 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
2036 if (!Val0
->getType()->isIntOrIntVector() &&
2037 !isa
<PointerType
>(Val0
->getType()))
2038 return Error(ID
.Loc
, "icmp requires pointer or integer operands");
2039 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
2041 ID
.Kind
= ValID::t_Constant
;
2045 // Binary Operators.
2047 case lltok::kw_fadd
:
2049 case lltok::kw_fsub
:
2051 case lltok::kw_fmul
:
2052 case lltok::kw_udiv
:
2053 case lltok::kw_sdiv
:
2054 case lltok::kw_fdiv
:
2055 case lltok::kw_urem
:
2056 case lltok::kw_srem
:
2057 case lltok::kw_frem
: {
2061 unsigned Opc
= Lex
.getUIntVal();
2062 Constant
*Val0
, *Val1
;
2064 LocTy ModifierLoc
= Lex
.getLoc();
2065 if (Opc
== Instruction::Add
||
2066 Opc
== Instruction::Sub
||
2067 Opc
== Instruction::Mul
) {
2068 if (EatIfPresent(lltok::kw_nuw
))
2070 if (EatIfPresent(lltok::kw_nsw
)) {
2072 if (EatIfPresent(lltok::kw_nuw
))
2075 } else if (Opc
== Instruction::SDiv
) {
2076 if (EatIfPresent(lltok::kw_exact
))
2079 if (ParseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
2080 ParseGlobalTypeAndValue(Val0
) ||
2081 ParseToken(lltok::comma
, "expected comma in binary constantexpr") ||
2082 ParseGlobalTypeAndValue(Val1
) ||
2083 ParseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
2085 if (Val0
->getType() != Val1
->getType())
2086 return Error(ID
.Loc
, "operands of constexpr must have same type");
2087 if (!Val0
->getType()->isIntOrIntVector()) {
2089 return Error(ModifierLoc
, "nuw only applies to integer operations");
2091 return Error(ModifierLoc
, "nsw only applies to integer operations");
2093 // API compatibility: Accept either integer or floating-point types with
2094 // add, sub, and mul.
2095 if (!Val0
->getType()->isIntOrIntVector() &&
2096 !Val0
->getType()->isFPOrFPVector())
2097 return Error(ID
.Loc
,"constexpr requires integer, fp, or vector operands");
2098 Constant
*C
= ConstantExpr::get(Opc
, Val0
, Val1
);
2100 cast
<OverflowingBinaryOperator
>(C
)->setHasNoUnsignedWrap(true);
2102 cast
<OverflowingBinaryOperator
>(C
)->setHasNoSignedWrap(true);
2104 cast
<SDivOperator
>(C
)->setIsExact(true);
2106 ID
.Kind
= ValID::t_Constant
;
2110 // Logical Operations
2112 case lltok::kw_lshr
:
2113 case lltok::kw_ashr
:
2116 case lltok::kw_xor
: {
2117 unsigned Opc
= Lex
.getUIntVal();
2118 Constant
*Val0
, *Val1
;
2120 if (ParseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
2121 ParseGlobalTypeAndValue(Val0
) ||
2122 ParseToken(lltok::comma
, "expected comma in logical constantexpr") ||
2123 ParseGlobalTypeAndValue(Val1
) ||
2124 ParseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
2126 if (Val0
->getType() != Val1
->getType())
2127 return Error(ID
.Loc
, "operands of constexpr must have same type");
2128 if (!Val0
->getType()->isIntOrIntVector())
2129 return Error(ID
.Loc
,
2130 "constexpr requires integer or integer vector operands");
2131 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
2132 ID
.Kind
= ValID::t_Constant
;
2136 case lltok::kw_getelementptr
:
2137 case lltok::kw_shufflevector
:
2138 case lltok::kw_insertelement
:
2139 case lltok::kw_extractelement
:
2140 case lltok::kw_select
: {
2141 unsigned Opc
= Lex
.getUIntVal();
2142 SmallVector
<Constant
*, 16> Elts
;
2143 bool InBounds
= false;
2145 if (Opc
== Instruction::GetElementPtr
)
2146 InBounds
= EatIfPresent(lltok::kw_inbounds
);
2147 if (ParseToken(lltok::lparen
, "expected '(' in constantexpr") ||
2148 ParseGlobalValueVector(Elts
) ||
2149 ParseToken(lltok::rparen
, "expected ')' in constantexpr"))
2152 if (Opc
== Instruction::GetElementPtr
) {
2153 if (Elts
.size() == 0 || !isa
<PointerType
>(Elts
[0]->getType()))
2154 return Error(ID
.Loc
, "getelementptr requires pointer operand");
2156 if (!GetElementPtrInst::getIndexedType(Elts
[0]->getType(),
2157 (Value
**)(Elts
.data() + 1),
2159 return Error(ID
.Loc
, "invalid indices for getelementptr");
2160 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Elts
[0],
2161 Elts
.data() + 1, Elts
.size() - 1);
2163 cast
<GEPOperator
>(ID
.ConstantVal
)->setIsInBounds(true);
2164 } else if (Opc
== Instruction::Select
) {
2165 if (Elts
.size() != 3)
2166 return Error(ID
.Loc
, "expected three operands to select");
2167 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
2169 return Error(ID
.Loc
, Reason
);
2170 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
2171 } else if (Opc
== Instruction::ShuffleVector
) {
2172 if (Elts
.size() != 3)
2173 return Error(ID
.Loc
, "expected three operands to shufflevector");
2174 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
2175 return Error(ID
.Loc
, "invalid operands to shufflevector");
2177 ConstantExpr::getShuffleVector(Elts
[0], Elts
[1],Elts
[2]);
2178 } else if (Opc
== Instruction::ExtractElement
) {
2179 if (Elts
.size() != 2)
2180 return Error(ID
.Loc
, "expected two operands to extractelement");
2181 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
2182 return Error(ID
.Loc
, "invalid extractelement operands");
2183 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
2185 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
2186 if (Elts
.size() != 3)
2187 return Error(ID
.Loc
, "expected three operands to insertelement");
2188 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
2189 return Error(ID
.Loc
, "invalid insertelement operands");
2191 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
2194 ID
.Kind
= ValID::t_Constant
;
2203 /// ParseGlobalValue - Parse a global value with the specified type.
2204 bool LLParser::ParseGlobalValue(const Type
*Ty
, Constant
*&V
) {
2207 return ParseValID(ID
) ||
2208 ConvertGlobalValIDToValue(Ty
, ID
, V
);
2211 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2213 bool LLParser::ConvertGlobalValIDToValue(const Type
*Ty
, ValID
&ID
,
2215 if (isa
<FunctionType
>(Ty
))
2216 return Error(ID
.Loc
, "functions are not values, refer to them as pointers");
2219 default: llvm_unreachable("Unknown ValID!");
2220 case ValID::t_Metadata
:
2221 return Error(ID
.Loc
, "invalid use of metadata");
2222 case ValID::t_LocalID
:
2223 case ValID::t_LocalName
:
2224 return Error(ID
.Loc
, "invalid use of function-local name");
2225 case ValID::t_InlineAsm
:
2226 return Error(ID
.Loc
, "inline asm can only be an operand of call/invoke");
2227 case ValID::t_GlobalName
:
2228 V
= GetGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
);
2230 case ValID::t_GlobalID
:
2231 V
= GetGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
);
2233 case ValID::t_APSInt
:
2234 if (!isa
<IntegerType
>(Ty
))
2235 return Error(ID
.Loc
, "integer constant must have integer type");
2236 ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
2237 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
2239 case ValID::t_APFloat
:
2240 if (!Ty
->isFloatingPoint() ||
2241 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
2242 return Error(ID
.Loc
, "floating point constant invalid for type");
2244 // The lexer has no type info, so builds all float and double FP constants
2245 // as double. Fix this here. Long double does not need this.
2246 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble
&&
2247 Ty
== Type::getFloatTy(Context
)) {
2249 ID
.APFloatVal
.convert(APFloat::IEEEsingle
, APFloat::rmNearestTiesToEven
,
2252 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
2254 if (V
->getType() != Ty
)
2255 return Error(ID
.Loc
, "floating point constant does not have type '" +
2256 Ty
->getDescription() + "'");
2260 if (!isa
<PointerType
>(Ty
))
2261 return Error(ID
.Loc
, "null must be a pointer type");
2262 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
2264 case ValID::t_Undef
:
2265 // FIXME: LabelTy should not be a first-class type.
2266 if ((!Ty
->isFirstClassType() || Ty
== Type::getLabelTy(Context
)) &&
2267 !isa
<OpaqueType
>(Ty
))
2268 return Error(ID
.Loc
, "invalid type for undef constant");
2269 V
= UndefValue::get(Ty
);
2271 case ValID::t_EmptyArray
:
2272 if (!isa
<ArrayType
>(Ty
) || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
2273 return Error(ID
.Loc
, "invalid empty array initializer");
2274 V
= UndefValue::get(Ty
);
2277 // FIXME: LabelTy should not be a first-class type.
2278 if (!Ty
->isFirstClassType() || Ty
== Type::getLabelTy(Context
))
2279 return Error(ID
.Loc
, "invalid type for null constant");
2280 V
= Constant::getNullValue(Ty
);
2282 case ValID::t_Constant
:
2283 if (ID
.ConstantVal
->getType() != Ty
)
2284 return Error(ID
.Loc
, "constant expression type mismatch");
2290 bool LLParser::ParseGlobalTypeAndValue(Constant
*&V
) {
2291 PATypeHolder
Type(Type::getVoidTy(Context
));
2292 return ParseType(Type
) ||
2293 ParseGlobalValue(Type
, V
);
2296 /// ParseGlobalValueVector
2298 /// ::= TypeAndValue (',' TypeAndValue)*
2299 bool LLParser::ParseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
) {
2301 if (Lex
.getKind() == lltok::rbrace
||
2302 Lex
.getKind() == lltok::rsquare
||
2303 Lex
.getKind() == lltok::greater
||
2304 Lex
.getKind() == lltok::rparen
)
2308 if (ParseGlobalTypeAndValue(C
)) return true;
2311 while (EatIfPresent(lltok::comma
)) {
2312 if (ParseGlobalTypeAndValue(C
)) return true;
2320 //===----------------------------------------------------------------------===//
2321 // Function Parsing.
2322 //===----------------------------------------------------------------------===//
2324 bool LLParser::ConvertValIDToValue(const Type
*Ty
, ValID
&ID
, Value
*&V
,
2325 PerFunctionState
&PFS
) {
2326 if (ID
.Kind
== ValID::t_LocalID
)
2327 V
= PFS
.GetVal(ID
.UIntVal
, Ty
, ID
.Loc
);
2328 else if (ID
.Kind
== ValID::t_LocalName
)
2329 V
= PFS
.GetVal(ID
.StrVal
, Ty
, ID
.Loc
);
2330 else if (ID
.Kind
== ValID::t_InlineAsm
) {
2331 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
2332 const FunctionType
*FTy
=
2333 PTy
? dyn_cast
<FunctionType
>(PTy
->getElementType()) : 0;
2334 if (!FTy
|| !InlineAsm::Verify(FTy
, ID
.StrVal2
))
2335 return Error(ID
.Loc
, "invalid type for inline asm constraint string");
2336 V
= InlineAsm::get(FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
);
2338 } else if (ID
.Kind
== ValID::t_Metadata
) {
2342 if (ConvertGlobalValIDToValue(Ty
, ID
, C
)) return true;
2350 bool LLParser::ParseValue(const Type
*Ty
, Value
*&V
, PerFunctionState
&PFS
) {
2353 return ParseValID(ID
) ||
2354 ConvertValIDToValue(Ty
, ID
, V
, PFS
);
2357 bool LLParser::ParseTypeAndValue(Value
*&V
, PerFunctionState
&PFS
) {
2358 PATypeHolder
T(Type::getVoidTy(Context
));
2359 return ParseType(T
) ||
2360 ParseValue(T
, V
, PFS
);
2364 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2365 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2366 /// OptionalAlign OptGC
2367 bool LLParser::ParseFunctionHeader(Function
*&Fn
, bool isDefine
) {
2368 // Parse the linkage.
2369 LocTy LinkageLoc
= Lex
.getLoc();
2372 unsigned Visibility
, RetAttrs
;
2374 PATypeHolder
RetType(Type::getVoidTy(Context
));
2375 LocTy RetTypeLoc
= Lex
.getLoc();
2376 if (ParseOptionalLinkage(Linkage
) ||
2377 ParseOptionalVisibility(Visibility
) ||
2378 ParseOptionalCallingConv(CC
) ||
2379 ParseOptionalAttrs(RetAttrs
, 1) ||
2380 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/))
2383 // Verify that the linkage is ok.
2384 switch ((GlobalValue::LinkageTypes
)Linkage
) {
2385 case GlobalValue::ExternalLinkage
:
2386 break; // always ok.
2387 case GlobalValue::DLLImportLinkage
:
2388 case GlobalValue::ExternalWeakLinkage
:
2390 return Error(LinkageLoc
, "invalid linkage for function definition");
2392 case GlobalValue::PrivateLinkage
:
2393 case GlobalValue::LinkerPrivateLinkage
:
2394 case GlobalValue::InternalLinkage
:
2395 case GlobalValue::AvailableExternallyLinkage
:
2396 case GlobalValue::LinkOnceAnyLinkage
:
2397 case GlobalValue::LinkOnceODRLinkage
:
2398 case GlobalValue::WeakAnyLinkage
:
2399 case GlobalValue::WeakODRLinkage
:
2400 case GlobalValue::DLLExportLinkage
:
2402 return Error(LinkageLoc
, "invalid linkage for function declaration");
2404 case GlobalValue::AppendingLinkage
:
2405 case GlobalValue::GhostLinkage
:
2406 case GlobalValue::CommonLinkage
:
2407 return Error(LinkageLoc
, "invalid function linkage type");
2410 if (!FunctionType::isValidReturnType(RetType
) ||
2411 isa
<OpaqueType
>(RetType
))
2412 return Error(RetTypeLoc
, "invalid function return type");
2414 LocTy NameLoc
= Lex
.getLoc();
2416 std::string FunctionName
;
2417 if (Lex
.getKind() == lltok::GlobalVar
) {
2418 FunctionName
= Lex
.getStrVal();
2419 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
2420 unsigned NameID
= Lex
.getUIntVal();
2422 if (NameID
!= NumberedVals
.size())
2423 return TokError("function expected to be numbered '%" +
2424 utostr(NumberedVals
.size()) + "'");
2426 return TokError("expected function name");
2431 if (Lex
.getKind() != lltok::lparen
)
2432 return TokError("expected '(' in function argument list");
2434 std::vector
<ArgInfo
> ArgList
;
2437 std::string Section
;
2441 if (ParseArgumentList(ArgList
, isVarArg
, false) ||
2442 ParseOptionalAttrs(FuncAttrs
, 2) ||
2443 (EatIfPresent(lltok::kw_section
) &&
2444 ParseStringConstant(Section
)) ||
2445 ParseOptionalAlignment(Alignment
) ||
2446 (EatIfPresent(lltok::kw_gc
) &&
2447 ParseStringConstant(GC
)))
2450 // If the alignment was parsed as an attribute, move to the alignment field.
2451 if (FuncAttrs
& Attribute::Alignment
) {
2452 Alignment
= Attribute::getAlignmentFromAttrs(FuncAttrs
);
2453 FuncAttrs
&= ~Attribute::Alignment
;
2456 // Okay, if we got here, the function is syntactically valid. Convert types
2457 // and do semantic checks.
2458 std::vector
<const Type
*> ParamTypeList
;
2459 SmallVector
<AttributeWithIndex
, 8> Attrs
;
2460 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2462 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
2463 if (FuncAttrs
& ObsoleteFuncAttrs
) {
2464 RetAttrs
|= FuncAttrs
& ObsoleteFuncAttrs
;
2465 FuncAttrs
&= ~ObsoleteFuncAttrs
;
2468 if (RetAttrs
!= Attribute::None
)
2469 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
2471 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2472 ParamTypeList
.push_back(ArgList
[i
].Type
);
2473 if (ArgList
[i
].Attrs
!= Attribute::None
)
2474 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
2477 if (FuncAttrs
!= Attribute::None
)
2478 Attrs
.push_back(AttributeWithIndex::get(~0, FuncAttrs
));
2480 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
2482 if (PAL
.paramHasAttr(1, Attribute::StructRet
) &&
2483 RetType
!= Type::getVoidTy(Context
))
2484 return Error(RetTypeLoc
, "functions with 'sret' argument must return void");
2486 const FunctionType
*FT
=
2487 FunctionType::get(RetType
, ParamTypeList
, isVarArg
);
2488 const PointerType
*PFT
= PointerType::getUnqual(FT
);
2491 if (!FunctionName
.empty()) {
2492 // If this was a definition of a forward reference, remove the definition
2493 // from the forward reference table and fill in the forward ref.
2494 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator FRVI
=
2495 ForwardRefVals
.find(FunctionName
);
2496 if (FRVI
!= ForwardRefVals
.end()) {
2497 Fn
= M
->getFunction(FunctionName
);
2498 ForwardRefVals
.erase(FRVI
);
2499 } else if ((Fn
= M
->getFunction(FunctionName
))) {
2500 // If this function already exists in the symbol table, then it is
2501 // multiply defined. We accept a few cases for old backwards compat.
2502 // FIXME: Remove this stuff for LLVM 3.0.
2503 if (Fn
->getType() != PFT
|| Fn
->getAttributes() != PAL
||
2504 (!Fn
->isDeclaration() && isDefine
)) {
2505 // If the redefinition has different type or different attributes,
2506 // reject it. If both have bodies, reject it.
2507 return Error(NameLoc
, "invalid redefinition of function '" +
2508 FunctionName
+ "'");
2509 } else if (Fn
->isDeclaration()) {
2510 // Make sure to strip off any argument names so we can't get conflicts.
2511 for (Function::arg_iterator AI
= Fn
->arg_begin(), AE
= Fn
->arg_end();
2518 // If this is a definition of a forward referenced function, make sure the
2520 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator I
2521 = ForwardRefValIDs
.find(NumberedVals
.size());
2522 if (I
!= ForwardRefValIDs
.end()) {
2523 Fn
= cast
<Function
>(I
->second
.first
);
2524 if (Fn
->getType() != PFT
)
2525 return Error(NameLoc
, "type of definition and forward reference of '@" +
2526 utostr(NumberedVals
.size()) +"' disagree");
2527 ForwardRefValIDs
.erase(I
);
2532 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, FunctionName
, M
);
2533 else // Move the forward-reference to the correct spot in the module.
2534 M
->getFunctionList().splice(M
->end(), M
->getFunctionList(), Fn
);
2536 if (FunctionName
.empty())
2537 NumberedVals
.push_back(Fn
);
2539 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
2540 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
2541 Fn
->setCallingConv(CC
);
2542 Fn
->setAttributes(PAL
);
2543 Fn
->setAlignment(Alignment
);
2544 Fn
->setSection(Section
);
2545 if (!GC
.empty()) Fn
->setGC(GC
.c_str());
2547 // Add all of the arguments we parsed to the function.
2548 Function::arg_iterator ArgIt
= Fn
->arg_begin();
2549 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
2550 // If the argument has a name, insert it into the argument symbol table.
2551 if (ArgList
[i
].Name
.empty()) continue;
2553 // Set the name, if it conflicted, it will be auto-renamed.
2554 ArgIt
->setName(ArgList
[i
].Name
);
2556 if (ArgIt
->getNameStr() != ArgList
[i
].Name
)
2557 return Error(ArgList
[i
].Loc
, "redefinition of argument '%" +
2558 ArgList
[i
].Name
+ "'");
2565 /// ParseFunctionBody
2566 /// ::= '{' BasicBlock+ '}'
2567 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2569 bool LLParser::ParseFunctionBody(Function
&Fn
) {
2570 if (Lex
.getKind() != lltok::lbrace
&& Lex
.getKind() != lltok::kw_begin
)
2571 return TokError("expected '{' in function body");
2572 Lex
.Lex(); // eat the {.
2574 PerFunctionState
PFS(*this, Fn
);
2576 while (Lex
.getKind() != lltok::rbrace
&& Lex
.getKind() != lltok::kw_end
)
2577 if (ParseBasicBlock(PFS
)) return true;
2582 // Verify function is ok.
2583 return PFS
.VerifyFunctionComplete();
2587 /// ::= LabelStr? Instruction*
2588 bool LLParser::ParseBasicBlock(PerFunctionState
&PFS
) {
2589 // If this basic block starts out with a name, remember it.
2591 LocTy NameLoc
= Lex
.getLoc();
2592 if (Lex
.getKind() == lltok::LabelStr
) {
2593 Name
= Lex
.getStrVal();
2597 BasicBlock
*BB
= PFS
.DefineBB(Name
, NameLoc
);
2598 if (BB
== 0) return true;
2600 std::string NameStr
;
2602 // Parse the instructions in this block until we get a terminator.
2605 // This instruction may have three possibilities for a name: a) none
2606 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2607 LocTy NameLoc
= Lex
.getLoc();
2611 if (Lex
.getKind() == lltok::LocalVarID
) {
2612 NameID
= Lex
.getUIntVal();
2614 if (ParseToken(lltok::equal
, "expected '=' after instruction id"))
2616 } else if (Lex
.getKind() == lltok::LocalVar
||
2617 // FIXME: REMOVE IN LLVM 3.0
2618 Lex
.getKind() == lltok::StringConstant
) {
2619 NameStr
= Lex
.getStrVal();
2621 if (ParseToken(lltok::equal
, "expected '=' after instruction name"))
2625 if (ParseInstruction(Inst
, BB
, PFS
)) return true;
2627 BB
->getInstList().push_back(Inst
);
2629 // Set the name on the instruction.
2630 if (PFS
.SetInstName(NameID
, NameStr
, NameLoc
, Inst
)) return true;
2631 } while (!isa
<TerminatorInst
>(Inst
));
2636 //===----------------------------------------------------------------------===//
2637 // Instruction Parsing.
2638 //===----------------------------------------------------------------------===//
2640 /// ParseInstruction - Parse one of the many different instructions.
2642 bool LLParser::ParseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
2643 PerFunctionState
&PFS
) {
2644 lltok::Kind Token
= Lex
.getKind();
2645 if (Token
== lltok::Eof
)
2646 return TokError("found end of file when expecting more instructions");
2647 LocTy Loc
= Lex
.getLoc();
2648 unsigned KeywordVal
= Lex
.getUIntVal();
2649 Lex
.Lex(); // Eat the keyword.
2652 default: return Error(Loc
, "expected instruction opcode");
2653 // Terminator Instructions.
2654 case lltok::kw_unwind
: Inst
= new UnwindInst(Context
); return false;
2655 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
2656 case lltok::kw_ret
: return ParseRet(Inst
, BB
, PFS
);
2657 case lltok::kw_br
: return ParseBr(Inst
, PFS
);
2658 case lltok::kw_switch
: return ParseSwitch(Inst
, PFS
);
2659 case lltok::kw_invoke
: return ParseInvoke(Inst
, PFS
);
2660 // Binary Operators.
2663 case lltok::kw_mul
: {
2666 LocTy ModifierLoc
= Lex
.getLoc();
2667 if (EatIfPresent(lltok::kw_nuw
))
2669 if (EatIfPresent(lltok::kw_nsw
)) {
2671 if (EatIfPresent(lltok::kw_nuw
))
2674 // API compatibility: Accept either integer or floating-point types.
2675 bool Result
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 0);
2677 if (!Inst
->getType()->isIntOrIntVector()) {
2679 return Error(ModifierLoc
, "nuw only applies to integer operations");
2681 return Error(ModifierLoc
, "nsw only applies to integer operations");
2684 cast
<OverflowingBinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
2686 cast
<OverflowingBinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
2690 case lltok::kw_fadd
:
2691 case lltok::kw_fsub
:
2692 case lltok::kw_fmul
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
2694 case lltok::kw_sdiv
: {
2696 if (EatIfPresent(lltok::kw_exact
))
2698 bool Result
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
2701 cast
<SDivOperator
>(Inst
)->setIsExact(true);
2705 case lltok::kw_udiv
:
2706 case lltok::kw_urem
:
2707 case lltok::kw_srem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
2708 case lltok::kw_fdiv
:
2709 case lltok::kw_frem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
2711 case lltok::kw_lshr
:
2712 case lltok::kw_ashr
:
2715 case lltok::kw_xor
: return ParseLogical(Inst
, PFS
, KeywordVal
);
2716 case lltok::kw_icmp
:
2717 case lltok::kw_fcmp
: return ParseCompare(Inst
, PFS
, KeywordVal
);
2719 case lltok::kw_trunc
:
2720 case lltok::kw_zext
:
2721 case lltok::kw_sext
:
2722 case lltok::kw_fptrunc
:
2723 case lltok::kw_fpext
:
2724 case lltok::kw_bitcast
:
2725 case lltok::kw_uitofp
:
2726 case lltok::kw_sitofp
:
2727 case lltok::kw_fptoui
:
2728 case lltok::kw_fptosi
:
2729 case lltok::kw_inttoptr
:
2730 case lltok::kw_ptrtoint
: return ParseCast(Inst
, PFS
, KeywordVal
);
2732 case lltok::kw_select
: return ParseSelect(Inst
, PFS
);
2733 case lltok::kw_va_arg
: return ParseVA_Arg(Inst
, PFS
);
2734 case lltok::kw_extractelement
: return ParseExtractElement(Inst
, PFS
);
2735 case lltok::kw_insertelement
: return ParseInsertElement(Inst
, PFS
);
2736 case lltok::kw_shufflevector
: return ParseShuffleVector(Inst
, PFS
);
2737 case lltok::kw_phi
: return ParsePHI(Inst
, PFS
);
2738 case lltok::kw_call
: return ParseCall(Inst
, PFS
, false);
2739 case lltok::kw_tail
: return ParseCall(Inst
, PFS
, true);
2741 case lltok::kw_alloca
:
2742 case lltok::kw_malloc
: return ParseAlloc(Inst
, PFS
, KeywordVal
);
2743 case lltok::kw_free
: return ParseFree(Inst
, PFS
);
2744 case lltok::kw_load
: return ParseLoad(Inst
, PFS
, false);
2745 case lltok::kw_store
: return ParseStore(Inst
, PFS
, false);
2746 case lltok::kw_volatile
:
2747 if (EatIfPresent(lltok::kw_load
))
2748 return ParseLoad(Inst
, PFS
, true);
2749 else if (EatIfPresent(lltok::kw_store
))
2750 return ParseStore(Inst
, PFS
, true);
2752 return TokError("expected 'load' or 'store'");
2753 case lltok::kw_getresult
: return ParseGetResult(Inst
, PFS
);
2754 case lltok::kw_getelementptr
: return ParseGetElementPtr(Inst
, PFS
);
2755 case lltok::kw_extractvalue
: return ParseExtractValue(Inst
, PFS
);
2756 case lltok::kw_insertvalue
: return ParseInsertValue(Inst
, PFS
);
2760 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2761 bool LLParser::ParseCmpPredicate(unsigned &P
, unsigned Opc
) {
2762 if (Opc
== Instruction::FCmp
) {
2763 switch (Lex
.getKind()) {
2764 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2765 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
2766 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
2767 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
2768 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
2769 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
2770 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
2771 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
2772 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
2773 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
2774 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
2775 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
2776 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
2777 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
2778 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
2779 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
2780 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
2783 switch (Lex
.getKind()) {
2784 default: TokError("expected icmp predicate (e.g. 'eq')");
2785 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
2786 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
2787 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
2788 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
2789 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
2790 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
2791 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
2792 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
2793 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
2794 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
2801 //===----------------------------------------------------------------------===//
2802 // Terminator Instructions.
2803 //===----------------------------------------------------------------------===//
2805 /// ParseRet - Parse a return instruction.
2807 /// ::= 'ret' TypeAndValue
2808 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2809 bool LLParser::ParseRet(Instruction
*&Inst
, BasicBlock
*BB
,
2810 PerFunctionState
&PFS
) {
2811 PATypeHolder
Ty(Type::getVoidTy(Context
));
2812 if (ParseType(Ty
, true /*void allowed*/)) return true;
2814 if (Ty
== Type::getVoidTy(Context
)) {
2815 Inst
= ReturnInst::Create(Context
);
2820 if (ParseValue(Ty
, RV
, PFS
)) return true;
2822 // The normal case is one return value.
2823 if (Lex
.getKind() == lltok::comma
) {
2824 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2825 // of 'ret {i32,i32} {i32 1, i32 2}'
2826 SmallVector
<Value
*, 8> RVs
;
2829 while (EatIfPresent(lltok::comma
)) {
2830 if (ParseTypeAndValue(RV
, PFS
)) return true;
2834 RV
= UndefValue::get(PFS
.getFunction().getReturnType());
2835 for (unsigned i
= 0, e
= RVs
.size(); i
!= e
; ++i
) {
2836 Instruction
*I
= InsertValueInst::Create(RV
, RVs
[i
], i
, "mrv");
2837 BB
->getInstList().push_back(I
);
2841 Inst
= ReturnInst::Create(Context
, RV
);
2847 /// ::= 'br' TypeAndValue
2848 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2849 bool LLParser::ParseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2851 Value
*Op0
, *Op1
, *Op2
;
2852 if (ParseTypeAndValue(Op0
, Loc
, PFS
)) return true;
2854 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
2855 Inst
= BranchInst::Create(BB
);
2859 if (Op0
->getType() != Type::getInt1Ty(Context
))
2860 return Error(Loc
, "branch condition must have 'i1' type");
2862 if (ParseToken(lltok::comma
, "expected ',' after branch condition") ||
2863 ParseTypeAndValue(Op1
, Loc
, PFS
) ||
2864 ParseToken(lltok::comma
, "expected ',' after true destination") ||
2865 ParseTypeAndValue(Op2
, Loc2
, PFS
))
2868 if (!isa
<BasicBlock
>(Op1
))
2869 return Error(Loc
, "true destination of branch must be a basic block");
2870 if (!isa
<BasicBlock
>(Op2
))
2871 return Error(Loc2
, "true destination of branch must be a basic block");
2873 Inst
= BranchInst::Create(cast
<BasicBlock
>(Op1
), cast
<BasicBlock
>(Op2
), Op0
);
2879 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2881 /// ::= (TypeAndValue ',' TypeAndValue)*
2882 bool LLParser::ParseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2883 LocTy CondLoc
, BBLoc
;
2884 Value
*Cond
, *DefaultBB
;
2885 if (ParseTypeAndValue(Cond
, CondLoc
, PFS
) ||
2886 ParseToken(lltok::comma
, "expected ',' after switch condition") ||
2887 ParseTypeAndValue(DefaultBB
, BBLoc
, PFS
) ||
2888 ParseToken(lltok::lsquare
, "expected '[' with switch table"))
2891 if (!isa
<IntegerType
>(Cond
->getType()))
2892 return Error(CondLoc
, "switch condition must have integer type");
2893 if (!isa
<BasicBlock
>(DefaultBB
))
2894 return Error(BBLoc
, "default destination must be a basic block");
2896 // Parse the jump table pairs.
2897 SmallPtrSet
<Value
*, 32> SeenCases
;
2898 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
2899 while (Lex
.getKind() != lltok::rsquare
) {
2900 Value
*Constant
, *DestBB
;
2902 if (ParseTypeAndValue(Constant
, CondLoc
, PFS
) ||
2903 ParseToken(lltok::comma
, "expected ',' after case value") ||
2904 ParseTypeAndValue(DestBB
, BBLoc
, PFS
))
2907 if (!SeenCases
.insert(Constant
))
2908 return Error(CondLoc
, "duplicate case value in switch");
2909 if (!isa
<ConstantInt
>(Constant
))
2910 return Error(CondLoc
, "case value is not a constant integer");
2911 if (!isa
<BasicBlock
>(DestBB
))
2912 return Error(BBLoc
, "case destination is not a basic block");
2914 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
),
2915 cast
<BasicBlock
>(DestBB
)));
2918 Lex
.Lex(); // Eat the ']'.
2920 SwitchInst
*SI
= SwitchInst::Create(Cond
, cast
<BasicBlock
>(DefaultBB
),
2922 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
2923 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
2929 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2930 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2931 bool LLParser::ParseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2932 LocTy CallLoc
= Lex
.getLoc();
2933 unsigned RetAttrs
, FnAttrs
;
2935 PATypeHolder
RetType(Type::getVoidTy(Context
));
2938 SmallVector
<ParamInfo
, 16> ArgList
;
2940 Value
*NormalBB
, *UnwindBB
;
2941 if (ParseOptionalCallingConv(CC
) ||
2942 ParseOptionalAttrs(RetAttrs
, 1) ||
2943 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
2944 ParseValID(CalleeID
) ||
2945 ParseParameterList(ArgList
, PFS
) ||
2946 ParseOptionalAttrs(FnAttrs
, 2) ||
2947 ParseToken(lltok::kw_to
, "expected 'to' in invoke") ||
2948 ParseTypeAndValue(NormalBB
, PFS
) ||
2949 ParseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
2950 ParseTypeAndValue(UnwindBB
, PFS
))
2953 if (!isa
<BasicBlock
>(NormalBB
))
2954 return Error(CallLoc
, "normal destination is not a basic block");
2955 if (!isa
<BasicBlock
>(UnwindBB
))
2956 return Error(CallLoc
, "unwind destination is not a basic block");
2958 // If RetType is a non-function pointer type, then this is the short syntax
2959 // for the call, which means that RetType is just the return type. Infer the
2960 // rest of the function argument types from the arguments that are present.
2961 const PointerType
*PFTy
= 0;
2962 const FunctionType
*Ty
= 0;
2963 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
2964 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
2965 // Pull out the types of all of the arguments...
2966 std::vector
<const Type
*> ParamTypes
;
2967 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
2968 ParamTypes
.push_back(ArgList
[i
].V
->getType());
2970 if (!FunctionType::isValidReturnType(RetType
))
2971 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
2973 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
2974 PFTy
= PointerType::getUnqual(Ty
);
2977 // Look up the callee.
2979 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, PFS
)) return true;
2981 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2982 // function attributes.
2983 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
2984 if (FnAttrs
& ObsoleteFuncAttrs
) {
2985 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
2986 FnAttrs
&= ~ObsoleteFuncAttrs
;
2989 // Set up the Attributes for the function.
2990 SmallVector
<AttributeWithIndex
, 8> Attrs
;
2991 if (RetAttrs
!= Attribute::None
)
2992 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
2994 SmallVector
<Value
*, 8> Args
;
2996 // Loop through FunctionType's arguments and ensure they are specified
2997 // correctly. Also, gather any parameter attributes.
2998 FunctionType::param_iterator I
= Ty
->param_begin();
2999 FunctionType::param_iterator E
= Ty
->param_end();
3000 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3001 const Type
*ExpectedTy
= 0;
3004 } else if (!Ty
->isVarArg()) {
3005 return Error(ArgList
[i
].Loc
, "too many arguments specified");
3008 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
3009 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
3010 ExpectedTy
->getDescription() + "'");
3011 Args
.push_back(ArgList
[i
].V
);
3012 if (ArgList
[i
].Attrs
!= Attribute::None
)
3013 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
3017 return Error(CallLoc
, "not enough parameters specified for call");
3019 if (FnAttrs
!= Attribute::None
)
3020 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
3022 // Finish off the Attributes and check them
3023 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
3025 InvokeInst
*II
= InvokeInst::Create(Callee
, cast
<BasicBlock
>(NormalBB
),
3026 cast
<BasicBlock
>(UnwindBB
),
3027 Args
.begin(), Args
.end());
3028 II
->setCallingConv(CC
);
3029 II
->setAttributes(PAL
);
3036 //===----------------------------------------------------------------------===//
3037 // Binary Operators.
3038 //===----------------------------------------------------------------------===//
3041 /// ::= ArithmeticOps TypeAndValue ',' Value
3043 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3044 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3045 bool LLParser::ParseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
3046 unsigned Opc
, unsigned OperandType
) {
3047 LocTy Loc
; Value
*LHS
, *RHS
;
3048 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3049 ParseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
3050 ParseValue(LHS
->getType(), RHS
, PFS
))
3054 switch (OperandType
) {
3055 default: llvm_unreachable("Unknown operand type!");
3056 case 0: // int or FP.
3057 Valid
= LHS
->getType()->isIntOrIntVector() ||
3058 LHS
->getType()->isFPOrFPVector();
3060 case 1: Valid
= LHS
->getType()->isIntOrIntVector(); break;
3061 case 2: Valid
= LHS
->getType()->isFPOrFPVector(); break;
3065 return Error(Loc
, "invalid operand type for instruction");
3067 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3072 /// ::= ArithmeticOps TypeAndValue ',' Value {
3073 bool LLParser::ParseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
3075 LocTy Loc
; Value
*LHS
, *RHS
;
3076 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3077 ParseToken(lltok::comma
, "expected ',' in logical operation") ||
3078 ParseValue(LHS
->getType(), RHS
, PFS
))
3081 if (!LHS
->getType()->isIntOrIntVector())
3082 return Error(Loc
,"instruction requires integer or integer vector operands");
3084 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3090 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3091 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3092 bool LLParser::ParseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
3094 // Parse the integer/fp comparison predicate.
3098 if (ParseCmpPredicate(Pred
, Opc
) ||
3099 ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3100 ParseToken(lltok::comma
, "expected ',' after compare value") ||
3101 ParseValue(LHS
->getType(), RHS
, PFS
))
3104 if (Opc
== Instruction::FCmp
) {
3105 if (!LHS
->getType()->isFPOrFPVector())
3106 return Error(Loc
, "fcmp requires floating point operands");
3107 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
3109 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
3110 if (!LHS
->getType()->isIntOrIntVector() &&
3111 !isa
<PointerType
>(LHS
->getType()))
3112 return Error(Loc
, "icmp requires integer operands");
3113 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
3118 //===----------------------------------------------------------------------===//
3119 // Other Instructions.
3120 //===----------------------------------------------------------------------===//
3124 /// ::= CastOpc TypeAndValue 'to' Type
3125 bool LLParser::ParseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
3127 LocTy Loc
; Value
*Op
;
3128 PATypeHolder
DestTy(Type::getVoidTy(Context
));
3129 if (ParseTypeAndValue(Op
, Loc
, PFS
) ||
3130 ParseToken(lltok::kw_to
, "expected 'to' after cast value") ||
3134 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
3135 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
3136 return Error(Loc
, "invalid cast opcode for cast from '" +
3137 Op
->getType()->getDescription() + "' to '" +
3138 DestTy
->getDescription() + "'");
3140 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
3145 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3146 bool LLParser::ParseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3148 Value
*Op0
, *Op1
, *Op2
;
3149 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3150 ParseToken(lltok::comma
, "expected ',' after select condition") ||
3151 ParseTypeAndValue(Op1
, PFS
) ||
3152 ParseToken(lltok::comma
, "expected ',' after select value") ||
3153 ParseTypeAndValue(Op2
, PFS
))
3156 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
3157 return Error(Loc
, Reason
);
3159 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
3164 /// ::= 'va_arg' TypeAndValue ',' Type
3165 bool LLParser::ParseVA_Arg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3167 PATypeHolder
EltTy(Type::getVoidTy(Context
));
3169 if (ParseTypeAndValue(Op
, PFS
) ||
3170 ParseToken(lltok::comma
, "expected ',' after vaarg operand") ||
3171 ParseType(EltTy
, TypeLoc
))
3174 if (!EltTy
->isFirstClassType())
3175 return Error(TypeLoc
, "va_arg requires operand with first class type");
3177 Inst
= new VAArgInst(Op
, EltTy
);
3181 /// ParseExtractElement
3182 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3183 bool LLParser::ParseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3186 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3187 ParseToken(lltok::comma
, "expected ',' after extract value") ||
3188 ParseTypeAndValue(Op1
, PFS
))
3191 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
3192 return Error(Loc
, "invalid extractelement operands");
3194 Inst
= ExtractElementInst::Create(Op0
, Op1
);
3198 /// ParseInsertElement
3199 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3200 bool LLParser::ParseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3202 Value
*Op0
, *Op1
, *Op2
;
3203 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3204 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3205 ParseTypeAndValue(Op1
, PFS
) ||
3206 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3207 ParseTypeAndValue(Op2
, PFS
))
3210 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
3211 return Error(Loc
, "invalid insertelement operands");
3213 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
3217 /// ParseShuffleVector
3218 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3219 bool LLParser::ParseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3221 Value
*Op0
, *Op1
, *Op2
;
3222 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3223 ParseToken(lltok::comma
, "expected ',' after shuffle mask") ||
3224 ParseTypeAndValue(Op1
, PFS
) ||
3225 ParseToken(lltok::comma
, "expected ',' after shuffle value") ||
3226 ParseTypeAndValue(Op2
, PFS
))
3229 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
3230 return Error(Loc
, "invalid extractelement operands");
3232 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
3237 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3238 bool LLParser::ParsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3239 PATypeHolder
Ty(Type::getVoidTy(Context
));
3241 LocTy TypeLoc
= Lex
.getLoc();
3243 if (ParseType(Ty
) ||
3244 ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
3245 ParseValue(Ty
, Op0
, PFS
) ||
3246 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3247 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
3248 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
3251 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
3253 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
3255 if (!EatIfPresent(lltok::comma
))
3258 if (ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
3259 ParseValue(Ty
, Op0
, PFS
) ||
3260 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3261 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
3262 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
3266 if (!Ty
->isFirstClassType())
3267 return Error(TypeLoc
, "phi node must have first class type");
3269 PHINode
*PN
= PHINode::Create(Ty
);
3270 PN
->reserveOperandSpace(PHIVals
.size());
3271 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
3272 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
3278 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3279 /// ParameterList OptionalAttrs
3280 bool LLParser::ParseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
3282 unsigned RetAttrs
, FnAttrs
;
3284 PATypeHolder
RetType(Type::getVoidTy(Context
));
3287 SmallVector
<ParamInfo
, 16> ArgList
;
3288 LocTy CallLoc
= Lex
.getLoc();
3290 if ((isTail
&& ParseToken(lltok::kw_call
, "expected 'tail call'")) ||
3291 ParseOptionalCallingConv(CC
) ||
3292 ParseOptionalAttrs(RetAttrs
, 1) ||
3293 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
3294 ParseValID(CalleeID
) ||
3295 ParseParameterList(ArgList
, PFS
) ||
3296 ParseOptionalAttrs(FnAttrs
, 2))
3299 // If RetType is a non-function pointer type, then this is the short syntax
3300 // for the call, which means that RetType is just the return type. Infer the
3301 // rest of the function argument types from the arguments that are present.
3302 const PointerType
*PFTy
= 0;
3303 const FunctionType
*Ty
= 0;
3304 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
3305 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
3306 // Pull out the types of all of the arguments...
3307 std::vector
<const Type
*> ParamTypes
;
3308 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
3309 ParamTypes
.push_back(ArgList
[i
].V
->getType());
3311 if (!FunctionType::isValidReturnType(RetType
))
3312 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
3314 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
3315 PFTy
= PointerType::getUnqual(Ty
);
3318 // Look up the callee.
3320 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, PFS
)) return true;
3322 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3323 // function attributes.
3324 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
3325 if (FnAttrs
& ObsoleteFuncAttrs
) {
3326 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
3327 FnAttrs
&= ~ObsoleteFuncAttrs
;
3330 // Set up the Attributes for the function.
3331 SmallVector
<AttributeWithIndex
, 8> Attrs
;
3332 if (RetAttrs
!= Attribute::None
)
3333 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
3335 SmallVector
<Value
*, 8> Args
;
3337 // Loop through FunctionType's arguments and ensure they are specified
3338 // correctly. Also, gather any parameter attributes.
3339 FunctionType::param_iterator I
= Ty
->param_begin();
3340 FunctionType::param_iterator E
= Ty
->param_end();
3341 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3342 const Type
*ExpectedTy
= 0;
3345 } else if (!Ty
->isVarArg()) {
3346 return Error(ArgList
[i
].Loc
, "too many arguments specified");
3349 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
3350 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
3351 ExpectedTy
->getDescription() + "'");
3352 Args
.push_back(ArgList
[i
].V
);
3353 if (ArgList
[i
].Attrs
!= Attribute::None
)
3354 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
3358 return Error(CallLoc
, "not enough parameters specified for call");
3360 if (FnAttrs
!= Attribute::None
)
3361 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
3363 // Finish off the Attributes and check them
3364 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
3366 CallInst
*CI
= CallInst::Create(Callee
, Args
.begin(), Args
.end());
3367 CI
->setTailCall(isTail
);
3368 CI
->setCallingConv(CC
);
3369 CI
->setAttributes(PAL
);
3374 //===----------------------------------------------------------------------===//
3375 // Memory Instructions.
3376 //===----------------------------------------------------------------------===//
3379 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3380 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3381 bool LLParser::ParseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
,
3383 PATypeHolder
Ty(Type::getVoidTy(Context
));
3386 unsigned Alignment
= 0;
3387 if (ParseType(Ty
)) return true;
3389 if (EatIfPresent(lltok::comma
)) {
3390 if (Lex
.getKind() == lltok::kw_align
) {
3391 if (ParseOptionalAlignment(Alignment
)) return true;
3392 } else if (ParseTypeAndValue(Size
, SizeLoc
, PFS
) ||
3393 ParseOptionalCommaAlignment(Alignment
)) {
3398 if (Size
&& Size
->getType() != Type::getInt32Ty(Context
))
3399 return Error(SizeLoc
, "element count must be i32");
3401 if (Opc
== Instruction::Malloc
)
3402 Inst
= new MallocInst(Ty
, Size
, Alignment
);
3404 Inst
= new AllocaInst(Ty
, Size
, Alignment
);
3409 /// ::= 'free' TypeAndValue
3410 bool LLParser::ParseFree(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3411 Value
*Val
; LocTy Loc
;
3412 if (ParseTypeAndValue(Val
, Loc
, PFS
)) return true;
3413 if (!isa
<PointerType
>(Val
->getType()))
3414 return Error(Loc
, "operand to free must be a pointer");
3415 Inst
= new FreeInst(Val
);
3420 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3421 bool LLParser::ParseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
,
3423 Value
*Val
; LocTy Loc
;
3425 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3426 ParseOptionalCommaAlignment(Alignment
))
3429 if (!isa
<PointerType
>(Val
->getType()) ||
3430 !cast
<PointerType
>(Val
->getType())->getElementType()->isFirstClassType())
3431 return Error(Loc
, "load operand must be a pointer to a first class type");
3433 Inst
= new LoadInst(Val
, "", isVolatile
, Alignment
);
3438 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3439 bool LLParser::ParseStore(Instruction
*&Inst
, PerFunctionState
&PFS
,
3441 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
3443 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3444 ParseToken(lltok::comma
, "expected ',' after store operand") ||
3445 ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
3446 ParseOptionalCommaAlignment(Alignment
))
3449 if (!isa
<PointerType
>(Ptr
->getType()))
3450 return Error(PtrLoc
, "store operand must be a pointer");
3451 if (!Val
->getType()->isFirstClassType())
3452 return Error(Loc
, "store operand must be a first class value");
3453 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
3454 return Error(Loc
, "stored value and pointer type do not match");
3456 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, Alignment
);
3461 /// ::= 'getresult' TypeAndValue ',' i32
3462 /// FIXME: Remove support for getresult in LLVM 3.0
3463 bool LLParser::ParseGetResult(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3464 Value
*Val
; LocTy ValLoc
, EltLoc
;
3466 if (ParseTypeAndValue(Val
, ValLoc
, PFS
) ||
3467 ParseToken(lltok::comma
, "expected ',' after getresult operand") ||
3468 ParseUInt32(Element
, EltLoc
))
3471 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
3472 return Error(ValLoc
, "getresult inst requires an aggregate operand");
3473 if (!ExtractValueInst::getIndexedType(Val
->getType(), Element
))
3474 return Error(EltLoc
, "invalid getresult index for value");
3475 Inst
= ExtractValueInst::Create(Val
, Element
);
3479 /// ParseGetElementPtr
3480 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3481 bool LLParser::ParseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3482 Value
*Ptr
, *Val
; LocTy Loc
, EltLoc
;
3484 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
3486 if (ParseTypeAndValue(Ptr
, Loc
, PFS
)) return true;
3488 if (!isa
<PointerType
>(Ptr
->getType()))
3489 return Error(Loc
, "base of getelementptr must be a pointer");
3491 SmallVector
<Value
*, 16> Indices
;
3492 while (EatIfPresent(lltok::comma
)) {
3493 if (ParseTypeAndValue(Val
, EltLoc
, PFS
)) return true;
3494 if (!isa
<IntegerType
>(Val
->getType()))
3495 return Error(EltLoc
, "getelementptr index must be an integer");
3496 Indices
.push_back(Val
);
3499 if (!GetElementPtrInst::getIndexedType(Ptr
->getType(),
3500 Indices
.begin(), Indices
.end()))
3501 return Error(Loc
, "invalid getelementptr indices");
3502 Inst
= GetElementPtrInst::Create(Ptr
, Indices
.begin(), Indices
.end());
3504 cast
<GEPOperator
>(Inst
)->setIsInBounds(true);
3508 /// ParseExtractValue
3509 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3510 bool LLParser::ParseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3511 Value
*Val
; LocTy Loc
;
3512 SmallVector
<unsigned, 4> Indices
;
3513 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3514 ParseIndexList(Indices
))
3517 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
3518 return Error(Loc
, "extractvalue operand must be array or struct");
3520 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
3522 return Error(Loc
, "invalid indices for extractvalue");
3523 Inst
= ExtractValueInst::Create(Val
, Indices
.begin(), Indices
.end());
3527 /// ParseInsertValue
3528 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3529 bool LLParser::ParseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3530 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
3531 SmallVector
<unsigned, 4> Indices
;
3532 if (ParseTypeAndValue(Val0
, Loc0
, PFS
) ||
3533 ParseToken(lltok::comma
, "expected comma after insertvalue operand") ||
3534 ParseTypeAndValue(Val1
, Loc1
, PFS
) ||
3535 ParseIndexList(Indices
))
3538 if (!isa
<StructType
>(Val0
->getType()) && !isa
<ArrayType
>(Val0
->getType()))
3539 return Error(Loc0
, "extractvalue operand must be array or struct");
3541 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
3543 return Error(Loc0
, "invalid indices for insertvalue");
3544 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
.begin(), Indices
.end());
3548 //===----------------------------------------------------------------------===//
3549 // Embedded metadata.
3550 //===----------------------------------------------------------------------===//
3552 /// ParseMDNodeVector
3553 /// ::= Element (',' Element)*
3555 /// ::= 'null' | TypeAndValue
3556 bool LLParser::ParseMDNodeVector(SmallVectorImpl
<Value
*> &Elts
) {
3557 assert(Lex
.getKind() == lltok::lbrace
);
3561 if (Lex
.getKind() == lltok::kw_null
) {
3565 PATypeHolder
Ty(Type::getVoidTy(Context
));
3566 if (ParseType(Ty
)) return true;
3567 if (Lex
.getKind() == lltok::Metadata
) {
3569 MetadataBase
*Node
= 0;
3570 if (!ParseMDNode(Node
))
3573 MetadataBase
*MDS
= 0;
3574 if (ParseMDString(MDS
)) return true;
3579 if (ParseGlobalValue(Ty
, C
)) return true;
3584 } while (EatIfPresent(lltok::comma
));