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/MDNode.h"
22 #include "llvm/Module.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
30 /// ValID - Represents a reference of a definition of some sort with no type.
31 /// There are several cases where we have to parse the value but where the
32 /// type can depend on later context. This may either be a numeric reference
33 /// or a symbolic (%var) reference. This is just a discriminated union.
36 t_LocalID
, t_GlobalID
, // ID in UIntVal.
37 t_LocalName
, t_GlobalName
, // Name in StrVal.
38 t_APSInt
, t_APFloat
, // Value in APSIntVal/APFloatVal.
39 t_Null
, t_Undef
, t_Zero
, // No value.
40 t_EmptyArray
, // No value: []
41 t_Constant
, // Value in ConstantVal.
42 t_InlineAsm
// Value in StrVal/StrVal2/UIntVal.
47 std::string StrVal
, StrVal2
;
50 Constant
*ConstantVal
;
51 ValID() : APFloatVal(0.0) {}
55 /// Run: module ::= toplevelentity*
56 bool LLParser::Run() {
60 return ParseTopLevelEntities() ||
61 ValidateEndOfModule();
64 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
66 bool LLParser::ValidateEndOfModule() {
67 if (!ForwardRefTypes
.empty())
68 return Error(ForwardRefTypes
.begin()->second
.second
,
69 "use of undefined type named '" +
70 ForwardRefTypes
.begin()->first
+ "'");
71 if (!ForwardRefTypeIDs
.empty())
72 return Error(ForwardRefTypeIDs
.begin()->second
.second
,
73 "use of undefined type '%" +
74 utostr(ForwardRefTypeIDs
.begin()->first
) + "'");
76 if (!ForwardRefVals
.empty())
77 return Error(ForwardRefVals
.begin()->second
.second
,
78 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
81 if (!ForwardRefValIDs
.empty())
82 return Error(ForwardRefValIDs
.begin()->second
.second
,
83 "use of undefined value '@" +
84 utostr(ForwardRefValIDs
.begin()->first
) + "'");
86 // Look for intrinsic functions and CallInst that need to be upgraded
87 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
88 UpgradeCallsToIntrinsic(FI
++); // must be post-increment, as we remove
93 //===----------------------------------------------------------------------===//
95 //===----------------------------------------------------------------------===//
97 bool LLParser::ParseTopLevelEntities() {
99 switch (Lex
.getKind()) {
100 default: return TokError("expected top-level entity");
101 case lltok::Eof
: return false;
102 //case lltok::kw_define:
103 case lltok::kw_declare
: if (ParseDeclare()) return true; break;
104 case lltok::kw_define
: if (ParseDefine()) return true; break;
105 case lltok::kw_module
: if (ParseModuleAsm()) return true; break;
106 case lltok::kw_target
: if (ParseTargetDefinition()) return true; break;
107 case lltok::kw_deplibs
: if (ParseDepLibs()) return true; break;
108 case lltok::kw_type
: if (ParseUnnamedType()) return true; break;
109 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
110 case lltok::LocalVar
: if (ParseNamedType()) return true; break;
111 case lltok::GlobalVar
: if (ParseNamedGlobal()) return true; break;
113 // The Global variable production with no name can have many different
114 // optional leading prefixes, the production is:
115 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
116 // OptionalAddrSpace ('constant'|'global') ...
117 case lltok::kw_private
: // OptionalLinkage
118 case lltok::kw_internal
: // OptionalLinkage
119 case lltok::kw_weak
: // OptionalLinkage
120 case lltok::kw_weak_odr
: // OptionalLinkage
121 case lltok::kw_linkonce
: // OptionalLinkage
122 case lltok::kw_linkonce_odr
: // OptionalLinkage
123 case lltok::kw_appending
: // OptionalLinkage
124 case lltok::kw_dllexport
: // OptionalLinkage
125 case lltok::kw_common
: // OptionalLinkage
126 case lltok::kw_dllimport
: // OptionalLinkage
127 case lltok::kw_extern_weak
: // OptionalLinkage
128 case lltok::kw_external
: { // OptionalLinkage
129 unsigned Linkage
, Visibility
;
130 if (ParseOptionalLinkage(Linkage
) ||
131 ParseOptionalVisibility(Visibility
) ||
132 ParseGlobal("", 0, Linkage
, true, Visibility
))
136 case lltok::kw_default
: // OptionalVisibility
137 case lltok::kw_hidden
: // OptionalVisibility
138 case lltok::kw_protected
: { // OptionalVisibility
140 if (ParseOptionalVisibility(Visibility
) ||
141 ParseGlobal("", 0, 0, false, Visibility
))
146 case lltok::kw_thread_local
: // OptionalThreadLocal
147 case lltok::kw_addrspace
: // OptionalAddrSpace
148 case lltok::kw_constant
: // GlobalType
149 case lltok::kw_global
: // GlobalType
150 if (ParseGlobal("", 0, 0, false, 0)) return true;
158 /// ::= 'module' 'asm' STRINGCONSTANT
159 bool LLParser::ParseModuleAsm() {
160 assert(Lex
.getKind() == lltok::kw_module
);
164 if (ParseToken(lltok::kw_asm
, "expected 'module asm'") ||
165 ParseStringConstant(AsmStr
)) return true;
167 const std::string
&AsmSoFar
= M
->getModuleInlineAsm();
168 if (AsmSoFar
.empty())
169 M
->setModuleInlineAsm(AsmStr
);
171 M
->setModuleInlineAsm(AsmSoFar
+"\n"+AsmStr
);
176 /// ::= 'target' 'triple' '=' STRINGCONSTANT
177 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
178 bool LLParser::ParseTargetDefinition() {
179 assert(Lex
.getKind() == lltok::kw_target
);
182 default: return TokError("unknown target property");
183 case lltok::kw_triple
:
185 if (ParseToken(lltok::equal
, "expected '=' after target triple") ||
186 ParseStringConstant(Str
))
188 M
->setTargetTriple(Str
);
190 case lltok::kw_datalayout
:
192 if (ParseToken(lltok::equal
, "expected '=' after target datalayout") ||
193 ParseStringConstant(Str
))
195 M
->setDataLayout(Str
);
201 /// ::= 'deplibs' '=' '[' ']'
202 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
203 bool LLParser::ParseDepLibs() {
204 assert(Lex
.getKind() == lltok::kw_deplibs
);
206 if (ParseToken(lltok::equal
, "expected '=' after deplibs") ||
207 ParseToken(lltok::lsquare
, "expected '=' after deplibs"))
210 if (EatIfPresent(lltok::rsquare
))
214 if (ParseStringConstant(Str
)) return true;
217 while (EatIfPresent(lltok::comma
)) {
218 if (ParseStringConstant(Str
)) return true;
222 return ParseToken(lltok::rsquare
, "expected ']' at end of list");
227 bool LLParser::ParseUnnamedType() {
228 assert(Lex
.getKind() == lltok::kw_type
);
229 LocTy TypeLoc
= Lex
.getLoc();
230 Lex
.Lex(); // eat kw_type
232 PATypeHolder
Ty(Type::VoidTy
);
233 if (ParseType(Ty
)) return true;
235 unsigned TypeID
= NumberedTypes
.size();
237 // See if this type was previously referenced.
238 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
239 FI
= ForwardRefTypeIDs
.find(TypeID
);
240 if (FI
!= ForwardRefTypeIDs
.end()) {
241 if (FI
->second
.first
.get() == Ty
)
242 return Error(TypeLoc
, "self referential type is invalid");
244 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
245 Ty
= FI
->second
.first
.get();
246 ForwardRefTypeIDs
.erase(FI
);
249 NumberedTypes
.push_back(Ty
);
255 /// ::= LocalVar '=' 'type' type
256 bool LLParser::ParseNamedType() {
257 std::string Name
= Lex
.getStrVal();
258 LocTy NameLoc
= Lex
.getLoc();
259 Lex
.Lex(); // eat LocalVar.
261 PATypeHolder
Ty(Type::VoidTy
);
263 if (ParseToken(lltok::equal
, "expected '=' after name") ||
264 ParseToken(lltok::kw_type
, "expected 'type' after name") ||
268 // Set the type name, checking for conflicts as we do so.
269 bool AlreadyExists
= M
->addTypeName(Name
, Ty
);
270 if (!AlreadyExists
) return false;
272 // See if this type is a forward reference. We need to eagerly resolve
273 // types to allow recursive type redefinitions below.
274 std::map
<std::string
, std::pair
<PATypeHolder
, LocTy
> >::iterator
275 FI
= ForwardRefTypes
.find(Name
);
276 if (FI
!= ForwardRefTypes
.end()) {
277 if (FI
->second
.first
.get() == Ty
)
278 return Error(NameLoc
, "self referential type is invalid");
280 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
281 Ty
= FI
->second
.first
.get();
282 ForwardRefTypes
.erase(FI
);
285 // Inserting a name that is already defined, get the existing name.
286 const Type
*Existing
= M
->getTypeByName(Name
);
287 assert(Existing
&& "Conflict but no matching type?!");
289 // Otherwise, this is an attempt to redefine a type. That's okay if
290 // the redefinition is identical to the original.
291 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
292 if (Existing
== Ty
) return false;
294 // Any other kind of (non-equivalent) redefinition is an error.
295 return Error(NameLoc
, "redefinition of type named '" + Name
+ "' of type '" +
296 Ty
->getDescription() + "'");
301 /// ::= 'declare' FunctionHeader
302 bool LLParser::ParseDeclare() {
303 assert(Lex
.getKind() == lltok::kw_declare
);
307 return ParseFunctionHeader(F
, false);
311 /// ::= 'define' FunctionHeader '{' ...
312 bool LLParser::ParseDefine() {
313 assert(Lex
.getKind() == lltok::kw_define
);
317 return ParseFunctionHeader(F
, true) ||
318 ParseFunctionBody(*F
);
324 bool LLParser::ParseGlobalType(bool &IsConstant
) {
325 if (Lex
.getKind() == lltok::kw_constant
)
327 else if (Lex
.getKind() == lltok::kw_global
)
331 return TokError("expected 'global' or 'constant'");
337 /// ParseNamedGlobal:
338 /// GlobalVar '=' OptionalVisibility ALIAS ...
339 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
340 bool LLParser::ParseNamedGlobal() {
341 assert(Lex
.getKind() == lltok::GlobalVar
);
342 LocTy NameLoc
= Lex
.getLoc();
343 std::string Name
= Lex
.getStrVal();
347 unsigned Linkage
, Visibility
;
348 if (ParseToken(lltok::equal
, "expected '=' in global variable") ||
349 ParseOptionalLinkage(Linkage
, HasLinkage
) ||
350 ParseOptionalVisibility(Visibility
))
353 if (HasLinkage
|| Lex
.getKind() != lltok::kw_alias
)
354 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
);
355 return ParseAlias(Name
, NameLoc
, Visibility
);
359 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
362 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
363 /// ::= 'getelementptr' '(' ... ')'
365 /// Everything through visibility has already been parsed.
367 bool LLParser::ParseAlias(const std::string
&Name
, LocTy NameLoc
,
368 unsigned Visibility
) {
369 assert(Lex
.getKind() == lltok::kw_alias
);
372 LocTy LinkageLoc
= Lex
.getLoc();
373 if (ParseOptionalLinkage(Linkage
))
376 if (Linkage
!= GlobalValue::ExternalLinkage
&&
377 Linkage
!= GlobalValue::WeakAnyLinkage
&&
378 Linkage
!= GlobalValue::WeakODRLinkage
&&
379 Linkage
!= GlobalValue::InternalLinkage
&&
380 Linkage
!= GlobalValue::PrivateLinkage
)
381 return Error(LinkageLoc
, "invalid linkage type for alias");
384 LocTy AliaseeLoc
= Lex
.getLoc();
385 if (Lex
.getKind() != lltok::kw_bitcast
&&
386 Lex
.getKind() != lltok::kw_getelementptr
) {
387 if (ParseGlobalTypeAndValue(Aliasee
)) return true;
389 // The bitcast dest type is not present, it is implied by the dest type.
391 if (ParseValID(ID
)) return true;
392 if (ID
.Kind
!= ValID::t_Constant
)
393 return Error(AliaseeLoc
, "invalid aliasee");
394 Aliasee
= ID
.ConstantVal
;
397 if (!isa
<PointerType
>(Aliasee
->getType()))
398 return Error(AliaseeLoc
, "alias must have pointer type");
400 // Okay, create the alias but do not insert it into the module yet.
401 GlobalAlias
* GA
= new GlobalAlias(Aliasee
->getType(),
402 (GlobalValue::LinkageTypes
)Linkage
, Name
,
404 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
406 // See if this value already exists in the symbol table. If so, it is either
407 // a redefinition or a definition of a forward reference.
408 if (GlobalValue
*Val
=
409 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
))) {
410 // See if this was a redefinition. If so, there is no entry in
412 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
413 I
= ForwardRefVals
.find(Name
);
414 if (I
== ForwardRefVals
.end())
415 return Error(NameLoc
, "redefinition of global named '@" + Name
+ "'");
417 // Otherwise, this was a definition of forward ref. Verify that types
419 if (Val
->getType() != GA
->getType())
420 return Error(NameLoc
,
421 "forward reference and definition of alias have different types");
423 // If they agree, just RAUW the old value with the alias and remove the
425 Val
->replaceAllUsesWith(GA
);
426 Val
->eraseFromParent();
427 ForwardRefVals
.erase(I
);
430 // Insert into the module, we know its name won't collide now.
431 M
->getAliasList().push_back(GA
);
432 assert(GA
->getNameStr() == Name
&& "Should not be a name conflict!");
438 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
439 /// OptionalAddrSpace GlobalType Type Const
440 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
441 /// OptionalAddrSpace GlobalType Type Const
443 /// Everything through visibility has been parsed already.
445 bool LLParser::ParseGlobal(const std::string
&Name
, LocTy NameLoc
,
446 unsigned Linkage
, bool HasLinkage
,
447 unsigned Visibility
) {
449 bool ThreadLocal
, IsConstant
;
452 PATypeHolder
Ty(Type::VoidTy
);
453 if (ParseOptionalToken(lltok::kw_thread_local
, ThreadLocal
) ||
454 ParseOptionalAddrSpace(AddrSpace
) ||
455 ParseGlobalType(IsConstant
) ||
456 ParseType(Ty
, TyLoc
))
459 // If the linkage is specified and is external, then no initializer is
462 if (!HasLinkage
|| (Linkage
!= GlobalValue::DLLImportLinkage
&&
463 Linkage
!= GlobalValue::ExternalWeakLinkage
&&
464 Linkage
!= GlobalValue::ExternalLinkage
)) {
465 if (ParseGlobalValue(Ty
, Init
))
469 if (isa
<FunctionType
>(Ty
) || Ty
== Type::LabelTy
)
470 return Error(TyLoc
, "invalid type for global variable");
472 GlobalVariable
*GV
= 0;
474 // See if the global was forward referenced, if so, use the global.
476 if ((GV
= M
->getGlobalVariable(Name
, true)) &&
477 !ForwardRefVals
.erase(Name
))
478 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
480 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
481 I
= ForwardRefValIDs
.find(NumberedVals
.size());
482 if (I
!= ForwardRefValIDs
.end()) {
483 GV
= cast
<GlobalVariable
>(I
->second
.first
);
484 ForwardRefValIDs
.erase(I
);
489 GV
= new GlobalVariable(Ty
, false, GlobalValue::ExternalLinkage
, 0, Name
,
490 M
, false, AddrSpace
);
492 if (GV
->getType()->getElementType() != Ty
)
494 "forward reference and definition of global have different types");
496 // Move the forward-reference to the correct spot in the module.
497 M
->getGlobalList().splice(M
->global_end(), M
->getGlobalList(), GV
);
501 NumberedVals
.push_back(GV
);
503 // Set the parsed properties on the global.
505 GV
->setInitializer(Init
);
506 GV
->setConstant(IsConstant
);
507 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
508 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
509 GV
->setThreadLocal(ThreadLocal
);
511 // Parse attributes on the global.
512 while (Lex
.getKind() == lltok::comma
) {
515 if (Lex
.getKind() == lltok::kw_section
) {
517 GV
->setSection(Lex
.getStrVal());
518 if (ParseToken(lltok::StringConstant
, "expected global section string"))
520 } else if (Lex
.getKind() == lltok::kw_align
) {
522 if (ParseOptionalAlignment(Alignment
)) return true;
523 GV
->setAlignment(Alignment
);
525 TokError("unknown global variable property!");
533 //===----------------------------------------------------------------------===//
534 // GlobalValue Reference/Resolution Routines.
535 //===----------------------------------------------------------------------===//
537 /// GetGlobalVal - Get a value with the specified name or ID, creating a
538 /// forward reference record if needed. This can return null if the value
539 /// exists but does not have the right type.
540 GlobalValue
*LLParser::GetGlobalVal(const std::string
&Name
, const Type
*Ty
,
542 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
544 Error(Loc
, "global variable reference must have pointer type");
548 // Look this name up in the normal function symbol table.
550 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
552 // If this is a forward reference for the value, see if we already created a
553 // forward ref record.
555 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
556 I
= ForwardRefVals
.find(Name
);
557 if (I
!= ForwardRefVals
.end())
558 Val
= I
->second
.first
;
561 // If we have the value in the symbol table or fwd-ref table, return it.
563 if (Val
->getType() == Ty
) return Val
;
564 Error(Loc
, "'@" + Name
+ "' defined with type '" +
565 Val
->getType()->getDescription() + "'");
569 // Otherwise, create a new forward reference for this value and remember it.
571 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
572 // Function types can return opaque but functions can't.
573 if (isa
<OpaqueType
>(FT
->getReturnType())) {
574 Error(Loc
, "function may not return opaque type");
578 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, Name
, M
);
580 FwdVal
= new GlobalVariable(PTy
->getElementType(), false,
581 GlobalValue::ExternalWeakLinkage
, 0, Name
, M
);
584 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
588 GlobalValue
*LLParser::GetGlobalVal(unsigned ID
, const Type
*Ty
, LocTy Loc
) {
589 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
591 Error(Loc
, "global variable reference must have pointer type");
595 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
597 // If this is a forward reference for the value, see if we already created a
598 // forward ref record.
600 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
601 I
= ForwardRefValIDs
.find(ID
);
602 if (I
!= ForwardRefValIDs
.end())
603 Val
= I
->second
.first
;
606 // If we have the value in the symbol table or fwd-ref table, return it.
608 if (Val
->getType() == Ty
) return Val
;
609 Error(Loc
, "'@" + utostr(ID
) + "' defined with type '" +
610 Val
->getType()->getDescription() + "'");
614 // Otherwise, create a new forward reference for this value and remember it.
616 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
617 // Function types can return opaque but functions can't.
618 if (isa
<OpaqueType
>(FT
->getReturnType())) {
619 Error(Loc
, "function may not return opaque type");
622 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, "", M
);
624 FwdVal
= new GlobalVariable(PTy
->getElementType(), false,
625 GlobalValue::ExternalWeakLinkage
, 0, "", M
);
628 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
633 //===----------------------------------------------------------------------===//
635 //===----------------------------------------------------------------------===//
637 /// ParseToken - If the current token has the specified kind, eat it and return
638 /// success. Otherwise, emit the specified error and return failure.
639 bool LLParser::ParseToken(lltok::Kind T
, const char *ErrMsg
) {
640 if (Lex
.getKind() != T
)
641 return TokError(ErrMsg
);
646 /// ParseStringConstant
647 /// ::= StringConstant
648 bool LLParser::ParseStringConstant(std::string
&Result
) {
649 if (Lex
.getKind() != lltok::StringConstant
)
650 return TokError("expected string constant");
651 Result
= Lex
.getStrVal();
658 bool LLParser::ParseUInt32(unsigned &Val
) {
659 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
660 return TokError("expected integer");
661 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
662 if (Val64
!= unsigned(Val64
))
663 return TokError("expected 32-bit integer (too large)");
670 /// ParseOptionalAddrSpace
672 /// := 'addrspace' '(' uint32 ')'
673 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace
) {
675 if (!EatIfPresent(lltok::kw_addrspace
))
677 return ParseToken(lltok::lparen
, "expected '(' in address space") ||
678 ParseUInt32(AddrSpace
) ||
679 ParseToken(lltok::rparen
, "expected ')' in address space");
682 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
683 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
684 /// 2: function attr.
685 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
686 bool LLParser::ParseOptionalAttrs(unsigned &Attrs
, unsigned AttrKind
) {
687 Attrs
= Attribute::None
;
688 LocTy AttrLoc
= Lex
.getLoc();
691 switch (Lex
.getKind()) {
694 // Treat these as signext/zeroext if they occur in the argument list after
695 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
696 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
698 // FIXME: REMOVE THIS IN LLVM 3.0
700 if (Lex
.getKind() == lltok::kw_sext
)
701 Attrs
|= Attribute::SExt
;
703 Attrs
|= Attribute::ZExt
;
707 default: // End of attributes.
708 if (AttrKind
!= 2 && (Attrs
& Attribute::FunctionOnly
))
709 return Error(AttrLoc
, "invalid use of function-only attribute");
711 if (AttrKind
!= 0 && AttrKind
!= 3 && (Attrs
& Attribute::ParameterOnly
))
712 return Error(AttrLoc
, "invalid use of parameter-only attribute");
715 case lltok::kw_zeroext
: Attrs
|= Attribute::ZExt
; break;
716 case lltok::kw_signext
: Attrs
|= Attribute::SExt
; break;
717 case lltok::kw_inreg
: Attrs
|= Attribute::InReg
; break;
718 case lltok::kw_sret
: Attrs
|= Attribute::StructRet
; break;
719 case lltok::kw_noalias
: Attrs
|= Attribute::NoAlias
; break;
720 case lltok::kw_nocapture
: Attrs
|= Attribute::NoCapture
; break;
721 case lltok::kw_byval
: Attrs
|= Attribute::ByVal
; break;
722 case lltok::kw_nest
: Attrs
|= Attribute::Nest
; break;
724 case lltok::kw_noreturn
: Attrs
|= Attribute::NoReturn
; break;
725 case lltok::kw_nounwind
: Attrs
|= Attribute::NoUnwind
; break;
726 case lltok::kw_noinline
: Attrs
|= Attribute::NoInline
; break;
727 case lltok::kw_readnone
: Attrs
|= Attribute::ReadNone
; break;
728 case lltok::kw_readonly
: Attrs
|= Attribute::ReadOnly
; break;
729 case lltok::kw_alwaysinline
: Attrs
|= Attribute::AlwaysInline
; break;
730 case lltok::kw_optsize
: Attrs
|= Attribute::OptimizeForSize
; break;
731 case lltok::kw_ssp
: Attrs
|= Attribute::StackProtect
; break;
732 case lltok::kw_sspreq
: Attrs
|= Attribute::StackProtectReq
; break;
735 case lltok::kw_align
: {
737 if (ParseOptionalAlignment(Alignment
))
739 Attrs
|= Attribute::constructAlignmentFromInt(Alignment
);
747 /// ParseOptionalLinkage
754 /// ::= 'linkonce_odr'
759 /// ::= 'extern_weak'
761 bool LLParser::ParseOptionalLinkage(unsigned &Res
, bool &HasLinkage
) {
763 switch (Lex
.getKind()) {
764 default: Res
= GlobalValue::ExternalLinkage
; return false;
765 case lltok::kw_private
: Res
= GlobalValue::PrivateLinkage
; break;
766 case lltok::kw_internal
: Res
= GlobalValue::InternalLinkage
; break;
767 case lltok::kw_weak
: Res
= GlobalValue::WeakAnyLinkage
; break;
768 case lltok::kw_weak_odr
: Res
= GlobalValue::WeakODRLinkage
; break;
769 case lltok::kw_linkonce
: Res
= GlobalValue::LinkOnceAnyLinkage
; break;
770 case lltok::kw_linkonce_odr
: Res
= GlobalValue::LinkOnceODRLinkage
; break;
771 case lltok::kw_available_externally
:
772 Res
= GlobalValue::AvailableExternallyLinkage
;
774 case lltok::kw_appending
: Res
= GlobalValue::AppendingLinkage
; break;
775 case lltok::kw_dllexport
: Res
= GlobalValue::DLLExportLinkage
; break;
776 case lltok::kw_common
: Res
= GlobalValue::CommonLinkage
; break;
777 case lltok::kw_dllimport
: Res
= GlobalValue::DLLImportLinkage
; break;
778 case lltok::kw_extern_weak
: Res
= GlobalValue::ExternalWeakLinkage
; break;
779 case lltok::kw_external
: Res
= GlobalValue::ExternalLinkage
; break;
786 /// ParseOptionalVisibility
792 bool LLParser::ParseOptionalVisibility(unsigned &Res
) {
793 switch (Lex
.getKind()) {
794 default: Res
= GlobalValue::DefaultVisibility
; return false;
795 case lltok::kw_default
: Res
= GlobalValue::DefaultVisibility
; break;
796 case lltok::kw_hidden
: Res
= GlobalValue::HiddenVisibility
; break;
797 case lltok::kw_protected
: Res
= GlobalValue::ProtectedVisibility
; break;
803 /// ParseOptionalCallingConv
808 /// ::= 'x86_stdcallcc'
809 /// ::= 'x86_fastcallcc'
812 bool LLParser::ParseOptionalCallingConv(unsigned &CC
) {
813 switch (Lex
.getKind()) {
814 default: CC
= CallingConv::C
; return false;
815 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
816 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
817 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
818 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
819 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
820 case lltok::kw_cc
: Lex
.Lex(); return ParseUInt32(CC
);
826 /// ParseOptionalAlignment
829 bool LLParser::ParseOptionalAlignment(unsigned &Alignment
) {
831 if (!EatIfPresent(lltok::kw_align
))
833 LocTy AlignLoc
= Lex
.getLoc();
834 if (ParseUInt32(Alignment
)) return true;
835 if (!isPowerOf2_32(Alignment
))
836 return Error(AlignLoc
, "alignment is not a power of two");
840 /// ParseOptionalCommaAlignment
842 /// ::= ',' 'align' 4
843 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment
) {
845 if (!EatIfPresent(lltok::comma
))
847 return ParseToken(lltok::kw_align
, "expected 'align'") ||
848 ParseUInt32(Alignment
);
852 /// ::= (',' uint32)+
853 bool LLParser::ParseIndexList(SmallVectorImpl
<unsigned> &Indices
) {
854 if (Lex
.getKind() != lltok::comma
)
855 return TokError("expected ',' as start of index list");
857 while (EatIfPresent(lltok::comma
)) {
859 if (ParseUInt32(Idx
)) return true;
860 Indices
.push_back(Idx
);
866 //===----------------------------------------------------------------------===//
868 //===----------------------------------------------------------------------===//
870 /// ParseType - Parse and resolve a full type.
871 bool LLParser::ParseType(PATypeHolder
&Result
, bool AllowVoid
) {
872 LocTy TypeLoc
= Lex
.getLoc();
873 if (ParseTypeRec(Result
)) return true;
875 // Verify no unresolved uprefs.
877 return Error(UpRefs
.back().Loc
, "invalid unresolved type up reference");
879 if (!AllowVoid
&& Result
.get() == Type::VoidTy
)
880 return Error(TypeLoc
, "void type only allowed for function results");
885 /// HandleUpRefs - Every time we finish a new layer of types, this function is
886 /// called. It loops through the UpRefs vector, which is a list of the
887 /// currently active types. For each type, if the up-reference is contained in
888 /// the newly completed type, we decrement the level count. When the level
889 /// count reaches zero, the up-referenced type is the type that is passed in:
890 /// thus we can complete the cycle.
892 PATypeHolder
LLParser::HandleUpRefs(const Type
*ty
) {
893 // If Ty isn't abstract, or if there are no up-references in it, then there is
894 // nothing to resolve here.
895 if (!ty
->isAbstract() || UpRefs
.empty()) return ty
;
899 errs() << "Type '" << Ty
->getDescription()
900 << "' newly formed. Resolving upreferences.\n"
901 << UpRefs
.size() << " upreferences active!\n";
904 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
905 // to zero), we resolve them all together before we resolve them to Ty. At
906 // the end of the loop, if there is anything to resolve to Ty, it will be in
908 OpaqueType
*TypeToResolve
= 0;
910 for (unsigned i
= 0; i
!= UpRefs
.size(); ++i
) {
911 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
913 std::find(Ty
->subtype_begin(), Ty
->subtype_end(),
914 UpRefs
[i
].LastContainedTy
) != Ty
->subtype_end();
917 errs() << " UR#" << i
<< " - TypeContains(" << Ty
->getDescription() << ", "
918 << UpRefs
[i
].LastContainedTy
->getDescription() << ") = "
919 << (ContainsType
? "true" : "false")
920 << " level=" << UpRefs
[i
].NestingLevel
<< "\n";
925 // Decrement level of upreference
926 unsigned Level
= --UpRefs
[i
].NestingLevel
;
927 UpRefs
[i
].LastContainedTy
= Ty
;
929 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
934 errs() << " * Resolving upreference for " << UpRefs
[i
].UpRefTy
<< "\n";
937 TypeToResolve
= UpRefs
[i
].UpRefTy
;
939 UpRefs
[i
].UpRefTy
->refineAbstractTypeTo(TypeToResolve
);
940 UpRefs
.erase(UpRefs
.begin()+i
); // Remove from upreference list.
941 --i
; // Do not skip the next element.
945 TypeToResolve
->refineAbstractTypeTo(Ty
);
951 /// ParseTypeRec - The recursive function used to process the internal
952 /// implementation details of types.
953 bool LLParser::ParseTypeRec(PATypeHolder
&Result
) {
954 switch (Lex
.getKind()) {
956 return TokError("expected type");
958 // TypeRec ::= 'float' | 'void' (etc)
959 Result
= Lex
.getTyVal();
962 case lltok::kw_opaque
:
963 // TypeRec ::= 'opaque'
964 Result
= OpaqueType::get();
968 // TypeRec ::= '{' ... '}'
969 if (ParseStructType(Result
, false))
973 // TypeRec ::= '[' ... ']'
974 Lex
.Lex(); // eat the lsquare.
975 if (ParseArrayVectorType(Result
, false))
978 case lltok::less
: // Either vector or packed struct.
979 // TypeRec ::= '<' ... '>'
981 if (Lex
.getKind() == lltok::lbrace
) {
982 if (ParseStructType(Result
, true) ||
983 ParseToken(lltok::greater
, "expected '>' at end of packed struct"))
985 } else if (ParseArrayVectorType(Result
, true))
988 case lltok::LocalVar
:
989 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
991 if (const Type
*T
= M
->getTypeByName(Lex
.getStrVal())) {
994 Result
= OpaqueType::get();
995 ForwardRefTypes
.insert(std::make_pair(Lex
.getStrVal(),
996 std::make_pair(Result
,
998 M
->addTypeName(Lex
.getStrVal(), Result
.get());
1003 case lltok::LocalVarID
:
1005 if (Lex
.getUIntVal() < NumberedTypes
.size())
1006 Result
= NumberedTypes
[Lex
.getUIntVal()];
1008 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
1009 I
= ForwardRefTypeIDs
.find(Lex
.getUIntVal());
1010 if (I
!= ForwardRefTypeIDs
.end())
1011 Result
= I
->second
.first
;
1013 Result
= OpaqueType::get();
1014 ForwardRefTypeIDs
.insert(std::make_pair(Lex
.getUIntVal(),
1015 std::make_pair(Result
,
1021 case lltok::backslash
: {
1022 // TypeRec ::= '\' 4
1025 if (ParseUInt32(Val
)) return true;
1026 OpaqueType
*OT
= OpaqueType::get(); // Use temporary placeholder.
1027 UpRefs
.push_back(UpRefRecord(Lex
.getLoc(), Val
, OT
));
1033 // Parse the type suffixes.
1035 switch (Lex
.getKind()) {
1037 default: return false;
1039 // TypeRec ::= TypeRec '*'
1041 if (Result
.get() == Type::LabelTy
)
1042 return TokError("basic block pointers are invalid");
1043 if (Result
.get() == Type::VoidTy
)
1044 return TokError("pointers to void are invalid; use i8* instead");
1045 Result
= HandleUpRefs(PointerType::getUnqual(Result
.get()));
1049 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1050 case lltok::kw_addrspace
: {
1051 if (Result
.get() == Type::LabelTy
)
1052 return TokError("basic block pointers are invalid");
1053 if (Result
.get() == Type::VoidTy
)
1054 return TokError("pointers to void are invalid; use i8* instead");
1056 if (ParseOptionalAddrSpace(AddrSpace
) ||
1057 ParseToken(lltok::star
, "expected '*' in address space"))
1060 Result
= HandleUpRefs(PointerType::get(Result
.get(), AddrSpace
));
1064 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1066 if (ParseFunctionType(Result
))
1073 /// ParseParameterList
1075 /// ::= '(' Arg (',' Arg)* ')'
1077 /// ::= Type OptionalAttributes Value OptionalAttributes
1078 bool LLParser::ParseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
1079 PerFunctionState
&PFS
) {
1080 if (ParseToken(lltok::lparen
, "expected '(' in call"))
1083 while (Lex
.getKind() != lltok::rparen
) {
1084 // If this isn't the first argument, we need a comma.
1085 if (!ArgList
.empty() &&
1086 ParseToken(lltok::comma
, "expected ',' in argument list"))
1089 // Parse the argument.
1091 PATypeHolder
ArgTy(Type::VoidTy
);
1092 unsigned ArgAttrs1
, ArgAttrs2
;
1094 if (ParseType(ArgTy
, ArgLoc
) ||
1095 ParseOptionalAttrs(ArgAttrs1
, 0) ||
1096 ParseValue(ArgTy
, V
, PFS
) ||
1097 // FIXME: Should not allow attributes after the argument, remove this in
1099 ParseOptionalAttrs(ArgAttrs2
, 3))
1101 ArgList
.push_back(ParamInfo(ArgLoc
, V
, ArgAttrs1
|ArgAttrs2
));
1104 Lex
.Lex(); // Lex the ')'.
1110 /// ParseArgumentList - Parse the argument list for a function type or function
1111 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1112 /// ::= '(' ArgTypeListI ')'
1116 /// ::= ArgTypeList ',' '...'
1117 /// ::= ArgType (',' ArgType)*
1119 bool LLParser::ParseArgumentList(std::vector
<ArgInfo
> &ArgList
,
1120 bool &isVarArg
, bool inType
) {
1122 assert(Lex
.getKind() == lltok::lparen
);
1123 Lex
.Lex(); // eat the (.
1125 if (Lex
.getKind() == lltok::rparen
) {
1127 } else if (Lex
.getKind() == lltok::dotdotdot
) {
1131 LocTy TypeLoc
= Lex
.getLoc();
1132 PATypeHolder
ArgTy(Type::VoidTy
);
1136 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1137 // types (such as a function returning a pointer to itself). If parsing a
1138 // function prototype, we require fully resolved types.
1139 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1140 ParseOptionalAttrs(Attrs
, 0)) return true;
1142 if (ArgTy
== Type::VoidTy
)
1143 return Error(TypeLoc
, "argument can not have void type");
1145 if (Lex
.getKind() == lltok::LocalVar
||
1146 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1147 Name
= Lex
.getStrVal();
1151 if (!ArgTy
->isFirstClassType() && !isa
<OpaqueType
>(ArgTy
))
1152 return Error(TypeLoc
, "invalid type for function argument");
1154 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1156 while (EatIfPresent(lltok::comma
)) {
1157 // Handle ... at end of arg list.
1158 if (EatIfPresent(lltok::dotdotdot
)) {
1163 // Otherwise must be an argument type.
1164 TypeLoc
= Lex
.getLoc();
1165 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1166 ParseOptionalAttrs(Attrs
, 0)) return true;
1168 if (ArgTy
== Type::VoidTy
)
1169 return Error(TypeLoc
, "argument can not have void type");
1171 if (Lex
.getKind() == lltok::LocalVar
||
1172 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1173 Name
= Lex
.getStrVal();
1179 if (!ArgTy
->isFirstClassType() && !isa
<OpaqueType
>(ArgTy
))
1180 return Error(TypeLoc
, "invalid type for function argument");
1182 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1186 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
1189 /// ParseFunctionType
1190 /// ::= Type ArgumentList OptionalAttrs
1191 bool LLParser::ParseFunctionType(PATypeHolder
&Result
) {
1192 assert(Lex
.getKind() == lltok::lparen
);
1194 if (!FunctionType::isValidReturnType(Result
))
1195 return TokError("invalid function return type");
1197 std::vector
<ArgInfo
> ArgList
;
1200 if (ParseArgumentList(ArgList
, isVarArg
, true) ||
1201 // FIXME: Allow, but ignore attributes on function types!
1202 // FIXME: Remove in LLVM 3.0
1203 ParseOptionalAttrs(Attrs
, 2))
1206 // Reject names on the arguments lists.
1207 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
1208 if (!ArgList
[i
].Name
.empty())
1209 return Error(ArgList
[i
].Loc
, "argument name invalid in function type");
1210 if (!ArgList
[i
].Attrs
!= 0) {
1211 // Allow but ignore attributes on function types; this permits
1213 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1217 std::vector
<const Type
*> ArgListTy
;
1218 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
1219 ArgListTy
.push_back(ArgList
[i
].Type
);
1221 Result
= HandleUpRefs(FunctionType::get(Result
.get(), ArgListTy
, isVarArg
));
1225 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1228 /// ::= '{' TypeRec (',' TypeRec)* '}'
1229 /// ::= '<' '{' '}' '>'
1230 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1231 bool LLParser::ParseStructType(PATypeHolder
&Result
, bool Packed
) {
1232 assert(Lex
.getKind() == lltok::lbrace
);
1233 Lex
.Lex(); // Consume the '{'
1235 if (EatIfPresent(lltok::rbrace
)) {
1236 Result
= StructType::get(std::vector
<const Type
*>(), Packed
);
1240 std::vector
<PATypeHolder
> ParamsList
;
1241 LocTy EltTyLoc
= Lex
.getLoc();
1242 if (ParseTypeRec(Result
)) return true;
1243 ParamsList
.push_back(Result
);
1245 if (Result
== Type::VoidTy
)
1246 return Error(EltTyLoc
, "struct element can not have void type");
1248 while (EatIfPresent(lltok::comma
)) {
1249 EltTyLoc
= Lex
.getLoc();
1250 if (ParseTypeRec(Result
)) return true;
1252 if (Result
== Type::VoidTy
)
1253 return Error(EltTyLoc
, "struct element can not have void type");
1255 ParamsList
.push_back(Result
);
1258 if (ParseToken(lltok::rbrace
, "expected '}' at end of struct"))
1261 std::vector
<const Type
*> ParamsListTy
;
1262 for (unsigned i
= 0, e
= ParamsList
.size(); i
!= e
; ++i
)
1263 ParamsListTy
.push_back(ParamsList
[i
].get());
1264 Result
= HandleUpRefs(StructType::get(ParamsListTy
, Packed
));
1268 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1269 /// token has already been consumed.
1271 /// ::= '[' APSINTVAL 'x' Types ']'
1272 /// ::= '<' APSINTVAL 'x' Types '>'
1273 bool LLParser::ParseArrayVectorType(PATypeHolder
&Result
, bool isVector
) {
1274 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
1275 Lex
.getAPSIntVal().getBitWidth() > 64)
1276 return TokError("expected number in address space");
1278 LocTy SizeLoc
= Lex
.getLoc();
1279 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
1282 if (ParseToken(lltok::kw_x
, "expected 'x' after element count"))
1285 LocTy TypeLoc
= Lex
.getLoc();
1286 PATypeHolder
EltTy(Type::VoidTy
);
1287 if (ParseTypeRec(EltTy
)) return true;
1289 if (EltTy
== Type::VoidTy
)
1290 return Error(TypeLoc
, "array and vector element type cannot be void");
1292 if (ParseToken(isVector
? lltok::greater
: lltok::rsquare
,
1293 "expected end of sequential type"))
1298 return Error(SizeLoc
, "zero element vector is illegal");
1299 if ((unsigned)Size
!= Size
)
1300 return Error(SizeLoc
, "size too large for vector");
1301 if (!EltTy
->isFloatingPoint() && !EltTy
->isInteger())
1302 return Error(TypeLoc
, "vector element type must be fp or integer");
1303 Result
= VectorType::get(EltTy
, unsigned(Size
));
1305 if (!EltTy
->isFirstClassType() && !isa
<OpaqueType
>(EltTy
))
1306 return Error(TypeLoc
, "invalid array element type");
1307 Result
= HandleUpRefs(ArrayType::get(EltTy
, Size
));
1312 //===----------------------------------------------------------------------===//
1313 // Function Semantic Analysis.
1314 //===----------------------------------------------------------------------===//
1316 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
)
1319 // Insert unnamed arguments into the NumberedVals list.
1320 for (Function::arg_iterator AI
= F
.arg_begin(), E
= F
.arg_end();
1323 NumberedVals
.push_back(AI
);
1326 LLParser::PerFunctionState::~PerFunctionState() {
1327 // If there were any forward referenced non-basicblock values, delete them.
1328 for (std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1329 I
= ForwardRefVals
.begin(), E
= ForwardRefVals
.end(); I
!= E
; ++I
)
1330 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1331 I
->second
.first
->replaceAllUsesWith(UndefValue::get(I
->second
.first
1333 delete I
->second
.first
;
1334 I
->second
.first
= 0;
1337 for (std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1338 I
= ForwardRefValIDs
.begin(), E
= ForwardRefValIDs
.end(); I
!= E
; ++I
)
1339 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1340 I
->second
.first
->replaceAllUsesWith(UndefValue::get(I
->second
.first
1342 delete I
->second
.first
;
1343 I
->second
.first
= 0;
1347 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1348 if (!ForwardRefVals
.empty())
1349 return P
.Error(ForwardRefVals
.begin()->second
.second
,
1350 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
1352 if (!ForwardRefValIDs
.empty())
1353 return P
.Error(ForwardRefValIDs
.begin()->second
.second
,
1354 "use of undefined value '%" +
1355 utostr(ForwardRefValIDs
.begin()->first
) + "'");
1360 /// GetVal - Get a value with the specified name or ID, creating a
1361 /// forward reference record if needed. This can return null if the value
1362 /// exists but does not have the right type.
1363 Value
*LLParser::PerFunctionState::GetVal(const std::string
&Name
,
1364 const Type
*Ty
, LocTy Loc
) {
1365 // Look this name up in the normal function symbol table.
1366 Value
*Val
= F
.getValueSymbolTable().lookup(Name
);
1368 // If this is a forward reference for the value, see if we already created a
1369 // forward ref record.
1371 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1372 I
= ForwardRefVals
.find(Name
);
1373 if (I
!= ForwardRefVals
.end())
1374 Val
= I
->second
.first
;
1377 // If we have the value in the symbol table or fwd-ref table, return it.
1379 if (Val
->getType() == Ty
) return Val
;
1380 if (Ty
== Type::LabelTy
)
1381 P
.Error(Loc
, "'%" + Name
+ "' is not a basic block");
1383 P
.Error(Loc
, "'%" + Name
+ "' defined with type '" +
1384 Val
->getType()->getDescription() + "'");
1388 // Don't make placeholders with invalid type.
1389 if (!Ty
->isFirstClassType() && !isa
<OpaqueType
>(Ty
) && Ty
!= Type::LabelTy
) {
1390 P
.Error(Loc
, "invalid use of a non-first-class type");
1394 // Otherwise, create a new forward reference for this value and remember it.
1396 if (Ty
== Type::LabelTy
)
1397 FwdVal
= BasicBlock::Create(Name
, &F
);
1399 FwdVal
= new Argument(Ty
, Name
);
1401 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1405 Value
*LLParser::PerFunctionState::GetVal(unsigned ID
, const Type
*Ty
,
1407 // Look this name up in the normal function symbol table.
1408 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
1410 // If this is a forward reference for the value, see if we already created a
1411 // forward ref record.
1413 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1414 I
= ForwardRefValIDs
.find(ID
);
1415 if (I
!= ForwardRefValIDs
.end())
1416 Val
= I
->second
.first
;
1419 // If we have the value in the symbol table or fwd-ref table, return it.
1421 if (Val
->getType() == Ty
) return Val
;
1422 if (Ty
== Type::LabelTy
)
1423 P
.Error(Loc
, "'%" + utostr(ID
) + "' is not a basic block");
1425 P
.Error(Loc
, "'%" + utostr(ID
) + "' defined with type '" +
1426 Val
->getType()->getDescription() + "'");
1430 if (!Ty
->isFirstClassType() && !isa
<OpaqueType
>(Ty
) && Ty
!= Type::LabelTy
) {
1431 P
.Error(Loc
, "invalid use of a non-first-class type");
1435 // Otherwise, create a new forward reference for this value and remember it.
1437 if (Ty
== Type::LabelTy
)
1438 FwdVal
= BasicBlock::Create("", &F
);
1440 FwdVal
= new Argument(Ty
);
1442 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1446 /// SetInstName - After an instruction is parsed and inserted into its
1447 /// basic block, this installs its name.
1448 bool LLParser::PerFunctionState::SetInstName(int NameID
,
1449 const std::string
&NameStr
,
1450 LocTy NameLoc
, Instruction
*Inst
) {
1451 // If this instruction has void type, it cannot have a name or ID specified.
1452 if (Inst
->getType() == Type::VoidTy
) {
1453 if (NameID
!= -1 || !NameStr
.empty())
1454 return P
.Error(NameLoc
, "instructions returning void cannot have a name");
1458 // If this was a numbered instruction, verify that the instruction is the
1459 // expected value and resolve any forward references.
1460 if (NameStr
.empty()) {
1461 // If neither a name nor an ID was specified, just use the next ID.
1463 NameID
= NumberedVals
.size();
1465 if (unsigned(NameID
) != NumberedVals
.size())
1466 return P
.Error(NameLoc
, "instruction expected to be numbered '%" +
1467 utostr(NumberedVals
.size()) + "'");
1469 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator FI
=
1470 ForwardRefValIDs
.find(NameID
);
1471 if (FI
!= ForwardRefValIDs
.end()) {
1472 if (FI
->second
.first
->getType() != Inst
->getType())
1473 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1474 FI
->second
.first
->getType()->getDescription() + "'");
1475 FI
->second
.first
->replaceAllUsesWith(Inst
);
1476 ForwardRefValIDs
.erase(FI
);
1479 NumberedVals
.push_back(Inst
);
1483 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1484 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1485 FI
= ForwardRefVals
.find(NameStr
);
1486 if (FI
!= ForwardRefVals
.end()) {
1487 if (FI
->second
.first
->getType() != Inst
->getType())
1488 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1489 FI
->second
.first
->getType()->getDescription() + "'");
1490 FI
->second
.first
->replaceAllUsesWith(Inst
);
1491 ForwardRefVals
.erase(FI
);
1494 // Set the name on the instruction.
1495 Inst
->setName(NameStr
);
1497 if (Inst
->getNameStr() != NameStr
)
1498 return P
.Error(NameLoc
, "multiple definition of local value named '" +
1503 /// GetBB - Get a basic block with the specified name or ID, creating a
1504 /// forward reference record if needed.
1505 BasicBlock
*LLParser::PerFunctionState::GetBB(const std::string
&Name
,
1507 return cast_or_null
<BasicBlock
>(GetVal(Name
, Type::LabelTy
, Loc
));
1510 BasicBlock
*LLParser::PerFunctionState::GetBB(unsigned ID
, LocTy Loc
) {
1511 return cast_or_null
<BasicBlock
>(GetVal(ID
, Type::LabelTy
, Loc
));
1514 /// DefineBB - Define the specified basic block, which is either named or
1515 /// unnamed. If there is an error, this returns null otherwise it returns
1516 /// the block being defined.
1517 BasicBlock
*LLParser::PerFunctionState::DefineBB(const std::string
&Name
,
1521 BB
= GetBB(NumberedVals
.size(), Loc
);
1523 BB
= GetBB(Name
, Loc
);
1524 if (BB
== 0) return 0; // Already diagnosed error.
1526 // Move the block to the end of the function. Forward ref'd blocks are
1527 // inserted wherever they happen to be referenced.
1528 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
1530 // Remove the block from forward ref sets.
1532 ForwardRefValIDs
.erase(NumberedVals
.size());
1533 NumberedVals
.push_back(BB
);
1535 // BB forward references are already in the function symbol table.
1536 ForwardRefVals
.erase(Name
);
1542 //===----------------------------------------------------------------------===//
1544 //===----------------------------------------------------------------------===//
1546 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1547 /// type implied. For example, if we parse "4" we don't know what integer type
1548 /// it has. The value will later be combined with its type and checked for
1550 bool LLParser::ParseValID(ValID
&ID
) {
1551 ID
.Loc
= Lex
.getLoc();
1552 switch (Lex
.getKind()) {
1553 default: return TokError("expected value token");
1554 case lltok::GlobalID
: // @42
1555 ID
.UIntVal
= Lex
.getUIntVal();
1556 ID
.Kind
= ValID::t_GlobalID
;
1558 case lltok::GlobalVar
: // @foo
1559 ID
.StrVal
= Lex
.getStrVal();
1560 ID
.Kind
= ValID::t_GlobalName
;
1562 case lltok::LocalVarID
: // %42
1563 ID
.UIntVal
= Lex
.getUIntVal();
1564 ID
.Kind
= ValID::t_LocalID
;
1566 case lltok::LocalVar
: // %foo
1567 case lltok::StringConstant
: // "foo" - FIXME: REMOVE IN LLVM 3.0
1568 ID
.StrVal
= Lex
.getStrVal();
1569 ID
.Kind
= ValID::t_LocalName
;
1571 case lltok::Metadata
: { // !{...} MDNode, !"foo" MDString
1572 ID
.Kind
= ValID::t_Constant
;
1574 if (Lex
.getKind() == lltok::lbrace
) {
1575 SmallVector
<Value
*, 16> Elts
;
1576 if (ParseMDNodeVector(Elts
) ||
1577 ParseToken(lltok::rbrace
, "expected end of metadata node"))
1580 ID
.ConstantVal
= MDNode::get(&Elts
[0], Elts
.size());
1585 // ::= '!' STRINGCONSTANT
1587 if (ParseStringConstant(Str
)) return true;
1589 ID
.ConstantVal
= MDString::get(Str
.data(), Str
.data() + Str
.size());
1593 ID
.APSIntVal
= Lex
.getAPSIntVal();
1594 ID
.Kind
= ValID::t_APSInt
;
1596 case lltok::APFloat
:
1597 ID
.APFloatVal
= Lex
.getAPFloatVal();
1598 ID
.Kind
= ValID::t_APFloat
;
1600 case lltok::kw_true
:
1601 ID
.ConstantVal
= ConstantInt::getTrue();
1602 ID
.Kind
= ValID::t_Constant
;
1604 case lltok::kw_false
:
1605 ID
.ConstantVal
= ConstantInt::getFalse();
1606 ID
.Kind
= ValID::t_Constant
;
1608 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
1609 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
1610 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
1612 case lltok::lbrace
: {
1613 // ValID ::= '{' ConstVector '}'
1615 SmallVector
<Constant
*, 16> Elts
;
1616 if (ParseGlobalValueVector(Elts
) ||
1617 ParseToken(lltok::rbrace
, "expected end of struct constant"))
1620 ID
.ConstantVal
= ConstantStruct::get(&Elts
[0], Elts
.size(), false);
1621 ID
.Kind
= ValID::t_Constant
;
1625 // ValID ::= '<' ConstVector '>' --> Vector.
1626 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1628 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
1630 SmallVector
<Constant
*, 16> Elts
;
1631 LocTy FirstEltLoc
= Lex
.getLoc();
1632 if (ParseGlobalValueVector(Elts
) ||
1634 ParseToken(lltok::rbrace
, "expected end of packed struct")) ||
1635 ParseToken(lltok::greater
, "expected end of constant"))
1638 if (isPackedStruct
) {
1639 ID
.ConstantVal
= ConstantStruct::get(&Elts
[0], Elts
.size(), true);
1640 ID
.Kind
= ValID::t_Constant
;
1645 return Error(ID
.Loc
, "constant vector must not be empty");
1647 if (!Elts
[0]->getType()->isInteger() &&
1648 !Elts
[0]->getType()->isFloatingPoint())
1649 return Error(FirstEltLoc
,
1650 "vector elements must have integer or floating point type");
1652 // Verify that all the vector elements have the same type.
1653 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
1654 if (Elts
[i
]->getType() != Elts
[0]->getType())
1655 return Error(FirstEltLoc
,
1656 "vector element #" + utostr(i
) +
1657 " is not of type '" + Elts
[0]->getType()->getDescription());
1659 ID
.ConstantVal
= ConstantVector::get(&Elts
[0], Elts
.size());
1660 ID
.Kind
= ValID::t_Constant
;
1663 case lltok::lsquare
: { // Array Constant
1665 SmallVector
<Constant
*, 16> Elts
;
1666 LocTy FirstEltLoc
= Lex
.getLoc();
1667 if (ParseGlobalValueVector(Elts
) ||
1668 ParseToken(lltok::rsquare
, "expected end of array constant"))
1671 // Handle empty element.
1673 // Use undef instead of an array because it's inconvenient to determine
1674 // the element type at this point, there being no elements to examine.
1675 ID
.Kind
= ValID::t_EmptyArray
;
1679 if (!Elts
[0]->getType()->isFirstClassType())
1680 return Error(FirstEltLoc
, "invalid array element type: " +
1681 Elts
[0]->getType()->getDescription());
1683 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
1685 // Verify all elements are correct type!
1686 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
1687 if (Elts
[i
]->getType() != Elts
[0]->getType())
1688 return Error(FirstEltLoc
,
1689 "array element #" + utostr(i
) +
1690 " is not of type '" +Elts
[0]->getType()->getDescription());
1693 ID
.ConstantVal
= ConstantArray::get(ATy
, &Elts
[0], Elts
.size());
1694 ID
.Kind
= ValID::t_Constant
;
1697 case lltok::kw_c
: // c "foo"
1699 ID
.ConstantVal
= ConstantArray::get(Lex
.getStrVal(), false);
1700 if (ParseToken(lltok::StringConstant
, "expected string")) return true;
1701 ID
.Kind
= ValID::t_Constant
;
1704 case lltok::kw_asm
: {
1705 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1708 if (ParseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
1709 ParseStringConstant(ID
.StrVal
) ||
1710 ParseToken(lltok::comma
, "expected comma in inline asm expression") ||
1711 ParseToken(lltok::StringConstant
, "expected constraint string"))
1713 ID
.StrVal2
= Lex
.getStrVal();
1714 ID
.UIntVal
= HasSideEffect
;
1715 ID
.Kind
= ValID::t_InlineAsm
;
1719 case lltok::kw_trunc
:
1720 case lltok::kw_zext
:
1721 case lltok::kw_sext
:
1722 case lltok::kw_fptrunc
:
1723 case lltok::kw_fpext
:
1724 case lltok::kw_bitcast
:
1725 case lltok::kw_uitofp
:
1726 case lltok::kw_sitofp
:
1727 case lltok::kw_fptoui
:
1728 case lltok::kw_fptosi
:
1729 case lltok::kw_inttoptr
:
1730 case lltok::kw_ptrtoint
: {
1731 unsigned Opc
= Lex
.getUIntVal();
1732 PATypeHolder
DestTy(Type::VoidTy
);
1735 if (ParseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
1736 ParseGlobalTypeAndValue(SrcVal
) ||
1737 ParseToken(lltok::kw_to
, "expected 'to' int constantexpr cast") ||
1738 ParseType(DestTy
) ||
1739 ParseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
1741 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
1742 return Error(ID
.Loc
, "invalid cast opcode for cast from '" +
1743 SrcVal
->getType()->getDescription() + "' to '" +
1744 DestTy
->getDescription() + "'");
1745 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
, SrcVal
,
1747 ID
.Kind
= ValID::t_Constant
;
1750 case lltok::kw_extractvalue
: {
1753 SmallVector
<unsigned, 4> Indices
;
1754 if (ParseToken(lltok::lparen
, "expected '(' in extractvalue constantexpr")||
1755 ParseGlobalTypeAndValue(Val
) ||
1756 ParseIndexList(Indices
) ||
1757 ParseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
1759 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
1760 return Error(ID
.Loc
, "extractvalue operand must be array or struct");
1761 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
1763 return Error(ID
.Loc
, "invalid indices for extractvalue");
1764 ID
.ConstantVal
= ConstantExpr::getExtractValue(Val
,
1765 &Indices
[0], Indices
.size());
1766 ID
.Kind
= ValID::t_Constant
;
1769 case lltok::kw_insertvalue
: {
1771 Constant
*Val0
, *Val1
;
1772 SmallVector
<unsigned, 4> Indices
;
1773 if (ParseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr")||
1774 ParseGlobalTypeAndValue(Val0
) ||
1775 ParseToken(lltok::comma
, "expected comma in insertvalue constantexpr")||
1776 ParseGlobalTypeAndValue(Val1
) ||
1777 ParseIndexList(Indices
) ||
1778 ParseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
1780 if (!isa
<StructType
>(Val0
->getType()) && !isa
<ArrayType
>(Val0
->getType()))
1781 return Error(ID
.Loc
, "extractvalue operand must be array or struct");
1782 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
1784 return Error(ID
.Loc
, "invalid indices for insertvalue");
1785 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
,
1786 &Indices
[0], Indices
.size());
1787 ID
.Kind
= ValID::t_Constant
;
1790 case lltok::kw_icmp
:
1791 case lltok::kw_fcmp
:
1792 case lltok::kw_vicmp
:
1793 case lltok::kw_vfcmp
: {
1794 unsigned PredVal
, Opc
= Lex
.getUIntVal();
1795 Constant
*Val0
, *Val1
;
1797 if (ParseCmpPredicate(PredVal
, Opc
) ||
1798 ParseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
1799 ParseGlobalTypeAndValue(Val0
) ||
1800 ParseToken(lltok::comma
, "expected comma in compare constantexpr") ||
1801 ParseGlobalTypeAndValue(Val1
) ||
1802 ParseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
1805 if (Val0
->getType() != Val1
->getType())
1806 return Error(ID
.Loc
, "compare operands must have the same type");
1808 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
1810 if (Opc
== Instruction::FCmp
) {
1811 if (!Val0
->getType()->isFPOrFPVector())
1812 return Error(ID
.Loc
, "fcmp requires floating point operands");
1813 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
1814 } else if (Opc
== Instruction::ICmp
) {
1815 if (!Val0
->getType()->isIntOrIntVector() &&
1816 !isa
<PointerType
>(Val0
->getType()))
1817 return Error(ID
.Loc
, "icmp requires pointer or integer operands");
1818 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
1819 } else if (Opc
== Instruction::VFCmp
) {
1820 // FIXME: REMOVE VFCMP Support
1821 if (!Val0
->getType()->isFPOrFPVector() ||
1822 !isa
<VectorType
>(Val0
->getType()))
1823 return Error(ID
.Loc
, "vfcmp requires vector floating point operands");
1824 ID
.ConstantVal
= ConstantExpr::getVFCmp(Pred
, Val0
, Val1
);
1825 } else if (Opc
== Instruction::VICmp
) {
1826 // FIXME: REMOVE VICMP Support
1827 if (!Val0
->getType()->isIntOrIntVector() ||
1828 !isa
<VectorType
>(Val0
->getType()))
1829 return Error(ID
.Loc
, "vicmp requires vector floating point operands");
1830 ID
.ConstantVal
= ConstantExpr::getVICmp(Pred
, Val0
, Val1
);
1832 ID
.Kind
= ValID::t_Constant
;
1836 // Binary Operators.
1840 case lltok::kw_udiv
:
1841 case lltok::kw_sdiv
:
1842 case lltok::kw_fdiv
:
1843 case lltok::kw_urem
:
1844 case lltok::kw_srem
:
1845 case lltok::kw_frem
: {
1846 unsigned Opc
= Lex
.getUIntVal();
1847 Constant
*Val0
, *Val1
;
1849 if (ParseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
1850 ParseGlobalTypeAndValue(Val0
) ||
1851 ParseToken(lltok::comma
, "expected comma in binary constantexpr") ||
1852 ParseGlobalTypeAndValue(Val1
) ||
1853 ParseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
1855 if (Val0
->getType() != Val1
->getType())
1856 return Error(ID
.Loc
, "operands of constexpr must have same type");
1857 if (!Val0
->getType()->isIntOrIntVector() &&
1858 !Val0
->getType()->isFPOrFPVector())
1859 return Error(ID
.Loc
,"constexpr requires integer, fp, or vector operands");
1860 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
1861 ID
.Kind
= ValID::t_Constant
;
1865 // Logical Operations
1867 case lltok::kw_lshr
:
1868 case lltok::kw_ashr
:
1871 case lltok::kw_xor
: {
1872 unsigned Opc
= Lex
.getUIntVal();
1873 Constant
*Val0
, *Val1
;
1875 if (ParseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
1876 ParseGlobalTypeAndValue(Val0
) ||
1877 ParseToken(lltok::comma
, "expected comma in logical constantexpr") ||
1878 ParseGlobalTypeAndValue(Val1
) ||
1879 ParseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
1881 if (Val0
->getType() != Val1
->getType())
1882 return Error(ID
.Loc
, "operands of constexpr must have same type");
1883 if (!Val0
->getType()->isIntOrIntVector())
1884 return Error(ID
.Loc
,
1885 "constexpr requires integer or integer vector operands");
1886 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
1887 ID
.Kind
= ValID::t_Constant
;
1891 case lltok::kw_getelementptr
:
1892 case lltok::kw_shufflevector
:
1893 case lltok::kw_insertelement
:
1894 case lltok::kw_extractelement
:
1895 case lltok::kw_select
: {
1896 unsigned Opc
= Lex
.getUIntVal();
1897 SmallVector
<Constant
*, 16> Elts
;
1899 if (ParseToken(lltok::lparen
, "expected '(' in constantexpr") ||
1900 ParseGlobalValueVector(Elts
) ||
1901 ParseToken(lltok::rparen
, "expected ')' in constantexpr"))
1904 if (Opc
== Instruction::GetElementPtr
) {
1905 if (Elts
.size() == 0 || !isa
<PointerType
>(Elts
[0]->getType()))
1906 return Error(ID
.Loc
, "getelementptr requires pointer operand");
1908 if (!GetElementPtrInst::getIndexedType(Elts
[0]->getType(),
1909 (Value
**)&Elts
[1], Elts
.size()-1))
1910 return Error(ID
.Loc
, "invalid indices for getelementptr");
1911 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Elts
[0],
1912 &Elts
[1], Elts
.size()-1);
1913 } else if (Opc
== Instruction::Select
) {
1914 if (Elts
.size() != 3)
1915 return Error(ID
.Loc
, "expected three operands to select");
1916 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
1918 return Error(ID
.Loc
, Reason
);
1919 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
1920 } else if (Opc
== Instruction::ShuffleVector
) {
1921 if (Elts
.size() != 3)
1922 return Error(ID
.Loc
, "expected three operands to shufflevector");
1923 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
1924 return Error(ID
.Loc
, "invalid operands to shufflevector");
1925 ID
.ConstantVal
= ConstantExpr::getShuffleVector(Elts
[0], Elts
[1],Elts
[2]);
1926 } else if (Opc
== Instruction::ExtractElement
) {
1927 if (Elts
.size() != 2)
1928 return Error(ID
.Loc
, "expected two operands to extractelement");
1929 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
1930 return Error(ID
.Loc
, "invalid extractelement operands");
1931 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
1933 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
1934 if (Elts
.size() != 3)
1935 return Error(ID
.Loc
, "expected three operands to insertelement");
1936 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
1937 return Error(ID
.Loc
, "invalid insertelement operands");
1938 ID
.ConstantVal
= ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
1941 ID
.Kind
= ValID::t_Constant
;
1950 /// ParseGlobalValue - Parse a global value with the specified type.
1951 bool LLParser::ParseGlobalValue(const Type
*Ty
, Constant
*&V
) {
1954 return ParseValID(ID
) ||
1955 ConvertGlobalValIDToValue(Ty
, ID
, V
);
1958 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1960 bool LLParser::ConvertGlobalValIDToValue(const Type
*Ty
, ValID
&ID
,
1962 if (isa
<FunctionType
>(Ty
))
1963 return Error(ID
.Loc
, "functions are not values, refer to them as pointers");
1966 default: assert(0 && "Unknown ValID!");
1967 case ValID::t_LocalID
:
1968 case ValID::t_LocalName
:
1969 return Error(ID
.Loc
, "invalid use of function-local name");
1970 case ValID::t_InlineAsm
:
1971 return Error(ID
.Loc
, "inline asm can only be an operand of call/invoke");
1972 case ValID::t_GlobalName
:
1973 V
= GetGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
);
1975 case ValID::t_GlobalID
:
1976 V
= GetGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
);
1978 case ValID::t_APSInt
:
1979 if (!isa
<IntegerType
>(Ty
))
1980 return Error(ID
.Loc
, "integer constant must have integer type");
1981 ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
1982 V
= ConstantInt::get(ID
.APSIntVal
);
1984 case ValID::t_APFloat
:
1985 if (!Ty
->isFloatingPoint() ||
1986 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
1987 return Error(ID
.Loc
, "floating point constant invalid for type");
1989 // The lexer has no type info, so builds all float and double FP constants
1990 // as double. Fix this here. Long double does not need this.
1991 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble
&&
1992 Ty
== Type::FloatTy
) {
1994 ID
.APFloatVal
.convert(APFloat::IEEEsingle
, APFloat::rmNearestTiesToEven
,
1997 V
= ConstantFP::get(ID
.APFloatVal
);
1999 if (V
->getType() != Ty
)
2000 return Error(ID
.Loc
, "floating point constant does not have type '" +
2001 Ty
->getDescription() + "'");
2005 if (!isa
<PointerType
>(Ty
))
2006 return Error(ID
.Loc
, "null must be a pointer type");
2007 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
2009 case ValID::t_Undef
:
2010 // FIXME: LabelTy should not be a first-class type.
2011 if ((!Ty
->isFirstClassType() || Ty
== Type::LabelTy
) &&
2012 !isa
<OpaqueType
>(Ty
))
2013 return Error(ID
.Loc
, "invalid type for undef constant");
2014 V
= UndefValue::get(Ty
);
2016 case ValID::t_EmptyArray
:
2017 if (!isa
<ArrayType
>(Ty
) || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
2018 return Error(ID
.Loc
, "invalid empty array initializer");
2019 V
= UndefValue::get(Ty
);
2022 // FIXME: LabelTy should not be a first-class type.
2023 if (!Ty
->isFirstClassType() || Ty
== Type::LabelTy
)
2024 return Error(ID
.Loc
, "invalid type for null constant");
2025 V
= Constant::getNullValue(Ty
);
2027 case ValID::t_Constant
:
2028 if (ID
.ConstantVal
->getType() != Ty
)
2029 return Error(ID
.Loc
, "constant expression type mismatch");
2035 bool LLParser::ParseGlobalTypeAndValue(Constant
*&V
) {
2036 PATypeHolder
Type(Type::VoidTy
);
2037 return ParseType(Type
) ||
2038 ParseGlobalValue(Type
, V
);
2041 /// ParseGlobalValueVector
2043 /// ::= TypeAndValue (',' TypeAndValue)*
2044 bool LLParser::ParseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
) {
2046 if (Lex
.getKind() == lltok::rbrace
||
2047 Lex
.getKind() == lltok::rsquare
||
2048 Lex
.getKind() == lltok::greater
||
2049 Lex
.getKind() == lltok::rparen
)
2053 if (ParseGlobalTypeAndValue(C
)) return true;
2056 while (EatIfPresent(lltok::comma
)) {
2057 if (ParseGlobalTypeAndValue(C
)) return true;
2065 //===----------------------------------------------------------------------===//
2066 // Function Parsing.
2067 //===----------------------------------------------------------------------===//
2069 bool LLParser::ConvertValIDToValue(const Type
*Ty
, ValID
&ID
, Value
*&V
,
2070 PerFunctionState
&PFS
) {
2071 if (ID
.Kind
== ValID::t_LocalID
)
2072 V
= PFS
.GetVal(ID
.UIntVal
, Ty
, ID
.Loc
);
2073 else if (ID
.Kind
== ValID::t_LocalName
)
2074 V
= PFS
.GetVal(ID
.StrVal
, Ty
, ID
.Loc
);
2075 else if (ID
.Kind
== ValID::t_InlineAsm
) {
2076 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
2077 const FunctionType
*FTy
=
2078 PTy
? dyn_cast
<FunctionType
>(PTy
->getElementType()) : 0;
2079 if (!FTy
|| !InlineAsm::Verify(FTy
, ID
.StrVal2
))
2080 return Error(ID
.Loc
, "invalid type for inline asm constraint string");
2081 V
= InlineAsm::get(FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
);
2085 if (ConvertGlobalValIDToValue(Ty
, ID
, C
)) return true;
2093 bool LLParser::ParseValue(const Type
*Ty
, Value
*&V
, PerFunctionState
&PFS
) {
2096 return ParseValID(ID
) ||
2097 ConvertValIDToValue(Ty
, ID
, V
, PFS
);
2100 bool LLParser::ParseTypeAndValue(Value
*&V
, PerFunctionState
&PFS
) {
2101 PATypeHolder
T(Type::VoidTy
);
2102 return ParseType(T
) ||
2103 ParseValue(T
, V
, PFS
);
2107 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2108 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2109 /// OptionalAlign OptGC
2110 bool LLParser::ParseFunctionHeader(Function
*&Fn
, bool isDefine
) {
2111 // Parse the linkage.
2112 LocTy LinkageLoc
= Lex
.getLoc();
2115 unsigned Visibility
, CC
, RetAttrs
;
2116 PATypeHolder
RetType(Type::VoidTy
);
2117 LocTy RetTypeLoc
= Lex
.getLoc();
2118 if (ParseOptionalLinkage(Linkage
) ||
2119 ParseOptionalVisibility(Visibility
) ||
2120 ParseOptionalCallingConv(CC
) ||
2121 ParseOptionalAttrs(RetAttrs
, 1) ||
2122 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/))
2125 // Verify that the linkage is ok.
2126 switch ((GlobalValue::LinkageTypes
)Linkage
) {
2127 case GlobalValue::ExternalLinkage
:
2128 break; // always ok.
2129 case GlobalValue::DLLImportLinkage
:
2130 case GlobalValue::ExternalWeakLinkage
:
2132 return Error(LinkageLoc
, "invalid linkage for function definition");
2134 case GlobalValue::PrivateLinkage
:
2135 case GlobalValue::InternalLinkage
:
2136 case GlobalValue::AvailableExternallyLinkage
:
2137 case GlobalValue::LinkOnceAnyLinkage
:
2138 case GlobalValue::LinkOnceODRLinkage
:
2139 case GlobalValue::WeakAnyLinkage
:
2140 case GlobalValue::WeakODRLinkage
:
2141 case GlobalValue::DLLExportLinkage
:
2143 return Error(LinkageLoc
, "invalid linkage for function declaration");
2145 case GlobalValue::AppendingLinkage
:
2146 case GlobalValue::GhostLinkage
:
2147 case GlobalValue::CommonLinkage
:
2148 return Error(LinkageLoc
, "invalid function linkage type");
2151 if (!FunctionType::isValidReturnType(RetType
) ||
2152 isa
<OpaqueType
>(RetType
))
2153 return Error(RetTypeLoc
, "invalid function return type");
2155 LocTy NameLoc
= Lex
.getLoc();
2157 std::string FunctionName
;
2158 if (Lex
.getKind() == lltok::GlobalVar
) {
2159 FunctionName
= Lex
.getStrVal();
2160 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
2161 unsigned NameID
= Lex
.getUIntVal();
2163 if (NameID
!= NumberedVals
.size())
2164 return TokError("function expected to be numbered '%" +
2165 utostr(NumberedVals
.size()) + "'");
2167 return TokError("expected function name");
2172 if (Lex
.getKind() != lltok::lparen
)
2173 return TokError("expected '(' in function argument list");
2175 std::vector
<ArgInfo
> ArgList
;
2178 std::string Section
;
2182 if (ParseArgumentList(ArgList
, isVarArg
, false) ||
2183 ParseOptionalAttrs(FuncAttrs
, 2) ||
2184 (EatIfPresent(lltok::kw_section
) &&
2185 ParseStringConstant(Section
)) ||
2186 ParseOptionalAlignment(Alignment
) ||
2187 (EatIfPresent(lltok::kw_gc
) &&
2188 ParseStringConstant(GC
)))
2191 // If the alignment was parsed as an attribute, move to the alignment field.
2192 if (FuncAttrs
& Attribute::Alignment
) {
2193 Alignment
= Attribute::getAlignmentFromAttrs(FuncAttrs
);
2194 FuncAttrs
&= ~Attribute::Alignment
;
2197 // Okay, if we got here, the function is syntactically valid. Convert types
2198 // and do semantic checks.
2199 std::vector
<const Type
*> ParamTypeList
;
2200 SmallVector
<AttributeWithIndex
, 8> Attrs
;
2201 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2203 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
2204 if (FuncAttrs
& ObsoleteFuncAttrs
) {
2205 RetAttrs
|= FuncAttrs
& ObsoleteFuncAttrs
;
2206 FuncAttrs
&= ~ObsoleteFuncAttrs
;
2209 if (RetAttrs
!= Attribute::None
)
2210 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
2212 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2213 ParamTypeList
.push_back(ArgList
[i
].Type
);
2214 if (ArgList
[i
].Attrs
!= Attribute::None
)
2215 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
2218 if (FuncAttrs
!= Attribute::None
)
2219 Attrs
.push_back(AttributeWithIndex::get(~0, FuncAttrs
));
2221 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
2223 if (PAL
.paramHasAttr(1, Attribute::StructRet
) &&
2224 RetType
!= Type::VoidTy
)
2225 return Error(RetTypeLoc
, "functions with 'sret' argument must return void");
2227 const FunctionType
*FT
= FunctionType::get(RetType
, ParamTypeList
, isVarArg
);
2228 const PointerType
*PFT
= PointerType::getUnqual(FT
);
2231 if (!FunctionName
.empty()) {
2232 // If this was a definition of a forward reference, remove the definition
2233 // from the forward reference table and fill in the forward ref.
2234 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator FRVI
=
2235 ForwardRefVals
.find(FunctionName
);
2236 if (FRVI
!= ForwardRefVals
.end()) {
2237 Fn
= M
->getFunction(FunctionName
);
2238 ForwardRefVals
.erase(FRVI
);
2239 } else if ((Fn
= M
->getFunction(FunctionName
))) {
2240 // If this function already exists in the symbol table, then it is
2241 // multiply defined. We accept a few cases for old backwards compat.
2242 // FIXME: Remove this stuff for LLVM 3.0.
2243 if (Fn
->getType() != PFT
|| Fn
->getAttributes() != PAL
||
2244 (!Fn
->isDeclaration() && isDefine
)) {
2245 // If the redefinition has different type or different attributes,
2246 // reject it. If both have bodies, reject it.
2247 return Error(NameLoc
, "invalid redefinition of function '" +
2248 FunctionName
+ "'");
2249 } else if (Fn
->isDeclaration()) {
2250 // Make sure to strip off any argument names so we can't get conflicts.
2251 for (Function::arg_iterator AI
= Fn
->arg_begin(), AE
= Fn
->arg_end();
2257 } else if (FunctionName
.empty()) {
2258 // If this is a definition of a forward referenced function, make sure the
2260 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator I
2261 = ForwardRefValIDs
.find(NumberedVals
.size());
2262 if (I
!= ForwardRefValIDs
.end()) {
2263 Fn
= cast
<Function
>(I
->second
.first
);
2264 if (Fn
->getType() != PFT
)
2265 return Error(NameLoc
, "type of definition and forward reference of '@" +
2266 utostr(NumberedVals
.size()) +"' disagree");
2267 ForwardRefValIDs
.erase(I
);
2272 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, FunctionName
, M
);
2273 else // Move the forward-reference to the correct spot in the module.
2274 M
->getFunctionList().splice(M
->end(), M
->getFunctionList(), Fn
);
2276 if (FunctionName
.empty())
2277 NumberedVals
.push_back(Fn
);
2279 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
2280 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
2281 Fn
->setCallingConv(CC
);
2282 Fn
->setAttributes(PAL
);
2283 Fn
->setAlignment(Alignment
);
2284 Fn
->setSection(Section
);
2285 if (!GC
.empty()) Fn
->setGC(GC
.c_str());
2287 // Add all of the arguments we parsed to the function.
2288 Function::arg_iterator ArgIt
= Fn
->arg_begin();
2289 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
2290 // If the argument has a name, insert it into the argument symbol table.
2291 if (ArgList
[i
].Name
.empty()) continue;
2293 // Set the name, if it conflicted, it will be auto-renamed.
2294 ArgIt
->setName(ArgList
[i
].Name
);
2296 if (ArgIt
->getNameStr() != ArgList
[i
].Name
)
2297 return Error(ArgList
[i
].Loc
, "redefinition of argument '%" +
2298 ArgList
[i
].Name
+ "'");
2305 /// ParseFunctionBody
2306 /// ::= '{' BasicBlock+ '}'
2307 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2309 bool LLParser::ParseFunctionBody(Function
&Fn
) {
2310 if (Lex
.getKind() != lltok::lbrace
&& Lex
.getKind() != lltok::kw_begin
)
2311 return TokError("expected '{' in function body");
2312 Lex
.Lex(); // eat the {.
2314 PerFunctionState
PFS(*this, Fn
);
2316 while (Lex
.getKind() != lltok::rbrace
&& Lex
.getKind() != lltok::kw_end
)
2317 if (ParseBasicBlock(PFS
)) return true;
2322 // Verify function is ok.
2323 return PFS
.VerifyFunctionComplete();
2327 /// ::= LabelStr? Instruction*
2328 bool LLParser::ParseBasicBlock(PerFunctionState
&PFS
) {
2329 // If this basic block starts out with a name, remember it.
2331 LocTy NameLoc
= Lex
.getLoc();
2332 if (Lex
.getKind() == lltok::LabelStr
) {
2333 Name
= Lex
.getStrVal();
2337 BasicBlock
*BB
= PFS
.DefineBB(Name
, NameLoc
);
2338 if (BB
== 0) return true;
2340 std::string NameStr
;
2342 // Parse the instructions in this block until we get a terminator.
2345 // This instruction may have three possibilities for a name: a) none
2346 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2347 LocTy NameLoc
= Lex
.getLoc();
2351 if (Lex
.getKind() == lltok::LocalVarID
) {
2352 NameID
= Lex
.getUIntVal();
2354 if (ParseToken(lltok::equal
, "expected '=' after instruction id"))
2356 } else if (Lex
.getKind() == lltok::LocalVar
||
2357 // FIXME: REMOVE IN LLVM 3.0
2358 Lex
.getKind() == lltok::StringConstant
) {
2359 NameStr
= Lex
.getStrVal();
2361 if (ParseToken(lltok::equal
, "expected '=' after instruction name"))
2365 if (ParseInstruction(Inst
, BB
, PFS
)) return true;
2367 BB
->getInstList().push_back(Inst
);
2369 // Set the name on the instruction.
2370 if (PFS
.SetInstName(NameID
, NameStr
, NameLoc
, Inst
)) return true;
2371 } while (!isa
<TerminatorInst
>(Inst
));
2376 //===----------------------------------------------------------------------===//
2377 // Instruction Parsing.
2378 //===----------------------------------------------------------------------===//
2380 /// ParseInstruction - Parse one of the many different instructions.
2382 bool LLParser::ParseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
2383 PerFunctionState
&PFS
) {
2384 lltok::Kind Token
= Lex
.getKind();
2385 if (Token
== lltok::Eof
)
2386 return TokError("found end of file when expecting more instructions");
2387 LocTy Loc
= Lex
.getLoc();
2388 unsigned KeywordVal
= Lex
.getUIntVal();
2389 Lex
.Lex(); // Eat the keyword.
2392 default: return Error(Loc
, "expected instruction opcode");
2393 // Terminator Instructions.
2394 case lltok::kw_unwind
: Inst
= new UnwindInst(); return false;
2395 case lltok::kw_unreachable
: Inst
= new UnreachableInst(); return false;
2396 case lltok::kw_ret
: return ParseRet(Inst
, BB
, PFS
);
2397 case lltok::kw_br
: return ParseBr(Inst
, PFS
);
2398 case lltok::kw_switch
: return ParseSwitch(Inst
, PFS
);
2399 case lltok::kw_invoke
: return ParseInvoke(Inst
, PFS
);
2400 // Binary Operators.
2403 case lltok::kw_mul
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 0);
2405 case lltok::kw_udiv
:
2406 case lltok::kw_sdiv
:
2407 case lltok::kw_urem
:
2408 case lltok::kw_srem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
2409 case lltok::kw_fdiv
:
2410 case lltok::kw_frem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
2412 case lltok::kw_lshr
:
2413 case lltok::kw_ashr
:
2416 case lltok::kw_xor
: return ParseLogical(Inst
, PFS
, KeywordVal
);
2417 case lltok::kw_icmp
:
2418 case lltok::kw_fcmp
:
2419 case lltok::kw_vicmp
:
2420 case lltok::kw_vfcmp
: return ParseCompare(Inst
, PFS
, KeywordVal
);
2422 case lltok::kw_trunc
:
2423 case lltok::kw_zext
:
2424 case lltok::kw_sext
:
2425 case lltok::kw_fptrunc
:
2426 case lltok::kw_fpext
:
2427 case lltok::kw_bitcast
:
2428 case lltok::kw_uitofp
:
2429 case lltok::kw_sitofp
:
2430 case lltok::kw_fptoui
:
2431 case lltok::kw_fptosi
:
2432 case lltok::kw_inttoptr
:
2433 case lltok::kw_ptrtoint
: return ParseCast(Inst
, PFS
, KeywordVal
);
2435 case lltok::kw_select
: return ParseSelect(Inst
, PFS
);
2436 case lltok::kw_va_arg
: return ParseVA_Arg(Inst
, PFS
);
2437 case lltok::kw_extractelement
: return ParseExtractElement(Inst
, PFS
);
2438 case lltok::kw_insertelement
: return ParseInsertElement(Inst
, PFS
);
2439 case lltok::kw_shufflevector
: return ParseShuffleVector(Inst
, PFS
);
2440 case lltok::kw_phi
: return ParsePHI(Inst
, PFS
);
2441 case lltok::kw_call
: return ParseCall(Inst
, PFS
, false);
2442 case lltok::kw_tail
: return ParseCall(Inst
, PFS
, true);
2444 case lltok::kw_alloca
:
2445 case lltok::kw_malloc
: return ParseAlloc(Inst
, PFS
, KeywordVal
);
2446 case lltok::kw_free
: return ParseFree(Inst
, PFS
);
2447 case lltok::kw_load
: return ParseLoad(Inst
, PFS
, false);
2448 case lltok::kw_store
: return ParseStore(Inst
, PFS
, false);
2449 case lltok::kw_volatile
:
2450 if (EatIfPresent(lltok::kw_load
))
2451 return ParseLoad(Inst
, PFS
, true);
2452 else if (EatIfPresent(lltok::kw_store
))
2453 return ParseStore(Inst
, PFS
, true);
2455 return TokError("expected 'load' or 'store'");
2456 case lltok::kw_getresult
: return ParseGetResult(Inst
, PFS
);
2457 case lltok::kw_getelementptr
: return ParseGetElementPtr(Inst
, PFS
);
2458 case lltok::kw_extractvalue
: return ParseExtractValue(Inst
, PFS
);
2459 case lltok::kw_insertvalue
: return ParseInsertValue(Inst
, PFS
);
2463 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2464 bool LLParser::ParseCmpPredicate(unsigned &P
, unsigned Opc
) {
2465 // FIXME: REMOVE vicmp/vfcmp!
2466 if (Opc
== Instruction::FCmp
|| Opc
== Instruction::VFCmp
) {
2467 switch (Lex
.getKind()) {
2468 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2469 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
2470 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
2471 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
2472 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
2473 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
2474 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
2475 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
2476 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
2477 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
2478 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
2479 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
2480 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
2481 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
2482 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
2483 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
2484 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
2487 switch (Lex
.getKind()) {
2488 default: TokError("expected icmp predicate (e.g. 'eq')");
2489 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
2490 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
2491 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
2492 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
2493 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
2494 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
2495 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
2496 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
2497 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
2498 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
2505 //===----------------------------------------------------------------------===//
2506 // Terminator Instructions.
2507 //===----------------------------------------------------------------------===//
2509 /// ParseRet - Parse a return instruction.
2511 /// ::= 'ret' TypeAndValue
2512 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2513 bool LLParser::ParseRet(Instruction
*&Inst
, BasicBlock
*BB
,
2514 PerFunctionState
&PFS
) {
2515 PATypeHolder
Ty(Type::VoidTy
);
2516 if (ParseType(Ty
, true /*void allowed*/)) return true;
2518 if (Ty
== Type::VoidTy
) {
2519 Inst
= ReturnInst::Create();
2524 if (ParseValue(Ty
, RV
, PFS
)) return true;
2526 // The normal case is one return value.
2527 if (Lex
.getKind() == lltok::comma
) {
2528 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2529 // of 'ret {i32,i32} {i32 1, i32 2}'
2530 SmallVector
<Value
*, 8> RVs
;
2533 while (EatIfPresent(lltok::comma
)) {
2534 if (ParseTypeAndValue(RV
, PFS
)) return true;
2538 RV
= UndefValue::get(PFS
.getFunction().getReturnType());
2539 for (unsigned i
= 0, e
= RVs
.size(); i
!= e
; ++i
) {
2540 Instruction
*I
= InsertValueInst::Create(RV
, RVs
[i
], i
, "mrv");
2541 BB
->getInstList().push_back(I
);
2545 Inst
= ReturnInst::Create(RV
);
2551 /// ::= 'br' TypeAndValue
2552 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2553 bool LLParser::ParseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2555 Value
*Op0
, *Op1
, *Op2
;
2556 if (ParseTypeAndValue(Op0
, Loc
, PFS
)) return true;
2558 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
2559 Inst
= BranchInst::Create(BB
);
2563 if (Op0
->getType() != Type::Int1Ty
)
2564 return Error(Loc
, "branch condition must have 'i1' type");
2566 if (ParseToken(lltok::comma
, "expected ',' after branch condition") ||
2567 ParseTypeAndValue(Op1
, Loc
, PFS
) ||
2568 ParseToken(lltok::comma
, "expected ',' after true destination") ||
2569 ParseTypeAndValue(Op2
, Loc2
, PFS
))
2572 if (!isa
<BasicBlock
>(Op1
))
2573 return Error(Loc
, "true destination of branch must be a basic block");
2574 if (!isa
<BasicBlock
>(Op2
))
2575 return Error(Loc2
, "true destination of branch must be a basic block");
2577 Inst
= BranchInst::Create(cast
<BasicBlock
>(Op1
), cast
<BasicBlock
>(Op2
), Op0
);
2583 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2585 /// ::= (TypeAndValue ',' TypeAndValue)*
2586 bool LLParser::ParseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2587 LocTy CondLoc
, BBLoc
;
2588 Value
*Cond
, *DefaultBB
;
2589 if (ParseTypeAndValue(Cond
, CondLoc
, PFS
) ||
2590 ParseToken(lltok::comma
, "expected ',' after switch condition") ||
2591 ParseTypeAndValue(DefaultBB
, BBLoc
, PFS
) ||
2592 ParseToken(lltok::lsquare
, "expected '[' with switch table"))
2595 if (!isa
<IntegerType
>(Cond
->getType()))
2596 return Error(CondLoc
, "switch condition must have integer type");
2597 if (!isa
<BasicBlock
>(DefaultBB
))
2598 return Error(BBLoc
, "default destination must be a basic block");
2600 // Parse the jump table pairs.
2601 SmallPtrSet
<Value
*, 32> SeenCases
;
2602 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
2603 while (Lex
.getKind() != lltok::rsquare
) {
2604 Value
*Constant
, *DestBB
;
2606 if (ParseTypeAndValue(Constant
, CondLoc
, PFS
) ||
2607 ParseToken(lltok::comma
, "expected ',' after case value") ||
2608 ParseTypeAndValue(DestBB
, BBLoc
, PFS
))
2611 if (!SeenCases
.insert(Constant
))
2612 return Error(CondLoc
, "duplicate case value in switch");
2613 if (!isa
<ConstantInt
>(Constant
))
2614 return Error(CondLoc
, "case value is not a constant integer");
2615 if (!isa
<BasicBlock
>(DestBB
))
2616 return Error(BBLoc
, "case destination is not a basic block");
2618 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
),
2619 cast
<BasicBlock
>(DestBB
)));
2622 Lex
.Lex(); // Eat the ']'.
2624 SwitchInst
*SI
= SwitchInst::Create(Cond
, cast
<BasicBlock
>(DefaultBB
),
2626 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
2627 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
2633 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2634 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2635 bool LLParser::ParseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2636 LocTy CallLoc
= Lex
.getLoc();
2637 unsigned CC
, RetAttrs
, FnAttrs
;
2638 PATypeHolder
RetType(Type::VoidTy
);
2641 SmallVector
<ParamInfo
, 16> ArgList
;
2643 Value
*NormalBB
, *UnwindBB
;
2644 if (ParseOptionalCallingConv(CC
) ||
2645 ParseOptionalAttrs(RetAttrs
, 1) ||
2646 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
2647 ParseValID(CalleeID
) ||
2648 ParseParameterList(ArgList
, PFS
) ||
2649 ParseOptionalAttrs(FnAttrs
, 2) ||
2650 ParseToken(lltok::kw_to
, "expected 'to' in invoke") ||
2651 ParseTypeAndValue(NormalBB
, PFS
) ||
2652 ParseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
2653 ParseTypeAndValue(UnwindBB
, PFS
))
2656 if (!isa
<BasicBlock
>(NormalBB
))
2657 return Error(CallLoc
, "normal destination is not a basic block");
2658 if (!isa
<BasicBlock
>(UnwindBB
))
2659 return Error(CallLoc
, "unwind destination is not a basic block");
2661 // If RetType is a non-function pointer type, then this is the short syntax
2662 // for the call, which means that RetType is just the return type. Infer the
2663 // rest of the function argument types from the arguments that are present.
2664 const PointerType
*PFTy
= 0;
2665 const FunctionType
*Ty
= 0;
2666 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
2667 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
2668 // Pull out the types of all of the arguments...
2669 std::vector
<const Type
*> ParamTypes
;
2670 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
2671 ParamTypes
.push_back(ArgList
[i
].V
->getType());
2673 if (!FunctionType::isValidReturnType(RetType
))
2674 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
2676 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
2677 PFTy
= PointerType::getUnqual(Ty
);
2680 // Look up the callee.
2682 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, PFS
)) return true;
2684 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2685 // function attributes.
2686 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
2687 if (FnAttrs
& ObsoleteFuncAttrs
) {
2688 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
2689 FnAttrs
&= ~ObsoleteFuncAttrs
;
2692 // Set up the Attributes for the function.
2693 SmallVector
<AttributeWithIndex
, 8> Attrs
;
2694 if (RetAttrs
!= Attribute::None
)
2695 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
2697 SmallVector
<Value
*, 8> Args
;
2699 // Loop through FunctionType's arguments and ensure they are specified
2700 // correctly. Also, gather any parameter attributes.
2701 FunctionType::param_iterator I
= Ty
->param_begin();
2702 FunctionType::param_iterator E
= Ty
->param_end();
2703 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2704 const Type
*ExpectedTy
= 0;
2707 } else if (!Ty
->isVarArg()) {
2708 return Error(ArgList
[i
].Loc
, "too many arguments specified");
2711 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
2712 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
2713 ExpectedTy
->getDescription() + "'");
2714 Args
.push_back(ArgList
[i
].V
);
2715 if (ArgList
[i
].Attrs
!= Attribute::None
)
2716 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
2720 return Error(CallLoc
, "not enough parameters specified for call");
2722 if (FnAttrs
!= Attribute::None
)
2723 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
2725 // Finish off the Attributes and check them
2726 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
2728 InvokeInst
*II
= InvokeInst::Create(Callee
, cast
<BasicBlock
>(NormalBB
),
2729 cast
<BasicBlock
>(UnwindBB
),
2730 Args
.begin(), Args
.end());
2731 II
->setCallingConv(CC
);
2732 II
->setAttributes(PAL
);
2739 //===----------------------------------------------------------------------===//
2740 // Binary Operators.
2741 //===----------------------------------------------------------------------===//
2744 /// ::= ArithmeticOps TypeAndValue ',' Value
2746 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2747 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2748 bool LLParser::ParseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
2749 unsigned Opc
, unsigned OperandType
) {
2750 LocTy Loc
; Value
*LHS
, *RHS
;
2751 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
2752 ParseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
2753 ParseValue(LHS
->getType(), RHS
, PFS
))
2757 switch (OperandType
) {
2758 default: assert(0 && "Unknown operand type!");
2759 case 0: // int or FP.
2760 Valid
= LHS
->getType()->isIntOrIntVector() ||
2761 LHS
->getType()->isFPOrFPVector();
2763 case 1: Valid
= LHS
->getType()->isIntOrIntVector(); break;
2764 case 2: Valid
= LHS
->getType()->isFPOrFPVector(); break;
2768 return Error(Loc
, "invalid operand type for instruction");
2770 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
2775 /// ::= ArithmeticOps TypeAndValue ',' Value {
2776 bool LLParser::ParseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
2778 LocTy Loc
; Value
*LHS
, *RHS
;
2779 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
2780 ParseToken(lltok::comma
, "expected ',' in logical operation") ||
2781 ParseValue(LHS
->getType(), RHS
, PFS
))
2784 if (!LHS
->getType()->isIntOrIntVector())
2785 return Error(Loc
,"instruction requires integer or integer vector operands");
2787 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
2793 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2794 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2795 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2796 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2797 bool LLParser::ParseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
2799 // Parse the integer/fp comparison predicate.
2803 if (ParseCmpPredicate(Pred
, Opc
) ||
2804 ParseTypeAndValue(LHS
, Loc
, PFS
) ||
2805 ParseToken(lltok::comma
, "expected ',' after compare value") ||
2806 ParseValue(LHS
->getType(), RHS
, PFS
))
2809 if (Opc
== Instruction::FCmp
) {
2810 if (!LHS
->getType()->isFPOrFPVector())
2811 return Error(Loc
, "fcmp requires floating point operands");
2812 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
2813 } else if (Opc
== Instruction::ICmp
) {
2814 if (!LHS
->getType()->isIntOrIntVector() &&
2815 !isa
<PointerType
>(LHS
->getType()))
2816 return Error(Loc
, "icmp requires integer operands");
2817 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
2818 } else if (Opc
== Instruction::VFCmp
) {
2819 if (!LHS
->getType()->isFPOrFPVector() || !isa
<VectorType
>(LHS
->getType()))
2820 return Error(Loc
, "vfcmp requires vector floating point operands");
2821 Inst
= new VFCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
2822 } else if (Opc
== Instruction::VICmp
) {
2823 if (!LHS
->getType()->isIntOrIntVector() || !isa
<VectorType
>(LHS
->getType()))
2824 return Error(Loc
, "vicmp requires vector floating point operands");
2825 Inst
= new VICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
2830 //===----------------------------------------------------------------------===//
2831 // Other Instructions.
2832 //===----------------------------------------------------------------------===//
2836 /// ::= CastOpc TypeAndValue 'to' Type
2837 bool LLParser::ParseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
2839 LocTy Loc
; Value
*Op
;
2840 PATypeHolder
DestTy(Type::VoidTy
);
2841 if (ParseTypeAndValue(Op
, Loc
, PFS
) ||
2842 ParseToken(lltok::kw_to
, "expected 'to' after cast value") ||
2846 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
2847 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
2848 return Error(Loc
, "invalid cast opcode for cast from '" +
2849 Op
->getType()->getDescription() + "' to '" +
2850 DestTy
->getDescription() + "'");
2852 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
2857 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2858 bool LLParser::ParseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2860 Value
*Op0
, *Op1
, *Op2
;
2861 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
2862 ParseToken(lltok::comma
, "expected ',' after select condition") ||
2863 ParseTypeAndValue(Op1
, PFS
) ||
2864 ParseToken(lltok::comma
, "expected ',' after select value") ||
2865 ParseTypeAndValue(Op2
, PFS
))
2868 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
2869 return Error(Loc
, Reason
);
2871 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
2876 /// ::= 'va_arg' TypeAndValue ',' Type
2877 bool LLParser::ParseVA_Arg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2879 PATypeHolder
EltTy(Type::VoidTy
);
2881 if (ParseTypeAndValue(Op
, PFS
) ||
2882 ParseToken(lltok::comma
, "expected ',' after vaarg operand") ||
2883 ParseType(EltTy
, TypeLoc
))
2886 if (!EltTy
->isFirstClassType())
2887 return Error(TypeLoc
, "va_arg requires operand with first class type");
2889 Inst
= new VAArgInst(Op
, EltTy
);
2893 /// ParseExtractElement
2894 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2895 bool LLParser::ParseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2898 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
2899 ParseToken(lltok::comma
, "expected ',' after extract value") ||
2900 ParseTypeAndValue(Op1
, PFS
))
2903 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
2904 return Error(Loc
, "invalid extractelement operands");
2906 Inst
= new ExtractElementInst(Op0
, Op1
);
2910 /// ParseInsertElement
2911 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2912 bool LLParser::ParseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2914 Value
*Op0
, *Op1
, *Op2
;
2915 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
2916 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
2917 ParseTypeAndValue(Op1
, PFS
) ||
2918 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
2919 ParseTypeAndValue(Op2
, PFS
))
2922 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
2923 return Error(Loc
, "invalid extractelement operands");
2925 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
2929 /// ParseShuffleVector
2930 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2931 bool LLParser::ParseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2933 Value
*Op0
, *Op1
, *Op2
;
2934 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
2935 ParseToken(lltok::comma
, "expected ',' after shuffle mask") ||
2936 ParseTypeAndValue(Op1
, PFS
) ||
2937 ParseToken(lltok::comma
, "expected ',' after shuffle value") ||
2938 ParseTypeAndValue(Op2
, PFS
))
2941 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
2942 return Error(Loc
, "invalid extractelement operands");
2944 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
2949 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2950 bool LLParser::ParsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2951 PATypeHolder
Ty(Type::VoidTy
);
2953 LocTy TypeLoc
= Lex
.getLoc();
2955 if (ParseType(Ty
) ||
2956 ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
2957 ParseValue(Ty
, Op0
, PFS
) ||
2958 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
2959 ParseValue(Type::LabelTy
, Op1
, PFS
) ||
2960 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
2963 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
2965 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
2967 if (!EatIfPresent(lltok::comma
))
2970 if (ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
2971 ParseValue(Ty
, Op0
, PFS
) ||
2972 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
2973 ParseValue(Type::LabelTy
, Op1
, PFS
) ||
2974 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
2978 if (!Ty
->isFirstClassType())
2979 return Error(TypeLoc
, "phi node must have first class type");
2981 PHINode
*PN
= PHINode::Create(Ty
);
2982 PN
->reserveOperandSpace(PHIVals
.size());
2983 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
2984 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
2990 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2991 /// ParameterList OptionalAttrs
2992 bool LLParser::ParseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
2994 unsigned CC
, RetAttrs
, FnAttrs
;
2995 PATypeHolder
RetType(Type::VoidTy
);
2998 SmallVector
<ParamInfo
, 16> ArgList
;
2999 LocTy CallLoc
= Lex
.getLoc();
3001 if ((isTail
&& ParseToken(lltok::kw_call
, "expected 'tail call'")) ||
3002 ParseOptionalCallingConv(CC
) ||
3003 ParseOptionalAttrs(RetAttrs
, 1) ||
3004 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
3005 ParseValID(CalleeID
) ||
3006 ParseParameterList(ArgList
, PFS
) ||
3007 ParseOptionalAttrs(FnAttrs
, 2))
3010 // If RetType is a non-function pointer type, then this is the short syntax
3011 // for the call, which means that RetType is just the return type. Infer the
3012 // rest of the function argument types from the arguments that are present.
3013 const PointerType
*PFTy
= 0;
3014 const FunctionType
*Ty
= 0;
3015 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
3016 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
3017 // Pull out the types of all of the arguments...
3018 std::vector
<const Type
*> ParamTypes
;
3019 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
3020 ParamTypes
.push_back(ArgList
[i
].V
->getType());
3022 if (!FunctionType::isValidReturnType(RetType
))
3023 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
3025 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
3026 PFTy
= PointerType::getUnqual(Ty
);
3029 // Look up the callee.
3031 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, PFS
)) return true;
3033 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3034 // function attributes.
3035 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
3036 if (FnAttrs
& ObsoleteFuncAttrs
) {
3037 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
3038 FnAttrs
&= ~ObsoleteFuncAttrs
;
3041 // Set up the Attributes for the function.
3042 SmallVector
<AttributeWithIndex
, 8> Attrs
;
3043 if (RetAttrs
!= Attribute::None
)
3044 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
3046 SmallVector
<Value
*, 8> Args
;
3048 // Loop through FunctionType's arguments and ensure they are specified
3049 // correctly. Also, gather any parameter attributes.
3050 FunctionType::param_iterator I
= Ty
->param_begin();
3051 FunctionType::param_iterator E
= Ty
->param_end();
3052 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3053 const Type
*ExpectedTy
= 0;
3056 } else if (!Ty
->isVarArg()) {
3057 return Error(ArgList
[i
].Loc
, "too many arguments specified");
3060 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
3061 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
3062 ExpectedTy
->getDescription() + "'");
3063 Args
.push_back(ArgList
[i
].V
);
3064 if (ArgList
[i
].Attrs
!= Attribute::None
)
3065 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
3069 return Error(CallLoc
, "not enough parameters specified for call");
3071 if (FnAttrs
!= Attribute::None
)
3072 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
3074 // Finish off the Attributes and check them
3075 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
3077 CallInst
*CI
= CallInst::Create(Callee
, Args
.begin(), Args
.end());
3078 CI
->setTailCall(isTail
);
3079 CI
->setCallingConv(CC
);
3080 CI
->setAttributes(PAL
);
3085 //===----------------------------------------------------------------------===//
3086 // Memory Instructions.
3087 //===----------------------------------------------------------------------===//
3090 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3091 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3092 bool LLParser::ParseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
,
3094 PATypeHolder
Ty(Type::VoidTy
);
3097 unsigned Alignment
= 0;
3098 if (ParseType(Ty
)) return true;
3100 if (EatIfPresent(lltok::comma
)) {
3101 if (Lex
.getKind() == lltok::kw_align
) {
3102 if (ParseOptionalAlignment(Alignment
)) return true;
3103 } else if (ParseTypeAndValue(Size
, SizeLoc
, PFS
) ||
3104 ParseOptionalCommaAlignment(Alignment
)) {
3109 if (Size
&& Size
->getType() != Type::Int32Ty
)
3110 return Error(SizeLoc
, "element count must be i32");
3112 if (Opc
== Instruction::Malloc
)
3113 Inst
= new MallocInst(Ty
, Size
, Alignment
);
3115 Inst
= new AllocaInst(Ty
, Size
, Alignment
);
3120 /// ::= 'free' TypeAndValue
3121 bool LLParser::ParseFree(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3122 Value
*Val
; LocTy Loc
;
3123 if (ParseTypeAndValue(Val
, Loc
, PFS
)) return true;
3124 if (!isa
<PointerType
>(Val
->getType()))
3125 return Error(Loc
, "operand to free must be a pointer");
3126 Inst
= new FreeInst(Val
);
3131 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3132 bool LLParser::ParseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
,
3134 Value
*Val
; LocTy Loc
;
3136 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3137 ParseOptionalCommaAlignment(Alignment
))
3140 if (!isa
<PointerType
>(Val
->getType()) ||
3141 !cast
<PointerType
>(Val
->getType())->getElementType()->isFirstClassType())
3142 return Error(Loc
, "load operand must be a pointer to a first class type");
3144 Inst
= new LoadInst(Val
, "", isVolatile
, Alignment
);
3149 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3150 bool LLParser::ParseStore(Instruction
*&Inst
, PerFunctionState
&PFS
,
3152 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
3154 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3155 ParseToken(lltok::comma
, "expected ',' after store operand") ||
3156 ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
3157 ParseOptionalCommaAlignment(Alignment
))
3160 if (!isa
<PointerType
>(Ptr
->getType()))
3161 return Error(PtrLoc
, "store operand must be a pointer");
3162 if (!Val
->getType()->isFirstClassType())
3163 return Error(Loc
, "store operand must be a first class value");
3164 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
3165 return Error(Loc
, "stored value and pointer type do not match");
3167 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, Alignment
);
3172 /// ::= 'getresult' TypeAndValue ',' uint
3173 /// FIXME: Remove support for getresult in LLVM 3.0
3174 bool LLParser::ParseGetResult(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3175 Value
*Val
; LocTy ValLoc
, EltLoc
;
3177 if (ParseTypeAndValue(Val
, ValLoc
, PFS
) ||
3178 ParseToken(lltok::comma
, "expected ',' after getresult operand") ||
3179 ParseUInt32(Element
, EltLoc
))
3182 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
3183 return Error(ValLoc
, "getresult inst requires an aggregate operand");
3184 if (!ExtractValueInst::getIndexedType(Val
->getType(), Element
))
3185 return Error(EltLoc
, "invalid getresult index for value");
3186 Inst
= ExtractValueInst::Create(Val
, Element
);
3190 /// ParseGetElementPtr
3191 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3192 bool LLParser::ParseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3193 Value
*Ptr
, *Val
; LocTy Loc
, EltLoc
;
3194 if (ParseTypeAndValue(Ptr
, Loc
, PFS
)) return true;
3196 if (!isa
<PointerType
>(Ptr
->getType()))
3197 return Error(Loc
, "base of getelementptr must be a pointer");
3199 SmallVector
<Value
*, 16> Indices
;
3200 while (EatIfPresent(lltok::comma
)) {
3201 if (ParseTypeAndValue(Val
, EltLoc
, PFS
)) return true;
3202 if (!isa
<IntegerType
>(Val
->getType()))
3203 return Error(EltLoc
, "getelementptr index must be an integer");
3204 Indices
.push_back(Val
);
3207 if (!GetElementPtrInst::getIndexedType(Ptr
->getType(),
3208 Indices
.begin(), Indices
.end()))
3209 return Error(Loc
, "invalid getelementptr indices");
3210 Inst
= GetElementPtrInst::Create(Ptr
, Indices
.begin(), Indices
.end());
3214 /// ParseExtractValue
3215 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3216 bool LLParser::ParseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3217 Value
*Val
; LocTy Loc
;
3218 SmallVector
<unsigned, 4> Indices
;
3219 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3220 ParseIndexList(Indices
))
3223 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
3224 return Error(Loc
, "extractvalue operand must be array or struct");
3226 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
3228 return Error(Loc
, "invalid indices for extractvalue");
3229 Inst
= ExtractValueInst::Create(Val
, Indices
.begin(), Indices
.end());
3233 /// ParseInsertValue
3234 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3235 bool LLParser::ParseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3236 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
3237 SmallVector
<unsigned, 4> Indices
;
3238 if (ParseTypeAndValue(Val0
, Loc0
, PFS
) ||
3239 ParseToken(lltok::comma
, "expected comma after insertvalue operand") ||
3240 ParseTypeAndValue(Val1
, Loc1
, PFS
) ||
3241 ParseIndexList(Indices
))
3244 if (!isa
<StructType
>(Val0
->getType()) && !isa
<ArrayType
>(Val0
->getType()))
3245 return Error(Loc0
, "extractvalue operand must be array or struct");
3247 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
3249 return Error(Loc0
, "invalid indices for insertvalue");
3250 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
.begin(), Indices
.end());
3254 //===----------------------------------------------------------------------===//
3255 // Embedded metadata.
3256 //===----------------------------------------------------------------------===//
3258 /// ParseMDNodeVector
3259 /// ::= Element (',' Element)*
3261 /// ::= 'null' | TypeAndValue
3262 bool LLParser::ParseMDNodeVector(SmallVectorImpl
<Value
*> &Elts
) {
3263 assert(Lex
.getKind() == lltok::lbrace
);
3267 if (Lex
.getKind() == lltok::kw_null
) {
3272 if (ParseGlobalTypeAndValue(C
)) return true;
3276 } while (EatIfPresent(lltok::comma
));