1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Assembly/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
30 int yyerror(const char *ErrorMsg
); // Forward declarations to prevent "implicit
31 int yylex(); // declaration" of xxx warnings.
35 std
::string CurFilename
;
39 static Module
*ParserResult
;
41 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
42 // relating to upreferences in the input stream.
44 //#define DEBUG_UPREFS 1
46 #define UR_OUT(X) std::cerr << X
51 #define YYERROR_VERBOSE 1
53 static bool ObsoleteVarArgs
;
54 static bool NewVarArgs
;
55 static BasicBlock
*CurBB
;
56 static GlobalVariable
*CurGV
;
59 // This contains info used when building the body of a function. It is
60 // destroyed when the function is completed.
62 typedef std
::vector
<Value
*> ValueList
; // Numbered defs
64 ResolveDefinitions
(std
::map
<const Type
*,ValueList
> &LateResolvers
,
65 std
::map
<const Type
*,ValueList
> *FutureLateResolvers
= 0);
67 static struct PerModuleInfo
{
68 Module
*CurrentModule
;
69 std
::map
<const Type
*, ValueList
> Values
; // Module level numbered definitions
70 std
::map
<const Type
*,ValueList
> LateResolveValues
;
71 std
::vector
<PATypeHolder
> Types
;
72 std
::map
<ValID
, PATypeHolder
> LateResolveTypes
;
74 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
75 /// how they were referenced and on which line of the input they came from so
76 /// that we can resolve them later and print error messages as appropriate.
77 std
::map
<Value
*, std
::pair
<ValID
, int> > PlaceHolderInfo
;
79 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
80 // references to global values. Global values may be referenced before they
81 // are defined, and if so, the temporary object that they represent is held
82 // here. This is used for forward references of GlobalValues.
84 typedef std
::map
<std
::pair
<const PointerType
*,
85 ValID
>, GlobalValue
*> GlobalRefsType
;
86 GlobalRefsType GlobalRefs
;
89 // If we could not resolve some functions at function compilation time
90 // (calls to functions before they are defined), resolve them now... Types
91 // are resolved when the constant pool has been completely parsed.
93 ResolveDefinitions
(LateResolveValues
);
95 // Check to make sure that all global value forward references have been
98 if
(!GlobalRefs.empty
()) {
99 std
::string UndefinedReferences
= "Unresolved global references exist:\n";
101 for
(GlobalRefsType
::iterator I
= GlobalRefs.begin
(), E
=GlobalRefs.end
();
103 UndefinedReferences
+= " " + I
->first.first
->getDescription
() + " " +
104 I
->first.second.getName
() + "\n";
106 ThrowException
(UndefinedReferences
);
109 // Look for intrinsic functions and CallInst that need to be upgraded
110 for
(Module
::iterator FI
= CurrentModule
->begin
(),
111 FE
= CurrentModule
->end
(); FI
!= FE
; )
112 UpgradeCallsToIntrinsic
(FI
++);
114 Values.clear
(); // Clear out function local definitions
119 // GetForwardRefForGlobal - Check to see if there is a forward reference
120 // for this global. If so, remove it from the GlobalRefs map and return it.
121 // If not, just return null.
122 GlobalValue
*GetForwardRefForGlobal
(const PointerType
*PTy
, ValID ID
) {
123 // Check to see if there is a forward reference to this global variable...
124 // if there is, eliminate it and patch the reference to use the new def'n.
125 GlobalRefsType
::iterator I
= GlobalRefs.find
(std
::make_pair
(PTy
, ID
));
126 GlobalValue
*Ret
= 0;
127 if
(I
!= GlobalRefs.end
()) {
135 static struct PerFunctionInfo
{
136 Function
*CurrentFunction
; // Pointer to current function being created
138 std
::map
<const Type
*, ValueList
> Values
; // Keep track of #'d definitions
139 std
::map
<const Type
*, ValueList
> LateResolveValues
;
140 bool isDeclare
; // Is this function a forward declararation?
142 /// BBForwardRefs - When we see forward references to basic blocks, keep
143 /// track of them here.
144 std
::map
<BasicBlock
*, std
::pair
<ValID
, int> > BBForwardRefs
;
145 std
::vector
<BasicBlock
*> NumberedBlocks
;
148 inline PerFunctionInfo
() {
153 inline
void FunctionStart
(Function
*M
) {
158 void FunctionDone
() {
159 NumberedBlocks.clear
();
161 // Any forward referenced blocks left?
162 if
(!BBForwardRefs.empty
())
163 ThrowException
("Undefined reference to label " +
164 BBForwardRefs.begin
()->first
->getName
());
166 // Resolve all forward references now.
167 ResolveDefinitions
(LateResolveValues
, &CurModule.LateResolveValues
);
169 Values.clear
(); // Clear out function local definitions
173 } CurFun
; // Info for the current function...
175 static bool inFunctionScope
() { return CurFun.CurrentFunction
!= 0; }
178 //===----------------------------------------------------------------------===//
179 // Code to handle definitions of all the types
180 //===----------------------------------------------------------------------===//
182 static int InsertValue
(Value
*V
,
183 std
::map
<const Type
*,ValueList
> &ValueTab
= CurFun.Values
) {
184 if
(V
->hasName
()) return
-1; // Is this a numbered definition?
186 // Yes, insert the value into the value table...
187 ValueList
&List
= ValueTab
[V
->getType
()];
189 return List.size
()-1;
192 static const Type
*getTypeVal
(const ValID
&D
, bool DoNotImprovise
= false
) {
194 case ValID
::NumberVal
: // Is it a numbered definition?
195 // Module constants occupy the lowest numbered slots...
196 if
((unsigned)D.Num
< CurModule.Types.size
())
197 return CurModule.Types
[(unsigned)D.Num
];
199 case ValID
::NameVal
: // Is it a named definition?
200 if
(const Type
*N
= CurModule.CurrentModule
->getTypeByName
(D.Name
)) {
201 D.destroy
(); // Free old strdup'd memory...
206 ThrowException
("Internal parser error: Invalid symbol type reference!");
209 // If we reached here, we referenced either a symbol that we don't know about
210 // or an id number that hasn't been read yet. We may be referencing something
211 // forward, so just create an entry to be resolved later and get to it...
213 if
(DoNotImprovise
) return
0; // Do we just want a null to be returned?
216 if
(inFunctionScope
()) {
217 if
(D.Type
== ValID
::NameVal
)
218 ThrowException
("Reference to an undefined type: '" + D.getName
() + "'");
220 ThrowException
("Reference to an undefined type: #" + itostr
(D.Num
));
223 std
::map
<ValID
, PATypeHolder
>::iterator I
=CurModule.LateResolveTypes.find
(D
);
224 if
(I
!= CurModule.LateResolveTypes.end
())
227 Type
*Typ
= OpaqueType
::get
();
228 CurModule.LateResolveTypes.insert
(std
::make_pair
(D
, Typ
));
232 static Value
*lookupInSymbolTable
(const Type
*Ty
, const std
::string &Name
) {
233 SymbolTable
&SymTab
=
234 inFunctionScope
() ? CurFun.CurrentFunction
->getSymbolTable
() :
235 CurModule.CurrentModule
->getSymbolTable
();
236 return SymTab.lookup
(Ty
, Name
);
239 // getValNonImprovising - Look up the value specified by the provided type and
240 // the provided ValID. If the value exists and has already been defined, return
241 // it. Otherwise return null.
243 static Value
*getValNonImprovising
(const Type
*Ty
, const ValID
&D
) {
244 if
(isa
<FunctionType
>(Ty
))
245 ThrowException
("Functions are not values and "
246 "must be referenced as pointers");
249 case ValID
::NumberVal
: { // Is it a numbered definition?
250 unsigned Num
= (unsigned)D.Num
;
252 // Module constants occupy the lowest numbered slots...
253 std
::map
<const Type
*,ValueList
>::iterator VI
= CurModule.Values.find
(Ty
);
254 if
(VI
!= CurModule.Values.end
()) {
255 if
(Num
< VI
->second.size
())
256 return VI
->second
[Num
];
257 Num
-= VI
->second.size
();
260 // Make sure that our type is within bounds
261 VI
= CurFun.Values.find
(Ty
);
262 if
(VI
== CurFun.Values.end
()) return
0;
264 // Check that the number is within bounds...
265 if
(VI
->second.size
() <= Num
) return
0;
267 return VI
->second
[Num
];
270 case ValID
::NameVal
: { // Is it a named definition?
271 Value
*N
= lookupInSymbolTable
(Ty
, std
::string(D.Name
));
272 if
(N
== 0) return
0;
274 D.destroy
(); // Free old strdup'd memory...
278 // Check to make sure that "Ty" is an integral type, and that our
279 // value will fit into the specified type...
280 case ValID
::ConstSIntVal
: // Is it a constant pool reference??
281 if
(!ConstantSInt
::isValueValidForType
(Ty
, D.ConstPool64
))
282 ThrowException
("Signed integral constant '" +
283 itostr
(D.ConstPool64
) + "' is invalid for type '" +
284 Ty
->getDescription
() + "'!");
285 return ConstantSInt
::get
(Ty
, D.ConstPool64
);
287 case ValID
::ConstUIntVal
: // Is it an unsigned const pool reference?
288 if
(!ConstantUInt
::isValueValidForType
(Ty
, D.UConstPool64
)) {
289 if
(!ConstantSInt
::isValueValidForType
(Ty
, D.ConstPool64
)) {
290 ThrowException
("Integral constant '" + utostr
(D.UConstPool64
) +
291 "' is invalid or out of range!");
292 } else
{ // This is really a signed reference. Transmogrify.
293 return ConstantSInt
::get
(Ty
, D.ConstPool64
);
296 return ConstantUInt
::get
(Ty
, D.UConstPool64
);
299 case ValID
::ConstFPVal
: // Is it a floating point const pool reference?
300 if
(!ConstantFP
::isValueValidForType
(Ty
, D.ConstPoolFP
))
301 ThrowException
("FP constant invalid for type!!");
302 return ConstantFP
::get
(Ty
, D.ConstPoolFP
);
304 case ValID
::ConstNullVal
: // Is it a null value?
305 if
(!isa
<PointerType
>(Ty
))
306 ThrowException
("Cannot create a a non pointer null!");
307 return ConstantPointerNull
::get
(cast
<PointerType
>(Ty
));
309 case ValID
::ConstUndefVal
: // Is it an undef value?
310 return UndefValue
::get
(Ty
);
312 case ValID
::ConstZeroVal
: // Is it a zero value?
313 return Constant
::getNullValue
(Ty
);
315 case ValID
::ConstantVal
: // Fully resolved constant?
316 if
(D.ConstantValue
->getType
() != Ty
)
317 ThrowException
("Constant expression type different from required type!");
318 return D.ConstantValue
;
320 case ValID
::InlineAsmVal
: { // Inline asm expression
321 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
322 const FunctionType
*FTy
=
323 PTy ? dyn_cast
<FunctionType
>(PTy
->getElementType
()) : 0;
324 if
(!FTy ||
!InlineAsm
::Verify
(FTy
, D.IAD
->Constraints
))
325 ThrowException
("Invalid type for asm constraint string!");
326 InlineAsm
*IA
= InlineAsm
::get
(FTy
, D.IAD
->AsmString
, D.IAD
->Constraints
,
327 D.IAD
->HasSideEffects
);
328 D.destroy
(); // Free InlineAsmDescriptor.
332 assert
(0 && "Unhandled case!");
336 assert
(0 && "Unhandled case!");
340 // getVal - This function is identical to getValNonImprovising, except that if a
341 // value is not already defined, it "improvises" by creating a placeholder var
342 // that looks and acts just like the requested variable. When the value is
343 // defined later, all uses of the placeholder variable are replaced with the
346 static Value
*getVal
(const Type
*Ty
, const ValID
&ID
) {
347 if
(Ty
== Type
::LabelTy
)
348 ThrowException
("Cannot use a basic block here");
350 // See if the value has already been defined.
351 Value
*V
= getValNonImprovising
(Ty
, ID
);
354 if
(!Ty
->isFirstClassType
() && !isa
<OpaqueType
>(Ty
))
355 ThrowException
("Invalid use of a composite type!");
357 // If we reached here, we referenced either a symbol that we don't know about
358 // or an id number that hasn't been read yet. We may be referencing something
359 // forward, so just create an entry to be resolved later and get to it...
361 V
= new Argument
(Ty
);
363 // Remember where this forward reference came from. FIXME, shouldn't we try
364 // to recycle these things??
365 CurModule.PlaceHolderInfo.insert
(std
::make_pair
(V
, std
::make_pair
(ID
,
368 if
(inFunctionScope
())
369 InsertValue
(V
, CurFun.LateResolveValues
);
371 InsertValue
(V
, CurModule.LateResolveValues
);
375 /// getBBVal - This is used for two purposes:
376 /// * If isDefinition is true, a new basic block with the specified ID is being
378 /// * If isDefinition is true, this is a reference to a basic block, which may
379 /// or may not be a forward reference.
381 static BasicBlock
*getBBVal
(const ValID
&ID
, bool isDefinition
= false
) {
382 assert
(inFunctionScope
() && "Can't get basic block at global scope!");
387 default
: ThrowException
("Illegal label reference " + ID.getName
());
388 case ValID
::NumberVal
: // Is it a numbered definition?
389 if
(unsigned(ID.Num
) >= CurFun.NumberedBlocks.size
())
390 CurFun.NumberedBlocks.resize
(ID.Num
+1);
391 BB
= CurFun.NumberedBlocks
[ID.Num
];
393 case ValID
::NameVal
: // Is it a named definition?
395 if
(Value
*N
= CurFun.CurrentFunction
->
396 getSymbolTable
().lookup
(Type
::LabelTy
, Name
))
397 BB
= cast
<BasicBlock
>(N
);
401 // See if the block has already been defined.
403 // If this is the definition of the block, make sure the existing value was
404 // just a forward reference. If it was a forward reference, there will be
405 // an entry for it in the PlaceHolderInfo map.
406 if
(isDefinition
&& !CurFun.BBForwardRefs.erase
(BB
))
407 // The existing value was a definition, not a forward reference.
408 ThrowException
("Redefinition of label " + ID.getName
());
410 ID.destroy
(); // Free strdup'd memory.
414 // Otherwise this block has not been seen before.
415 BB
= new BasicBlock
("", CurFun.CurrentFunction
);
416 if
(ID.Type
== ValID
::NameVal
) {
417 BB
->setName
(ID.Name
);
419 CurFun.NumberedBlocks
[ID.Num
] = BB
;
422 // If this is not a definition, keep track of it so we can use it as a forward
425 // Remember where this forward reference came from.
426 CurFun.BBForwardRefs
[BB
] = std
::make_pair
(ID
, llvmAsmlineno
);
428 // The forward declaration could have been inserted anywhere in the
429 // function: insert it into the correct place now.
430 CurFun.CurrentFunction
->getBasicBlockList
().remove
(BB
);
431 CurFun.CurrentFunction
->getBasicBlockList
().push_back
(BB
);
438 //===----------------------------------------------------------------------===//
439 // Code to handle forward references in instructions
440 //===----------------------------------------------------------------------===//
442 // This code handles the late binding needed with statements that reference
443 // values not defined yet... for example, a forward branch, or the PHI node for
446 // This keeps a table (CurFun.LateResolveValues) of all such forward references
447 // and back patchs after we are done.
450 // ResolveDefinitions - If we could not resolve some defs at parsing
451 // time (forward branches, phi functions for loops, etc...) resolve the
455 ResolveDefinitions
(std
::map
<const Type
*,ValueList
> &LateResolvers
,
456 std
::map
<const Type
*,ValueList
> *FutureLateResolvers
) {
457 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
458 for
(std
::map
<const Type
*,ValueList
>::iterator LRI
= LateResolvers.begin
(),
459 E
= LateResolvers.end
(); LRI
!= E
; ++LRI
) {
460 ValueList
&List
= LRI
->second
;
461 while
(!List.empty
()) {
462 Value
*V
= List.back
();
465 std
::map
<Value
*, std
::pair
<ValID
, int> >::iterator PHI
=
466 CurModule.PlaceHolderInfo.find
(V
);
467 assert
(PHI
!= CurModule.PlaceHolderInfo.end
() && "Placeholder error!");
469 ValID
&DID
= PHI
->second.first
;
471 Value
*TheRealValue
= getValNonImprovising
(LRI
->first
, DID
);
473 V
->replaceAllUsesWith
(TheRealValue
);
475 CurModule.PlaceHolderInfo.erase
(PHI
);
476 } else if
(FutureLateResolvers
) {
477 // Functions have their unresolved items forwarded to the module late
479 InsertValue
(V
, *FutureLateResolvers
);
481 if
(DID.Type
== ValID
::NameVal
)
482 ThrowException
("Reference to an invalid definition: '" +DID.getName
()+
483 "' of type '" + V
->getType
()->getDescription
() + "'",
486 ThrowException
("Reference to an invalid definition: #" +
487 itostr
(DID.Num
) + " of type '" +
488 V
->getType
()->getDescription
() + "'",
494 LateResolvers.clear
();
497 // ResolveTypeTo - A brand new type was just declared. This means that (if
498 // name is not null) things referencing Name can be resolved. Otherwise, things
499 // refering to the number can be resolved. Do this now.
501 static void ResolveTypeTo
(char *Name
, const Type
*ToTy
) {
503 if
(Name
) D
= ValID
::create
(Name
);
504 else D
= ValID
::create
((int)CurModule.Types.size
());
506 std
::map
<ValID
, PATypeHolder
>::iterator I
=
507 CurModule.LateResolveTypes.find
(D
);
508 if
(I
!= CurModule.LateResolveTypes.end
()) {
509 ((DerivedType
*)I
->second.get
())->refineAbstractTypeTo
(ToTy
);
510 CurModule.LateResolveTypes.erase
(I
);
514 // setValueName - Set the specified value to the name given. The name may be
515 // null potentially, in which case this is a noop. The string passed in is
516 // assumed to be a malloc'd string buffer, and is free'd by this function.
518 static void setValueName
(Value
*V
, char *NameStr
) {
520 std
::string Name
(NameStr
); // Copy string
521 free
(NameStr
); // Free old string
523 if
(V
->getType
() == Type
::VoidTy
)
524 ThrowException
("Can't assign name '" + Name
+"' to value with void type!");
526 assert
(inFunctionScope
() && "Must be in function scope!");
527 SymbolTable
&ST
= CurFun.CurrentFunction
->getSymbolTable
();
528 if
(ST.lookup
(V
->getType
(), Name
))
529 ThrowException
("Redefinition of value named '" + Name
+ "' in the '" +
530 V
->getType
()->getDescription
() + "' type plane!");
537 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
538 /// this is a declaration, otherwise it is a definition.
539 static GlobalVariable
*
540 ParseGlobalVariable
(char *NameStr
,GlobalValue
::LinkageTypes Linkage
,
541 bool isConstantGlobal
, const Type
*Ty
,
542 Constant
*Initializer
) {
543 if
(isa
<FunctionType
>(Ty
))
544 ThrowException
("Cannot declare global vars of function type!");
546 const PointerType
*PTy
= PointerType
::get
(Ty
);
550 Name
= NameStr
; // Copy string
551 free
(NameStr
); // Free old string
554 // See if this global value was forward referenced. If so, recycle the
558 ID
= ValID
::create
((char*)Name.c_str
());
560 ID
= ValID
::create
((int)CurModule.Values
[PTy
].size
());
563 if
(GlobalValue
*FWGV
= CurModule.GetForwardRefForGlobal
(PTy
, ID
)) {
564 // Move the global to the end of the list, from whereever it was
565 // previously inserted.
566 GlobalVariable
*GV
= cast
<GlobalVariable
>(FWGV
);
567 CurModule.CurrentModule
->getGlobalList
().remove
(GV
);
568 CurModule.CurrentModule
->getGlobalList
().push_back
(GV
);
569 GV
->setInitializer
(Initializer
);
570 GV
->setLinkage
(Linkage
);
571 GV
->setConstant
(isConstantGlobal
);
572 InsertValue
(GV
, CurModule.Values
);
576 // If this global has a name, check to see if there is already a definition
577 // of this global in the module. If so, merge as appropriate. Note that
578 // this is really just a hack around problems in the CFE. :(
580 // We are a simple redefinition of a value, check to see if it is defined
581 // the same as the old one.
582 if
(GlobalVariable
*EGV
=
583 CurModule.CurrentModule
->getGlobalVariable
(Name
, Ty
)) {
584 // We are allowed to redefine a global variable in two circumstances:
585 // 1. If at least one of the globals is uninitialized or
586 // 2. If both initializers have the same value.
588 if
(!EGV
->hasInitializer
() ||
!Initializer ||
589 EGV
->getInitializer
() == Initializer
) {
591 // Make sure the existing global version gets the initializer! Make
592 // sure that it also gets marked const if the new version is.
593 if
(Initializer
&& !EGV
->hasInitializer
())
594 EGV
->setInitializer
(Initializer
);
595 if
(isConstantGlobal
)
596 EGV
->setConstant
(true
);
597 EGV
->setLinkage
(Linkage
);
601 ThrowException
("Redefinition of global variable named '" + Name
+
602 "' in the '" + Ty
->getDescription
() + "' type plane!");
606 // Otherwise there is no existing GV to use, create one now.
608 new GlobalVariable
(Ty
, isConstantGlobal
, Linkage
, Initializer
, Name
,
609 CurModule.CurrentModule
);
610 InsertValue
(GV
, CurModule.Values
);
614 // setTypeName - Set the specified type to the name given. The name may be
615 // null potentially, in which case this is a noop. The string passed in is
616 // assumed to be a malloc'd string buffer, and is freed by this function.
618 // This function returns true if the type has already been defined, but is
619 // allowed to be redefined in the specified context. If the name is a new name
620 // for the type plane, it is inserted and false is returned.
621 static bool setTypeName
(const Type
*T
, char *NameStr
) {
622 assert
(!inFunctionScope
() && "Can't give types function-local names!");
623 if
(NameStr
== 0) return false
;
625 std
::string Name
(NameStr
); // Copy string
626 free
(NameStr
); // Free old string
628 // We don't allow assigning names to void type
629 if
(T
== Type
::VoidTy
)
630 ThrowException
("Can't assign name '" + Name
+ "' to the void type!");
632 // Set the type name, checking for conflicts as we do so.
633 bool AlreadyExists
= CurModule.CurrentModule
->addTypeName
(Name
, T
);
635 if
(AlreadyExists
) { // Inserting a name that is already defined???
636 const Type
*Existing
= CurModule.CurrentModule
->getTypeByName
(Name
);
637 assert
(Existing
&& "Conflict but no matching type?");
639 // There is only one case where this is allowed: when we are refining an
640 // opaque type. In this case, Existing will be an opaque type.
641 if
(const OpaqueType
*OpTy
= dyn_cast
<OpaqueType
>(Existing
)) {
642 // We ARE replacing an opaque type!
643 const_cast
<OpaqueType
*>(OpTy
)->refineAbstractTypeTo
(T
);
647 // Otherwise, this is an attempt to redefine a type. That's okay if
648 // the redefinition is identical to the original. This will be so if
649 // Existing and T point to the same Type object. In this one case we
650 // allow the equivalent redefinition.
651 if
(Existing
== T
) return true
; // Yes, it's equal.
653 // Any other kind of (non-equivalent) redefinition is an error.
654 ThrowException
("Redefinition of type named '" + Name
+ "' in the '" +
655 T
->getDescription
() + "' type plane!");
661 //===----------------------------------------------------------------------===//
662 // Code for handling upreferences in type names...
665 // TypeContains - Returns true if Ty directly contains E in it.
667 static bool TypeContains
(const Type
*Ty
, const Type
*E
) {
668 return std
::find
(Ty
->subtype_begin
(), Ty
->subtype_end
(),
669 E
) != Ty
->subtype_end
();
674 // NestingLevel - The number of nesting levels that need to be popped before
675 // this type is resolved.
676 unsigned NestingLevel
;
678 // LastContainedTy - This is the type at the current binding level for the
679 // type. Every time we reduce the nesting level, this gets updated.
680 const Type
*LastContainedTy
;
682 // UpRefTy - This is the actual opaque type that the upreference is
686 UpRefRecord
(unsigned NL
, OpaqueType
*URTy
)
687 : NestingLevel
(NL
), LastContainedTy
(URTy
), UpRefTy
(URTy
) {}
691 // UpRefs - A list of the outstanding upreferences that need to be resolved.
692 static std
::vector
<UpRefRecord
> UpRefs
;
694 /// HandleUpRefs - Every time we finish a new layer of types, this function is
695 /// called. It loops through the UpRefs vector, which is a list of the
696 /// currently active types. For each type, if the up reference is contained in
697 /// the newly completed type, we decrement the level count. When the level
698 /// count reaches zero, the upreferenced type is the type that is passed in:
699 /// thus we can complete the cycle.
701 static PATypeHolder HandleUpRefs
(const Type
*ty
) {
702 if
(!ty
->isAbstract
()) return ty
;
704 UR_OUT
("Type '" << Ty
->getDescription
() <<
705 "' newly formed. Resolving upreferences.\n" <<
706 UpRefs.size
() << " upreferences active!\n");
708 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
709 // to zero), we resolve them all together before we resolve them to Ty. At
710 // the end of the loop, if there is anything to resolve to Ty, it will be in
712 OpaqueType
*TypeToResolve
= 0;
714 for
(unsigned i
= 0; i
!= UpRefs.size
(); ++i
) {
715 UR_OUT
(" UR#" << i
<< " - TypeContains(" << Ty
->getDescription
() << ", "
716 << UpRefs
[i
].second
->getDescription
() << ") = "
717 << (TypeContains
(Ty
, UpRefs
[i
].second
) ?
"true" : "false") << "\n");
718 if
(TypeContains
(Ty
, UpRefs
[i
].LastContainedTy
)) {
719 // Decrement level of upreference
720 unsigned Level
= --UpRefs
[i
].NestingLevel
;
721 UpRefs
[i
].LastContainedTy
= Ty
;
722 UR_OUT
(" Uplevel Ref Level = " << Level
<< "\n");
723 if
(Level
== 0) { // Upreference should be resolved!
724 if
(!TypeToResolve
) {
725 TypeToResolve
= UpRefs
[i
].UpRefTy
;
727 UR_OUT
(" * Resolving upreference for "
728 << UpRefs
[i
].second
->getDescription
() << "\n";
729 std
::string OldName
= UpRefs
[i
].UpRefTy
->getDescription
());
730 UpRefs
[i
].UpRefTy
->refineAbstractTypeTo
(TypeToResolve
);
731 UR_OUT
(" * Type '" << OldName
<< "' refined upreference to: "
732 << (const void*)Ty
<< ", " << Ty
->getDescription
() << "\n");
734 UpRefs.erase
(UpRefs.begin
()+i
); // Remove from upreference list...
735 --i
; // Do not skip the next element...
741 UR_OUT
(" * Resolving upreference for "
742 << UpRefs
[i
].second
->getDescription
() << "\n";
743 std
::string OldName
= TypeToResolve
->getDescription
());
744 TypeToResolve
->refineAbstractTypeTo
(Ty
);
751 // common code from the two 'RunVMAsmParser' functions
752 static Module
* RunParser
(Module
* M
) {
754 llvmAsmlineno
= 1; // Reset the current line number...
755 ObsoleteVarArgs
= false
;
758 CurModule.CurrentModule
= M
;
759 yyparse(); // Parse the file, potentially throwing exception
761 Module
*Result
= ParserResult
;
764 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
767 if
((F
= Result
->getNamedFunction
("llvm.va_start"))
768 && F
->getFunctionType
()->getNumParams
() == 0)
769 ObsoleteVarArgs
= true
;
770 if
((F
= Result
->getNamedFunction
("llvm.va_copy"))
771 && F
->getFunctionType
()->getNumParams
() == 1)
772 ObsoleteVarArgs
= true
;
775 if
(ObsoleteVarArgs
&& NewVarArgs
)
776 ThrowException
("This file is corrupt: it uses both new and old style varargs");
778 if
(ObsoleteVarArgs
) {
779 if
(Function
* F
= Result
->getNamedFunction
("llvm.va_start")) {
780 if
(F
->arg_size
() != 0)
781 ThrowException
("Obsolete va_start takes 0 argument!");
785 //bar = alloca typeof(foo)
789 const Type
* RetTy
= Type
::getPrimitiveType
(Type
::VoidTyID
);
790 const Type
* ArgTy
= F
->getFunctionType
()->getReturnType
();
791 const Type
* ArgTyPtr
= PointerType
::get
(ArgTy
);
792 Function
* NF
= Result
->getOrInsertFunction
("llvm.va_start",
793 RetTy
, ArgTyPtr
, (Type
*)0);
795 while
(!F
->use_empty
()) {
796 CallInst
* CI
= cast
<CallInst
>(F
->use_back
());
797 AllocaInst
* bar
= new AllocaInst
(ArgTy
, 0, "vastart.fix.1", CI
);
798 new CallInst
(NF
, bar
, "", CI
);
799 Value
* foo
= new LoadInst
(bar
, "vastart.fix.2", CI
);
800 CI
->replaceAllUsesWith
(foo
);
801 CI
->getParent
()->getInstList
().erase
(CI
);
803 Result
->getFunctionList
().erase
(F
);
806 if
(Function
* F
= Result
->getNamedFunction
("llvm.va_end")) {
807 if
(F
->arg_size
() != 1)
808 ThrowException
("Obsolete va_end takes 1 argument!");
812 //bar = alloca 1 of typeof(foo)
814 const Type
* RetTy
= Type
::getPrimitiveType
(Type
::VoidTyID
);
815 const Type
* ArgTy
= F
->getFunctionType
()->getParamType
(0);
816 const Type
* ArgTyPtr
= PointerType
::get
(ArgTy
);
817 Function
* NF
= Result
->getOrInsertFunction
("llvm.va_end",
818 RetTy
, ArgTyPtr
, (Type
*)0);
820 while
(!F
->use_empty
()) {
821 CallInst
* CI
= cast
<CallInst
>(F
->use_back
());
822 AllocaInst
* bar
= new AllocaInst
(ArgTy
, 0, "vaend.fix.1", CI
);
823 new StoreInst
(CI
->getOperand
(1), bar
, CI
);
824 new CallInst
(NF
, bar
, "", CI
);
825 CI
->getParent
()->getInstList
().erase
(CI
);
827 Result
->getFunctionList
().erase
(F
);
830 if
(Function
* F
= Result
->getNamedFunction
("llvm.va_copy")) {
831 if
(F
->arg_size
() != 1)
832 ThrowException
("Obsolete va_copy takes 1 argument!");
835 //a = alloca 1 of typeof(foo)
836 //b = alloca 1 of typeof(foo)
841 const Type
* RetTy
= Type
::getPrimitiveType
(Type
::VoidTyID
);
842 const Type
* ArgTy
= F
->getFunctionType
()->getReturnType
();
843 const Type
* ArgTyPtr
= PointerType
::get
(ArgTy
);
844 Function
* NF
= Result
->getOrInsertFunction
("llvm.va_copy",
845 RetTy
, ArgTyPtr
, ArgTyPtr
,
848 while
(!F
->use_empty
()) {
849 CallInst
* CI
= cast
<CallInst
>(F
->use_back
());
850 AllocaInst
* a
= new AllocaInst
(ArgTy
, 0, "vacopy.fix.1", CI
);
851 AllocaInst
* b
= new AllocaInst
(ArgTy
, 0, "vacopy.fix.2", CI
);
852 new StoreInst
(CI
->getOperand
(1), b
, CI
);
853 new CallInst
(NF
, a
, b
, "", CI
);
854 Value
* foo
= new LoadInst
(a
, "vacopy.fix.3", CI
);
855 CI
->replaceAllUsesWith
(foo
);
856 CI
->getParent
()->getInstList
().erase
(CI
);
858 Result
->getFunctionList
().erase
(F
);
866 //===----------------------------------------------------------------------===//
867 // RunVMAsmParser - Define an interface to this parser
868 //===----------------------------------------------------------------------===//
870 Module
*llvm
::RunVMAsmParser
(const std
::string &Filename
, FILE *F
) {
873 CurFilename
= Filename
;
874 return RunParser
(new Module
(CurFilename
));
877 Module
*llvm
::RunVMAsmParser
(const char * AsmString
, Module
* M
) {
878 set_scan_string
(AsmString
);
880 CurFilename
= "from_memory";
882 return RunParser
(new Module
(CurFilename
));
891 llvm
::Module
*ModuleVal
;
892 llvm
::Function
*FunctionVal
;
893 std
::pair
<llvm
::PATypeHolder
*, char*> *ArgVal
;
894 llvm
::BasicBlock
*BasicBlockVal
;
895 llvm
::TerminatorInst
*TermInstVal
;
896 llvm
::Instruction
*InstVal
;
897 llvm
::Constant
*ConstVal
;
899 const llvm
::Type
*PrimType
;
900 llvm
::PATypeHolder
*TypeVal
;
901 llvm
::Value
*ValueVal
;
903 std
::vector
<std
::pair
<llvm
::PATypeHolder
*,char*> > *ArgList
;
904 std
::vector
<llvm
::Value
*> *ValueList
;
905 std
::list
<llvm
::PATypeHolder
> *TypeList
;
906 // Represent the RHS of PHI node
907 std
::list
<std
::pair
<llvm
::Value
*,
908 llvm
::BasicBlock
*> > *PHIList
;
909 std
::vector
<std
::pair
<llvm
::Constant
*, llvm
::BasicBlock
*> > *JumpTable
;
910 std
::vector
<llvm
::Constant
*> *ConstVector
;
912 llvm
::GlobalValue
::LinkageTypes Linkage
;
920 char *StrVal
; // This memory is strdup'd!
921 llvm
::ValID ValIDVal
; // strdup'd memory maybe!
923 llvm
::Instruction
::BinaryOps BinaryOpVal
;
924 llvm
::Instruction
::TermOps TermOpVal
;
925 llvm
::Instruction
::MemoryOps MemOpVal
;
926 llvm
::Instruction
::OtherOps OtherOpVal
;
927 llvm
::Module
::Endianness Endianness
;
930 %type
<ModuleVal
> Module FunctionList
931 %type
<FunctionVal
> Function FunctionProto FunctionHeader BasicBlockList
932 %type
<BasicBlockVal
> BasicBlock InstructionList
933 %type
<TermInstVal
> BBTerminatorInst
934 %type
<InstVal
> Inst InstVal MemoryInst
935 %type
<ConstVal
> ConstVal ConstExpr
936 %type
<ConstVector
> ConstVector
937 %type
<ArgList
> ArgList ArgListH
938 %type
<ArgVal
> ArgVal
939 %type
<PHIList
> PHIList
940 %type
<ValueList
> ValueRefList ValueRefListE
// For call param lists
941 %type
<ValueList
> IndexList
// For GEP derived indices
942 %type
<TypeList
> TypeListI ArgTypeListI
943 %type
<JumpTable
> JumpTable
944 %type
<BoolVal
> GlobalType
// GLOBAL or CONSTANT?
945 %type
<BoolVal
> OptVolatile
// 'volatile' or not
946 %type
<BoolVal
> OptTailCall
// TAIL CALL or plain CALL.
947 %type
<BoolVal
> OptSideEffect
// 'sideeffect' or not.
948 %type
<Linkage
> OptLinkage
949 %type
<Endianness
> BigOrLittle
951 // ValueRef - Unresolved reference to a definition or BB
952 %type
<ValIDVal
> ValueRef ConstValueRef SymbolicValueRef
953 %type
<ValueVal
> ResolvedVal
// <type> <valref> pair
954 // Tokens and types for handling constant integer values
956 // ESINT64VAL - A negative number within long long range
957 %token
<SInt64Val
> ESINT64VAL
959 // EUINT64VAL - A positive number within uns. long long range
960 %token
<UInt64Val
> EUINT64VAL
961 %type
<SInt64Val
> EINT64VAL
963 %token
<SIntVal
> SINTVAL
// Signed 32 bit ints...
964 %token
<UIntVal
> UINTVAL
// Unsigned 32 bit ints...
965 %type
<SIntVal
> INTVAL
966 %token
<FPVal
> FPVAL
// Float or Double constant
969 %type
<TypeVal
> Types TypesV UpRTypes UpRTypesV
970 %type
<PrimType
> SIntType UIntType IntType FPType PrimType
// Classifications
971 %token
<PrimType
> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
972 %token
<PrimType
> FLOAT DOUBLE TYPE LABEL
974 %token
<StrVal
> VAR_ID LABELSTR STRINGCONSTANT
975 %type
<StrVal
> Name OptName OptAssign
976 %type
<UIntVal
> OptAlign OptCAlign
977 %type
<StrVal
> OptSection SectionString
979 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
980 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
981 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
982 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
983 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
984 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
985 %type
<UIntVal
> OptCallingConv
987 // Basic Block Terminating Operators
988 %token
<TermOpVal
> RET BR SWITCH INVOKE UNWIND UNREACHABLE
991 %type
<BinaryOpVal
> ArithmeticOps LogicalOps SetCondOps
// Binops Subcatagories
992 %token
<BinaryOpVal
> ADD SUB MUL DIV REM AND OR XOR
993 %token
<BinaryOpVal
> SETLE SETGE SETLT SETGT SETEQ SETNE
// Binary Comarators
995 // Memory Instructions
996 %token
<MemOpVal
> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
999 %type
<OtherOpVal
> ShiftOps
1000 %token
<OtherOpVal
> PHI_TOK CAST SELECT SHL SHR VAARG
1001 %token
<OtherOpVal
> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1002 %token VAARG_old VANEXT_old
//OBSOLETE
1008 // Handle constant integer size restriction and conversion...
1012 if
($1 > (uint32_t)INT32_MAX
) // Outside of my range!
1013 ThrowException
("Value too large for type!");
1018 EINT64VAL
: ESINT64VAL
; // These have same type and can't cause problems...
1019 EINT64VAL
: EUINT64VAL
{
1020 if
($1 > (uint64_t)INT64_MAX
) // Outside of my range!
1021 ThrowException
("Value too large for type!");
1025 // Operations that are notably excluded from this list include:
1026 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1028 ArithmeticOps: ADD | SUB | MUL | DIV | REM
;
1029 LogicalOps
: AND | OR | XOR
;
1030 SetCondOps
: SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
;
1032 ShiftOps
: SHL | SHR
;
1034 // These are some types that allow classification if we only want a particular
1035 // thing... for example, only a signed, unsigned, or integral type.
1036 SIntType
: LONG | INT | SHORT | SBYTE
;
1037 UIntType
: ULONG | UINT | USHORT | UBYTE
;
1038 IntType
: SIntType | UIntType
;
1039 FPType
: FLOAT | DOUBLE
;
1041 // OptAssign - Value producing statements have an optional assignment component
1042 OptAssign
: Name
'=' {
1049 OptLinkage
: INTERNAL
{ $$
= GlobalValue
::InternalLinkage
; } |
1050 LINKONCE
{ $$
= GlobalValue
::LinkOnceLinkage
; } |
1051 WEAK
{ $$
= GlobalValue
::WeakLinkage
; } |
1052 APPENDING
{ $$
= GlobalValue
::AppendingLinkage
; } |
1053 /*empty*/ { $$
= GlobalValue
::ExternalLinkage
; };
1055 OptCallingConv
: /*empty*/ { $$
= CallingConv
::C
; } |
1056 CCC_TOK
{ $$
= CallingConv
::C
; } |
1057 CSRETCC_TOK
{ $$
= CallingConv
::CSRet
; } |
1058 FASTCC_TOK
{ $$
= CallingConv
::Fast
; } |
1059 COLDCC_TOK
{ $$
= CallingConv
::Cold
; } |
1061 if
((unsigned)$2 != $2)
1062 ThrowException
("Calling conv too large!");
1066 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1067 // a comma before it.
1068 OptAlign
: /*empty*/ { $$
= 0; } |
1071 if
($$
!= 0 && !isPowerOf2_32
($$
))
1072 ThrowException
("Alignment must be a power of two!");
1074 OptCAlign
: /*empty*/ { $$
= 0; } |
1075 ',' ALIGN EUINT64VAL
{
1077 if
($$
!= 0 && !isPowerOf2_32
($$
))
1078 ThrowException
("Alignment must be a power of two!");
1082 SectionString
: SECTION STRINGCONSTANT
{
1083 for
(unsigned i
= 0, e
= strlen
($2); i
!= e
; ++i
)
1084 if
($2[i
] == '"' ||
$2[i
] == '\\')
1085 ThrowException
("Invalid character in section name!");
1089 OptSection
: /*empty*/ { $$
= 0; } |
1090 SectionString
{ $$
= $1; };
1092 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1093 // is set to be the global we are processing.
1095 GlobalVarAttributes
: /* empty */ {} |
1096 ',' GlobalVarAttribute GlobalVarAttributes
{};
1097 GlobalVarAttribute
: SectionString
{
1098 CurGV
->setSection
($1);
1101 | ALIGN EUINT64VAL
{
1102 if
($2 != 0 && !isPowerOf2_32
($2))
1103 ThrowException
("Alignment must be a power of two!");
1104 CurGV
->setAlignment
($2);
1107 //===----------------------------------------------------------------------===//
1108 // Types includes all predefined types... except void, because it can only be
1109 // used in specific contexts (function returning void for example). To have
1110 // access to it, a user must explicitly use TypesV.
1113 // TypesV includes all of 'Types', but it also includes the void type.
1114 TypesV
: Types | VOID
{ $$
= new PATypeHolder
($1); };
1115 UpRTypesV
: UpRTypes | VOID
{ $$
= new PATypeHolder
($1); };
1118 if
(!UpRefs.empty
())
1119 ThrowException
("Invalid upreference in type: " + (*$1)->getDescription
());
1124 // Derived types are added later...
1126 PrimType
: BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
;
1127 PrimType
: LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL
;
1129 $$
= new PATypeHolder
(OpaqueType
::get
());
1132 $$
= new PATypeHolder
($1);
1134 UpRTypes
: SymbolicValueRef
{ // Named types are also simple types...
1135 $$
= new PATypeHolder
(getTypeVal
($1));
1138 // Include derived types in the Types production.
1140 UpRTypes
: '\\' EUINT64VAL
{ // Type UpReference
1141 if
($2 > (uint64_t)~
0U) ThrowException
("Value out of range!");
1142 OpaqueType
*OT
= OpaqueType
::get
(); // Use temporary placeholder
1143 UpRefs.push_back
(UpRefRecord
((unsigned)$2, OT
)); // Add to vector...
1144 $$
= new PATypeHolder
(OT
);
1145 UR_OUT
("New Upreference!\n");
1147 | UpRTypesV
'(' ArgTypeListI
')' { // Function derived type?
1148 std
::vector
<const Type
*> Params
;
1149 for
(std
::list
<llvm
::PATypeHolder
>::iterator I
= $3->begin
(),
1150 E
= $3->end
(); I
!= E
; ++I
)
1151 Params.push_back
(*I
);
1152 bool isVarArg
= Params.size
() && Params.back
() == Type
::VoidTy
;
1153 if
(isVarArg
) Params.pop_back
();
1155 $$
= new PATypeHolder
(HandleUpRefs
(FunctionType
::get
(*$1,Params
,isVarArg
)));
1156 delete
$3; // Delete the argument list
1157 delete
$1; // Delete the return type handle
1159 |
'[' EUINT64VAL
'x' UpRTypes
']' { // Sized array type?
1160 $$
= new PATypeHolder
(HandleUpRefs
(ArrayType
::get
(*$4, (unsigned)$2)));
1163 |
'<' EUINT64VAL
'x' UpRTypes
'>' { // Packed array type?
1164 const llvm
::Type
* ElemTy
= $4->get
();
1165 if
((unsigned)$2 != $2)
1166 ThrowException
("Unsigned result not equal to signed result");
1167 if
(!ElemTy
->isPrimitiveType
())
1168 ThrowException
("Elemental type of a PackedType must be primitive");
1169 if
(!isPowerOf2_32
($2))
1170 ThrowException
("Vector length should be a power of 2!");
1171 $$
= new PATypeHolder
(HandleUpRefs
(PackedType
::get
(*$4, (unsigned)$2)));
1174 |
'{' TypeListI
'}' { // Structure type?
1175 std
::vector
<const Type
*> Elements
;
1176 for
(std
::list
<llvm
::PATypeHolder
>::iterator I
= $2->begin
(),
1177 E
= $2->end
(); I
!= E
; ++I
)
1178 Elements.push_back
(*I
);
1180 $$
= new PATypeHolder
(HandleUpRefs
(StructType
::get
(Elements
)));
1183 |
'{' '}' { // Empty structure type?
1184 $$
= new PATypeHolder
(StructType
::get
(std
::vector
<const Type
*>()));
1186 | UpRTypes
'*' { // Pointer type?
1187 $$
= new PATypeHolder
(HandleUpRefs
(PointerType
::get
(*$1)));
1191 // TypeList - Used for struct declarations and as a basis for function type
1192 // declaration type lists
1194 TypeListI
: UpRTypes
{
1195 $$
= new std
::list
<PATypeHolder
>();
1196 $$
->push_back
(*$1); delete
$1;
1198 | TypeListI
',' UpRTypes
{
1199 ($$
=$1)->push_back
(*$3); delete
$3;
1202 // ArgTypeList - List of types for a function type declaration...
1203 ArgTypeListI
: TypeListI
1204 | TypeListI
',' DOTDOTDOT
{
1205 ($$
=$1)->push_back
(Type
::VoidTy
);
1208 ($$
= new std
::list
<PATypeHolder
>())->push_back
(Type
::VoidTy
);
1211 $$
= new std
::list
<PATypeHolder
>();
1214 // ConstVal - The various declarations that go into the constant pool. This
1215 // production is used ONLY to represent constants that show up AFTER a 'const',
1216 // 'constant' or 'global' token at global scope. Constants that can be inlined
1217 // into other expressions (such as integers and constexprs) are handled by the
1218 // ResolvedVal, ValueRef and ConstValueRef productions.
1220 ConstVal: Types
'[' ConstVector
']' { // Nonempty unsized arr
1221 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1223 ThrowException
("Cannot make array constant with type: '" +
1224 (*$1)->getDescription
() + "'!");
1225 const Type
*ETy
= ATy
->getElementType
();
1226 int NumElements
= ATy
->getNumElements
();
1228 // Verify that we have the correct size...
1229 if
(NumElements
!= -1 && NumElements
!= (int)$3->size
())
1230 ThrowException
("Type mismatch: constant sized array initialized with " +
1231 utostr
($3->size
()) + " arguments, but has size of " +
1232 itostr
(NumElements
) + "!");
1234 // Verify all elements are correct type!
1235 for
(unsigned i
= 0; i
< $3->size
(); i
++) {
1236 if
(ETy
!= (*$3)[i
]->getType
())
1237 ThrowException
("Element #" + utostr
(i
) + " is not of type '" +
1238 ETy
->getDescription
() +"' as required!\nIt is of type '"+
1239 (*$3)[i
]->getType
()->getDescription
() + "'.");
1242 $$
= ConstantArray
::get
(ATy
, *$3);
1243 delete
$1; delete
$3;
1246 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1248 ThrowException
("Cannot make array constant with type: '" +
1249 (*$1)->getDescription
() + "'!");
1251 int NumElements
= ATy
->getNumElements
();
1252 if
(NumElements
!= -1 && NumElements
!= 0)
1253 ThrowException
("Type mismatch: constant sized array initialized with 0"
1254 " arguments, but has size of " + itostr
(NumElements
) +"!");
1255 $$
= ConstantArray
::get
(ATy
, std
::vector
<Constant
*>());
1258 | Types
'c' STRINGCONSTANT
{
1259 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1261 ThrowException
("Cannot make array constant with type: '" +
1262 (*$1)->getDescription
() + "'!");
1264 int NumElements
= ATy
->getNumElements
();
1265 const Type
*ETy
= ATy
->getElementType
();
1266 char *EndStr
= UnEscapeLexed
($3, true
);
1267 if
(NumElements
!= -1 && NumElements
!= (EndStr
-$3))
1268 ThrowException
("Can't build string constant of size " +
1269 itostr
((int)(EndStr
-$3)) +
1270 " when array has size " + itostr
(NumElements
) + "!");
1271 std
::vector
<Constant
*> Vals
;
1272 if
(ETy
== Type
::SByteTy
) {
1273 for
(signed char *C
= (signed char *)$3; C
!= (signed char *)EndStr
; ++C
)
1274 Vals.push_back
(ConstantSInt
::get
(ETy
, *C
));
1275 } else if
(ETy
== Type
::UByteTy
) {
1276 for
(unsigned char *C
= (unsigned char *)$3;
1277 C
!= (unsigned char*)EndStr
; ++C
)
1278 Vals.push_back
(ConstantUInt
::get
(ETy
, *C
));
1281 ThrowException
("Cannot build string arrays of non byte sized elements!");
1284 $$
= ConstantArray
::get
(ATy
, Vals
);
1287 | Types
'<' ConstVector
'>' { // Nonempty unsized arr
1288 const PackedType
*PTy
= dyn_cast
<PackedType
>($1->get
());
1290 ThrowException
("Cannot make packed constant with type: '" +
1291 (*$1)->getDescription
() + "'!");
1292 const Type
*ETy
= PTy
->getElementType
();
1293 int NumElements
= PTy
->getNumElements
();
1295 // Verify that we have the correct size...
1296 if
(NumElements
!= -1 && NumElements
!= (int)$3->size
())
1297 ThrowException
("Type mismatch: constant sized packed initialized with " +
1298 utostr
($3->size
()) + " arguments, but has size of " +
1299 itostr
(NumElements
) + "!");
1301 // Verify all elements are correct type!
1302 for
(unsigned i
= 0; i
< $3->size
(); i
++) {
1303 if
(ETy
!= (*$3)[i
]->getType
())
1304 ThrowException
("Element #" + utostr
(i
) + " is not of type '" +
1305 ETy
->getDescription
() +"' as required!\nIt is of type '"+
1306 (*$3)[i
]->getType
()->getDescription
() + "'.");
1309 $$
= ConstantPacked
::get
(PTy
, *$3);
1310 delete
$1; delete
$3;
1312 | Types
'{' ConstVector
'}' {
1313 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1315 ThrowException
("Cannot make struct constant with type: '" +
1316 (*$1)->getDescription
() + "'!");
1318 if
($3->size
() != STy
->getNumContainedTypes
())
1319 ThrowException
("Illegal number of initializers for structure type!");
1321 // Check to ensure that constants are compatible with the type initializer!
1322 for
(unsigned i
= 0, e
= $3->size
(); i
!= e
; ++i
)
1323 if
((*$3)[i
]->getType
() != STy
->getElementType
(i
))
1324 ThrowException
("Expected type '" +
1325 STy
->getElementType
(i
)->getDescription
() +
1326 "' for element #" + utostr
(i
) +
1327 " of structure initializer!");
1329 $$
= ConstantStruct
::get
(STy
, *$3);
1330 delete
$1; delete
$3;
1333 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1335 ThrowException
("Cannot make struct constant with type: '" +
1336 (*$1)->getDescription
() + "'!");
1338 if
(STy
->getNumContainedTypes
() != 0)
1339 ThrowException
("Illegal number of initializers for structure type!");
1341 $$
= ConstantStruct
::get
(STy
, std
::vector
<Constant
*>());
1345 const PointerType
*PTy
= dyn_cast
<PointerType
>($1->get
());
1347 ThrowException
("Cannot make null pointer constant with type: '" +
1348 (*$1)->getDescription
() + "'!");
1350 $$
= ConstantPointerNull
::get
(PTy
);
1354 $$
= UndefValue
::get
($1->get
());
1357 | Types SymbolicValueRef
{
1358 const PointerType
*Ty
= dyn_cast
<PointerType
>($1->get
());
1360 ThrowException
("Global const reference must be a pointer type!");
1362 // ConstExprs can exist in the body of a function, thus creating
1363 // GlobalValues whenever they refer to a variable. Because we are in
1364 // the context of a function, getValNonImprovising will search the functions
1365 // symbol table instead of the module symbol table for the global symbol,
1366 // which throws things all off. To get around this, we just tell
1367 // getValNonImprovising that we are at global scope here.
1369 Function
*SavedCurFn
= CurFun.CurrentFunction
;
1370 CurFun.CurrentFunction
= 0;
1372 Value
*V
= getValNonImprovising
(Ty
, $2);
1374 CurFun.CurrentFunction
= SavedCurFn
;
1376 // If this is an initializer for a constant pointer, which is referencing a
1377 // (currently) undefined variable, create a stub now that shall be replaced
1378 // in the future with the right type of variable.
1381 assert
(isa
<PointerType
>(Ty
) && "Globals may only be used as pointers!");
1382 const PointerType
*PT
= cast
<PointerType
>(Ty
);
1384 // First check to see if the forward references value is already created!
1385 PerModuleInfo
::GlobalRefsType
::iterator I
=
1386 CurModule.GlobalRefs.find
(std
::make_pair
(PT
, $2));
1388 if
(I
!= CurModule.GlobalRefs.end
()) {
1389 V
= I
->second
; // Placeholder already exists, use it...
1393 if
($2.Type
== ValID
::NameVal
) Name
= $2.Name
;
1395 // Create the forward referenced global.
1397 if
(const FunctionType
*FTy
=
1398 dyn_cast
<FunctionType
>(PT
->getElementType
())) {
1399 GV
= new Function
(FTy
, GlobalValue
::ExternalLinkage
, Name
,
1400 CurModule.CurrentModule
);
1402 GV
= new GlobalVariable
(PT
->getElementType
(), false
,
1403 GlobalValue
::ExternalLinkage
, 0,
1404 Name
, CurModule.CurrentModule
);
1407 // Keep track of the fact that we have a forward ref to recycle it
1408 CurModule.GlobalRefs.insert
(std
::make_pair
(std
::make_pair
(PT
, $2), GV
));
1413 $$
= cast
<GlobalValue
>(V
);
1414 delete
$1; // Free the type handle
1417 if
($1->get
() != $2->getType
())
1418 ThrowException
("Mismatched types for constant expression!");
1422 | Types ZEROINITIALIZER
{
1423 const Type
*Ty
= $1->get
();
1424 if
(isa
<FunctionType
>(Ty
) || Ty
== Type
::LabelTy || isa
<OpaqueType
>(Ty
))
1425 ThrowException
("Cannot create a null initialized value of this type!");
1426 $$
= Constant
::getNullValue
(Ty
);
1430 ConstVal
: SIntType EINT64VAL
{ // integral constants
1431 if
(!ConstantSInt
::isValueValidForType
($1, $2))
1432 ThrowException
("Constant value doesn't fit in type!");
1433 $$
= ConstantSInt
::get
($1, $2);
1435 | UIntType EUINT64VAL
{ // integral constants
1436 if
(!ConstantUInt
::isValueValidForType
($1, $2))
1437 ThrowException
("Constant value doesn't fit in type!");
1438 $$
= ConstantUInt
::get
($1, $2);
1440 | BOOL TRUETOK
{ // Boolean constants
1441 $$
= ConstantBool
::True
;
1443 | BOOL FALSETOK
{ // Boolean constants
1444 $$
= ConstantBool
::False
;
1446 | FPType FPVAL
{ // Float & Double constants
1447 if
(!ConstantFP
::isValueValidForType
($1, $2))
1448 ThrowException
("Floating point constant invalid for type!!");
1449 $$
= ConstantFP
::get
($1, $2);
1453 ConstExpr: CAST
'(' ConstVal TO Types
')' {
1454 if
(!$3->getType
()->isFirstClassType
())
1455 ThrowException
("cast constant expression from a non-primitive type: '" +
1456 $3->getType
()->getDescription
() + "'!");
1457 if
(!$5->get
()->isFirstClassType
())
1458 ThrowException
("cast constant expression to a non-primitive type: '" +
1459 $5->get
()->getDescription
() + "'!");
1460 $$
= ConstantExpr
::getCast
($3, $5->get
());
1463 | GETELEMENTPTR
'(' ConstVal IndexList
')' {
1464 if
(!isa
<PointerType
>($3->getType
()))
1465 ThrowException
("GetElementPtr requires a pointer operand!");
1467 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1468 // indices to uint struct indices for compatibility.
1469 generic_gep_type_iterator
<std
::vector
<Value
*>::iterator
>
1470 GTI
= gep_type_begin
($3->getType
(), $4->begin
(), $4->end
()),
1471 GTE
= gep_type_end
($3->getType
(), $4->begin
(), $4->end
());
1472 for
(unsigned i
= 0, e
= $4->size
(); i
!= e
&& GTI
!= GTE
; ++i
, ++GTI
)
1473 if
(isa
<StructType
>(*GTI
)) // Only change struct indices
1474 if
(ConstantUInt
*CUI
= dyn_cast
<ConstantUInt
>((*$4)[i
]))
1475 if
(CUI
->getType
() == Type
::UByteTy
)
1476 (*$4)[i
] = ConstantExpr
::getCast
(CUI
, Type
::UIntTy
);
1479 GetElementPtrInst
::getIndexedType
($3->getType
(), *$4, true
);
1481 ThrowException
("Index list invalid for constant getelementptr!");
1483 std
::vector
<Constant
*> IdxVec
;
1484 for
(unsigned i
= 0, e
= $4->size
(); i
!= e
; ++i
)
1485 if
(Constant
*C
= dyn_cast
<Constant
>((*$4)[i
]))
1486 IdxVec.push_back
(C
);
1488 ThrowException
("Indices to constant getelementptr must be constants!");
1492 $$
= ConstantExpr
::getGetElementPtr
($3, IdxVec
);
1494 | SELECT
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1495 if
($3->getType
() != Type
::BoolTy
)
1496 ThrowException
("Select condition must be of boolean type!");
1497 if
($5->getType
() != $7->getType
())
1498 ThrowException
("Select operand types must match!");
1499 $$
= ConstantExpr
::getSelect
($3, $5, $7);
1501 | ArithmeticOps
'(' ConstVal
',' ConstVal
')' {
1502 if
($3->getType
() != $5->getType
())
1503 ThrowException
("Binary operator types must match!");
1504 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1505 // To retain backward compatibility with these early compilers, we emit a
1506 // cast to the appropriate integer type automatically if we are in the
1507 // broken case. See PR424 for more information.
1508 if
(!isa
<PointerType
>($3->getType
())) {
1509 $$
= ConstantExpr
::get
($1, $3, $5);
1511 const Type
*IntPtrTy
= 0;
1512 switch
(CurModule.CurrentModule
->getPointerSize
()) {
1513 case Module
::Pointer32
: IntPtrTy
= Type
::IntTy
; break
;
1514 case Module
::Pointer64
: IntPtrTy
= Type
::LongTy
; break
;
1515 default
: ThrowException
("invalid pointer binary constant expr!");
1517 $$
= ConstantExpr
::get
($1, ConstantExpr
::getCast
($3, IntPtrTy
),
1518 ConstantExpr
::getCast
($5, IntPtrTy
));
1519 $$
= ConstantExpr
::getCast
($$
, $3->getType
());
1522 | LogicalOps
'(' ConstVal
',' ConstVal
')' {
1523 if
($3->getType
() != $5->getType
())
1524 ThrowException
("Logical operator types must match!");
1525 if
(!$3->getType
()->isIntegral
()) {
1526 if
(!isa
<PackedType
>($3->getType
()) ||
1527 !cast
<PackedType
>($3->getType
())->getElementType
()->isIntegral
())
1528 ThrowException
("Logical operator requires integral operands!");
1530 $$
= ConstantExpr
::get
($1, $3, $5);
1532 | SetCondOps
'(' ConstVal
',' ConstVal
')' {
1533 if
($3->getType
() != $5->getType
())
1534 ThrowException
("setcc operand types must match!");
1535 $$
= ConstantExpr
::get
($1, $3, $5);
1537 | ShiftOps
'(' ConstVal
',' ConstVal
')' {
1538 if
($5->getType
() != Type
::UByteTy
)
1539 ThrowException
("Shift count for shift constant must be unsigned byte!");
1540 if
(!$3->getType
()->isInteger
())
1541 ThrowException
("Shift constant expression requires integer operand!");
1542 $$
= ConstantExpr
::get
($1, $3, $5);
1544 | EXTRACTELEMENT
'(' ConstVal
',' ConstVal
')' {
1545 if
(!ExtractElementInst
::isValidOperands
($3, $5))
1546 ThrowException
("Invalid extractelement operands!");
1547 $$
= ConstantExpr
::getExtractElement
($3, $5);
1549 | INSERTELEMENT
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1550 if
(!InsertElementInst
::isValidOperands
($3, $5, $7))
1551 ThrowException
("Invalid insertelement operands!");
1552 $$
= ConstantExpr
::getInsertElement
($3, $5, $7);
1554 | SHUFFLEVECTOR
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1555 if
(!ShuffleVectorInst
::isValidOperands
($3, $5, $7))
1556 ThrowException
("Invalid shufflevector operands!");
1557 $$
= ConstantExpr
::getShuffleVector
($3, $5, $7);
1561 // ConstVector - A list of comma separated constants.
1562 ConstVector
: ConstVector
',' ConstVal
{
1563 ($$
= $1)->push_back
($3);
1566 $$
= new std
::vector
<Constant
*>();
1571 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1572 GlobalType
: GLOBAL
{ $$
= false
; } | CONSTANT
{ $$
= true
; };
1575 //===----------------------------------------------------------------------===//
1576 // Rules to match Modules
1577 //===----------------------------------------------------------------------===//
1579 // Module rule: Capture the result of parsing the whole file into a result
1582 Module
: FunctionList
{
1583 $$
= ParserResult
= $1;
1584 CurModule.ModuleDone
();
1587 // FunctionList - A list of functions, preceeded by a constant pool.
1589 FunctionList
: FunctionList Function
{
1591 CurFun.FunctionDone
();
1593 | FunctionList FunctionProto
{
1596 | FunctionList MODULE ASM_TOK AsmBlock
{
1599 | FunctionList IMPLEMENTATION
{
1603 $$
= CurModule.CurrentModule
;
1604 // Emit an error if there are any unresolved types left.
1605 if
(!CurModule.LateResolveTypes.empty
()) {
1606 const ValID
&DID
= CurModule.LateResolveTypes.begin
()->first
;
1607 if
(DID.Type
== ValID
::NameVal
)
1608 ThrowException
("Reference to an undefined type: '"+DID.getName
() + "'");
1610 ThrowException
("Reference to an undefined type: #" + itostr
(DID.Num
));
1614 // ConstPool - Constants with optional names assigned to them.
1615 ConstPool
: ConstPool OptAssign TYPE TypesV
{
1616 // Eagerly resolve types. This is not an optimization, this is a
1617 // requirement that is due to the fact that we could have this:
1619 // %list = type { %list * }
1620 // %list = type { %list * } ; repeated type decl
1622 // If types are not resolved eagerly, then the two types will not be
1623 // determined to be the same type!
1625 ResolveTypeTo
($2, *$4);
1627 if
(!setTypeName
(*$4, $2) && !$2) {
1628 // If this is a named type that is not a redefinition, add it to the slot
1630 CurModule.Types.push_back
(*$4);
1635 | ConstPool FunctionProto
{ // Function prototypes can be in const pool
1637 | ConstPool MODULE ASM_TOK AsmBlock
{ // Asm blocks can be in the const pool
1639 | ConstPool OptAssign OptLinkage GlobalType ConstVal
{
1640 if
($5 == 0) ThrowException
("Global value initializer is not a constant!");
1641 CurGV
= ParseGlobalVariable
($2, $3, $4, $5->getType
(), $5);
1642 } GlobalVarAttributes
{
1645 | ConstPool OptAssign EXTERNAL GlobalType Types
{
1646 CurGV
= ParseGlobalVariable
($2, GlobalValue
::ExternalLinkage
,
1649 } GlobalVarAttributes
{
1652 | ConstPool TARGET TargetDefinition
{
1654 | ConstPool DEPLIBS
'=' LibrariesDefinition
{
1656 |
/* empty: end of list */ {
1660 AsmBlock
: STRINGCONSTANT
{
1661 const std
::string &AsmSoFar
= CurModule.CurrentModule
->getModuleInlineAsm
();
1662 char *EndStr
= UnEscapeLexed
($1, true
);
1663 std
::string NewAsm
($1, EndStr
);
1666 if
(AsmSoFar.empty
())
1667 CurModule.CurrentModule
->setModuleInlineAsm
(NewAsm
);
1669 CurModule.CurrentModule
->setModuleInlineAsm
(AsmSoFar
+"\n"+NewAsm
);
1672 BigOrLittle
: BIG
{ $$
= Module
::BigEndian
; };
1673 BigOrLittle
: LITTLE
{ $$
= Module
::LittleEndian
; };
1675 TargetDefinition
: ENDIAN
'=' BigOrLittle
{
1676 CurModule.CurrentModule
->setEndianness
($3);
1678 | POINTERSIZE
'=' EUINT64VAL
{
1680 CurModule.CurrentModule
->setPointerSize
(Module
::Pointer32
);
1682 CurModule.CurrentModule
->setPointerSize
(Module
::Pointer64
);
1684 ThrowException
("Invalid pointer size: '" + utostr
($3) + "'!");
1686 | TRIPLE
'=' STRINGCONSTANT
{
1687 CurModule.CurrentModule
->setTargetTriple
($3);
1691 LibrariesDefinition
: '[' LibList
']';
1693 LibList
: LibList
',' STRINGCONSTANT
{
1694 CurModule.CurrentModule
->addLibrary
($3);
1698 CurModule.CurrentModule
->addLibrary
($1);
1701 |
/* empty: end of list */ {
1705 //===----------------------------------------------------------------------===//
1706 // Rules to match Function Headers
1707 //===----------------------------------------------------------------------===//
1709 Name
: VAR_ID | STRINGCONSTANT
;
1710 OptName
: Name |
/*empty*/ { $$
= 0; };
1712 ArgVal
: Types OptName
{
1713 if
(*$1 == Type
::VoidTy
)
1714 ThrowException
("void typed arguments are invalid!");
1715 $$
= new std
::pair
<PATypeHolder
*, char*>($1, $2);
1718 ArgListH
: ArgListH
',' ArgVal
{
1724 $$
= new std
::vector
<std
::pair
<PATypeHolder
*,char*> >();
1729 ArgList
: ArgListH
{
1732 | ArgListH
',' DOTDOTDOT
{
1734 $$
->push_back
(std
::pair
<PATypeHolder
*,
1735 char*>(new PATypeHolder
(Type
::VoidTy
), 0));
1738 $$
= new std
::vector
<std
::pair
<PATypeHolder
*,char*> >();
1739 $$
->push_back
(std
::make_pair
(new PATypeHolder
(Type
::VoidTy
), (char*)0));
1745 FunctionHeaderH
: OptCallingConv TypesV Name
'(' ArgList
')'
1746 OptSection OptAlign
{
1748 std
::string FunctionName
($3);
1749 free
($3); // Free strdup'd memory!
1751 if
(!(*$2)->isFirstClassType
() && *$2 != Type
::VoidTy
)
1752 ThrowException
("LLVM functions cannot return aggregate types!");
1754 std
::vector
<const Type
*> ParamTypeList
;
1755 if
($5) { // If there are arguments...
1756 for
(std
::vector
<std
::pair
<PATypeHolder
*,char*> >::iterator I
= $5->begin
();
1757 I
!= $5->end
(); ++I
)
1758 ParamTypeList.push_back
(I
->first
->get
());
1761 bool isVarArg
= ParamTypeList.size
() && ParamTypeList.back
() == Type
::VoidTy
;
1762 if
(isVarArg
) ParamTypeList.pop_back
();
1764 const FunctionType
*FT
= FunctionType
::get
(*$2, ParamTypeList
, isVarArg
);
1765 const PointerType
*PFT
= PointerType
::get
(FT
);
1769 if
(!FunctionName.empty
()) {
1770 ID
= ValID
::create
((char*)FunctionName.c_str
());
1772 ID
= ValID
::create
((int)CurModule.Values
[PFT
].size
());
1776 // See if this function was forward referenced. If so, recycle the object.
1777 if
(GlobalValue
*FWRef
= CurModule.GetForwardRefForGlobal
(PFT
, ID
)) {
1778 // Move the function to the end of the list, from whereever it was
1779 // previously inserted.
1780 Fn
= cast
<Function
>(FWRef
);
1781 CurModule.CurrentModule
->getFunctionList
().remove
(Fn
);
1782 CurModule.CurrentModule
->getFunctionList
().push_back
(Fn
);
1783 } else if
(!FunctionName.empty
() && // Merge with an earlier prototype?
1784 (Fn
= CurModule.CurrentModule
->getFunction
(FunctionName
, FT
))) {
1785 // If this is the case, either we need to be a forward decl, or it needs
1787 if
(!CurFun.isDeclare
&& !Fn
->isExternal
())
1788 ThrowException
("Redefinition of function '" + FunctionName
+ "'!");
1790 // Make sure to strip off any argument names so we can't get conflicts.
1791 if
(Fn
->isExternal
())
1792 for
(Function
::arg_iterator AI
= Fn
->arg_begin
(), AE
= Fn
->arg_end
();
1796 } else
{ // Not already defined?
1797 Fn
= new Function
(FT
, GlobalValue
::ExternalLinkage
, FunctionName
,
1798 CurModule.CurrentModule
);
1799 InsertValue
(Fn
, CurModule.Values
);
1802 CurFun.FunctionStart
(Fn
);
1803 Fn
->setCallingConv
($1);
1804 Fn
->setAlignment
($8);
1810 // Add all of the arguments we parsed to the function...
1811 if
($5) { // Is null if empty...
1812 if
(isVarArg
) { // Nuke the last entry
1813 assert
($5->back
().first
->get
() == Type
::VoidTy
&& $5->back
().second
== 0&&
1814 "Not a varargs marker!");
1815 delete
$5->back
().first
;
1816 $5->pop_back
(); // Delete the last entry
1818 Function
::arg_iterator ArgIt
= Fn
->arg_begin
();
1819 for
(std
::vector
<std
::pair
<PATypeHolder
*,char*> >::iterator I
= $5->begin
();
1820 I
!= $5->end
(); ++I
, ++ArgIt
) {
1821 delete I
->first
; // Delete the typeholder...
1823 setValueName
(ArgIt
, I
->second
); // Insert arg into symtab...
1827 delete
$5; // We're now done with the argument list
1831 BEGIN
: BEGINTOK |
'{'; // Allow BEGIN or '{' to start a function
1833 FunctionHeader
: OptLinkage FunctionHeaderH BEGIN
{
1834 $$
= CurFun.CurrentFunction
;
1836 // Make sure that we keep track of the linkage type even if there was a
1837 // previous "declare".
1841 END
: ENDTOK |
'}'; // Allow end of '}' to end a function
1843 Function
: BasicBlockList END
{
1847 FunctionProto
: DECLARE
{ CurFun.isDeclare
= true
; } FunctionHeaderH
{
1848 $$
= CurFun.CurrentFunction
;
1849 CurFun.FunctionDone
();
1852 //===----------------------------------------------------------------------===//
1853 // Rules to match Basic Blocks
1854 //===----------------------------------------------------------------------===//
1856 OptSideEffect
: /* empty */ {
1863 ConstValueRef
: ESINT64VAL
{ // A reference to a direct constant
1864 $$
= ValID
::create
($1);
1867 $$
= ValID
::create
($1);
1869 | FPVAL
{ // Perhaps it's an FP constant?
1870 $$
= ValID
::create
($1);
1873 $$
= ValID
::create
(ConstantBool
::True
);
1876 $$
= ValID
::create
(ConstantBool
::False
);
1879 $$
= ValID
::createNull
();
1882 $$
= ValID
::createUndef
();
1884 | ZEROINITIALIZER
{ // A vector zero constant.
1885 $$
= ValID
::createZeroInit
();
1887 |
'<' ConstVector
'>' { // Nonempty unsized packed vector
1888 const Type
*ETy
= (*$2)[0]->getType
();
1889 int NumElements
= $2->size
();
1891 PackedType
* pt
= PackedType
::get
(ETy
, NumElements
);
1892 PATypeHolder
* PTy
= new PATypeHolder
(
1900 // Verify all elements are correct type!
1901 for
(unsigned i
= 0; i
< $2->size
(); i
++) {
1902 if
(ETy
!= (*$2)[i
]->getType
())
1903 ThrowException
("Element #" + utostr
(i
) + " is not of type '" +
1904 ETy
->getDescription
() +"' as required!\nIt is of type '" +
1905 (*$2)[i
]->getType
()->getDescription
() + "'.");
1908 $$
= ValID
::create
(ConstantPacked
::get
(pt
, *$2));
1909 delete PTy
; delete
$2;
1912 $$
= ValID
::create
($1);
1914 | ASM_TOK OptSideEffect STRINGCONSTANT
',' STRINGCONSTANT
{
1915 char *End
= UnEscapeLexed
($3, true
);
1916 std
::string AsmStr
= std
::string($3, End
);
1917 End
= UnEscapeLexed
($5, true
);
1918 std
::string Constraints
= std
::string($5, End
);
1919 $$
= ValID
::createInlineAsm
(AsmStr
, Constraints
, $2);
1924 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1927 SymbolicValueRef
: INTVAL
{ // Is it an integer reference...?
1928 $$
= ValID
::create
($1);
1930 | Name
{ // Is it a named reference...?
1931 $$
= ValID
::create
($1);
1934 // ValueRef - A reference to a definition... either constant or symbolic
1935 ValueRef
: SymbolicValueRef | ConstValueRef
;
1938 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1939 // type immediately preceeds the value reference, and allows complex constant
1940 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1941 ResolvedVal
: Types ValueRef
{
1942 $$
= getVal
(*$1, $2); delete
$1;
1945 BasicBlockList
: BasicBlockList BasicBlock
{
1948 | FunctionHeader BasicBlock
{ // Do not allow functions with 0 basic blocks
1953 // Basic blocks are terminated by branching instructions:
1954 // br, br/cc, switch, ret
1956 BasicBlock
: InstructionList OptAssign BBTerminatorInst
{
1957 setValueName
($3, $2);
1960 $1->getInstList
().push_back
($3);
1965 InstructionList
: InstructionList Inst
{
1966 $1->getInstList
().push_back
($2);
1970 $$
= CurBB
= getBBVal
(ValID
::create
((int)CurFun.NextBBNum
++), true
);
1972 // Make sure to move the basic block to the correct location in the
1973 // function, instead of leaving it inserted wherever it was first
1975 Function
::BasicBlockListType
&BBL
=
1976 CurFun.CurrentFunction
->getBasicBlockList
();
1977 BBL.splice
(BBL.end
(), BBL
, $$
);
1980 $$
= CurBB
= getBBVal
(ValID
::create
($1), true
);
1982 // Make sure to move the basic block to the correct location in the
1983 // function, instead of leaving it inserted wherever it was first
1985 Function
::BasicBlockListType
&BBL
=
1986 CurFun.CurrentFunction
->getBasicBlockList
();
1987 BBL.splice
(BBL.end
(), BBL
, $$
);
1990 BBTerminatorInst
: RET ResolvedVal
{ // Return with a result...
1991 $$
= new ReturnInst
($2);
1993 | RET VOID
{ // Return with no result...
1994 $$
= new ReturnInst
();
1996 | BR LABEL ValueRef
{ // Unconditional Branch...
1997 $$
= new BranchInst
(getBBVal
($3));
1998 } // Conditional Branch...
1999 | BR BOOL ValueRef
',' LABEL ValueRef
',' LABEL ValueRef
{
2000 $$
= new BranchInst
(getBBVal
($6), getBBVal
($9), getVal
(Type
::BoolTy
, $3));
2002 | SWITCH IntType ValueRef
',' LABEL ValueRef
'[' JumpTable
']' {
2003 SwitchInst
*S
= new SwitchInst
(getVal
($2, $3), getBBVal
($6), $8->size
());
2006 std
::vector
<std
::pair
<Constant
*,BasicBlock
*> >::iterator I
= $8->begin
(),
2008 for
(; I
!= E
; ++I
) {
2009 if
(ConstantInt
*CI
= dyn_cast
<ConstantInt
>(I
->first
))
2010 S
->addCase
(CI
, I
->second
);
2012 ThrowException
("Switch case is constant, but not a simple integer!");
2016 | SWITCH IntType ValueRef
',' LABEL ValueRef
'[' ']' {
2017 SwitchInst
*S
= new SwitchInst
(getVal
($2, $3), getBBVal
($6), 0);
2020 | INVOKE OptCallingConv TypesV ValueRef
'(' ValueRefListE
')'
2021 TO LABEL ValueRef UNWIND LABEL ValueRef
{
2022 const PointerType
*PFTy
;
2023 const FunctionType
*Ty
;
2025 if
(!(PFTy
= dyn_cast
<PointerType
>($3->get
())) ||
2026 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType
()))) {
2027 // Pull out the types of all of the arguments...
2028 std
::vector
<const Type
*> ParamTypes
;
2030 for
(std
::vector
<Value
*>::iterator I
= $6->begin
(), E
= $6->end
();
2032 ParamTypes.push_back
((*I
)->getType
());
2035 bool isVarArg
= ParamTypes.size
() && ParamTypes.back
() == Type
::VoidTy
;
2036 if
(isVarArg
) ParamTypes.pop_back
();
2038 Ty
= FunctionType
::get
($3->get
(), ParamTypes
, isVarArg
);
2039 PFTy
= PointerType
::get
(Ty
);
2042 Value
*V
= getVal
(PFTy
, $4); // Get the function we're calling...
2044 BasicBlock
*Normal
= getBBVal
($10);
2045 BasicBlock
*Except
= getBBVal
($13);
2047 // Create the call node...
2048 if
(!$6) { // Has no arguments?
2049 $$
= new InvokeInst
(V
, Normal
, Except
, std
::vector
<Value
*>());
2050 } else
{ // Has arguments?
2051 // Loop through FunctionType's arguments and ensure they are specified
2054 FunctionType
::param_iterator I
= Ty
->param_begin
();
2055 FunctionType
::param_iterator E
= Ty
->param_end
();
2056 std
::vector
<Value
*>::iterator ArgI
= $6->begin
(), ArgE
= $6->end
();
2058 for
(; ArgI
!= ArgE
&& I
!= E
; ++ArgI
, ++I
)
2059 if
((*ArgI
)->getType
() != *I
)
2060 ThrowException
("Parameter " +(*ArgI
)->getName
()+ " is not of type '" +
2061 (*I
)->getDescription
() + "'!");
2063 if
(I
!= E ||
(ArgI
!= ArgE
&& !Ty
->isVarArg
()))
2064 ThrowException
("Invalid number of parameters detected!");
2066 $$
= new InvokeInst
(V
, Normal
, Except
, *$6);
2068 cast
<InvokeInst
>($$
)->setCallingConv
($2);
2074 $$
= new UnwindInst
();
2077 $$
= new UnreachableInst
();
2082 JumpTable
: JumpTable IntType ConstValueRef
',' LABEL ValueRef
{
2084 Constant
*V
= cast
<Constant
>(getValNonImprovising
($2, $3));
2086 ThrowException
("May only switch on a constant pool value!");
2088 $$
->push_back
(std
::make_pair
(V
, getBBVal
($6)));
2090 | IntType ConstValueRef
',' LABEL ValueRef
{
2091 $$
= new std
::vector
<std
::pair
<Constant
*, BasicBlock
*> >();
2092 Constant
*V
= cast
<Constant
>(getValNonImprovising
($1, $2));
2095 ThrowException
("May only switch on a constant pool value!");
2097 $$
->push_back
(std
::make_pair
(V
, getBBVal
($5)));
2100 Inst
: OptAssign InstVal
{
2101 // Is this definition named?? if so, assign the name...
2102 setValueName
($2, $1);
2107 PHIList
: Types
'[' ValueRef
',' ValueRef
']' { // Used for PHI nodes
2108 $$
= new std
::list
<std
::pair
<Value
*, BasicBlock
*> >();
2109 $$
->push_back
(std
::make_pair
(getVal
(*$1, $3), getBBVal
($5)));
2112 | PHIList
',' '[' ValueRef
',' ValueRef
']' {
2114 $1->push_back
(std
::make_pair
(getVal
($1->front
().first
->getType
(), $4),
2119 ValueRefList
: ResolvedVal
{ // Used for call statements, and memory insts...
2120 $$
= new std
::vector
<Value
*>();
2123 | ValueRefList
',' ResolvedVal
{
2128 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2129 ValueRefListE
: ValueRefList |
/*empty*/ { $$
= 0; };
2131 OptTailCall
: TAIL CALL
{
2140 InstVal
: ArithmeticOps Types ValueRef
',' ValueRef
{
2141 if
(!(*$2)->isInteger
() && !(*$2)->isFloatingPoint
() &&
2142 !isa
<PackedType
>((*$2).get
()))
2144 "Arithmetic operator requires integer, FP, or packed operands!");
2145 if
(isa
<PackedType
>((*$2).get
()) && $1 == Instruction
::Rem
)
2146 ThrowException
("Rem not supported on packed types!");
2147 $$
= BinaryOperator
::create
($1, getVal
(*$2, $3), getVal
(*$2, $5));
2149 ThrowException
("binary operator returned null!");
2152 | LogicalOps Types ValueRef
',' ValueRef
{
2153 if
(!(*$2)->isIntegral
()) {
2154 if
(!isa
<PackedType
>($2->get
()) ||
2155 !cast
<PackedType
>($2->get
())->getElementType
()->isIntegral
())
2156 ThrowException
("Logical operator requires integral operands!");
2158 $$
= BinaryOperator
::create
($1, getVal
(*$2, $3), getVal
(*$2, $5));
2160 ThrowException
("binary operator returned null!");
2163 | SetCondOps Types ValueRef
',' ValueRef
{
2164 if
(isa
<PackedType
>((*$2).get
())) {
2166 "PackedTypes currently not supported in setcc instructions!");
2168 $$
= new SetCondInst
($1, getVal
(*$2, $3), getVal
(*$2, $5));
2170 ThrowException
("binary operator returned null!");
2174 std
::cerr
<< "WARNING: Use of eliminated 'not' instruction:"
2175 << " Replacing with 'xor'.\n";
2177 Value
*Ones
= ConstantIntegral
::getAllOnesValue
($2->getType
());
2179 ThrowException
("Expected integral type for not instruction!");
2181 $$
= BinaryOperator
::create
(Instruction
::Xor
, $2, Ones
);
2183 ThrowException
("Could not create a xor instruction!");
2185 | ShiftOps ResolvedVal
',' ResolvedVal
{
2186 if
($4->getType
() != Type
::UByteTy
)
2187 ThrowException
("Shift amount must be ubyte!");
2188 if
(!$2->getType
()->isInteger
())
2189 ThrowException
("Shift constant expression requires integer operand!");
2190 $$
= new ShiftInst
($1, $2, $4);
2192 | CAST ResolvedVal TO Types
{
2193 if
(!$4->get
()->isFirstClassType
())
2194 ThrowException
("cast instruction to a non-primitive type: '" +
2195 $4->get
()->getDescription
() + "'!");
2196 $$
= new CastInst
($2, *$4);
2199 | SELECT ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2200 if
($2->getType
() != Type
::BoolTy
)
2201 ThrowException
("select condition must be boolean!");
2202 if
($4->getType
() != $6->getType
())
2203 ThrowException
("select value types should match!");
2204 $$
= new SelectInst
($2, $4, $6);
2206 | VAARG ResolvedVal
',' Types
{
2208 $$
= new VAArgInst
($2, *$4);
2211 | VAARG_old ResolvedVal
',' Types
{
2212 ObsoleteVarArgs
= true
;
2213 const Type
* ArgTy
= $2->getType
();
2214 Function
* NF
= CurModule.CurrentModule
->
2215 getOrInsertFunction
("llvm.va_copy", ArgTy
, ArgTy
, (Type
*)0);
2218 //foo = alloca 1 of t
2222 AllocaInst
* foo
= new AllocaInst
(ArgTy
, 0, "vaarg.fix");
2223 CurBB
->getInstList
().push_back
(foo
);
2224 CallInst
* bar
= new CallInst
(NF
, $2);
2225 CurBB
->getInstList
().push_back
(bar
);
2226 CurBB
->getInstList
().push_back
(new StoreInst
(bar
, foo
));
2227 $$
= new VAArgInst
(foo
, *$4);
2230 | VANEXT_old ResolvedVal
',' Types
{
2231 ObsoleteVarArgs
= true
;
2232 const Type
* ArgTy
= $2->getType
();
2233 Function
* NF
= CurModule.CurrentModule
->
2234 getOrInsertFunction
("llvm.va_copy", ArgTy
, ArgTy
, (Type
*)0);
2236 //b = vanext a, t ->
2237 //foo = alloca 1 of t
2240 //tmp = vaarg foo, t
2242 AllocaInst
* foo
= new AllocaInst
(ArgTy
, 0, "vanext.fix");
2243 CurBB
->getInstList
().push_back
(foo
);
2244 CallInst
* bar
= new CallInst
(NF
, $2);
2245 CurBB
->getInstList
().push_back
(bar
);
2246 CurBB
->getInstList
().push_back
(new StoreInst
(bar
, foo
));
2247 Instruction
* tmp
= new VAArgInst
(foo
, *$4);
2248 CurBB
->getInstList
().push_back
(tmp
);
2249 $$
= new LoadInst
(foo
);
2252 | EXTRACTELEMENT ResolvedVal
',' ResolvedVal
{
2253 if
(!ExtractElementInst
::isValidOperands
($2, $4))
2254 ThrowException
("Invalid extractelement operands!");
2255 $$
= new ExtractElementInst
($2, $4);
2257 | INSERTELEMENT ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2258 if
(!InsertElementInst
::isValidOperands
($2, $4, $6))
2259 ThrowException
("Invalid insertelement operands!");
2260 $$
= new InsertElementInst
($2, $4, $6);
2262 | SHUFFLEVECTOR ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2263 if
(!ShuffleVectorInst
::isValidOperands
($2, $4, $6))
2264 ThrowException
("Invalid shufflevector operands!");
2265 $$
= new ShuffleVectorInst
($2, $4, $6);
2268 const Type
*Ty
= $2->front
().first
->getType
();
2269 if
(!Ty
->isFirstClassType
())
2270 ThrowException
("PHI node operands must be of first class type!");
2271 $$
= new PHINode
(Ty
);
2272 ((PHINode
*)$$
)->reserveOperandSpace
($2->size
());
2273 while
($2->begin
() != $2->end
()) {
2274 if
($2->front
().first
->getType
() != Ty
)
2275 ThrowException
("All elements of a PHI node must be of the same type!");
2276 cast
<PHINode
>($$
)->addIncoming
($2->front
().first
, $2->front
().second
);
2279 delete
$2; // Free the list...
2281 | OptTailCall OptCallingConv TypesV ValueRef
'(' ValueRefListE
')' {
2282 const PointerType
*PFTy
;
2283 const FunctionType
*Ty
;
2285 if
(!(PFTy
= dyn_cast
<PointerType
>($3->get
())) ||
2286 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType
()))) {
2287 // Pull out the types of all of the arguments...
2288 std
::vector
<const Type
*> ParamTypes
;
2290 for
(std
::vector
<Value
*>::iterator I
= $6->begin
(), E
= $6->end
();
2292 ParamTypes.push_back
((*I
)->getType
());
2295 bool isVarArg
= ParamTypes.size
() && ParamTypes.back
() == Type
::VoidTy
;
2296 if
(isVarArg
) ParamTypes.pop_back
();
2298 if
(!(*$3)->isFirstClassType
() && *$3 != Type
::VoidTy
)
2299 ThrowException
("LLVM functions cannot return aggregate types!");
2301 Ty
= FunctionType
::get
($3->get
(), ParamTypes
, isVarArg
);
2302 PFTy
= PointerType
::get
(Ty
);
2305 Value
*V
= getVal
(PFTy
, $4); // Get the function we're calling...
2307 // Create the call node...
2308 if
(!$6) { // Has no arguments?
2309 // Make sure no arguments is a good thing!
2310 if
(Ty
->getNumParams
() != 0)
2311 ThrowException
("No arguments passed to a function that "
2312 "expects arguments!");
2314 $$
= new CallInst
(V
, std
::vector
<Value
*>());
2315 } else
{ // Has arguments?
2316 // Loop through FunctionType's arguments and ensure they are specified
2319 FunctionType
::param_iterator I
= Ty
->param_begin
();
2320 FunctionType
::param_iterator E
= Ty
->param_end
();
2321 std
::vector
<Value
*>::iterator ArgI
= $6->begin
(), ArgE
= $6->end
();
2323 for
(; ArgI
!= ArgE
&& I
!= E
; ++ArgI
, ++I
)
2324 if
((*ArgI
)->getType
() != *I
)
2325 ThrowException
("Parameter " +(*ArgI
)->getName
()+ " is not of type '" +
2326 (*I
)->getDescription
() + "'!");
2328 if
(I
!= E ||
(ArgI
!= ArgE
&& !Ty
->isVarArg
()))
2329 ThrowException
("Invalid number of parameters detected!");
2331 $$
= new CallInst
(V
, *$6);
2333 cast
<CallInst
>($$
)->setTailCall
($1);
2334 cast
<CallInst
>($$
)->setCallingConv
($2);
2343 // IndexList - List of indices for GEP based instructions...
2344 IndexList
: ',' ValueRefList
{
2347 $$
= new std
::vector
<Value
*>();
2350 OptVolatile
: VOLATILE
{
2359 MemoryInst
: MALLOC Types OptCAlign
{
2360 $$
= new MallocInst
(*$2, 0, $3);
2363 | MALLOC Types
',' UINT ValueRef OptCAlign
{
2364 $$
= new MallocInst
(*$2, getVal
($4, $5), $6);
2367 | ALLOCA Types OptCAlign
{
2368 $$
= new AllocaInst
(*$2, 0, $3);
2371 | ALLOCA Types
',' UINT ValueRef OptCAlign
{
2372 $$
= new AllocaInst
(*$2, getVal
($4, $5), $6);
2375 | FREE ResolvedVal
{
2376 if
(!isa
<PointerType
>($2->getType
()))
2377 ThrowException
("Trying to free nonpointer type " +
2378 $2->getType
()->getDescription
() + "!");
2379 $$
= new FreeInst
($2);
2382 | OptVolatile LOAD Types ValueRef
{
2383 if
(!isa
<PointerType
>($3->get
()))
2384 ThrowException
("Can't load from nonpointer type: " +
2385 (*$3)->getDescription
());
2386 if
(!cast
<PointerType
>($3->get
())->getElementType
()->isFirstClassType
())
2387 ThrowException
("Can't load from pointer of non-first-class type: " +
2388 (*$3)->getDescription
());
2389 $$
= new LoadInst
(getVal
(*$3, $4), "", $1);
2392 | OptVolatile STORE ResolvedVal
',' Types ValueRef
{
2393 const PointerType
*PT
= dyn_cast
<PointerType
>($5->get
());
2395 ThrowException
("Can't store to a nonpointer type: " +
2396 (*$5)->getDescription
());
2397 const Type
*ElTy
= PT
->getElementType
();
2398 if
(ElTy
!= $3->getType
())
2399 ThrowException
("Can't store '" + $3->getType
()->getDescription
() +
2400 "' into space of type '" + ElTy
->getDescription
() + "'!");
2402 $$
= new StoreInst
($3, getVal
(*$5, $6), $1);
2405 | GETELEMENTPTR Types ValueRef IndexList
{
2406 if
(!isa
<PointerType
>($2->get
()))
2407 ThrowException
("getelementptr insn requires pointer operand!");
2409 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2410 // indices to uint struct indices for compatibility.
2411 generic_gep_type_iterator
<std
::vector
<Value
*>::iterator
>
2412 GTI
= gep_type_begin
($2->get
(), $4->begin
(), $4->end
()),
2413 GTE
= gep_type_end
($2->get
(), $4->begin
(), $4->end
());
2414 for
(unsigned i
= 0, e
= $4->size
(); i
!= e
&& GTI
!= GTE
; ++i
, ++GTI
)
2415 if
(isa
<StructType
>(*GTI
)) // Only change struct indices
2416 if
(ConstantUInt
*CUI
= dyn_cast
<ConstantUInt
>((*$4)[i
]))
2417 if
(CUI
->getType
() == Type
::UByteTy
)
2418 (*$4)[i
] = ConstantExpr
::getCast
(CUI
, Type
::UIntTy
);
2420 if
(!GetElementPtrInst
::getIndexedType
(*$2, *$4, true
))
2421 ThrowException
("Invalid getelementptr indices for type '" +
2422 (*$2)->getDescription
()+ "'!");
2423 $$
= new GetElementPtrInst
(getVal
(*$2, $3), *$4);
2424 delete
$2; delete
$4;
2429 int yyerror(const char *ErrorMsg
) {
2431 = std
::string((CurFilename
== "-") ? std
::string("<stdin>") : CurFilename
)
2432 + ":" + utostr
((unsigned) llvmAsmlineno
) + ": ";
2433 std
::string errMsg
= std
::string(ErrorMsg
) + "\n" + where
+ " while reading ";
2434 if
(yychar == YYEMPTY ||
yychar == 0)
2435 errMsg
+= "end-of-file.";
2437 errMsg
+= "token: '" + std
::string(llvmAsmtext
, llvmAsmleng
) + "'";
2438 ThrowException
(errMsg
);