blob: 3525567cf2c698ec0a0e33da4cbec75f234328eb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the bison parser for LLVM assembly languages files.
11//
12//===----------------------------------------------------------------------===//
13
14%{
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/ValueSymbolTable.h"
Chandler Carrutha228e392007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/Streams.h"
28#include <algorithm>
29#include <list>
30#include <map>
31#include <utility>
32#ifndef NDEBUG
33#define YYDEBUG 1
34#endif
35
36// The following is a gross hack. In order to rid the libAsmParser library of
37// exceptions, we have to have a way of getting the yyparse function to go into
38// an error situation. So, whenever we want an error to occur, the GenerateError
39// function (see bottom of file) sets TriggerError. Then, at the end of each
40// production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
41// (a goto) to put YACC in error state. Furthermore, several calls to
42// GenerateError are made from inside productions and they must simulate the
43// previous exception behavior by exiting the production immediately. We have
44// replaced these with the GEN_ERROR macro which calls GeneratError and then
45// immediately invokes YYERROR. This would be so much cleaner if it was a
46// recursive descent parser.
47static bool TriggerError = false;
48#define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
49#define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
50
51int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
52int yylex(); // declaration" of xxx warnings.
53int yyparse();
54
55namespace llvm {
56 std::string CurFilename;
57#if YYDEBUG
58static cl::opt<bool>
59Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
60 cl::Hidden, cl::init(false));
61#endif
62}
63using namespace llvm;
64
65static Module *ParserResult;
66
67// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
68// relating to upreferences in the input stream.
69//
70//#define DEBUG_UPREFS 1
71#ifdef DEBUG_UPREFS
72#define UR_OUT(X) cerr << X
73#else
74#define UR_OUT(X)
75#endif
76
77#define YYERROR_VERBOSE 1
78
79static GlobalVariable *CurGV;
80
81
82// This contains info used when building the body of a function. It is
83// destroyed when the function is completed.
84//
85typedef std::vector<Value *> ValueList; // Numbered defs
86
87static void
88ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
89
90static struct PerModuleInfo {
91 Module *CurrentModule;
92 ValueList Values; // Module level numbered definitions
93 ValueList LateResolveValues;
94 std::vector<PATypeHolder> Types;
95 std::map<ValID, PATypeHolder> LateResolveTypes;
96
97 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
98 /// how they were referenced and on which line of the input they came from so
99 /// that we can resolve them later and print error messages as appropriate.
100 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
101
102 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
103 // references to global values. Global values may be referenced before they
104 // are defined, and if so, the temporary object that they represent is held
105 // here. This is used for forward references of GlobalValues.
106 //
107 typedef std::map<std::pair<const PointerType *,
108 ValID>, GlobalValue*> GlobalRefsType;
109 GlobalRefsType GlobalRefs;
110
111 void ModuleDone() {
112 // If we could not resolve some functions at function compilation time
113 // (calls to functions before they are defined), resolve them now... Types
114 // are resolved when the constant pool has been completely parsed.
115 //
116 ResolveDefinitions(LateResolveValues);
117 if (TriggerError)
118 return;
119
120 // Check to make sure that all global value forward references have been
121 // resolved!
122 //
123 if (!GlobalRefs.empty()) {
124 std::string UndefinedReferences = "Unresolved global references exist:\n";
125
126 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
127 I != E; ++I) {
128 UndefinedReferences += " " + I->first.first->getDescription() + " " +
129 I->first.second.getName() + "\n";
130 }
131 GenerateError(UndefinedReferences);
132 return;
133 }
134
Chandler Carrutha228e392007-08-04 01:51:18 +0000135 // Look for intrinsic functions and CallInst that need to be upgraded
136 for (Module::iterator FI = CurrentModule->begin(),
137 FE = CurrentModule->end(); FI != FE; )
138 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
139
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 Values.clear(); // Clear out function local definitions
141 Types.clear();
142 CurrentModule = 0;
143 }
144
145 // GetForwardRefForGlobal - Check to see if there is a forward reference
146 // for this global. If so, remove it from the GlobalRefs map and return it.
147 // If not, just return null.
148 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
149 // Check to see if there is a forward reference to this global variable...
150 // if there is, eliminate it and patch the reference to use the new def'n.
151 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
152 GlobalValue *Ret = 0;
153 if (I != GlobalRefs.end()) {
154 Ret = I->second;
155 GlobalRefs.erase(I);
156 }
157 return Ret;
158 }
159
160 bool TypeIsUnresolved(PATypeHolder* PATy) {
161 // If it isn't abstract, its resolved
162 const Type* Ty = PATy->get();
163 if (!Ty->isAbstract())
164 return false;
165 // Traverse the type looking for abstract types. If it isn't abstract then
166 // we don't need to traverse that leg of the type.
167 std::vector<const Type*> WorkList, SeenList;
168 WorkList.push_back(Ty);
169 while (!WorkList.empty()) {
170 const Type* Ty = WorkList.back();
171 SeenList.push_back(Ty);
172 WorkList.pop_back();
173 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
174 // Check to see if this is an unresolved type
175 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
176 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
177 for ( ; I != E; ++I) {
178 if (I->second.get() == OpTy)
179 return true;
180 }
181 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
182 const Type* TheTy = SeqTy->getElementType();
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
185 E = SeenList.end();
186 for ( ; I != E; ++I)
187 if (*I == TheTy)
188 break;
189 if (I == E)
190 WorkList.push_back(TheTy);
191 }
192 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
193 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
194 const Type* TheTy = StrTy->getElementType(i);
195 if (TheTy->isAbstract() && TheTy != Ty) {
196 std::vector<const Type*>::iterator I = SeenList.begin(),
197 E = SeenList.end();
198 for ( ; I != E; ++I)
199 if (*I == TheTy)
200 break;
201 if (I == E)
202 WorkList.push_back(TheTy);
203 }
204 }
205 }
206 }
207 return false;
208 }
209} CurModule;
210
211static struct PerFunctionInfo {
212 Function *CurrentFunction; // Pointer to current function being created
213
214 ValueList Values; // Keep track of #'d definitions
215 unsigned NextValNum;
216 ValueList LateResolveValues;
217 bool isDeclare; // Is this function a forward declararation?
218 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
219 GlobalValue::VisibilityTypes Visibility;
220
221 /// BBForwardRefs - When we see forward references to basic blocks, keep
222 /// track of them here.
223 std::map<ValID, BasicBlock*> BBForwardRefs;
224
225 inline PerFunctionInfo() {
226 CurrentFunction = 0;
227 isDeclare = false;
228 Linkage = GlobalValue::ExternalLinkage;
229 Visibility = GlobalValue::DefaultVisibility;
230 }
231
232 inline void FunctionStart(Function *M) {
233 CurrentFunction = M;
234 NextValNum = 0;
235 }
236
237 void FunctionDone() {
238 // Any forward referenced blocks left?
239 if (!BBForwardRefs.empty()) {
240 GenerateError("Undefined reference to label " +
241 BBForwardRefs.begin()->second->getName());
242 return;
243 }
244
245 // Resolve all forward references now.
246 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
247
248 Values.clear(); // Clear out function local definitions
249 BBForwardRefs.clear();
250 CurrentFunction = 0;
251 isDeclare = false;
252 Linkage = GlobalValue::ExternalLinkage;
253 Visibility = GlobalValue::DefaultVisibility;
254 }
255} CurFun; // Info for the current function...
256
257static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
258
259
260//===----------------------------------------------------------------------===//
261// Code to handle definitions of all the types
262//===----------------------------------------------------------------------===//
263
264static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
265 // Things that have names or are void typed don't get slot numbers
266 if (V->hasName() || (V->getType() == Type::VoidTy))
267 return;
268
269 // In the case of function values, we have to allow for the forward reference
270 // of basic blocks, which are included in the numbering. Consequently, we keep
271 // track of the next insertion location with NextValNum. When a BB gets
272 // inserted, it could change the size of the CurFun.Values vector.
273 if (&ValueTab == &CurFun.Values) {
274 if (ValueTab.size() <= CurFun.NextValNum)
275 ValueTab.resize(CurFun.NextValNum+1);
276 ValueTab[CurFun.NextValNum++] = V;
277 return;
278 }
279 // For all other lists, its okay to just tack it on the back of the vector.
280 ValueTab.push_back(V);
281}
282
283static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
284 switch (D.Type) {
285 case ValID::LocalID: // Is it a numbered definition?
286 // Module constants occupy the lowest numbered slots...
287 if (D.Num < CurModule.Types.size())
288 return CurModule.Types[D.Num];
289 break;
290 case ValID::LocalName: // Is it a named definition?
291 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
292 D.destroy(); // Free old strdup'd memory...
293 return N;
294 }
295 break;
296 default:
297 GenerateError("Internal parser error: Invalid symbol type reference");
298 return 0;
299 }
300
301 // If we reached here, we referenced either a symbol that we don't know about
302 // or an id number that hasn't been read yet. We may be referencing something
303 // forward, so just create an entry to be resolved later and get to it...
304 //
305 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
306
307
308 if (inFunctionScope()) {
309 if (D.Type == ValID::LocalName) {
310 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
311 return 0;
312 } else {
313 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
314 return 0;
315 }
316 }
317
318 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
319 if (I != CurModule.LateResolveTypes.end())
320 return I->second;
321
322 Type *Typ = OpaqueType::get();
323 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
324 return Typ;
325 }
326
327// getExistingVal - Look up the value specified by the provided type and
328// the provided ValID. If the value exists and has already been defined, return
329// it. Otherwise return null.
330//
331static Value *getExistingVal(const Type *Ty, const ValID &D) {
332 if (isa<FunctionType>(Ty)) {
333 GenerateError("Functions are not values and "
334 "must be referenced as pointers");
335 return 0;
336 }
337
338 switch (D.Type) {
339 case ValID::LocalID: { // Is it a numbered definition?
340 // Check that the number is within bounds.
341 if (D.Num >= CurFun.Values.size())
342 return 0;
343 Value *Result = CurFun.Values[D.Num];
344 if (Ty != Result->getType()) {
345 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
346 Result->getType()->getDescription() + "' does not match "
347 "expected type, '" + Ty->getDescription() + "'");
348 return 0;
349 }
350 return Result;
351 }
352 case ValID::GlobalID: { // Is it a numbered definition?
353 if (D.Num >= CurModule.Values.size())
354 return 0;
355 Value *Result = CurModule.Values[D.Num];
356 if (Ty != Result->getType()) {
357 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
358 Result->getType()->getDescription() + "' does not match "
359 "expected type, '" + Ty->getDescription() + "'");
360 return 0;
361 }
362 return Result;
363 }
364
365 case ValID::LocalName: { // Is it a named definition?
366 if (!inFunctionScope())
367 return 0;
368 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
369 Value *N = SymTab.lookup(D.getName());
370 if (N == 0)
371 return 0;
372 if (N->getType() != Ty)
373 return 0;
374
375 D.destroy(); // Free old strdup'd memory...
376 return N;
377 }
378 case ValID::GlobalName: { // Is it a named definition?
379 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
380 Value *N = SymTab.lookup(D.getName());
381 if (N == 0)
382 return 0;
383 if (N->getType() != Ty)
384 return 0;
385
386 D.destroy(); // Free old strdup'd memory...
387 return N;
388 }
389
390 // Check to make sure that "Ty" is an integral type, and that our
391 // value will fit into the specified type...
392 case ValID::ConstSIntVal: // Is it a constant pool reference??
393 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
394 GenerateError("Signed integral constant '" +
395 itostr(D.ConstPool64) + "' is invalid for type '" +
396 Ty->getDescription() + "'");
397 return 0;
398 }
399 return ConstantInt::get(Ty, D.ConstPool64, true);
400
401 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
402 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
403 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
404 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
405 "' is invalid or out of range");
406 return 0;
407 } else { // This is really a signed reference. Transmogrify.
408 return ConstantInt::get(Ty, D.ConstPool64, true);
409 }
410 } else {
411 return ConstantInt::get(Ty, D.UConstPool64);
412 }
413
414 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000415 if (!ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 GenerateError("FP constant invalid for type");
417 return 0;
418 }
Dale Johannesen1616e902007-09-11 18:32:33 +0000419 // Lexer has no type info, so builds all float and double FP constants
420 // as double. Fix this here. Long double does not need this.
421 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
422 Ty==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000423 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
424 return ConstantFP::get(Ty, *D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425
426 case ValID::ConstNullVal: // Is it a null value?
427 if (!isa<PointerType>(Ty)) {
428 GenerateError("Cannot create a a non pointer null");
429 return 0;
430 }
431 return ConstantPointerNull::get(cast<PointerType>(Ty));
432
433 case ValID::ConstUndefVal: // Is it an undef value?
434 return UndefValue::get(Ty);
435
436 case ValID::ConstZeroVal: // Is it a zero value?
437 return Constant::getNullValue(Ty);
438
439 case ValID::ConstantVal: // Fully resolved constant?
440 if (D.ConstantValue->getType() != Ty) {
441 GenerateError("Constant expression type different from required type");
442 return 0;
443 }
444 return D.ConstantValue;
445
446 case ValID::InlineAsmVal: { // Inline asm expression
447 const PointerType *PTy = dyn_cast<PointerType>(Ty);
448 const FunctionType *FTy =
449 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
450 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
451 GenerateError("Invalid type for asm constraint string");
452 return 0;
453 }
454 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
455 D.IAD->HasSideEffects);
456 D.destroy(); // Free InlineAsmDescriptor.
457 return IA;
458 }
459 default:
460 assert(0 && "Unhandled case!");
461 return 0;
462 } // End of switch
463
464 assert(0 && "Unhandled case!");
465 return 0;
466}
467
468// getVal - This function is identical to getExistingVal, except that if a
469// value is not already defined, it "improvises" by creating a placeholder var
470// that looks and acts just like the requested variable. When the value is
471// defined later, all uses of the placeholder variable are replaced with the
472// real thing.
473//
474static Value *getVal(const Type *Ty, const ValID &ID) {
475 if (Ty == Type::LabelTy) {
476 GenerateError("Cannot use a basic block here");
477 return 0;
478 }
479
480 // See if the value has already been defined.
481 Value *V = getExistingVal(Ty, ID);
482 if (V) return V;
483 if (TriggerError) return 0;
484
485 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
486 GenerateError("Invalid use of a composite type");
487 return 0;
488 }
489
490 // If we reached here, we referenced either a symbol that we don't know about
491 // or an id number that hasn't been read yet. We may be referencing something
492 // forward, so just create an entry to be resolved later and get to it...
493 //
494 switch (ID.Type) {
495 case ValID::GlobalName:
496 case ValID::GlobalID: {
497 const PointerType *PTy = dyn_cast<PointerType>(Ty);
498 if (!PTy) {
499 GenerateError("Invalid type for reference to global" );
500 return 0;
501 }
502 const Type* ElTy = PTy->getElementType();
503 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
504 V = new Function(FTy, GlobalValue::ExternalLinkage);
505 else
506 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage);
507 break;
508 }
509 default:
510 V = new Argument(Ty);
511 }
512
513 // Remember where this forward reference came from. FIXME, shouldn't we try
514 // to recycle these things??
515 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
516 llvmAsmlineno)));
517
518 if (inFunctionScope())
519 InsertValue(V, CurFun.LateResolveValues);
520 else
521 InsertValue(V, CurModule.LateResolveValues);
522 return V;
523}
524
525/// defineBBVal - This is a definition of a new basic block with the specified
526/// identifier which must be the same as CurFun.NextValNum, if its numeric.
527static BasicBlock *defineBBVal(const ValID &ID) {
528 assert(inFunctionScope() && "Can't get basic block at global scope!");
529
530 BasicBlock *BB = 0;
531
532 // First, see if this was forward referenced
533
534 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
535 if (BBI != CurFun.BBForwardRefs.end()) {
536 BB = BBI->second;
537 // The forward declaration could have been inserted anywhere in the
538 // function: insert it into the correct place now.
539 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
540 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
541
542 // We're about to erase the entry, save the key so we can clean it up.
543 ValID Tmp = BBI->first;
544
545 // Erase the forward ref from the map as its no longer "forward"
546 CurFun.BBForwardRefs.erase(ID);
547
548 // The key has been removed from the map but so we don't want to leave
549 // strdup'd memory around so destroy it too.
550 Tmp.destroy();
551
552 // If its a numbered definition, bump the number and set the BB value.
553 if (ID.Type == ValID::LocalID) {
554 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
555 InsertValue(BB);
556 }
557
558 ID.destroy();
559 return BB;
560 }
561
562 // We haven't seen this BB before and its first mention is a definition.
563 // Just create it and return it.
564 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
565 BB = new BasicBlock(Name, CurFun.CurrentFunction);
566 if (ID.Type == ValID::LocalID) {
567 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
568 InsertValue(BB);
569 }
570
571 ID.destroy(); // Free strdup'd memory
572 return BB;
573}
574
575/// getBBVal - get an existing BB value or create a forward reference for it.
576///
577static BasicBlock *getBBVal(const ValID &ID) {
578 assert(inFunctionScope() && "Can't get basic block at global scope!");
579
580 BasicBlock *BB = 0;
581
582 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
583 if (BBI != CurFun.BBForwardRefs.end()) {
584 BB = BBI->second;
585 } if (ID.Type == ValID::LocalName) {
586 std::string Name = ID.getName();
587 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
588 if (N)
589 if (N->getType()->getTypeID() == Type::LabelTyID)
590 BB = cast<BasicBlock>(N);
591 else
592 GenerateError("Reference to label '" + Name + "' is actually of type '"+
593 N->getType()->getDescription() + "'");
594 } else if (ID.Type == ValID::LocalID) {
595 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
596 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
597 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
598 else
599 GenerateError("Reference to label '%" + utostr(ID.Num) +
600 "' is actually of type '"+
601 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
602 }
603 } else {
604 GenerateError("Illegal label reference " + ID.getName());
605 return 0;
606 }
607
608 // If its already been defined, return it now.
609 if (BB) {
610 ID.destroy(); // Free strdup'd memory.
611 return BB;
612 }
613
614 // Otherwise, this block has not been seen before, create it.
615 std::string Name;
616 if (ID.Type == ValID::LocalName)
617 Name = ID.getName();
618 BB = new BasicBlock(Name, CurFun.CurrentFunction);
619
620 // Insert it in the forward refs map.
621 CurFun.BBForwardRefs[ID] = BB;
622
623 return BB;
624}
625
626
627//===----------------------------------------------------------------------===//
628// Code to handle forward references in instructions
629//===----------------------------------------------------------------------===//
630//
631// This code handles the late binding needed with statements that reference
632// values not defined yet... for example, a forward branch, or the PHI node for
633// a loop body.
634//
635// This keeps a table (CurFun.LateResolveValues) of all such forward references
636// and back patchs after we are done.
637//
638
639// ResolveDefinitions - If we could not resolve some defs at parsing
640// time (forward branches, phi functions for loops, etc...) resolve the
641// defs now...
642//
643static void
644ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
645 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
646 while (!LateResolvers.empty()) {
647 Value *V = LateResolvers.back();
648 LateResolvers.pop_back();
649
650 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
651 CurModule.PlaceHolderInfo.find(V);
652 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
653
654 ValID &DID = PHI->second.first;
655
656 Value *TheRealValue = getExistingVal(V->getType(), DID);
657 if (TriggerError)
658 return;
659 if (TheRealValue) {
660 V->replaceAllUsesWith(TheRealValue);
661 delete V;
662 CurModule.PlaceHolderInfo.erase(PHI);
663 } else if (FutureLateResolvers) {
664 // Functions have their unresolved items forwarded to the module late
665 // resolver table
666 InsertValue(V, *FutureLateResolvers);
667 } else {
668 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
669 GenerateError("Reference to an invalid definition: '" +DID.getName()+
670 "' of type '" + V->getType()->getDescription() + "'",
671 PHI->second.second);
672 return;
673 } else {
674 GenerateError("Reference to an invalid definition: #" +
675 itostr(DID.Num) + " of type '" +
676 V->getType()->getDescription() + "'",
677 PHI->second.second);
678 return;
679 }
680 }
681 }
682 LateResolvers.clear();
683}
684
685// ResolveTypeTo - A brand new type was just declared. This means that (if
686// name is not null) things referencing Name can be resolved. Otherwise, things
687// refering to the number can be resolved. Do this now.
688//
689static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
690 ValID D;
691 if (Name)
692 D = ValID::createLocalName(*Name);
693 else
694 D = ValID::createLocalID(CurModule.Types.size());
695
696 std::map<ValID, PATypeHolder>::iterator I =
697 CurModule.LateResolveTypes.find(D);
698 if (I != CurModule.LateResolveTypes.end()) {
699 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
700 CurModule.LateResolveTypes.erase(I);
701 }
702}
703
704// setValueName - Set the specified value to the name given. The name may be
705// null potentially, in which case this is a noop. The string passed in is
706// assumed to be a malloc'd string buffer, and is free'd by this function.
707//
708static void setValueName(Value *V, std::string *NameStr) {
709 if (!NameStr) return;
710 std::string Name(*NameStr); // Copy string
711 delete NameStr; // Free old string
712
713 if (V->getType() == Type::VoidTy) {
714 GenerateError("Can't assign name '" + Name+"' to value with void type");
715 return;
716 }
717
718 assert(inFunctionScope() && "Must be in function scope!");
719 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
720 if (ST.lookup(Name)) {
721 GenerateError("Redefinition of value '" + Name + "' of type '" +
722 V->getType()->getDescription() + "'");
723 return;
724 }
725
726 // Set the name.
727 V->setName(Name);
728}
729
730/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
731/// this is a declaration, otherwise it is a definition.
732static GlobalVariable *
733ParseGlobalVariable(std::string *NameStr,
734 GlobalValue::LinkageTypes Linkage,
735 GlobalValue::VisibilityTypes Visibility,
736 bool isConstantGlobal, const Type *Ty,
737 Constant *Initializer, bool IsThreadLocal) {
738 if (isa<FunctionType>(Ty)) {
739 GenerateError("Cannot declare global vars of function type");
740 return 0;
741 }
742
743 const PointerType *PTy = PointerType::get(Ty);
744
745 std::string Name;
746 if (NameStr) {
747 Name = *NameStr; // Copy string
748 delete NameStr; // Free old string
749 }
750
751 // See if this global value was forward referenced. If so, recycle the
752 // object.
753 ValID ID;
754 if (!Name.empty()) {
755 ID = ValID::createGlobalName(Name);
756 } else {
757 ID = ValID::createGlobalID(CurModule.Values.size());
758 }
759
760 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
761 // Move the global to the end of the list, from whereever it was
762 // previously inserted.
763 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
764 CurModule.CurrentModule->getGlobalList().remove(GV);
765 CurModule.CurrentModule->getGlobalList().push_back(GV);
766 GV->setInitializer(Initializer);
767 GV->setLinkage(Linkage);
768 GV->setVisibility(Visibility);
769 GV->setConstant(isConstantGlobal);
770 GV->setThreadLocal(IsThreadLocal);
771 InsertValue(GV, CurModule.Values);
772 return GV;
773 }
774
775 // If this global has a name
776 if (!Name.empty()) {
777 // if the global we're parsing has an initializer (is a definition) and
778 // has external linkage.
779 if (Initializer && Linkage != GlobalValue::InternalLinkage)
780 // If there is already a global with external linkage with this name
781 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
782 // If we allow this GVar to get created, it will be renamed in the
783 // symbol table because it conflicts with an existing GVar. We can't
784 // allow redefinition of GVars whose linking indicates that their name
785 // must stay the same. Issue the error.
786 GenerateError("Redefinition of global variable named '" + Name +
787 "' of type '" + Ty->getDescription() + "'");
788 return 0;
789 }
790 }
791
792 // Otherwise there is no existing GV to use, create one now.
793 GlobalVariable *GV =
794 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
795 CurModule.CurrentModule, IsThreadLocal);
796 GV->setVisibility(Visibility);
797 InsertValue(GV, CurModule.Values);
798 return GV;
799}
800
801// setTypeName - Set the specified type to the name given. The name may be
802// null potentially, in which case this is a noop. The string passed in is
803// assumed to be a malloc'd string buffer, and is freed by this function.
804//
805// This function returns true if the type has already been defined, but is
806// allowed to be redefined in the specified context. If the name is a new name
807// for the type plane, it is inserted and false is returned.
808static bool setTypeName(const Type *T, std::string *NameStr) {
809 assert(!inFunctionScope() && "Can't give types function-local names!");
810 if (NameStr == 0) return false;
811
812 std::string Name(*NameStr); // Copy string
813 delete NameStr; // Free old string
814
815 // We don't allow assigning names to void type
816 if (T == Type::VoidTy) {
817 GenerateError("Can't assign name '" + Name + "' to the void type");
818 return false;
819 }
820
821 // Set the type name, checking for conflicts as we do so.
822 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
823
824 if (AlreadyExists) { // Inserting a name that is already defined???
825 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
826 assert(Existing && "Conflict but no matching type?!");
827
828 // There is only one case where this is allowed: when we are refining an
829 // opaque type. In this case, Existing will be an opaque type.
830 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
831 // We ARE replacing an opaque type!
832 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
833 return true;
834 }
835
836 // Otherwise, this is an attempt to redefine a type. That's okay if
837 // the redefinition is identical to the original. This will be so if
838 // Existing and T point to the same Type object. In this one case we
839 // allow the equivalent redefinition.
840 if (Existing == T) return true; // Yes, it's equal.
841
842 // Any other kind of (non-equivalent) redefinition is an error.
843 GenerateError("Redefinition of type named '" + Name + "' of type '" +
844 T->getDescription() + "'");
845 }
846
847 return false;
848}
849
850//===----------------------------------------------------------------------===//
851// Code for handling upreferences in type names...
852//
853
854// TypeContains - Returns true if Ty directly contains E in it.
855//
856static bool TypeContains(const Type *Ty, const Type *E) {
857 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
858 E) != Ty->subtype_end();
859}
860
861namespace {
862 struct UpRefRecord {
863 // NestingLevel - The number of nesting levels that need to be popped before
864 // this type is resolved.
865 unsigned NestingLevel;
866
867 // LastContainedTy - This is the type at the current binding level for the
868 // type. Every time we reduce the nesting level, this gets updated.
869 const Type *LastContainedTy;
870
871 // UpRefTy - This is the actual opaque type that the upreference is
872 // represented with.
873 OpaqueType *UpRefTy;
874
875 UpRefRecord(unsigned NL, OpaqueType *URTy)
876 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
877 };
878}
879
880// UpRefs - A list of the outstanding upreferences that need to be resolved.
881static std::vector<UpRefRecord> UpRefs;
882
883/// HandleUpRefs - Every time we finish a new layer of types, this function is
884/// called. It loops through the UpRefs vector, which is a list of the
885/// currently active types. For each type, if the up reference is contained in
886/// the newly completed type, we decrement the level count. When the level
887/// count reaches zero, the upreferenced type is the type that is passed in:
888/// thus we can complete the cycle.
889///
890static PATypeHolder HandleUpRefs(const Type *ty) {
891 // If Ty isn't abstract, or if there are no up-references in it, then there is
892 // nothing to resolve here.
893 if (!ty->isAbstract() || UpRefs.empty()) return ty;
894
895 PATypeHolder Ty(ty);
896 UR_OUT("Type '" << Ty->getDescription() <<
897 "' newly formed. Resolving upreferences.\n" <<
898 UpRefs.size() << " upreferences active!\n");
899
900 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
901 // to zero), we resolve them all together before we resolve them to Ty. At
902 // the end of the loop, if there is anything to resolve to Ty, it will be in
903 // this variable.
904 OpaqueType *TypeToResolve = 0;
905
906 for (unsigned i = 0; i != UpRefs.size(); ++i) {
907 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
908 << UpRefs[i].second->getDescription() << ") = "
909 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
910 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
911 // Decrement level of upreference
912 unsigned Level = --UpRefs[i].NestingLevel;
913 UpRefs[i].LastContainedTy = Ty;
914 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
915 if (Level == 0) { // Upreference should be resolved!
916 if (!TypeToResolve) {
917 TypeToResolve = UpRefs[i].UpRefTy;
918 } else {
919 UR_OUT(" * Resolving upreference for "
920 << UpRefs[i].second->getDescription() << "\n";
921 std::string OldName = UpRefs[i].UpRefTy->getDescription());
922 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
923 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
924 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
925 }
926 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
927 --i; // Do not skip the next element...
928 }
929 }
930 }
931
932 if (TypeToResolve) {
933 UR_OUT(" * Resolving upreference for "
934 << UpRefs[i].second->getDescription() << "\n";
935 std::string OldName = TypeToResolve->getDescription());
936 TypeToResolve->refineAbstractTypeTo(Ty);
937 }
938
939 return Ty;
940}
941
942//===----------------------------------------------------------------------===//
943// RunVMAsmParser - Define an interface to this parser
944//===----------------------------------------------------------------------===//
945//
946static Module* RunParser(Module * M);
947
948Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
949 set_scan_file(F);
950
951 CurFilename = Filename;
952 return RunParser(new Module(CurFilename));
953}
954
955Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
956 set_scan_string(AsmString);
957
958 CurFilename = "from_memory";
959 if (M == NULL) {
960 return RunParser(new Module (CurFilename));
961 } else {
962 return RunParser(M);
963 }
964}
965
966%}
967
968%union {
969 llvm::Module *ModuleVal;
970 llvm::Function *FunctionVal;
971 llvm::BasicBlock *BasicBlockVal;
972 llvm::TerminatorInst *TermInstVal;
973 llvm::Instruction *InstVal;
974 llvm::Constant *ConstVal;
975
976 const llvm::Type *PrimType;
977 std::list<llvm::PATypeHolder> *TypeList;
978 llvm::PATypeHolder *TypeVal;
979 llvm::Value *ValueVal;
980 std::vector<llvm::Value*> *ValueList;
981 llvm::ArgListType *ArgList;
982 llvm::TypeWithAttrs TypeWithAttrs;
983 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000984 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985
986 // Represent the RHS of PHI node
987 std::list<std::pair<llvm::Value*,
988 llvm::BasicBlock*> > *PHIList;
989 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
990 std::vector<llvm::Constant*> *ConstVector;
991
992 llvm::GlobalValue::LinkageTypes Linkage;
993 llvm::GlobalValue::VisibilityTypes Visibility;
994 uint16_t ParamAttrs;
995 llvm::APInt *APIntVal;
996 int64_t SInt64Val;
997 uint64_t UInt64Val;
998 int SIntVal;
999 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001000 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 bool BoolVal;
1002
1003 std::string *StrVal; // This memory must be deleted
1004 llvm::ValID ValIDVal;
1005
1006 llvm::Instruction::BinaryOps BinaryOpVal;
1007 llvm::Instruction::TermOps TermOpVal;
1008 llvm::Instruction::MemoryOps MemOpVal;
1009 llvm::Instruction::CastOps CastOpVal;
1010 llvm::Instruction::OtherOps OtherOpVal;
1011 llvm::ICmpInst::Predicate IPredicate;
1012 llvm::FCmpInst::Predicate FPredicate;
1013}
1014
1015%type <ModuleVal> Module
1016%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1017%type <BasicBlockVal> BasicBlock InstructionList
1018%type <TermInstVal> BBTerminatorInst
1019%type <InstVal> Inst InstVal MemoryInst
1020%type <ConstVal> ConstVal ConstExpr AliaseeRef
1021%type <ConstVector> ConstVector
1022%type <ArgList> ArgList ArgListH
1023%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001024%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025%type <ValueList> IndexList // For GEP indices
1026%type <TypeList> TypeListI
1027%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1028%type <TypeWithAttrs> ArgType
1029%type <JumpTable> JumpTable
1030%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1031%type <BoolVal> ThreadLocal // 'thread_local' or not
1032%type <BoolVal> OptVolatile // 'volatile' or not
1033%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1034%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1035%type <Linkage> GVInternalLinkage GVExternalLinkage
1036%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1037%type <Linkage> AliasLinkage
1038%type <Visibility> GVVisibilityStyle
1039
1040// ValueRef - Unresolved reference to a definition or BB
1041%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1042%type <ValueVal> ResolvedVal // <type> <valref> pair
1043// Tokens and types for handling constant integer values
1044//
1045// ESINT64VAL - A negative number within long long range
1046%token <SInt64Val> ESINT64VAL
1047
1048// EUINT64VAL - A positive number within uns. long long range
1049%token <UInt64Val> EUINT64VAL
1050
1051// ESAPINTVAL - A negative number with arbitrary precision
1052%token <APIntVal> ESAPINTVAL
1053
1054// EUAPINTVAL - A positive number with arbitrary precision
1055%token <APIntVal> EUAPINTVAL
1056
1057%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1058%token <FPVal> FPVAL // Float or Double constant
1059
1060// Built in types...
1061%type <TypeVal> Types ResultTypes
1062%type <PrimType> IntType FPType PrimType // Classifications
1063%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001064%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065%token TYPE
1066
1067
1068%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1069%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1070%type <StrVal> LocalName OptLocalName OptLocalAssign
1071%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1072%type <StrVal> OptSection SectionString
1073
1074%type <UIntVal> OptAlign OptCAlign
1075
1076%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1077%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1078%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1079%token DLLIMPORT DLLEXPORT EXTERN_WEAK
1080%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1081%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1082%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1083%token DATALAYOUT
1084%type <UIntVal> OptCallingConv
1085%type <ParamAttrs> OptParamAttrs ParamAttr
1086%type <ParamAttrs> OptFuncAttrs FuncAttr
1087
1088// Basic Block Terminating Operators
1089%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1090
1091// Binary Operators
1092%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1093%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1094%token <BinaryOpVal> SHL LSHR ASHR
1095
1096%token <OtherOpVal> ICMP FCMP
1097%type <IPredicate> IPredicates
1098%type <FPredicate> FPredicates
1099%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1100%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1101
1102// Memory Instructions
1103%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1104
1105// Cast Operators
1106%type <CastOpVal> CastOps
1107%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1108%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1109
1110// Other Operators
1111%token <OtherOpVal> PHI_TOK SELECT VAARG
1112%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1113
1114// Function Attributes
Duncan Sands38947cd2007-07-27 12:58:54 +00001115%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Anton Korobeynikov3b8a5f32007-11-14 09:52:30 +00001116%token CONST PURE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117
1118// Visibility Styles
1119%token DEFAULT HIDDEN PROTECTED
1120
1121%start Module
1122%%
1123
1124
1125// Operations that are notably excluded from this list include:
1126// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1127//
1128ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1129LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1130CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1131 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1132
1133IPredicates
1134 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1135 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1136 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1137 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1138 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1139 ;
1140
1141FPredicates
1142 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1143 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1144 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1145 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1146 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1147 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1148 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1149 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1150 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1151 ;
1152
1153// These are some types that allow classification if we only want a particular
1154// thing... for example, only a signed, unsigned, or integral type.
1155IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001156FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001157
1158LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1159OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1160
1161/// OptLocalAssign - Value producing statements have an optional assignment
1162/// component.
1163OptLocalAssign : LocalName '=' {
1164 $$ = $1;
1165 CHECK_FOR_ERROR
1166 }
1167 | /*empty*/ {
1168 $$ = 0;
1169 CHECK_FOR_ERROR
1170 };
1171
1172GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1173
1174OptGlobalAssign : GlobalAssign
1175 | /*empty*/ {
1176 $$ = 0;
1177 CHECK_FOR_ERROR
1178 };
1179
1180GlobalAssign : GlobalName '=' {
1181 $$ = $1;
1182 CHECK_FOR_ERROR
1183 };
1184
1185GVInternalLinkage
1186 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1187 | WEAK { $$ = GlobalValue::WeakLinkage; }
1188 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1189 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1190 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1191 ;
1192
1193GVExternalLinkage
1194 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1195 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1196 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1197 ;
1198
1199GVVisibilityStyle
1200 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1201 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1202 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1203 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1204 ;
1205
1206FunctionDeclareLinkage
1207 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1208 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1209 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1210 ;
1211
1212FunctionDefineLinkage
1213 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1214 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1215 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1216 | WEAK { $$ = GlobalValue::WeakLinkage; }
1217 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1218 ;
1219
1220AliasLinkage
1221 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1222 | WEAK { $$ = GlobalValue::WeakLinkage; }
1223 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1224 ;
1225
1226OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1227 CCC_TOK { $$ = CallingConv::C; } |
1228 FASTCC_TOK { $$ = CallingConv::Fast; } |
1229 COLDCC_TOK { $$ = CallingConv::Cold; } |
1230 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1231 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1232 CC_TOK EUINT64VAL {
1233 if ((unsigned)$2 != $2)
1234 GEN_ERROR("Calling conv too large");
1235 $$ = $2;
1236 CHECK_FOR_ERROR
1237 };
1238
Reid Spencerf234bed2007-07-19 23:13:04 +00001239ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001240 | ZEXT { $$ = ParamAttr::ZExt; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001241 | SIGNEXT { $$ = ParamAttr::SExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001242 | SEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 | INREG { $$ = ParamAttr::InReg; }
1244 | SRET { $$ = ParamAttr::StructRet; }
1245 | NOALIAS { $$ = ParamAttr::NoAlias; }
Duncan Sands38947cd2007-07-27 12:58:54 +00001246 | BYVAL { $$ = ParamAttr::ByVal; }
1247 | NEST { $$ = ParamAttr::Nest; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 ;
1249
1250OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1251 | OptParamAttrs ParamAttr {
1252 $$ = $1 | $2;
1253 }
1254 ;
1255
1256FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1257 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001258 | ZEROEXT { $$ = ParamAttr::ZExt; }
1259 | SIGNEXT { $$ = ParamAttr::SExt; }
Anton Korobeynikov3b8a5f32007-11-14 09:52:30 +00001260 | PURE { $$ = ParamAttr::Pure; }
1261 | CONST { $$ = ParamAttr::Const; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 ;
1263
1264OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1265 | OptFuncAttrs FuncAttr {
1266 $$ = $1 | $2;
1267 }
1268 ;
1269
1270// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1271// a comma before it.
1272OptAlign : /*empty*/ { $$ = 0; } |
1273 ALIGN EUINT64VAL {
1274 $$ = $2;
1275 if ($$ != 0 && !isPowerOf2_32($$))
1276 GEN_ERROR("Alignment must be a power of two");
1277 CHECK_FOR_ERROR
1278};
1279OptCAlign : /*empty*/ { $$ = 0; } |
1280 ',' ALIGN EUINT64VAL {
1281 $$ = $3;
1282 if ($$ != 0 && !isPowerOf2_32($$))
1283 GEN_ERROR("Alignment must be a power of two");
1284 CHECK_FOR_ERROR
1285};
1286
1287
1288SectionString : SECTION STRINGCONSTANT {
1289 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1290 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1291 GEN_ERROR("Invalid character in section name");
1292 $$ = $2;
1293 CHECK_FOR_ERROR
1294};
1295
1296OptSection : /*empty*/ { $$ = 0; } |
1297 SectionString { $$ = $1; };
1298
1299// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1300// is set to be the global we are processing.
1301//
1302GlobalVarAttributes : /* empty */ {} |
1303 ',' GlobalVarAttribute GlobalVarAttributes {};
1304GlobalVarAttribute : SectionString {
1305 CurGV->setSection(*$1);
1306 delete $1;
1307 CHECK_FOR_ERROR
1308 }
1309 | ALIGN EUINT64VAL {
1310 if ($2 != 0 && !isPowerOf2_32($2))
1311 GEN_ERROR("Alignment must be a power of two");
1312 CurGV->setAlignment($2);
1313 CHECK_FOR_ERROR
1314 };
1315
1316//===----------------------------------------------------------------------===//
1317// Types includes all predefined types... except void, because it can only be
1318// used in specific contexts (function returning void for example).
1319
1320// Derived types are added later...
1321//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001322PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323
1324Types
1325 : OPAQUE {
1326 $$ = new PATypeHolder(OpaqueType::get());
1327 CHECK_FOR_ERROR
1328 }
1329 | PrimType {
1330 $$ = new PATypeHolder($1);
1331 CHECK_FOR_ERROR
1332 }
1333 | Types '*' { // Pointer type?
1334 if (*$1 == Type::LabelTy)
1335 GEN_ERROR("Cannot form a pointer to a basic block");
1336 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1337 delete $1;
1338 CHECK_FOR_ERROR
1339 }
1340 | SymbolicValueRef { // Named types are also simple types...
1341 const Type* tmp = getTypeVal($1);
1342 CHECK_FOR_ERROR
1343 $$ = new PATypeHolder(tmp);
1344 }
1345 | '\\' EUINT64VAL { // Type UpReference
1346 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1347 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1348 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1349 $$ = new PATypeHolder(OT);
1350 UR_OUT("New Upreference!\n");
1351 CHECK_FOR_ERROR
1352 }
1353 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1354 std::vector<const Type*> Params;
1355 ParamAttrsVector Attrs;
1356 if ($5 != ParamAttr::None) {
1357 ParamAttrsWithIndex X; X.index = 0; X.attrs = $5;
1358 Attrs.push_back(X);
1359 }
1360 unsigned index = 1;
1361 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1362 for (; I != E; ++I, ++index) {
1363 const Type *Ty = I->Ty->get();
1364 Params.push_back(Ty);
1365 if (Ty != Type::VoidTy)
1366 if (I->Attrs != ParamAttr::None) {
1367 ParamAttrsWithIndex X; X.index = index; X.attrs = I->Attrs;
1368 Attrs.push_back(X);
1369 }
1370 }
1371 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1372 if (isVarArg) Params.pop_back();
1373
1374 ParamAttrsList *ActualAttrs = 0;
1375 if (!Attrs.empty())
1376 ActualAttrs = ParamAttrsList::get(Attrs);
1377 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, ActualAttrs);
1378 delete $3; // Delete the argument list
1379 delete $1; // Delete the return type handle
1380 $$ = new PATypeHolder(HandleUpRefs(FT));
1381 CHECK_FOR_ERROR
1382 }
1383 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1384 std::vector<const Type*> Params;
1385 ParamAttrsVector Attrs;
1386 if ($5 != ParamAttr::None) {
1387 ParamAttrsWithIndex X; X.index = 0; X.attrs = $5;
1388 Attrs.push_back(X);
1389 }
1390 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1391 unsigned index = 1;
1392 for ( ; I != E; ++I, ++index) {
1393 const Type* Ty = I->Ty->get();
1394 Params.push_back(Ty);
1395 if (Ty != Type::VoidTy)
1396 if (I->Attrs != ParamAttr::None) {
1397 ParamAttrsWithIndex X; X.index = index; X.attrs = I->Attrs;
1398 Attrs.push_back(X);
1399 }
1400 }
1401 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1402 if (isVarArg) Params.pop_back();
1403
1404 ParamAttrsList *ActualAttrs = 0;
1405 if (!Attrs.empty())
1406 ActualAttrs = ParamAttrsList::get(Attrs);
1407
1408 FunctionType *FT = FunctionType::get($1, Params, isVarArg, ActualAttrs);
1409 delete $3; // Delete the argument list
1410 $$ = new PATypeHolder(HandleUpRefs(FT));
1411 CHECK_FOR_ERROR
1412 }
1413
1414 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1415 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1416 delete $4;
1417 CHECK_FOR_ERROR
1418 }
1419 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1420 const llvm::Type* ElemTy = $4->get();
1421 if ((unsigned)$2 != $2)
1422 GEN_ERROR("Unsigned result not equal to signed result");
1423 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1424 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1426 delete $4;
1427 CHECK_FOR_ERROR
1428 }
1429 | '{' TypeListI '}' { // Structure type?
1430 std::vector<const Type*> Elements;
1431 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1432 E = $2->end(); I != E; ++I)
1433 Elements.push_back(*I);
1434
1435 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1436 delete $2;
1437 CHECK_FOR_ERROR
1438 }
1439 | '{' '}' { // Empty structure type?
1440 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1441 CHECK_FOR_ERROR
1442 }
1443 | '<' '{' TypeListI '}' '>' {
1444 std::vector<const Type*> Elements;
1445 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1446 E = $3->end(); I != E; ++I)
1447 Elements.push_back(*I);
1448
1449 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1450 delete $3;
1451 CHECK_FOR_ERROR
1452 }
1453 | '<' '{' '}' '>' { // Empty structure type?
1454 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1455 CHECK_FOR_ERROR
1456 }
1457 ;
1458
1459ArgType
1460 : Types OptParamAttrs {
1461 $$.Ty = $1;
1462 $$.Attrs = $2;
1463 }
1464 ;
1465
1466ResultTypes
1467 : Types {
1468 if (!UpRefs.empty())
1469 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1470 if (!(*$1)->isFirstClassType())
1471 GEN_ERROR("LLVM functions cannot return aggregate types");
1472 $$ = $1;
1473 }
1474 | VOID {
1475 $$ = new PATypeHolder(Type::VoidTy);
1476 }
1477 ;
1478
1479ArgTypeList : ArgType {
1480 $$ = new TypeWithAttrsList();
1481 $$->push_back($1);
1482 CHECK_FOR_ERROR
1483 }
1484 | ArgTypeList ',' ArgType {
1485 ($$=$1)->push_back($3);
1486 CHECK_FOR_ERROR
1487 }
1488 ;
1489
1490ArgTypeListI
1491 : ArgTypeList
1492 | ArgTypeList ',' DOTDOTDOT {
1493 $$=$1;
1494 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1495 TWA.Ty = new PATypeHolder(Type::VoidTy);
1496 $$->push_back(TWA);
1497 CHECK_FOR_ERROR
1498 }
1499 | DOTDOTDOT {
1500 $$ = new TypeWithAttrsList;
1501 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1502 TWA.Ty = new PATypeHolder(Type::VoidTy);
1503 $$->push_back(TWA);
1504 CHECK_FOR_ERROR
1505 }
1506 | /*empty*/ {
1507 $$ = new TypeWithAttrsList();
1508 CHECK_FOR_ERROR
1509 };
1510
1511// TypeList - Used for struct declarations and as a basis for function type
1512// declaration type lists
1513//
1514TypeListI : Types {
1515 $$ = new std::list<PATypeHolder>();
1516 $$->push_back(*$1);
1517 delete $1;
1518 CHECK_FOR_ERROR
1519 }
1520 | TypeListI ',' Types {
1521 ($$=$1)->push_back(*$3);
1522 delete $3;
1523 CHECK_FOR_ERROR
1524 };
1525
1526// ConstVal - The various declarations that go into the constant pool. This
1527// production is used ONLY to represent constants that show up AFTER a 'const',
1528// 'constant' or 'global' token at global scope. Constants that can be inlined
1529// into other expressions (such as integers and constexprs) are handled by the
1530// ResolvedVal, ValueRef and ConstValueRef productions.
1531//
1532ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1533 if (!UpRefs.empty())
1534 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1535 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1536 if (ATy == 0)
1537 GEN_ERROR("Cannot make array constant with type: '" +
1538 (*$1)->getDescription() + "'");
1539 const Type *ETy = ATy->getElementType();
1540 int NumElements = ATy->getNumElements();
1541
1542 // Verify that we have the correct size...
1543 if (NumElements != -1 && NumElements != (int)$3->size())
1544 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1545 utostr($3->size()) + " arguments, but has size of " +
1546 itostr(NumElements) + "");
1547
1548 // Verify all elements are correct type!
1549 for (unsigned i = 0; i < $3->size(); i++) {
1550 if (ETy != (*$3)[i]->getType())
1551 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1552 ETy->getDescription() +"' as required!\nIt is of type '"+
1553 (*$3)[i]->getType()->getDescription() + "'.");
1554 }
1555
1556 $$ = ConstantArray::get(ATy, *$3);
1557 delete $1; delete $3;
1558 CHECK_FOR_ERROR
1559 }
1560 | Types '[' ']' {
1561 if (!UpRefs.empty())
1562 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1563 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1564 if (ATy == 0)
1565 GEN_ERROR("Cannot make array constant with type: '" +
1566 (*$1)->getDescription() + "'");
1567
1568 int NumElements = ATy->getNumElements();
1569 if (NumElements != -1 && NumElements != 0)
1570 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1571 " arguments, but has size of " + itostr(NumElements) +"");
1572 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1573 delete $1;
1574 CHECK_FOR_ERROR
1575 }
1576 | Types 'c' STRINGCONSTANT {
1577 if (!UpRefs.empty())
1578 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1579 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1580 if (ATy == 0)
1581 GEN_ERROR("Cannot make array constant with type: '" +
1582 (*$1)->getDescription() + "'");
1583
1584 int NumElements = ATy->getNumElements();
1585 const Type *ETy = ATy->getElementType();
1586 if (NumElements != -1 && NumElements != int($3->length()))
1587 GEN_ERROR("Can't build string constant of size " +
1588 itostr((int)($3->length())) +
1589 " when array has size " + itostr(NumElements) + "");
1590 std::vector<Constant*> Vals;
1591 if (ETy == Type::Int8Ty) {
1592 for (unsigned i = 0; i < $3->length(); ++i)
1593 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1594 } else {
1595 delete $3;
1596 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1597 }
1598 delete $3;
1599 $$ = ConstantArray::get(ATy, Vals);
1600 delete $1;
1601 CHECK_FOR_ERROR
1602 }
1603 | Types '<' ConstVector '>' { // Nonempty unsized arr
1604 if (!UpRefs.empty())
1605 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1606 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1607 if (PTy == 0)
1608 GEN_ERROR("Cannot make packed constant with type: '" +
1609 (*$1)->getDescription() + "'");
1610 const Type *ETy = PTy->getElementType();
1611 int NumElements = PTy->getNumElements();
1612
1613 // Verify that we have the correct size...
1614 if (NumElements != -1 && NumElements != (int)$3->size())
1615 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1616 utostr($3->size()) + " arguments, but has size of " +
1617 itostr(NumElements) + "");
1618
1619 // Verify all elements are correct type!
1620 for (unsigned i = 0; i < $3->size(); i++) {
1621 if (ETy != (*$3)[i]->getType())
1622 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1623 ETy->getDescription() +"' as required!\nIt is of type '"+
1624 (*$3)[i]->getType()->getDescription() + "'.");
1625 }
1626
1627 $$ = ConstantVector::get(PTy, *$3);
1628 delete $1; delete $3;
1629 CHECK_FOR_ERROR
1630 }
1631 | Types '{' ConstVector '}' {
1632 const StructType *STy = dyn_cast<StructType>($1->get());
1633 if (STy == 0)
1634 GEN_ERROR("Cannot make struct constant with type: '" +
1635 (*$1)->getDescription() + "'");
1636
1637 if ($3->size() != STy->getNumContainedTypes())
1638 GEN_ERROR("Illegal number of initializers for structure type");
1639
1640 // Check to ensure that constants are compatible with the type initializer!
1641 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1642 if ((*$3)[i]->getType() != STy->getElementType(i))
1643 GEN_ERROR("Expected type '" +
1644 STy->getElementType(i)->getDescription() +
1645 "' for element #" + utostr(i) +
1646 " of structure initializer");
1647
1648 // Check to ensure that Type is not packed
1649 if (STy->isPacked())
1650 GEN_ERROR("Unpacked Initializer to vector type '" +
1651 STy->getDescription() + "'");
1652
1653 $$ = ConstantStruct::get(STy, *$3);
1654 delete $1; delete $3;
1655 CHECK_FOR_ERROR
1656 }
1657 | Types '{' '}' {
1658 if (!UpRefs.empty())
1659 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1660 const StructType *STy = dyn_cast<StructType>($1->get());
1661 if (STy == 0)
1662 GEN_ERROR("Cannot make struct constant with type: '" +
1663 (*$1)->getDescription() + "'");
1664
1665 if (STy->getNumContainedTypes() != 0)
1666 GEN_ERROR("Illegal number of initializers for structure type");
1667
1668 // Check to ensure that Type is not packed
1669 if (STy->isPacked())
1670 GEN_ERROR("Unpacked Initializer to vector type '" +
1671 STy->getDescription() + "'");
1672
1673 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1674 delete $1;
1675 CHECK_FOR_ERROR
1676 }
1677 | Types '<' '{' ConstVector '}' '>' {
1678 const StructType *STy = dyn_cast<StructType>($1->get());
1679 if (STy == 0)
1680 GEN_ERROR("Cannot make struct constant with type: '" +
1681 (*$1)->getDescription() + "'");
1682
1683 if ($4->size() != STy->getNumContainedTypes())
1684 GEN_ERROR("Illegal number of initializers for structure type");
1685
1686 // Check to ensure that constants are compatible with the type initializer!
1687 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1688 if ((*$4)[i]->getType() != STy->getElementType(i))
1689 GEN_ERROR("Expected type '" +
1690 STy->getElementType(i)->getDescription() +
1691 "' for element #" + utostr(i) +
1692 " of structure initializer");
1693
1694 // Check to ensure that Type is packed
1695 if (!STy->isPacked())
1696 GEN_ERROR("Vector initializer to non-vector type '" +
1697 STy->getDescription() + "'");
1698
1699 $$ = ConstantStruct::get(STy, *$4);
1700 delete $1; delete $4;
1701 CHECK_FOR_ERROR
1702 }
1703 | Types '<' '{' '}' '>' {
1704 if (!UpRefs.empty())
1705 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1706 const StructType *STy = dyn_cast<StructType>($1->get());
1707 if (STy == 0)
1708 GEN_ERROR("Cannot make struct constant with type: '" +
1709 (*$1)->getDescription() + "'");
1710
1711 if (STy->getNumContainedTypes() != 0)
1712 GEN_ERROR("Illegal number of initializers for structure type");
1713
1714 // Check to ensure that Type is packed
1715 if (!STy->isPacked())
1716 GEN_ERROR("Vector initializer to non-vector type '" +
1717 STy->getDescription() + "'");
1718
1719 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1720 delete $1;
1721 CHECK_FOR_ERROR
1722 }
1723 | Types NULL_TOK {
1724 if (!UpRefs.empty())
1725 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1726 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1727 if (PTy == 0)
1728 GEN_ERROR("Cannot make null pointer constant with type: '" +
1729 (*$1)->getDescription() + "'");
1730
1731 $$ = ConstantPointerNull::get(PTy);
1732 delete $1;
1733 CHECK_FOR_ERROR
1734 }
1735 | Types UNDEF {
1736 if (!UpRefs.empty())
1737 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1738 $$ = UndefValue::get($1->get());
1739 delete $1;
1740 CHECK_FOR_ERROR
1741 }
1742 | Types SymbolicValueRef {
1743 if (!UpRefs.empty())
1744 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1745 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1746 if (Ty == 0)
1747 GEN_ERROR("Global const reference must be a pointer type");
1748
1749 // ConstExprs can exist in the body of a function, thus creating
1750 // GlobalValues whenever they refer to a variable. Because we are in
1751 // the context of a function, getExistingVal will search the functions
1752 // symbol table instead of the module symbol table for the global symbol,
1753 // which throws things all off. To get around this, we just tell
1754 // getExistingVal that we are at global scope here.
1755 //
1756 Function *SavedCurFn = CurFun.CurrentFunction;
1757 CurFun.CurrentFunction = 0;
1758
1759 Value *V = getExistingVal(Ty, $2);
1760 CHECK_FOR_ERROR
1761
1762 CurFun.CurrentFunction = SavedCurFn;
1763
1764 // If this is an initializer for a constant pointer, which is referencing a
1765 // (currently) undefined variable, create a stub now that shall be replaced
1766 // in the future with the right type of variable.
1767 //
1768 if (V == 0) {
1769 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1770 const PointerType *PT = cast<PointerType>(Ty);
1771
1772 // First check to see if the forward references value is already created!
1773 PerModuleInfo::GlobalRefsType::iterator I =
1774 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1775
1776 if (I != CurModule.GlobalRefs.end()) {
1777 V = I->second; // Placeholder already exists, use it...
1778 $2.destroy();
1779 } else {
1780 std::string Name;
1781 if ($2.Type == ValID::GlobalName)
1782 Name = $2.getName();
1783 else if ($2.Type != ValID::GlobalID)
1784 GEN_ERROR("Invalid reference to global");
1785
1786 // Create the forward referenced global.
1787 GlobalValue *GV;
1788 if (const FunctionType *FTy =
1789 dyn_cast<FunctionType>(PT->getElementType())) {
1790 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1791 CurModule.CurrentModule);
1792 } else {
1793 GV = new GlobalVariable(PT->getElementType(), false,
1794 GlobalValue::ExternalWeakLinkage, 0,
1795 Name, CurModule.CurrentModule);
1796 }
1797
1798 // Keep track of the fact that we have a forward ref to recycle it
1799 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1800 V = GV;
1801 }
1802 }
1803
1804 $$ = cast<GlobalValue>(V);
1805 delete $1; // Free the type handle
1806 CHECK_FOR_ERROR
1807 }
1808 | Types ConstExpr {
1809 if (!UpRefs.empty())
1810 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1811 if ($1->get() != $2->getType())
1812 GEN_ERROR("Mismatched types for constant expression: " +
1813 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1814 $$ = $2;
1815 delete $1;
1816 CHECK_FOR_ERROR
1817 }
1818 | Types ZEROINITIALIZER {
1819 if (!UpRefs.empty())
1820 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1821 const Type *Ty = $1->get();
1822 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1823 GEN_ERROR("Cannot create a null initialized value of this type");
1824 $$ = Constant::getNullValue(Ty);
1825 delete $1;
1826 CHECK_FOR_ERROR
1827 }
1828 | IntType ESINT64VAL { // integral constants
1829 if (!ConstantInt::isValueValidForType($1, $2))
1830 GEN_ERROR("Constant value doesn't fit in type");
1831 $$ = ConstantInt::get($1, $2, true);
1832 CHECK_FOR_ERROR
1833 }
1834 | IntType ESAPINTVAL { // arbitrary precision integer constants
1835 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1836 if ($2->getBitWidth() > BitWidth) {
1837 GEN_ERROR("Constant value does not fit in type");
1838 }
1839 $2->sextOrTrunc(BitWidth);
1840 $$ = ConstantInt::get(*$2);
1841 delete $2;
1842 CHECK_FOR_ERROR
1843 }
1844 | IntType EUINT64VAL { // integral constants
1845 if (!ConstantInt::isValueValidForType($1, $2))
1846 GEN_ERROR("Constant value doesn't fit in type");
1847 $$ = ConstantInt::get($1, $2, false);
1848 CHECK_FOR_ERROR
1849 }
1850 | IntType EUAPINTVAL { // arbitrary precision integer constants
1851 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1852 if ($2->getBitWidth() > BitWidth) {
1853 GEN_ERROR("Constant value does not fit in type");
1854 }
1855 $2->zextOrTrunc(BitWidth);
1856 $$ = ConstantInt::get(*$2);
1857 delete $2;
1858 CHECK_FOR_ERROR
1859 }
1860 | INTTYPE TRUETOK { // Boolean constants
1861 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1862 $$ = ConstantInt::getTrue();
1863 CHECK_FOR_ERROR
1864 }
1865 | INTTYPE FALSETOK { // Boolean constants
1866 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1867 $$ = ConstantInt::getFalse();
1868 CHECK_FOR_ERROR
1869 }
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00001870 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001871 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen1616e902007-09-11 18:32:33 +00001873 // Lexer has no type info, so builds all float and double FP constants
1874 // as double. Fix this here. Long double is done right.
1875 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001876 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1877 $$ = ConstantFP::get($1, *$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001878 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879 CHECK_FOR_ERROR
1880 };
1881
1882
1883ConstExpr: CastOps '(' ConstVal TO Types ')' {
1884 if (!UpRefs.empty())
1885 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1886 Constant *Val = $3;
1887 const Type *DestTy = $5->get();
1888 if (!CastInst::castIsValid($1, $3, DestTy))
1889 GEN_ERROR("invalid cast opcode for cast from '" +
1890 Val->getType()->getDescription() + "' to '" +
1891 DestTy->getDescription() + "'");
1892 $$ = ConstantExpr::getCast($1, $3, DestTy);
1893 delete $5;
1894 }
1895 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1896 if (!isa<PointerType>($3->getType()))
1897 GEN_ERROR("GetElementPtr requires a pointer operand");
1898
1899 const Type *IdxTy =
David Greene393be882007-09-04 15:46:09 +00001900 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901 true);
1902 if (!IdxTy)
1903 GEN_ERROR("Index list invalid for constant getelementptr");
1904
1905 SmallVector<Constant*, 8> IdxVec;
1906 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1907 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1908 IdxVec.push_back(C);
1909 else
1910 GEN_ERROR("Indices to constant getelementptr must be constants");
1911
1912 delete $4;
1913
1914 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1915 CHECK_FOR_ERROR
1916 }
1917 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1918 if ($3->getType() != Type::Int1Ty)
1919 GEN_ERROR("Select condition must be of boolean type");
1920 if ($5->getType() != $7->getType())
1921 GEN_ERROR("Select operand types must match");
1922 $$ = ConstantExpr::getSelect($3, $5, $7);
1923 CHECK_FOR_ERROR
1924 }
1925 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1926 if ($3->getType() != $5->getType())
1927 GEN_ERROR("Binary operator types must match");
1928 CHECK_FOR_ERROR;
1929 $$ = ConstantExpr::get($1, $3, $5);
1930 }
1931 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1932 if ($3->getType() != $5->getType())
1933 GEN_ERROR("Logical operator types must match");
1934 if (!$3->getType()->isInteger()) {
1935 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1936 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1937 GEN_ERROR("Logical operator requires integral operands");
1938 }
1939 $$ = ConstantExpr::get($1, $3, $5);
1940 CHECK_FOR_ERROR
1941 }
1942 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1943 if ($4->getType() != $6->getType())
1944 GEN_ERROR("icmp operand types must match");
1945 $$ = ConstantExpr::getICmp($2, $4, $6);
1946 }
1947 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1948 if ($4->getType() != $6->getType())
1949 GEN_ERROR("fcmp operand types must match");
1950 $$ = ConstantExpr::getFCmp($2, $4, $6);
1951 }
1952 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1953 if (!ExtractElementInst::isValidOperands($3, $5))
1954 GEN_ERROR("Invalid extractelement operands");
1955 $$ = ConstantExpr::getExtractElement($3, $5);
1956 CHECK_FOR_ERROR
1957 }
1958 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1959 if (!InsertElementInst::isValidOperands($3, $5, $7))
1960 GEN_ERROR("Invalid insertelement operands");
1961 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1962 CHECK_FOR_ERROR
1963 }
1964 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1965 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1966 GEN_ERROR("Invalid shufflevector operands");
1967 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1968 CHECK_FOR_ERROR
1969 };
1970
1971
1972// ConstVector - A list of comma separated constants.
1973ConstVector : ConstVector ',' ConstVal {
1974 ($$ = $1)->push_back($3);
1975 CHECK_FOR_ERROR
1976 }
1977 | ConstVal {
1978 $$ = new std::vector<Constant*>();
1979 $$->push_back($1);
1980 CHECK_FOR_ERROR
1981 };
1982
1983
1984// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1985GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1986
1987// ThreadLocal
1988ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1989
1990// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1991AliaseeRef : ResultTypes SymbolicValueRef {
1992 const Type* VTy = $1->get();
1993 Value *V = getVal(VTy, $2);
Chris Lattner0f800522007-08-06 21:00:37 +00001994 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1996 if (!Aliasee)
1997 GEN_ERROR("Aliases can be created only to global values");
1998
1999 $$ = Aliasee;
2000 CHECK_FOR_ERROR
2001 delete $1;
2002 }
2003 | BITCAST '(' AliaseeRef TO Types ')' {
2004 Constant *Val = $3;
2005 const Type *DestTy = $5->get();
2006 if (!CastInst::castIsValid($1, $3, DestTy))
2007 GEN_ERROR("invalid cast opcode for cast from '" +
2008 Val->getType()->getDescription() + "' to '" +
2009 DestTy->getDescription() + "'");
2010
2011 $$ = ConstantExpr::getCast($1, $3, DestTy);
2012 CHECK_FOR_ERROR
2013 delete $5;
2014 };
2015
2016//===----------------------------------------------------------------------===//
2017// Rules to match Modules
2018//===----------------------------------------------------------------------===//
2019
2020// Module rule: Capture the result of parsing the whole file into a result
2021// variable...
2022//
2023Module
2024 : DefinitionList {
2025 $$ = ParserResult = CurModule.CurrentModule;
2026 CurModule.ModuleDone();
2027 CHECK_FOR_ERROR;
2028 }
2029 | /*empty*/ {
2030 $$ = ParserResult = CurModule.CurrentModule;
2031 CurModule.ModuleDone();
2032 CHECK_FOR_ERROR;
2033 }
2034 ;
2035
2036DefinitionList
2037 : Definition
2038 | DefinitionList Definition
2039 ;
2040
2041Definition
2042 : DEFINE { CurFun.isDeclare = false; } Function {
2043 CurFun.FunctionDone();
2044 CHECK_FOR_ERROR
2045 }
2046 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2047 CHECK_FOR_ERROR
2048 }
2049 | MODULE ASM_TOK AsmBlock {
2050 CHECK_FOR_ERROR
2051 }
2052 | OptLocalAssign TYPE Types {
2053 if (!UpRefs.empty())
2054 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2055 // Eagerly resolve types. This is not an optimization, this is a
2056 // requirement that is due to the fact that we could have this:
2057 //
2058 // %list = type { %list * }
2059 // %list = type { %list * } ; repeated type decl
2060 //
2061 // If types are not resolved eagerly, then the two types will not be
2062 // determined to be the same type!
2063 //
2064 ResolveTypeTo($1, *$3);
2065
2066 if (!setTypeName(*$3, $1) && !$1) {
2067 CHECK_FOR_ERROR
2068 // If this is a named type that is not a redefinition, add it to the slot
2069 // table.
2070 CurModule.Types.push_back(*$3);
2071 }
2072
2073 delete $3;
2074 CHECK_FOR_ERROR
2075 }
2076 | OptLocalAssign TYPE VOID {
2077 ResolveTypeTo($1, $3);
2078
2079 if (!setTypeName($3, $1) && !$1) {
2080 CHECK_FOR_ERROR
2081 // If this is a named type that is not a redefinition, add it to the slot
2082 // table.
2083 CurModule.Types.push_back($3);
2084 }
2085 CHECK_FOR_ERROR
2086 }
2087 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal {
2088 /* "Externally Visible" Linkage */
2089 if ($5 == 0)
2090 GEN_ERROR("Global value initializer is not a constant");
2091 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2092 $2, $4, $5->getType(), $5, $3);
2093 CHECK_FOR_ERROR
2094 } GlobalVarAttributes {
2095 CurGV = 0;
2096 }
2097 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2098 ConstVal {
2099 if ($6 == 0)
2100 GEN_ERROR("Global value initializer is not a constant");
2101 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4);
2102 CHECK_FOR_ERROR
2103 } GlobalVarAttributes {
2104 CurGV = 0;
2105 }
2106 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2107 Types {
2108 if (!UpRefs.empty())
2109 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2110 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4);
2111 CHECK_FOR_ERROR
2112 delete $6;
2113 } GlobalVarAttributes {
2114 CurGV = 0;
2115 CHECK_FOR_ERROR
2116 }
2117 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2118 std::string Name;
2119 if ($1) {
2120 Name = *$1;
2121 delete $1;
2122 }
2123 if (Name.empty())
2124 GEN_ERROR("Alias name cannot be empty");
2125
2126 Constant* Aliasee = $5;
2127 if (Aliasee == 0)
2128 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2129
2130 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2131 CurModule.CurrentModule);
2132 GA->setVisibility($2);
2133 InsertValue(GA, CurModule.Values);
Chris Lattner9d99b312007-09-10 23:23:53 +00002134
2135
2136 // If there was a forward reference of this alias, resolve it now.
2137
2138 ValID ID;
2139 if (!Name.empty())
2140 ID = ValID::createGlobalName(Name);
2141 else
2142 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2143
2144 if (GlobalValue *FWGV =
2145 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2146 // Replace uses of the fwdref with the actual alias.
2147 FWGV->replaceAllUsesWith(GA);
2148 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2149 GV->eraseFromParent();
2150 else
2151 cast<Function>(FWGV)->eraseFromParent();
2152 }
2153 ID.destroy();
2154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 CHECK_FOR_ERROR
2156 }
2157 | TARGET TargetDefinition {
2158 CHECK_FOR_ERROR
2159 }
2160 | DEPLIBS '=' LibrariesDefinition {
2161 CHECK_FOR_ERROR
2162 }
2163 ;
2164
2165
2166AsmBlock : STRINGCONSTANT {
2167 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2168 if (AsmSoFar.empty())
2169 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2170 else
2171 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2172 delete $1;
2173 CHECK_FOR_ERROR
2174};
2175
2176TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2177 CurModule.CurrentModule->setTargetTriple(*$3);
2178 delete $3;
2179 }
2180 | DATALAYOUT '=' STRINGCONSTANT {
2181 CurModule.CurrentModule->setDataLayout(*$3);
2182 delete $3;
2183 };
2184
2185LibrariesDefinition : '[' LibList ']';
2186
2187LibList : LibList ',' STRINGCONSTANT {
2188 CurModule.CurrentModule->addLibrary(*$3);
2189 delete $3;
2190 CHECK_FOR_ERROR
2191 }
2192 | STRINGCONSTANT {
2193 CurModule.CurrentModule->addLibrary(*$1);
2194 delete $1;
2195 CHECK_FOR_ERROR
2196 }
2197 | /* empty: end of list */ {
2198 CHECK_FOR_ERROR
2199 }
2200 ;
2201
2202//===----------------------------------------------------------------------===//
2203// Rules to match Function Headers
2204//===----------------------------------------------------------------------===//
2205
2206ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2207 if (!UpRefs.empty())
2208 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2209 if (*$3 == Type::VoidTy)
2210 GEN_ERROR("void typed arguments are invalid");
2211 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2212 $$ = $1;
2213 $1->push_back(E);
2214 CHECK_FOR_ERROR
2215 }
2216 | Types OptParamAttrs OptLocalName {
2217 if (!UpRefs.empty())
2218 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2219 if (*$1 == Type::VoidTy)
2220 GEN_ERROR("void typed arguments are invalid");
2221 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2222 $$ = new ArgListType;
2223 $$->push_back(E);
2224 CHECK_FOR_ERROR
2225 };
2226
2227ArgList : ArgListH {
2228 $$ = $1;
2229 CHECK_FOR_ERROR
2230 }
2231 | ArgListH ',' DOTDOTDOT {
2232 $$ = $1;
2233 struct ArgListEntry E;
2234 E.Ty = new PATypeHolder(Type::VoidTy);
2235 E.Name = 0;
2236 E.Attrs = ParamAttr::None;
2237 $$->push_back(E);
2238 CHECK_FOR_ERROR
2239 }
2240 | DOTDOTDOT {
2241 $$ = new ArgListType;
2242 struct ArgListEntry E;
2243 E.Ty = new PATypeHolder(Type::VoidTy);
2244 E.Name = 0;
2245 E.Attrs = ParamAttr::None;
2246 $$->push_back(E);
2247 CHECK_FOR_ERROR
2248 }
2249 | /* empty */ {
2250 $$ = 0;
2251 CHECK_FOR_ERROR
2252 };
2253
2254FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2255 OptFuncAttrs OptSection OptAlign {
2256 std::string FunctionName(*$3);
2257 delete $3; // Free strdup'd memory!
2258
2259 // Check the function result for abstractness if this is a define. We should
2260 // have no abstract types at this point
2261 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2262 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2263
2264 std::vector<const Type*> ParamTypeList;
2265 ParamAttrsVector Attrs;
2266 if ($7 != ParamAttr::None) {
2267 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $7;
2268 Attrs.push_back(PAWI);
2269 }
2270 if ($5) { // If there are arguments...
2271 unsigned index = 1;
2272 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2273 const Type* Ty = I->Ty->get();
2274 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2275 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2276 ParamTypeList.push_back(Ty);
2277 if (Ty != Type::VoidTy)
2278 if (I->Attrs != ParamAttr::None) {
2279 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2280 Attrs.push_back(PAWI);
2281 }
2282 }
2283 }
2284
2285 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2286 if (isVarArg) ParamTypeList.pop_back();
2287
2288 ParamAttrsList *PAL = 0;
2289 if (!Attrs.empty())
2290 PAL = ParamAttrsList::get(Attrs);
2291
2292 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg, PAL);
2293 const PointerType *PFT = PointerType::get(FT);
2294 delete $2;
2295
2296 ValID ID;
2297 if (!FunctionName.empty()) {
2298 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2299 } else {
2300 ID = ValID::createGlobalID(CurModule.Values.size());
2301 }
2302
2303 Function *Fn = 0;
2304 // See if this function was forward referenced. If so, recycle the object.
2305 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2306 // Move the function to the end of the list, from whereever it was
2307 // previously inserted.
2308 Fn = cast<Function>(FWRef);
2309 CurModule.CurrentModule->getFunctionList().remove(Fn);
2310 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2311 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2312 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2313 if (Fn->getFunctionType() != FT) {
2314 // The existing function doesn't have the same type. This is an overload
2315 // error.
2316 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2317 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2318 // Neither the existing or the current function is a declaration and they
2319 // have the same name and same type. Clearly this is a redefinition.
2320 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2321 } if (Fn->isDeclaration()) {
2322 // Make sure to strip off any argument names so we can't get conflicts.
2323 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2324 AI != AE; ++AI)
2325 AI->setName("");
2326 }
2327 } else { // Not already defined?
2328 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2329 CurModule.CurrentModule);
2330
2331 InsertValue(Fn, CurModule.Values);
2332 }
2333
2334 CurFun.FunctionStart(Fn);
2335
2336 if (CurFun.isDeclare) {
2337 // If we have declaration, always overwrite linkage. This will allow us to
2338 // correctly handle cases, when pointer to function is passed as argument to
2339 // another function.
2340 Fn->setLinkage(CurFun.Linkage);
2341 Fn->setVisibility(CurFun.Visibility);
2342 }
2343 Fn->setCallingConv($1);
2344 Fn->setAlignment($9);
2345 if ($8) {
2346 Fn->setSection(*$8);
2347 delete $8;
2348 }
2349
2350 // Add all of the arguments we parsed to the function...
2351 if ($5) { // Is null if empty...
2352 if (isVarArg) { // Nuke the last entry
2353 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2354 "Not a varargs marker!");
2355 delete $5->back().Ty;
2356 $5->pop_back(); // Delete the last entry
2357 }
2358 Function::arg_iterator ArgIt = Fn->arg_begin();
2359 Function::arg_iterator ArgEnd = Fn->arg_end();
2360 unsigned Idx = 1;
2361 for (ArgListType::iterator I = $5->begin();
2362 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2363 delete I->Ty; // Delete the typeholder...
2364 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2365 CHECK_FOR_ERROR
2366 InsertValue(ArgIt);
2367 Idx++;
2368 }
2369
2370 delete $5; // We're now done with the argument list
2371 }
2372 CHECK_FOR_ERROR
2373};
2374
2375BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2376
2377FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2378 $$ = CurFun.CurrentFunction;
2379
2380 // Make sure that we keep track of the linkage type even if there was a
2381 // previous "declare".
2382 $$->setLinkage($1);
2383 $$->setVisibility($2);
2384};
2385
2386END : ENDTOK | '}'; // Allow end of '}' to end a function
2387
2388Function : BasicBlockList END {
2389 $$ = $1;
2390 CHECK_FOR_ERROR
2391};
2392
2393FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2394 CurFun.CurrentFunction->setLinkage($1);
2395 CurFun.CurrentFunction->setVisibility($2);
2396 $$ = CurFun.CurrentFunction;
2397 CurFun.FunctionDone();
2398 CHECK_FOR_ERROR
2399 };
2400
2401//===----------------------------------------------------------------------===//
2402// Rules to match Basic Blocks
2403//===----------------------------------------------------------------------===//
2404
2405OptSideEffect : /* empty */ {
2406 $$ = false;
2407 CHECK_FOR_ERROR
2408 }
2409 | SIDEEFFECT {
2410 $$ = true;
2411 CHECK_FOR_ERROR
2412 };
2413
2414ConstValueRef : ESINT64VAL { // A reference to a direct constant
2415 $$ = ValID::create($1);
2416 CHECK_FOR_ERROR
2417 }
2418 | EUINT64VAL {
2419 $$ = ValID::create($1);
2420 CHECK_FOR_ERROR
2421 }
2422 | FPVAL { // Perhaps it's an FP constant?
2423 $$ = ValID::create($1);
2424 CHECK_FOR_ERROR
2425 }
2426 | TRUETOK {
2427 $$ = ValID::create(ConstantInt::getTrue());
2428 CHECK_FOR_ERROR
2429 }
2430 | FALSETOK {
2431 $$ = ValID::create(ConstantInt::getFalse());
2432 CHECK_FOR_ERROR
2433 }
2434 | NULL_TOK {
2435 $$ = ValID::createNull();
2436 CHECK_FOR_ERROR
2437 }
2438 | UNDEF {
2439 $$ = ValID::createUndef();
2440 CHECK_FOR_ERROR
2441 }
2442 | ZEROINITIALIZER { // A vector zero constant.
2443 $$ = ValID::createZeroInit();
2444 CHECK_FOR_ERROR
2445 }
2446 | '<' ConstVector '>' { // Nonempty unsized packed vector
2447 const Type *ETy = (*$2)[0]->getType();
2448 int NumElements = $2->size();
2449
2450 VectorType* pt = VectorType::get(ETy, NumElements);
2451 PATypeHolder* PTy = new PATypeHolder(
2452 HandleUpRefs(
2453 VectorType::get(
2454 ETy,
2455 NumElements)
2456 )
2457 );
2458
2459 // Verify all elements are correct type!
2460 for (unsigned i = 0; i < $2->size(); i++) {
2461 if (ETy != (*$2)[i]->getType())
2462 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2463 ETy->getDescription() +"' as required!\nIt is of type '" +
2464 (*$2)[i]->getType()->getDescription() + "'.");
2465 }
2466
2467 $$ = ValID::create(ConstantVector::get(pt, *$2));
2468 delete PTy; delete $2;
2469 CHECK_FOR_ERROR
2470 }
2471 | ConstExpr {
2472 $$ = ValID::create($1);
2473 CHECK_FOR_ERROR
2474 }
2475 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2476 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2477 delete $3;
2478 delete $5;
2479 CHECK_FOR_ERROR
2480 };
2481
2482// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2483// another value.
2484//
2485SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2486 $$ = ValID::createLocalID($1);
2487 CHECK_FOR_ERROR
2488 }
2489 | GLOBALVAL_ID {
2490 $$ = ValID::createGlobalID($1);
2491 CHECK_FOR_ERROR
2492 }
2493 | LocalName { // Is it a named reference...?
2494 $$ = ValID::createLocalName(*$1);
2495 delete $1;
2496 CHECK_FOR_ERROR
2497 }
2498 | GlobalName { // Is it a named reference...?
2499 $$ = ValID::createGlobalName(*$1);
2500 delete $1;
2501 CHECK_FOR_ERROR
2502 };
2503
2504// ValueRef - A reference to a definition... either constant or symbolic
2505ValueRef : SymbolicValueRef | ConstValueRef;
2506
2507
2508// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2509// type immediately preceeds the value reference, and allows complex constant
2510// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2511ResolvedVal : Types ValueRef {
2512 if (!UpRefs.empty())
2513 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2514 $$ = getVal(*$1, $2);
2515 delete $1;
2516 CHECK_FOR_ERROR
2517 }
2518 ;
2519
2520BasicBlockList : BasicBlockList BasicBlock {
2521 $$ = $1;
2522 CHECK_FOR_ERROR
2523 }
2524 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2525 $$ = $1;
2526 CHECK_FOR_ERROR
2527 };
2528
2529
2530// Basic blocks are terminated by branching instructions:
2531// br, br/cc, switch, ret
2532//
2533BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2534 setValueName($3, $2);
2535 CHECK_FOR_ERROR
2536 InsertValue($3);
2537 $1->getInstList().push_back($3);
2538 $$ = $1;
2539 CHECK_FOR_ERROR
2540 };
2541
2542InstructionList : InstructionList Inst {
2543 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2544 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2545 if (CI2->getParent() == 0)
2546 $1->getInstList().push_back(CI2);
2547 $1->getInstList().push_back($2);
2548 $$ = $1;
2549 CHECK_FOR_ERROR
2550 }
2551 | /* empty */ { // Empty space between instruction lists
2552 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2553 CHECK_FOR_ERROR
2554 }
2555 | LABELSTR { // Labelled (named) basic block
2556 $$ = defineBBVal(ValID::createLocalName(*$1));
2557 delete $1;
2558 CHECK_FOR_ERROR
2559
2560 };
2561
2562BBTerminatorInst : RET ResolvedVal { // Return with a result...
2563 $$ = new ReturnInst($2);
2564 CHECK_FOR_ERROR
2565 }
2566 | RET VOID { // Return with no result...
2567 $$ = new ReturnInst();
2568 CHECK_FOR_ERROR
2569 }
2570 | BR LABEL ValueRef { // Unconditional Branch...
2571 BasicBlock* tmpBB = getBBVal($3);
2572 CHECK_FOR_ERROR
2573 $$ = new BranchInst(tmpBB);
2574 } // Conditional Branch...
2575 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2576 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2577 BasicBlock* tmpBBA = getBBVal($6);
2578 CHECK_FOR_ERROR
2579 BasicBlock* tmpBBB = getBBVal($9);
2580 CHECK_FOR_ERROR
2581 Value* tmpVal = getVal(Type::Int1Ty, $3);
2582 CHECK_FOR_ERROR
2583 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2584 }
2585 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2586 Value* tmpVal = getVal($2, $3);
2587 CHECK_FOR_ERROR
2588 BasicBlock* tmpBB = getBBVal($6);
2589 CHECK_FOR_ERROR
2590 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2591 $$ = S;
2592
2593 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2594 E = $8->end();
2595 for (; I != E; ++I) {
2596 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2597 S->addCase(CI, I->second);
2598 else
2599 GEN_ERROR("Switch case is constant, but not a simple integer");
2600 }
2601 delete $8;
2602 CHECK_FOR_ERROR
2603 }
2604 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2605 Value* tmpVal = getVal($2, $3);
2606 CHECK_FOR_ERROR
2607 BasicBlock* tmpBB = getBBVal($6);
2608 CHECK_FOR_ERROR
2609 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2610 $$ = S;
2611 CHECK_FOR_ERROR
2612 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002613 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002614 TO LABEL ValueRef UNWIND LABEL ValueRef {
2615
2616 // Handle the short syntax
2617 const PointerType *PFTy = 0;
2618 const FunctionType *Ty = 0;
2619 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2620 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2621 // Pull out the types of all of the arguments...
2622 std::vector<const Type*> ParamTypes;
2623 ParamAttrsVector Attrs;
2624 if ($8 != ParamAttr::None) {
2625 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2626 Attrs.push_back(PAWI);
2627 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002628 ParamList::iterator I = $6->begin(), E = $6->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002629 unsigned index = 1;
2630 for (; I != E; ++I, ++index) {
2631 const Type *Ty = I->Val->getType();
2632 if (Ty == Type::VoidTy)
2633 GEN_ERROR("Short call syntax cannot be used with varargs");
2634 ParamTypes.push_back(Ty);
2635 if (I->Attrs != ParamAttr::None) {
2636 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2637 Attrs.push_back(PAWI);
2638 }
2639 }
2640
2641 ParamAttrsList *PAL = 0;
2642 if (!Attrs.empty())
2643 PAL = ParamAttrsList::get(Attrs);
2644 Ty = FunctionType::get($3->get(), ParamTypes, false, PAL);
2645 PFTy = PointerType::get(Ty);
2646 }
2647
2648 delete $3;
2649
2650 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2651 CHECK_FOR_ERROR
2652 BasicBlock *Normal = getBBVal($11);
2653 CHECK_FOR_ERROR
2654 BasicBlock *Except = getBBVal($14);
2655 CHECK_FOR_ERROR
2656
2657 // Check the arguments
2658 ValueList Args;
2659 if ($6->empty()) { // Has no arguments?
2660 // Make sure no arguments is a good thing!
2661 if (Ty->getNumParams() != 0)
2662 GEN_ERROR("No arguments passed to a function that "
2663 "expects arguments");
2664 } else { // Has arguments?
2665 // Loop through FunctionType's arguments and ensure they are specified
2666 // correctly!
2667 FunctionType::param_iterator I = Ty->param_begin();
2668 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002669 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002670
2671 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2672 if (ArgI->Val->getType() != *I)
2673 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2674 (*I)->getDescription() + "'");
2675 Args.push_back(ArgI->Val);
2676 }
2677
2678 if (Ty->isVarArg()) {
2679 if (I == E)
2680 for (; ArgI != ArgE; ++ArgI)
2681 Args.push_back(ArgI->Val); // push the remaining varargs
2682 } else if (I != E || ArgI != ArgE)
2683 GEN_ERROR("Invalid number of parameters detected");
2684 }
2685
2686 // Create the InvokeInst
David Greene8278ef52007-08-27 19:04:21 +00002687 InvokeInst *II = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002688 II->setCallingConv($2);
2689 $$ = II;
2690 delete $6;
2691 CHECK_FOR_ERROR
2692 }
2693 | UNWIND {
2694 $$ = new UnwindInst();
2695 CHECK_FOR_ERROR
2696 }
2697 | UNREACHABLE {
2698 $$ = new UnreachableInst();
2699 CHECK_FOR_ERROR
2700 };
2701
2702
2703
2704JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2705 $$ = $1;
2706 Constant *V = cast<Constant>(getExistingVal($2, $3));
2707 CHECK_FOR_ERROR
2708 if (V == 0)
2709 GEN_ERROR("May only switch on a constant pool value");
2710
2711 BasicBlock* tmpBB = getBBVal($6);
2712 CHECK_FOR_ERROR
2713 $$->push_back(std::make_pair(V, tmpBB));
2714 }
2715 | IntType ConstValueRef ',' LABEL ValueRef {
2716 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2717 Constant *V = cast<Constant>(getExistingVal($1, $2));
2718 CHECK_FOR_ERROR
2719
2720 if (V == 0)
2721 GEN_ERROR("May only switch on a constant pool value");
2722
2723 BasicBlock* tmpBB = getBBVal($5);
2724 CHECK_FOR_ERROR
2725 $$->push_back(std::make_pair(V, tmpBB));
2726 };
2727
2728Inst : OptLocalAssign InstVal {
2729 // Is this definition named?? if so, assign the name...
2730 setValueName($2, $1);
2731 CHECK_FOR_ERROR
2732 InsertValue($2);
2733 $$ = $2;
2734 CHECK_FOR_ERROR
2735 };
2736
2737
2738PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2739 if (!UpRefs.empty())
2740 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2741 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2742 Value* tmpVal = getVal(*$1, $3);
2743 CHECK_FOR_ERROR
2744 BasicBlock* tmpBB = getBBVal($5);
2745 CHECK_FOR_ERROR
2746 $$->push_back(std::make_pair(tmpVal, tmpBB));
2747 delete $1;
2748 }
2749 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2750 $$ = $1;
2751 Value* tmpVal = getVal($1->front().first->getType(), $4);
2752 CHECK_FOR_ERROR
2753 BasicBlock* tmpBB = getBBVal($6);
2754 CHECK_FOR_ERROR
2755 $1->push_back(std::make_pair(tmpVal, tmpBB));
2756 };
2757
2758
Dale Johannesencfb19e62007-11-05 21:20:28 +00002759ParamList : Types ValueRef OptParamAttrs {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002760 if (!UpRefs.empty())
2761 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2762 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00002763 $$ = new ParamList();
2764 ParamListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 $$->push_back(E);
2766 delete $1;
2767 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002768 | LABEL ValueRef OptParamAttrs {
2769 // Labels are only valid in ASMs
2770 $$ = new ParamList();
2771 ParamListEntry E; E.Attrs = $3; E.Val = getBBVal($2);
2772 $$->push_back(E);
2773 }
2774 | ParamList ',' Types ValueRef OptParamAttrs {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 if (!UpRefs.empty())
2776 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2777 $$ = $1;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002778 ParamListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779 $$->push_back(E);
2780 delete $3;
2781 CHECK_FOR_ERROR
2782 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002783 | ParamList ',' LABEL ValueRef OptParamAttrs {
2784 $$ = $1;
2785 ParamListEntry E; E.Attrs = $5; E.Val = getBBVal($4);
2786 $$->push_back(E);
2787 CHECK_FOR_ERROR
2788 }
2789 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002790
2791IndexList // Used for gep instructions and constant expressions
2792 : /*empty*/ { $$ = new std::vector<Value*>(); }
2793 | IndexList ',' ResolvedVal {
2794 $$ = $1;
2795 $$->push_back($3);
2796 CHECK_FOR_ERROR
2797 }
2798 ;
2799
2800OptTailCall : TAIL CALL {
2801 $$ = true;
2802 CHECK_FOR_ERROR
2803 }
2804 | CALL {
2805 $$ = false;
2806 CHECK_FOR_ERROR
2807 };
2808
2809InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2810 if (!UpRefs.empty())
2811 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2812 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2813 !isa<VectorType>((*$2).get()))
2814 GEN_ERROR(
2815 "Arithmetic operator requires integer, FP, or packed operands");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002816 Value* val1 = getVal(*$2, $3);
2817 CHECK_FOR_ERROR
2818 Value* val2 = getVal(*$2, $5);
2819 CHECK_FOR_ERROR
2820 $$ = BinaryOperator::create($1, val1, val2);
2821 if ($$ == 0)
2822 GEN_ERROR("binary operator returned null");
2823 delete $2;
2824 }
2825 | LogicalOps Types ValueRef ',' ValueRef {
2826 if (!UpRefs.empty())
2827 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2828 if (!(*$2)->isInteger()) {
2829 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2830 !cast<VectorType>($2->get())->getElementType()->isInteger())
2831 GEN_ERROR("Logical operator requires integral operands");
2832 }
2833 Value* tmpVal1 = getVal(*$2, $3);
2834 CHECK_FOR_ERROR
2835 Value* tmpVal2 = getVal(*$2, $5);
2836 CHECK_FOR_ERROR
2837 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2838 if ($$ == 0)
2839 GEN_ERROR("binary operator returned null");
2840 delete $2;
2841 }
2842 | ICMP IPredicates Types ValueRef ',' ValueRef {
2843 if (!UpRefs.empty())
2844 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2845 if (isa<VectorType>((*$3).get()))
2846 GEN_ERROR("Vector types not supported by icmp instruction");
2847 Value* tmpVal1 = getVal(*$3, $4);
2848 CHECK_FOR_ERROR
2849 Value* tmpVal2 = getVal(*$3, $6);
2850 CHECK_FOR_ERROR
2851 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2852 if ($$ == 0)
2853 GEN_ERROR("icmp operator returned null");
2854 delete $3;
2855 }
2856 | FCMP FPredicates Types ValueRef ',' ValueRef {
2857 if (!UpRefs.empty())
2858 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2859 if (isa<VectorType>((*$3).get()))
2860 GEN_ERROR("Vector types not supported by fcmp instruction");
2861 Value* tmpVal1 = getVal(*$3, $4);
2862 CHECK_FOR_ERROR
2863 Value* tmpVal2 = getVal(*$3, $6);
2864 CHECK_FOR_ERROR
2865 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2866 if ($$ == 0)
2867 GEN_ERROR("fcmp operator returned null");
2868 delete $3;
2869 }
2870 | CastOps ResolvedVal TO Types {
2871 if (!UpRefs.empty())
2872 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2873 Value* Val = $2;
2874 const Type* DestTy = $4->get();
2875 if (!CastInst::castIsValid($1, Val, DestTy))
2876 GEN_ERROR("invalid cast opcode for cast from '" +
2877 Val->getType()->getDescription() + "' to '" +
2878 DestTy->getDescription() + "'");
2879 $$ = CastInst::create($1, Val, DestTy);
2880 delete $4;
2881 }
2882 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2883 if ($2->getType() != Type::Int1Ty)
2884 GEN_ERROR("select condition must be boolean");
2885 if ($4->getType() != $6->getType())
2886 GEN_ERROR("select value types should match");
2887 $$ = new SelectInst($2, $4, $6);
2888 CHECK_FOR_ERROR
2889 }
2890 | VAARG ResolvedVal ',' Types {
2891 if (!UpRefs.empty())
2892 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2893 $$ = new VAArgInst($2, *$4);
2894 delete $4;
2895 CHECK_FOR_ERROR
2896 }
2897 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2898 if (!ExtractElementInst::isValidOperands($2, $4))
2899 GEN_ERROR("Invalid extractelement operands");
2900 $$ = new ExtractElementInst($2, $4);
2901 CHECK_FOR_ERROR
2902 }
2903 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2904 if (!InsertElementInst::isValidOperands($2, $4, $6))
2905 GEN_ERROR("Invalid insertelement operands");
2906 $$ = new InsertElementInst($2, $4, $6);
2907 CHECK_FOR_ERROR
2908 }
2909 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2910 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2911 GEN_ERROR("Invalid shufflevector operands");
2912 $$ = new ShuffleVectorInst($2, $4, $6);
2913 CHECK_FOR_ERROR
2914 }
2915 | PHI_TOK PHIList {
2916 const Type *Ty = $2->front().first->getType();
2917 if (!Ty->isFirstClassType())
2918 GEN_ERROR("PHI node operands must be of first class type");
2919 $$ = new PHINode(Ty);
2920 ((PHINode*)$$)->reserveOperandSpace($2->size());
2921 while ($2->begin() != $2->end()) {
2922 if ($2->front().first->getType() != Ty)
2923 GEN_ERROR("All elements of a PHI node must be of the same type");
2924 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2925 $2->pop_front();
2926 }
2927 delete $2; // Free the list...
2928 CHECK_FOR_ERROR
2929 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002930 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931 OptFuncAttrs {
2932
2933 // Handle the short syntax
2934 const PointerType *PFTy = 0;
2935 const FunctionType *Ty = 0;
2936 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2937 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2938 // Pull out the types of all of the arguments...
2939 std::vector<const Type*> ParamTypes;
2940 ParamAttrsVector Attrs;
2941 if ($8 != ParamAttr::None) {
2942 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2943 Attrs.push_back(PAWI);
2944 }
2945 unsigned index = 1;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002946 ParamList::iterator I = $6->begin(), E = $6->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947 for (; I != E; ++I, ++index) {
2948 const Type *Ty = I->Val->getType();
2949 if (Ty == Type::VoidTy)
2950 GEN_ERROR("Short call syntax cannot be used with varargs");
2951 ParamTypes.push_back(Ty);
2952 if (I->Attrs != ParamAttr::None) {
2953 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2954 Attrs.push_back(PAWI);
2955 }
2956 }
2957
2958 ParamAttrsList *PAL = 0;
2959 if (!Attrs.empty())
2960 PAL = ParamAttrsList::get(Attrs);
2961
2962 Ty = FunctionType::get($3->get(), ParamTypes, false, PAL);
2963 PFTy = PointerType::get(Ty);
2964 }
2965
2966 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2967 CHECK_FOR_ERROR
2968
2969 // Check for call to invalid intrinsic to avoid crashing later.
2970 if (Function *theF = dyn_cast<Function>(V)) {
2971 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2972 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2973 !theF->getIntrinsicID(true))
2974 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2975 theF->getName() + "'");
2976 }
2977
2978 // Check the arguments
2979 ValueList Args;
2980 if ($6->empty()) { // Has no arguments?
2981 // Make sure no arguments is a good thing!
2982 if (Ty->getNumParams() != 0)
2983 GEN_ERROR("No arguments passed to a function that "
2984 "expects arguments");
2985 } else { // Has arguments?
2986 // Loop through FunctionType's arguments and ensure they are specified
2987 // correctly!
2988 //
2989 FunctionType::param_iterator I = Ty->param_begin();
2990 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002991 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002992
2993 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2994 if (ArgI->Val->getType() != *I)
2995 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2996 (*I)->getDescription() + "'");
2997 Args.push_back(ArgI->Val);
2998 }
2999 if (Ty->isVarArg()) {
3000 if (I == E)
3001 for (; ArgI != ArgE; ++ArgI)
3002 Args.push_back(ArgI->Val); // push the remaining varargs
3003 } else if (I != E || ArgI != ArgE)
3004 GEN_ERROR("Invalid number of parameters detected");
3005 }
3006 // Create the call node
David Greeneb1c4a7b2007-08-01 03:43:44 +00003007 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003008 CI->setTailCall($1);
3009 CI->setCallingConv($2);
3010 $$ = CI;
3011 delete $6;
3012 delete $3;
3013 CHECK_FOR_ERROR
3014 }
3015 | MemoryInst {
3016 $$ = $1;
3017 CHECK_FOR_ERROR
3018 };
3019
3020OptVolatile : VOLATILE {
3021 $$ = true;
3022 CHECK_FOR_ERROR
3023 }
3024 | /* empty */ {
3025 $$ = false;
3026 CHECK_FOR_ERROR
3027 };
3028
3029
3030
3031MemoryInst : MALLOC Types OptCAlign {
3032 if (!UpRefs.empty())
3033 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3034 $$ = new MallocInst(*$2, 0, $3);
3035 delete $2;
3036 CHECK_FOR_ERROR
3037 }
3038 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3039 if (!UpRefs.empty())
3040 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3041 Value* tmpVal = getVal($4, $5);
3042 CHECK_FOR_ERROR
3043 $$ = new MallocInst(*$2, tmpVal, $6);
3044 delete $2;
3045 }
3046 | ALLOCA Types OptCAlign {
3047 if (!UpRefs.empty())
3048 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3049 $$ = new AllocaInst(*$2, 0, $3);
3050 delete $2;
3051 CHECK_FOR_ERROR
3052 }
3053 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3054 if (!UpRefs.empty())
3055 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3056 Value* tmpVal = getVal($4, $5);
3057 CHECK_FOR_ERROR
3058 $$ = new AllocaInst(*$2, tmpVal, $6);
3059 delete $2;
3060 }
3061 | FREE ResolvedVal {
3062 if (!isa<PointerType>($2->getType()))
3063 GEN_ERROR("Trying to free nonpointer type " +
3064 $2->getType()->getDescription() + "");
3065 $$ = new FreeInst($2);
3066 CHECK_FOR_ERROR
3067 }
3068
3069 | OptVolatile LOAD Types ValueRef OptCAlign {
3070 if (!UpRefs.empty())
3071 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3072 if (!isa<PointerType>($3->get()))
3073 GEN_ERROR("Can't load from nonpointer type: " +
3074 (*$3)->getDescription());
3075 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3076 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3077 (*$3)->getDescription());
3078 Value* tmpVal = getVal(*$3, $4);
3079 CHECK_FOR_ERROR
3080 $$ = new LoadInst(tmpVal, "", $1, $5);
3081 delete $3;
3082 }
3083 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3084 if (!UpRefs.empty())
3085 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3086 const PointerType *PT = dyn_cast<PointerType>($5->get());
3087 if (!PT)
3088 GEN_ERROR("Can't store to a nonpointer type: " +
3089 (*$5)->getDescription());
3090 const Type *ElTy = PT->getElementType();
3091 if (ElTy != $3->getType())
3092 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3093 "' into space of type '" + ElTy->getDescription() + "'");
3094
3095 Value* tmpVal = getVal(*$5, $6);
3096 CHECK_FOR_ERROR
3097 $$ = new StoreInst($3, tmpVal, $1, $7);
3098 delete $5;
3099 }
3100 | GETELEMENTPTR Types ValueRef IndexList {
3101 if (!UpRefs.empty())
3102 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3103 if (!isa<PointerType>($2->get()))
3104 GEN_ERROR("getelementptr insn requires pointer operand");
3105
David Greene393be882007-09-04 15:46:09 +00003106 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 GEN_ERROR("Invalid getelementptr indices for type '" +
3108 (*$2)->getDescription()+ "'");
3109 Value* tmpVal = getVal(*$2, $3);
3110 CHECK_FOR_ERROR
David Greene393be882007-09-04 15:46:09 +00003111 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112 delete $2;
3113 delete $4;
3114 };
3115
3116
3117%%
3118
3119// common code from the two 'RunVMAsmParser' functions
3120static Module* RunParser(Module * M) {
3121
3122 llvmAsmlineno = 1; // Reset the current line number...
3123 CurModule.CurrentModule = M;
3124#if YYDEBUG
3125 yydebug = Debug;
3126#endif
3127
3128 // Check to make sure the parser succeeded
3129 if (yyparse()) {
3130 if (ParserResult)
3131 delete ParserResult;
3132 return 0;
3133 }
3134
3135 // Emit an error if there are any unresolved types left.
3136 if (!CurModule.LateResolveTypes.empty()) {
3137 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3138 if (DID.Type == ValID::LocalName) {
3139 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3140 } else {
3141 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3142 }
3143 if (ParserResult)
3144 delete ParserResult;
3145 return 0;
3146 }
3147
3148 // Emit an error if there are any unresolved values left.
3149 if (!CurModule.LateResolveValues.empty()) {
3150 Value *V = CurModule.LateResolveValues.back();
3151 std::map<Value*, std::pair<ValID, int> >::iterator I =
3152 CurModule.PlaceHolderInfo.find(V);
3153
3154 if (I != CurModule.PlaceHolderInfo.end()) {
3155 ValID &DID = I->second.first;
3156 if (DID.Type == ValID::LocalName) {
3157 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3158 } else {
3159 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3160 }
3161 if (ParserResult)
3162 delete ParserResult;
3163 return 0;
3164 }
3165 }
3166
3167 // Check to make sure that parsing produced a result
3168 if (!ParserResult)
3169 return 0;
3170
3171 // Reset ParserResult variable while saving its value for the result.
3172 Module *Result = ParserResult;
3173 ParserResult = 0;
3174
3175 return Result;
3176}
3177
3178void llvm::GenerateError(const std::string &message, int LineNo) {
3179 if (LineNo == -1) LineNo = llvmAsmlineno;
3180 // TODO: column number in exception
3181 if (TheParseError)
3182 TheParseError->setError(CurFilename, message, LineNo);
3183 TriggerError = 1;
3184}
3185
3186int yyerror(const char *ErrorMsg) {
3187 std::string where
3188 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3189 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
3190 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3191 if (yychar != YYEMPTY && yychar != 0)
3192 errMsg += " while reading token: '" + std::string(llvmAsmtext, llvmAsmleng)+
3193 "'";
3194 GenerateError(errMsg);
3195 return 0;
3196}