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