blob: b2667a34e9831cb09cf7771168bbb5c7aaba2303 [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//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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??
Chris Lattner59363a32008-02-19 04:36:25 +0000381 if (!isa<IntegerType>(Ty) ||
382 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 GenerateError("Signed integral constant '" +
384 itostr(D.ConstPool64) + "' is invalid for type '" +
385 Ty->getDescription() + "'");
386 return 0;
387 }
388 return ConstantInt::get(Ty, D.ConstPool64, true);
389
390 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000391 if (isa<IntegerType>(Ty) &&
392 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 return ConstantInt::get(Ty, D.UConstPool64);
Chris Lattner59363a32008-02-19 04:36:25 +0000394
395 if (!isa<IntegerType>(Ty) ||
396 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range for type '" +
399 Ty->getDescription() + "'");
400 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 }
Chris Lattner59363a32008-02-19 04:36:25 +0000402 // This is really a signed reference. Transmogrify.
403 return ConstantInt::get(Ty, D.ConstPool64, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404
405 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000406 if (!Ty->isFloatingPoint() ||
407 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 GenerateError("FP constant invalid for type");
409 return 0;
410 }
Dale Johannesen255b8fe2007-09-11 18:33:39 +0000411 // Lexer has no type info, so builds all float and double FP constants
412 // as double. Fix this here. Long double does not need this.
413 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
414 Ty==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000415 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
416 return ConstantFP::get(Ty, *D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417
418 case ValID::ConstNullVal: // Is it a null value?
419 if (!isa<PointerType>(Ty)) {
420 GenerateError("Cannot create a a non pointer null");
421 return 0;
422 }
423 return ConstantPointerNull::get(cast<PointerType>(Ty));
424
425 case ValID::ConstUndefVal: // Is it an undef value?
426 return UndefValue::get(Ty);
427
428 case ValID::ConstZeroVal: // Is it a zero value?
429 return Constant::getNullValue(Ty);
430
431 case ValID::ConstantVal: // Fully resolved constant?
432 if (D.ConstantValue->getType() != Ty) {
433 GenerateError("Constant expression type different from required type");
434 return 0;
435 }
436 return D.ConstantValue;
437
438 case ValID::InlineAsmVal: { // Inline asm expression
439 const PointerType *PTy = dyn_cast<PointerType>(Ty);
440 const FunctionType *FTy =
441 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
442 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
443 GenerateError("Invalid type for asm constraint string");
444 return 0;
445 }
446 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
447 D.IAD->HasSideEffects);
448 D.destroy(); // Free InlineAsmDescriptor.
449 return IA;
450 }
451 default:
452 assert(0 && "Unhandled case!");
453 return 0;
454 } // End of switch
455
456 assert(0 && "Unhandled case!");
457 return 0;
458}
459
460// getVal - This function is identical to getExistingVal, except that if a
461// value is not already defined, it "improvises" by creating a placeholder var
462// that looks and acts just like the requested variable. When the value is
463// defined later, all uses of the placeholder variable are replaced with the
464// real thing.
465//
466static Value *getVal(const Type *Ty, const ValID &ID) {
467 if (Ty == Type::LabelTy) {
468 GenerateError("Cannot use a basic block here");
469 return 0;
470 }
471
472 // See if the value has already been defined.
473 Value *V = getExistingVal(Ty, ID);
474 if (V) return V;
475 if (TriggerError) return 0;
476
477 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
478 GenerateError("Invalid use of a composite type");
479 return 0;
480 }
481
482 // If we reached here, we referenced either a symbol that we don't know about
483 // or an id number that hasn't been read yet. We may be referencing something
484 // forward, so just create an entry to be resolved later and get to it...
485 //
486 switch (ID.Type) {
487 case ValID::GlobalName:
488 case ValID::GlobalID: {
489 const PointerType *PTy = dyn_cast<PointerType>(Ty);
490 if (!PTy) {
491 GenerateError("Invalid type for reference to global" );
492 return 0;
493 }
494 const Type* ElTy = PTy->getElementType();
495 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
496 V = new Function(FTy, GlobalValue::ExternalLinkage);
497 else
Christopher Lamb0a243582007-12-11 09:02:08 +0000498 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
499 (Module*)0, false, PTy->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 break;
501 }
502 default:
503 V = new Argument(Ty);
504 }
505
506 // Remember where this forward reference came from. FIXME, shouldn't we try
507 // to recycle these things??
508 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000509 LLLgetLineNo())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
511 if (inFunctionScope())
512 InsertValue(V, CurFun.LateResolveValues);
513 else
514 InsertValue(V, CurModule.LateResolveValues);
515 return V;
516}
517
518/// defineBBVal - This is a definition of a new basic block with the specified
519/// identifier which must be the same as CurFun.NextValNum, if its numeric.
520static BasicBlock *defineBBVal(const ValID &ID) {
521 assert(inFunctionScope() && "Can't get basic block at global scope!");
522
523 BasicBlock *BB = 0;
524
525 // First, see if this was forward referenced
526
527 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
528 if (BBI != CurFun.BBForwardRefs.end()) {
529 BB = BBI->second;
530 // The forward declaration could have been inserted anywhere in the
531 // function: insert it into the correct place now.
532 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
533 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
534
535 // We're about to erase the entry, save the key so we can clean it up.
536 ValID Tmp = BBI->first;
537
538 // Erase the forward ref from the map as its no longer "forward"
539 CurFun.BBForwardRefs.erase(ID);
540
541 // The key has been removed from the map but so we don't want to leave
542 // strdup'd memory around so destroy it too.
543 Tmp.destroy();
544
545 // If its a numbered definition, bump the number and set the BB value.
546 if (ID.Type == ValID::LocalID) {
547 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
548 InsertValue(BB);
549 }
550
551 ID.destroy();
552 return BB;
553 }
554
555 // We haven't seen this BB before and its first mention is a definition.
556 // Just create it and return it.
557 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
558 BB = new BasicBlock(Name, CurFun.CurrentFunction);
559 if (ID.Type == ValID::LocalID) {
560 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
561 InsertValue(BB);
562 }
563
564 ID.destroy(); // Free strdup'd memory
565 return BB;
566}
567
568/// getBBVal - get an existing BB value or create a forward reference for it.
569///
570static BasicBlock *getBBVal(const ValID &ID) {
571 assert(inFunctionScope() && "Can't get basic block at global scope!");
572
573 BasicBlock *BB = 0;
574
575 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
576 if (BBI != CurFun.BBForwardRefs.end()) {
577 BB = BBI->second;
578 } if (ID.Type == ValID::LocalName) {
579 std::string Name = ID.getName();
580 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000581 if (N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 if (N->getType()->getTypeID() == Type::LabelTyID)
583 BB = cast<BasicBlock>(N);
584 else
585 GenerateError("Reference to label '" + Name + "' is actually of type '"+
586 N->getType()->getDescription() + "'");
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000587 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 } else if (ID.Type == ValID::LocalID) {
589 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
590 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
591 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
592 else
593 GenerateError("Reference to label '%" + utostr(ID.Num) +
594 "' is actually of type '"+
595 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
596 }
597 } else {
598 GenerateError("Illegal label reference " + ID.getName());
599 return 0;
600 }
601
602 // If its already been defined, return it now.
603 if (BB) {
604 ID.destroy(); // Free strdup'd memory.
605 return BB;
606 }
607
608 // Otherwise, this block has not been seen before, create it.
609 std::string Name;
610 if (ID.Type == ValID::LocalName)
611 Name = ID.getName();
612 BB = new BasicBlock(Name, CurFun.CurrentFunction);
613
614 // Insert it in the forward refs map.
615 CurFun.BBForwardRefs[ID] = BB;
616
617 return BB;
618}
619
620
621//===----------------------------------------------------------------------===//
622// Code to handle forward references in instructions
623//===----------------------------------------------------------------------===//
624//
625// This code handles the late binding needed with statements that reference
626// values not defined yet... for example, a forward branch, or the PHI node for
627// a loop body.
628//
629// This keeps a table (CurFun.LateResolveValues) of all such forward references
630// and back patchs after we are done.
631//
632
633// ResolveDefinitions - If we could not resolve some defs at parsing
634// time (forward branches, phi functions for loops, etc...) resolve the
635// defs now...
636//
637static void
638ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
639 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
640 while (!LateResolvers.empty()) {
641 Value *V = LateResolvers.back();
642 LateResolvers.pop_back();
643
644 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
645 CurModule.PlaceHolderInfo.find(V);
646 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
647
648 ValID &DID = PHI->second.first;
649
650 Value *TheRealValue = getExistingVal(V->getType(), DID);
651 if (TriggerError)
652 return;
653 if (TheRealValue) {
654 V->replaceAllUsesWith(TheRealValue);
655 delete V;
656 CurModule.PlaceHolderInfo.erase(PHI);
657 } else if (FutureLateResolvers) {
658 // Functions have their unresolved items forwarded to the module late
659 // resolver table
660 InsertValue(V, *FutureLateResolvers);
661 } else {
662 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
663 GenerateError("Reference to an invalid definition: '" +DID.getName()+
664 "' of type '" + V->getType()->getDescription() + "'",
665 PHI->second.second);
666 return;
667 } else {
668 GenerateError("Reference to an invalid definition: #" +
669 itostr(DID.Num) + " of type '" +
670 V->getType()->getDescription() + "'",
671 PHI->second.second);
672 return;
673 }
674 }
675 }
676 LateResolvers.clear();
677}
678
679// ResolveTypeTo - A brand new type was just declared. This means that (if
680// name is not null) things referencing Name can be resolved. Otherwise, things
681// refering to the number can be resolved. Do this now.
682//
683static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
684 ValID D;
685 if (Name)
686 D = ValID::createLocalName(*Name);
687 else
688 D = ValID::createLocalID(CurModule.Types.size());
689
690 std::map<ValID, PATypeHolder>::iterator I =
691 CurModule.LateResolveTypes.find(D);
692 if (I != CurModule.LateResolveTypes.end()) {
693 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
694 CurModule.LateResolveTypes.erase(I);
695 }
696}
697
698// setValueName - Set the specified value to the name given. The name may be
699// null potentially, in which case this is a noop. The string passed in is
700// assumed to be a malloc'd string buffer, and is free'd by this function.
701//
702static void setValueName(Value *V, std::string *NameStr) {
703 if (!NameStr) return;
704 std::string Name(*NameStr); // Copy string
705 delete NameStr; // Free old string
706
707 if (V->getType() == Type::VoidTy) {
708 GenerateError("Can't assign name '" + Name+"' to value with void type");
709 return;
710 }
711
712 assert(inFunctionScope() && "Must be in function scope!");
713 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
714 if (ST.lookup(Name)) {
715 GenerateError("Redefinition of value '" + Name + "' of type '" +
716 V->getType()->getDescription() + "'");
717 return;
718 }
719
720 // Set the name.
721 V->setName(Name);
722}
723
724/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
725/// this is a declaration, otherwise it is a definition.
726static GlobalVariable *
727ParseGlobalVariable(std::string *NameStr,
728 GlobalValue::LinkageTypes Linkage,
729 GlobalValue::VisibilityTypes Visibility,
730 bool isConstantGlobal, const Type *Ty,
Christopher Lamb0a243582007-12-11 09:02:08 +0000731 Constant *Initializer, bool IsThreadLocal,
732 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 if (isa<FunctionType>(Ty)) {
734 GenerateError("Cannot declare global vars of function type");
735 return 0;
736 }
737
Christopher Lamb0a243582007-12-11 09:02:08 +0000738 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739
740 std::string Name;
741 if (NameStr) {
742 Name = *NameStr; // Copy string
743 delete NameStr; // Free old string
744 }
745
746 // See if this global value was forward referenced. If so, recycle the
747 // object.
748 ValID ID;
749 if (!Name.empty()) {
750 ID = ValID::createGlobalName(Name);
751 } else {
752 ID = ValID::createGlobalID(CurModule.Values.size());
753 }
754
755 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
756 // Move the global to the end of the list, from whereever it was
757 // previously inserted.
758 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
759 CurModule.CurrentModule->getGlobalList().remove(GV);
760 CurModule.CurrentModule->getGlobalList().push_back(GV);
761 GV->setInitializer(Initializer);
762 GV->setLinkage(Linkage);
763 GV->setVisibility(Visibility);
764 GV->setConstant(isConstantGlobal);
765 GV->setThreadLocal(IsThreadLocal);
766 InsertValue(GV, CurModule.Values);
767 return GV;
768 }
769
770 // If this global has a name
771 if (!Name.empty()) {
772 // if the global we're parsing has an initializer (is a definition) and
773 // has external linkage.
774 if (Initializer && Linkage != GlobalValue::InternalLinkage)
775 // If there is already a global with external linkage with this name
776 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
777 // If we allow this GVar to get created, it will be renamed in the
778 // symbol table because it conflicts with an existing GVar. We can't
779 // allow redefinition of GVars whose linking indicates that their name
780 // must stay the same. Issue the error.
781 GenerateError("Redefinition of global variable named '" + Name +
782 "' of type '" + Ty->getDescription() + "'");
783 return 0;
784 }
785 }
786
787 // Otherwise there is no existing GV to use, create one now.
788 GlobalVariable *GV =
789 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb0a243582007-12-11 09:02:08 +0000790 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791 GV->setVisibility(Visibility);
792 InsertValue(GV, CurModule.Values);
793 return GV;
794}
795
796// setTypeName - Set the specified type to the name given. The name may be
797// null potentially, in which case this is a noop. The string passed in is
798// assumed to be a malloc'd string buffer, and is freed by this function.
799//
800// This function returns true if the type has already been defined, but is
801// allowed to be redefined in the specified context. If the name is a new name
802// for the type plane, it is inserted and false is returned.
803static bool setTypeName(const Type *T, std::string *NameStr) {
804 assert(!inFunctionScope() && "Can't give types function-local names!");
805 if (NameStr == 0) return false;
806
807 std::string Name(*NameStr); // Copy string
808 delete NameStr; // Free old string
809
810 // We don't allow assigning names to void type
811 if (T == Type::VoidTy) {
812 GenerateError("Can't assign name '" + Name + "' to the void type");
813 return false;
814 }
815
816 // Set the type name, checking for conflicts as we do so.
817 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
818
819 if (AlreadyExists) { // Inserting a name that is already defined???
820 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
821 assert(Existing && "Conflict but no matching type?!");
822
823 // There is only one case where this is allowed: when we are refining an
824 // opaque type. In this case, Existing will be an opaque type.
825 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
826 // We ARE replacing an opaque type!
827 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
828 return true;
829 }
830
831 // Otherwise, this is an attempt to redefine a type. That's okay if
832 // the redefinition is identical to the original. This will be so if
833 // Existing and T point to the same Type object. In this one case we
834 // allow the equivalent redefinition.
835 if (Existing == T) return true; // Yes, it's equal.
836
837 // Any other kind of (non-equivalent) redefinition is an error.
838 GenerateError("Redefinition of type named '" + Name + "' of type '" +
839 T->getDescription() + "'");
840 }
841
842 return false;
843}
844
845//===----------------------------------------------------------------------===//
846// Code for handling upreferences in type names...
847//
848
849// TypeContains - Returns true if Ty directly contains E in it.
850//
851static bool TypeContains(const Type *Ty, const Type *E) {
852 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
853 E) != Ty->subtype_end();
854}
855
856namespace {
857 struct UpRefRecord {
858 // NestingLevel - The number of nesting levels that need to be popped before
859 // this type is resolved.
860 unsigned NestingLevel;
861
862 // LastContainedTy - This is the type at the current binding level for the
863 // type. Every time we reduce the nesting level, this gets updated.
864 const Type *LastContainedTy;
865
866 // UpRefTy - This is the actual opaque type that the upreference is
867 // represented with.
868 OpaqueType *UpRefTy;
869
870 UpRefRecord(unsigned NL, OpaqueType *URTy)
871 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
872 };
873}
874
875// UpRefs - A list of the outstanding upreferences that need to be resolved.
876static std::vector<UpRefRecord> UpRefs;
877
878/// HandleUpRefs - Every time we finish a new layer of types, this function is
879/// called. It loops through the UpRefs vector, which is a list of the
880/// currently active types. For each type, if the up reference is contained in
881/// the newly completed type, we decrement the level count. When the level
882/// count reaches zero, the upreferenced type is the type that is passed in:
883/// thus we can complete the cycle.
884///
885static PATypeHolder HandleUpRefs(const Type *ty) {
886 // If Ty isn't abstract, or if there are no up-references in it, then there is
887 // nothing to resolve here.
888 if (!ty->isAbstract() || UpRefs.empty()) return ty;
889
890 PATypeHolder Ty(ty);
891 UR_OUT("Type '" << Ty->getDescription() <<
892 "' newly formed. Resolving upreferences.\n" <<
893 UpRefs.size() << " upreferences active!\n");
894
895 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
896 // to zero), we resolve them all together before we resolve them to Ty. At
897 // the end of the loop, if there is anything to resolve to Ty, it will be in
898 // this variable.
899 OpaqueType *TypeToResolve = 0;
900
901 for (unsigned i = 0; i != UpRefs.size(); ++i) {
902 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
903 << UpRefs[i].second->getDescription() << ") = "
904 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
905 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
906 // Decrement level of upreference
907 unsigned Level = --UpRefs[i].NestingLevel;
908 UpRefs[i].LastContainedTy = Ty;
909 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
910 if (Level == 0) { // Upreference should be resolved!
911 if (!TypeToResolve) {
912 TypeToResolve = UpRefs[i].UpRefTy;
913 } else {
914 UR_OUT(" * Resolving upreference for "
915 << UpRefs[i].second->getDescription() << "\n";
916 std::string OldName = UpRefs[i].UpRefTy->getDescription());
917 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
918 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
919 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
920 }
921 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
922 --i; // Do not skip the next element...
923 }
924 }
925 }
926
927 if (TypeToResolve) {
928 UR_OUT(" * Resolving upreference for "
929 << UpRefs[i].second->getDescription() << "\n";
930 std::string OldName = TypeToResolve->getDescription());
931 TypeToResolve->refineAbstractTypeTo(Ty);
932 }
933
934 return Ty;
935}
936
937//===----------------------------------------------------------------------===//
938// RunVMAsmParser - Define an interface to this parser
939//===----------------------------------------------------------------------===//
940//
941static Module* RunParser(Module * M);
942
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000943Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
944 InitLLLexer(MB);
945 Module *M = RunParser(new Module(LLLgetFilename()));
946 FreeLexer();
947 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948}
949
950%}
951
952%union {
953 llvm::Module *ModuleVal;
954 llvm::Function *FunctionVal;
955 llvm::BasicBlock *BasicBlockVal;
956 llvm::TerminatorInst *TermInstVal;
957 llvm::Instruction *InstVal;
958 llvm::Constant *ConstVal;
959
960 const llvm::Type *PrimType;
961 std::list<llvm::PATypeHolder> *TypeList;
962 llvm::PATypeHolder *TypeVal;
963 llvm::Value *ValueVal;
964 std::vector<llvm::Value*> *ValueList;
965 llvm::ArgListType *ArgList;
966 llvm::TypeWithAttrs TypeWithAttrs;
967 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000968 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969
970 // Represent the RHS of PHI node
971 std::list<std::pair<llvm::Value*,
972 llvm::BasicBlock*> > *PHIList;
973 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
974 std::vector<llvm::Constant*> *ConstVector;
975
976 llvm::GlobalValue::LinkageTypes Linkage;
977 llvm::GlobalValue::VisibilityTypes Visibility;
Dale Johannesend915ee52008-02-19 21:40:51 +0000978 llvm::ParameterAttributes ParamAttrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979 llvm::APInt *APIntVal;
980 int64_t SInt64Val;
981 uint64_t UInt64Val;
982 int SIntVal;
983 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000984 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 bool BoolVal;
986
987 std::string *StrVal; // This memory must be deleted
988 llvm::ValID ValIDVal;
989
990 llvm::Instruction::BinaryOps BinaryOpVal;
991 llvm::Instruction::TermOps TermOpVal;
992 llvm::Instruction::MemoryOps MemOpVal;
993 llvm::Instruction::CastOps CastOpVal;
994 llvm::Instruction::OtherOps OtherOpVal;
995 llvm::ICmpInst::Predicate IPredicate;
996 llvm::FCmpInst::Predicate FPredicate;
997}
998
999%type <ModuleVal> Module
1000%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1001%type <BasicBlockVal> BasicBlock InstructionList
1002%type <TermInstVal> BBTerminatorInst
1003%type <InstVal> Inst InstVal MemoryInst
1004%type <ConstVal> ConstVal ConstExpr AliaseeRef
1005%type <ConstVector> ConstVector
1006%type <ArgList> ArgList ArgListH
1007%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001008%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009%type <ValueList> IndexList // For GEP indices
1010%type <TypeList> TypeListI
1011%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1012%type <TypeWithAttrs> ArgType
1013%type <JumpTable> JumpTable
1014%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1015%type <BoolVal> ThreadLocal // 'thread_local' or not
1016%type <BoolVal> OptVolatile // 'volatile' or not
1017%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1018%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1019%type <Linkage> GVInternalLinkage GVExternalLinkage
1020%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1021%type <Linkage> AliasLinkage
1022%type <Visibility> GVVisibilityStyle
1023
1024// ValueRef - Unresolved reference to a definition or BB
1025%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1026%type <ValueVal> ResolvedVal // <type> <valref> pair
1027// Tokens and types for handling constant integer values
1028//
1029// ESINT64VAL - A negative number within long long range
1030%token <SInt64Val> ESINT64VAL
1031
1032// EUINT64VAL - A positive number within uns. long long range
1033%token <UInt64Val> EUINT64VAL
1034
1035// ESAPINTVAL - A negative number with arbitrary precision
1036%token <APIntVal> ESAPINTVAL
1037
1038// EUAPINTVAL - A positive number with arbitrary precision
1039%token <APIntVal> EUAPINTVAL
1040
1041%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1042%token <FPVal> FPVAL // Float or Double constant
1043
1044// Built in types...
1045%type <TypeVal> Types ResultTypes
1046%type <PrimType> IntType FPType PrimType // Classifications
1047%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001048%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049%token TYPE
1050
1051
1052%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1053%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1054%type <StrVal> LocalName OptLocalName OptLocalAssign
1055%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001056%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057
Christopher Lamb668d9a02007-12-12 08:45:45 +00001058%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059
1060%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1061%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1062%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1063%token DLLIMPORT DLLEXPORT EXTERN_WEAK
Christopher Lamb0a243582007-12-11 09:02:08 +00001064%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1066%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1067%token DATALAYOUT
1068%type <UIntVal> OptCallingConv
1069%type <ParamAttrs> OptParamAttrs ParamAttr
1070%type <ParamAttrs> OptFuncAttrs FuncAttr
1071
1072// Basic Block Terminating Operators
1073%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1074
1075// Binary Operators
1076%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1077%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1078%token <BinaryOpVal> SHL LSHR ASHR
1079
1080%token <OtherOpVal> ICMP FCMP
1081%type <IPredicate> IPredicates
1082%type <FPredicate> FPredicates
1083%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1084%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1085
1086// Memory Instructions
1087%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1088
1089// Cast Operators
1090%type <CastOpVal> CastOps
1091%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1092%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1093
1094// Other Operators
1095%token <OtherOpVal> PHI_TOK SELECT VAARG
1096%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Devang Patel3b8849c2008-02-19 22:27:01 +00001097%token <OtherOpVal> GETRESULT
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098
1099// Function Attributes
Reid Spenceraa8ae282007-07-31 03:50:36 +00001100%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001101%token READNONE READONLY GC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102
1103// Visibility Styles
1104%token DEFAULT HIDDEN PROTECTED
1105
1106%start Module
1107%%
1108
1109
1110// Operations that are notably excluded from this list include:
1111// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1112//
1113ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1114LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1115CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1116 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1117
1118IPredicates
1119 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1120 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1121 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1122 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1123 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1124 ;
1125
1126FPredicates
1127 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1128 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1129 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1130 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1131 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1132 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1133 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1134 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1135 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1136 ;
1137
1138// These are some types that allow classification if we only want a particular
1139// thing... for example, only a signed, unsigned, or integral type.
1140IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001141FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142
1143LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1144OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1145
Christopher Lamb668d9a02007-12-12 08:45:45 +00001146OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1147 | /*empty*/ { $$=0; };
1148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149/// OptLocalAssign - Value producing statements have an optional assignment
1150/// component.
1151OptLocalAssign : LocalName '=' {
1152 $$ = $1;
1153 CHECK_FOR_ERROR
1154 }
1155 | /*empty*/ {
1156 $$ = 0;
1157 CHECK_FOR_ERROR
1158 };
1159
1160GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1161
1162OptGlobalAssign : GlobalAssign
1163 | /*empty*/ {
1164 $$ = 0;
1165 CHECK_FOR_ERROR
1166 };
1167
1168GlobalAssign : GlobalName '=' {
1169 $$ = $1;
1170 CHECK_FOR_ERROR
1171 };
1172
1173GVInternalLinkage
1174 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1175 | WEAK { $$ = GlobalValue::WeakLinkage; }
1176 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1177 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1178 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1179 ;
1180
1181GVExternalLinkage
1182 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1183 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1184 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1185 ;
1186
1187GVVisibilityStyle
1188 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1189 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1190 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1191 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1192 ;
1193
1194FunctionDeclareLinkage
1195 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1196 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1197 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1198 ;
1199
1200FunctionDefineLinkage
1201 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1202 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1203 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1204 | WEAK { $$ = GlobalValue::WeakLinkage; }
1205 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1206 ;
1207
1208AliasLinkage
1209 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1210 | WEAK { $$ = GlobalValue::WeakLinkage; }
1211 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1212 ;
1213
1214OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1215 CCC_TOK { $$ = CallingConv::C; } |
1216 FASTCC_TOK { $$ = CallingConv::Fast; } |
1217 COLDCC_TOK { $$ = CallingConv::Cold; } |
1218 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1219 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1220 CC_TOK EUINT64VAL {
1221 if ((unsigned)$2 != $2)
1222 GEN_ERROR("Calling conv too large");
1223 $$ = $2;
1224 CHECK_FOR_ERROR
1225 };
1226
Reid Spenceraa8ae282007-07-31 03:50:36 +00001227ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1228 | ZEXT { $$ = ParamAttr::ZExt; }
1229 | SIGNEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 | SEXT { $$ = ParamAttr::SExt; }
1231 | INREG { $$ = ParamAttr::InReg; }
1232 | SRET { $$ = ParamAttr::StructRet; }
1233 | NOALIAS { $$ = ParamAttr::NoAlias; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001234 | BYVAL { $$ = ParamAttr::ByVal; }
1235 | NEST { $$ = ParamAttr::Nest; }
Dale Johannesena79ecf32008-02-20 21:15:43 +00001236 | ALIGN EUINT64VAL { $$ = $2 << 16; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 ;
1238
1239OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1240 | OptParamAttrs ParamAttr {
1241 $$ = $1 | $2;
1242 }
1243 ;
1244
1245FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1246 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001247 | ZEROEXT { $$ = ParamAttr::ZExt; }
1248 | SIGNEXT { $$ = ParamAttr::SExt; }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001249 | READNONE { $$ = ParamAttr::ReadNone; }
1250 | READONLY { $$ = ParamAttr::ReadOnly; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 ;
1252
1253OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1254 | OptFuncAttrs FuncAttr {
1255 $$ = $1 | $2;
1256 }
1257 ;
1258
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001259OptGC : /* empty */ { $$ = 0; }
1260 | GC STRINGCONSTANT {
1261 $$ = $2;
1262 }
1263 ;
1264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1266// a comma before it.
1267OptAlign : /*empty*/ { $$ = 0; } |
1268 ALIGN EUINT64VAL {
1269 $$ = $2;
1270 if ($$ != 0 && !isPowerOf2_32($$))
1271 GEN_ERROR("Alignment must be a power of two");
1272 CHECK_FOR_ERROR
1273};
1274OptCAlign : /*empty*/ { $$ = 0; } |
1275 ',' ALIGN EUINT64VAL {
1276 $$ = $3;
1277 if ($$ != 0 && !isPowerOf2_32($$))
1278 GEN_ERROR("Alignment must be a power of two");
1279 CHECK_FOR_ERROR
1280};
1281
1282
Christopher Lamb0a243582007-12-11 09:02:08 +00001283
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284SectionString : SECTION STRINGCONSTANT {
1285 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1286 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1287 GEN_ERROR("Invalid character in section name");
1288 $$ = $2;
1289 CHECK_FOR_ERROR
1290};
1291
1292OptSection : /*empty*/ { $$ = 0; } |
1293 SectionString { $$ = $1; };
1294
1295// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1296// is set to be the global we are processing.
1297//
1298GlobalVarAttributes : /* empty */ {} |
1299 ',' GlobalVarAttribute GlobalVarAttributes {};
1300GlobalVarAttribute : SectionString {
1301 CurGV->setSection(*$1);
1302 delete $1;
1303 CHECK_FOR_ERROR
1304 }
1305 | ALIGN EUINT64VAL {
1306 if ($2 != 0 && !isPowerOf2_32($2))
1307 GEN_ERROR("Alignment must be a power of two");
1308 CurGV->setAlignment($2);
1309 CHECK_FOR_ERROR
1310 };
1311
1312//===----------------------------------------------------------------------===//
1313// Types includes all predefined types... except void, because it can only be
1314// used in specific contexts (function returning void for example).
1315
1316// Derived types are added later...
1317//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001318PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319
1320Types
1321 : OPAQUE {
1322 $$ = new PATypeHolder(OpaqueType::get());
1323 CHECK_FOR_ERROR
1324 }
1325 | PrimType {
1326 $$ = new PATypeHolder($1);
1327 CHECK_FOR_ERROR
1328 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00001329 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 if (*$1 == Type::LabelTy)
1331 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb668d9a02007-12-12 08:45:45 +00001332 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb0a243582007-12-11 09:02:08 +00001333 delete $1;
1334 CHECK_FOR_ERROR
1335 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 | SymbolicValueRef { // Named types are also simple types...
1337 const Type* tmp = getTypeVal($1);
1338 CHECK_FOR_ERROR
1339 $$ = new PATypeHolder(tmp);
1340 }
1341 | '\\' EUINT64VAL { // Type UpReference
1342 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1343 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1344 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1345 $$ = new PATypeHolder(OT);
1346 UR_OUT("New Upreference!\n");
1347 CHECK_FOR_ERROR
1348 }
1349 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001350 // Allow but ignore attributes on function types; this permits auto-upgrade.
1351 // FIXME: remove in LLVM 3.0.
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001352 const Type* RetTy = *$1;
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001353 if (!(RetTy->isFirstClassType() || RetTy == Type::VoidTy ||
1354 isa<OpaqueType>(RetTy)))
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001355 GEN_ERROR("LLVM Functions cannot return aggregates");
1356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001359 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 const Type *Ty = I->Ty->get();
1361 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001363
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1365 if (isVarArg) Params.pop_back();
1366
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001367 for (unsigned i = 0; i != Params.size(); ++i)
1368 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1369 GEN_ERROR("Function arguments must be value types!");
1370
1371 CHECK_FOR_ERROR
1372
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001373 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001374 delete $3; // Delete the argument list
1375 delete $1; // Delete the return type handle
1376 $$ = new PATypeHolder(HandleUpRefs(FT));
1377 CHECK_FOR_ERROR
1378 }
1379 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001380 // Allow but ignore attributes on function types; this permits auto-upgrade.
1381 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001384 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 const Type* Ty = I->Ty->get();
1386 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001388
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1390 if (isVarArg) Params.pop_back();
1391
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001392 for (unsigned i = 0; i != Params.size(); ++i)
1393 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1394 GEN_ERROR("Function arguments must be value types!");
1395
1396 CHECK_FOR_ERROR
1397
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001398 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001399 delete $3; // Delete the argument list
1400 $$ = new PATypeHolder(HandleUpRefs(FT));
1401 CHECK_FOR_ERROR
1402 }
1403
1404 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1405 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1406 delete $4;
1407 CHECK_FOR_ERROR
1408 }
1409 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1410 const llvm::Type* ElemTy = $4->get();
1411 if ((unsigned)$2 != $2)
1412 GEN_ERROR("Unsigned result not equal to signed result");
1413 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1414 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1416 delete $4;
1417 CHECK_FOR_ERROR
1418 }
1419 | '{' TypeListI '}' { // Structure type?
1420 std::vector<const Type*> Elements;
1421 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1422 E = $2->end(); I != E; ++I)
1423 Elements.push_back(*I);
1424
1425 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1426 delete $2;
1427 CHECK_FOR_ERROR
1428 }
1429 | '{' '}' { // Empty structure type?
1430 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1431 CHECK_FOR_ERROR
1432 }
1433 | '<' '{' TypeListI '}' '>' {
1434 std::vector<const Type*> Elements;
1435 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1436 E = $3->end(); I != E; ++I)
1437 Elements.push_back(*I);
1438
1439 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1440 delete $3;
1441 CHECK_FOR_ERROR
1442 }
1443 | '<' '{' '}' '>' { // Empty structure type?
1444 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1445 CHECK_FOR_ERROR
1446 }
1447 ;
1448
1449ArgType
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001450 : Types OptParamAttrs {
1451 // Allow but ignore attributes on function types; this permits auto-upgrade.
1452 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 $$.Ty = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001454 $$.Attrs = ParamAttr::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 }
1456 ;
1457
1458ResultTypes
1459 : Types {
1460 if (!UpRefs.empty())
1461 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1462 if (!(*$1)->isFirstClassType())
1463 GEN_ERROR("LLVM functions cannot return aggregate types");
1464 $$ = $1;
1465 }
1466 | VOID {
1467 $$ = new PATypeHolder(Type::VoidTy);
1468 }
1469 ;
1470
1471ArgTypeList : ArgType {
1472 $$ = new TypeWithAttrsList();
1473 $$->push_back($1);
1474 CHECK_FOR_ERROR
1475 }
1476 | ArgTypeList ',' ArgType {
1477 ($$=$1)->push_back($3);
1478 CHECK_FOR_ERROR
1479 }
1480 ;
1481
1482ArgTypeListI
1483 : ArgTypeList
1484 | ArgTypeList ',' DOTDOTDOT {
1485 $$=$1;
1486 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1487 TWA.Ty = new PATypeHolder(Type::VoidTy);
1488 $$->push_back(TWA);
1489 CHECK_FOR_ERROR
1490 }
1491 | DOTDOTDOT {
1492 $$ = new TypeWithAttrsList;
1493 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1494 TWA.Ty = new PATypeHolder(Type::VoidTy);
1495 $$->push_back(TWA);
1496 CHECK_FOR_ERROR
1497 }
1498 | /*empty*/ {
1499 $$ = new TypeWithAttrsList();
1500 CHECK_FOR_ERROR
1501 };
1502
1503// TypeList - Used for struct declarations and as a basis for function type
1504// declaration type lists
1505//
1506TypeListI : Types {
1507 $$ = new std::list<PATypeHolder>();
1508 $$->push_back(*$1);
1509 delete $1;
1510 CHECK_FOR_ERROR
1511 }
1512 | TypeListI ',' Types {
1513 ($$=$1)->push_back(*$3);
1514 delete $3;
1515 CHECK_FOR_ERROR
1516 };
1517
1518// ConstVal - The various declarations that go into the constant pool. This
1519// production is used ONLY to represent constants that show up AFTER a 'const',
1520// 'constant' or 'global' token at global scope. Constants that can be inlined
1521// into other expressions (such as integers and constexprs) are handled by the
1522// ResolvedVal, ValueRef and ConstValueRef productions.
1523//
1524ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1525 if (!UpRefs.empty())
1526 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1527 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1528 if (ATy == 0)
1529 GEN_ERROR("Cannot make array constant with type: '" +
1530 (*$1)->getDescription() + "'");
1531 const Type *ETy = ATy->getElementType();
1532 int NumElements = ATy->getNumElements();
1533
1534 // Verify that we have the correct size...
1535 if (NumElements != -1 && NumElements != (int)$3->size())
1536 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1537 utostr($3->size()) + " arguments, but has size of " +
1538 itostr(NumElements) + "");
1539
1540 // Verify all elements are correct type!
1541 for (unsigned i = 0; i < $3->size(); i++) {
1542 if (ETy != (*$3)[i]->getType())
1543 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1544 ETy->getDescription() +"' as required!\nIt is of type '"+
1545 (*$3)[i]->getType()->getDescription() + "'.");
1546 }
1547
1548 $$ = ConstantArray::get(ATy, *$3);
1549 delete $1; delete $3;
1550 CHECK_FOR_ERROR
1551 }
1552 | Types '[' ']' {
1553 if (!UpRefs.empty())
1554 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1555 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1556 if (ATy == 0)
1557 GEN_ERROR("Cannot make array constant with type: '" +
1558 (*$1)->getDescription() + "'");
1559
1560 int NumElements = ATy->getNumElements();
1561 if (NumElements != -1 && NumElements != 0)
1562 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1563 " arguments, but has size of " + itostr(NumElements) +"");
1564 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1565 delete $1;
1566 CHECK_FOR_ERROR
1567 }
1568 | Types 'c' STRINGCONSTANT {
1569 if (!UpRefs.empty())
1570 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1571 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1572 if (ATy == 0)
1573 GEN_ERROR("Cannot make array constant with type: '" +
1574 (*$1)->getDescription() + "'");
1575
1576 int NumElements = ATy->getNumElements();
1577 const Type *ETy = ATy->getElementType();
1578 if (NumElements != -1 && NumElements != int($3->length()))
1579 GEN_ERROR("Can't build string constant of size " +
1580 itostr((int)($3->length())) +
1581 " when array has size " + itostr(NumElements) + "");
1582 std::vector<Constant*> Vals;
1583 if (ETy == Type::Int8Ty) {
1584 for (unsigned i = 0; i < $3->length(); ++i)
1585 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1586 } else {
1587 delete $3;
1588 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1589 }
1590 delete $3;
1591 $$ = ConstantArray::get(ATy, Vals);
1592 delete $1;
1593 CHECK_FOR_ERROR
1594 }
1595 | Types '<' ConstVector '>' { // Nonempty unsized arr
1596 if (!UpRefs.empty())
1597 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1598 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1599 if (PTy == 0)
1600 GEN_ERROR("Cannot make packed constant with type: '" +
1601 (*$1)->getDescription() + "'");
1602 const Type *ETy = PTy->getElementType();
1603 int NumElements = PTy->getNumElements();
1604
1605 // Verify that we have the correct size...
1606 if (NumElements != -1 && NumElements != (int)$3->size())
1607 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1608 utostr($3->size()) + " arguments, but has size of " +
1609 itostr(NumElements) + "");
1610
1611 // Verify all elements are correct type!
1612 for (unsigned i = 0; i < $3->size(); i++) {
1613 if (ETy != (*$3)[i]->getType())
1614 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1615 ETy->getDescription() +"' as required!\nIt is of type '"+
1616 (*$3)[i]->getType()->getDescription() + "'.");
1617 }
1618
1619 $$ = ConstantVector::get(PTy, *$3);
1620 delete $1; delete $3;
1621 CHECK_FOR_ERROR
1622 }
1623 | Types '{' ConstVector '}' {
1624 const StructType *STy = dyn_cast<StructType>($1->get());
1625 if (STy == 0)
1626 GEN_ERROR("Cannot make struct constant with type: '" +
1627 (*$1)->getDescription() + "'");
1628
1629 if ($3->size() != STy->getNumContainedTypes())
1630 GEN_ERROR("Illegal number of initializers for structure type");
1631
1632 // Check to ensure that constants are compatible with the type initializer!
1633 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1634 if ((*$3)[i]->getType() != STy->getElementType(i))
1635 GEN_ERROR("Expected type '" +
1636 STy->getElementType(i)->getDescription() +
1637 "' for element #" + utostr(i) +
1638 " of structure initializer");
1639
1640 // Check to ensure that Type is not packed
1641 if (STy->isPacked())
1642 GEN_ERROR("Unpacked Initializer to vector type '" +
1643 STy->getDescription() + "'");
1644
1645 $$ = ConstantStruct::get(STy, *$3);
1646 delete $1; delete $3;
1647 CHECK_FOR_ERROR
1648 }
1649 | Types '{' '}' {
1650 if (!UpRefs.empty())
1651 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1652 const StructType *STy = dyn_cast<StructType>($1->get());
1653 if (STy == 0)
1654 GEN_ERROR("Cannot make struct constant with type: '" +
1655 (*$1)->getDescription() + "'");
1656
1657 if (STy->getNumContainedTypes() != 0)
1658 GEN_ERROR("Illegal number of initializers for structure type");
1659
1660 // Check to ensure that Type is not packed
1661 if (STy->isPacked())
1662 GEN_ERROR("Unpacked Initializer to vector type '" +
1663 STy->getDescription() + "'");
1664
1665 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1666 delete $1;
1667 CHECK_FOR_ERROR
1668 }
1669 | Types '<' '{' ConstVector '}' '>' {
1670 const StructType *STy = dyn_cast<StructType>($1->get());
1671 if (STy == 0)
1672 GEN_ERROR("Cannot make struct constant with type: '" +
1673 (*$1)->getDescription() + "'");
1674
1675 if ($4->size() != STy->getNumContainedTypes())
1676 GEN_ERROR("Illegal number of initializers for structure type");
1677
1678 // Check to ensure that constants are compatible with the type initializer!
1679 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1680 if ((*$4)[i]->getType() != STy->getElementType(i))
1681 GEN_ERROR("Expected type '" +
1682 STy->getElementType(i)->getDescription() +
1683 "' for element #" + utostr(i) +
1684 " of structure initializer");
1685
1686 // Check to ensure that Type is packed
1687 if (!STy->isPacked())
1688 GEN_ERROR("Vector initializer to non-vector type '" +
1689 STy->getDescription() + "'");
1690
1691 $$ = ConstantStruct::get(STy, *$4);
1692 delete $1; delete $4;
1693 CHECK_FOR_ERROR
1694 }
1695 | Types '<' '{' '}' '>' {
1696 if (!UpRefs.empty())
1697 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1698 const StructType *STy = dyn_cast<StructType>($1->get());
1699 if (STy == 0)
1700 GEN_ERROR("Cannot make struct constant with type: '" +
1701 (*$1)->getDescription() + "'");
1702
1703 if (STy->getNumContainedTypes() != 0)
1704 GEN_ERROR("Illegal number of initializers for structure type");
1705
1706 // Check to ensure that Type is packed
1707 if (!STy->isPacked())
1708 GEN_ERROR("Vector initializer to non-vector type '" +
1709 STy->getDescription() + "'");
1710
1711 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1712 delete $1;
1713 CHECK_FOR_ERROR
1714 }
1715 | Types NULL_TOK {
1716 if (!UpRefs.empty())
1717 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1718 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1719 if (PTy == 0)
1720 GEN_ERROR("Cannot make null pointer constant with type: '" +
1721 (*$1)->getDescription() + "'");
1722
1723 $$ = ConstantPointerNull::get(PTy);
1724 delete $1;
1725 CHECK_FOR_ERROR
1726 }
1727 | Types UNDEF {
1728 if (!UpRefs.empty())
1729 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1730 $$ = UndefValue::get($1->get());
1731 delete $1;
1732 CHECK_FOR_ERROR
1733 }
1734 | Types SymbolicValueRef {
1735 if (!UpRefs.empty())
1736 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1737 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1738 if (Ty == 0)
Devang Patel3b8849c2008-02-19 22:27:01 +00001739 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740
1741 // ConstExprs can exist in the body of a function, thus creating
1742 // GlobalValues whenever they refer to a variable. Because we are in
1743 // the context of a function, getExistingVal will search the functions
1744 // symbol table instead of the module symbol table for the global symbol,
1745 // which throws things all off. To get around this, we just tell
1746 // getExistingVal that we are at global scope here.
1747 //
1748 Function *SavedCurFn = CurFun.CurrentFunction;
1749 CurFun.CurrentFunction = 0;
1750
1751 Value *V = getExistingVal(Ty, $2);
1752 CHECK_FOR_ERROR
1753
1754 CurFun.CurrentFunction = SavedCurFn;
1755
1756 // If this is an initializer for a constant pointer, which is referencing a
1757 // (currently) undefined variable, create a stub now that shall be replaced
1758 // in the future with the right type of variable.
1759 //
1760 if (V == 0) {
1761 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1762 const PointerType *PT = cast<PointerType>(Ty);
1763
1764 // First check to see if the forward references value is already created!
1765 PerModuleInfo::GlobalRefsType::iterator I =
1766 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1767
1768 if (I != CurModule.GlobalRefs.end()) {
1769 V = I->second; // Placeholder already exists, use it...
1770 $2.destroy();
1771 } else {
1772 std::string Name;
1773 if ($2.Type == ValID::GlobalName)
1774 Name = $2.getName();
1775 else if ($2.Type != ValID::GlobalID)
1776 GEN_ERROR("Invalid reference to global");
1777
1778 // Create the forward referenced global.
1779 GlobalValue *GV;
1780 if (const FunctionType *FTy =
1781 dyn_cast<FunctionType>(PT->getElementType())) {
1782 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1783 CurModule.CurrentModule);
1784 } else {
1785 GV = new GlobalVariable(PT->getElementType(), false,
1786 GlobalValue::ExternalWeakLinkage, 0,
1787 Name, CurModule.CurrentModule);
1788 }
1789
1790 // Keep track of the fact that we have a forward ref to recycle it
1791 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1792 V = GV;
1793 }
1794 }
1795
1796 $$ = cast<GlobalValue>(V);
1797 delete $1; // Free the type handle
1798 CHECK_FOR_ERROR
1799 }
1800 | Types ConstExpr {
1801 if (!UpRefs.empty())
1802 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1803 if ($1->get() != $2->getType())
1804 GEN_ERROR("Mismatched types for constant expression: " +
1805 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1806 $$ = $2;
1807 delete $1;
1808 CHECK_FOR_ERROR
1809 }
1810 | Types ZEROINITIALIZER {
1811 if (!UpRefs.empty())
1812 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1813 const Type *Ty = $1->get();
1814 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1815 GEN_ERROR("Cannot create a null initialized value of this type");
1816 $$ = Constant::getNullValue(Ty);
1817 delete $1;
1818 CHECK_FOR_ERROR
1819 }
1820 | IntType ESINT64VAL { // integral constants
1821 if (!ConstantInt::isValueValidForType($1, $2))
1822 GEN_ERROR("Constant value doesn't fit in type");
1823 $$ = ConstantInt::get($1, $2, true);
1824 CHECK_FOR_ERROR
1825 }
1826 | IntType ESAPINTVAL { // arbitrary precision integer constants
1827 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1828 if ($2->getBitWidth() > BitWidth) {
1829 GEN_ERROR("Constant value does not fit in type");
1830 }
1831 $2->sextOrTrunc(BitWidth);
1832 $$ = ConstantInt::get(*$2);
1833 delete $2;
1834 CHECK_FOR_ERROR
1835 }
1836 | IntType EUINT64VAL { // integral constants
1837 if (!ConstantInt::isValueValidForType($1, $2))
1838 GEN_ERROR("Constant value doesn't fit in type");
1839 $$ = ConstantInt::get($1, $2, false);
1840 CHECK_FOR_ERROR
1841 }
1842 | IntType EUAPINTVAL { // arbitrary precision integer constants
1843 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1844 if ($2->getBitWidth() > BitWidth) {
1845 GEN_ERROR("Constant value does not fit in type");
1846 }
1847 $2->zextOrTrunc(BitWidth);
1848 $$ = ConstantInt::get(*$2);
1849 delete $2;
1850 CHECK_FOR_ERROR
1851 }
1852 | INTTYPE TRUETOK { // Boolean constants
1853 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1854 $$ = ConstantInt::getTrue();
1855 CHECK_FOR_ERROR
1856 }
1857 | INTTYPE FALSETOK { // Boolean constants
1858 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1859 $$ = ConstantInt::getFalse();
1860 CHECK_FOR_ERROR
1861 }
Dale Johannesen043064d2007-09-12 03:31:28 +00001862 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001863 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001864 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen255b8fe2007-09-11 18:33:39 +00001865 // Lexer has no type info, so builds all float and double FP constants
1866 // as double. Fix this here. Long double is done right.
1867 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001868 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1869 $$ = ConstantFP::get($1, *$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001870 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871 CHECK_FOR_ERROR
1872 };
1873
1874
1875ConstExpr: CastOps '(' ConstVal TO Types ')' {
1876 if (!UpRefs.empty())
1877 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1878 Constant *Val = $3;
1879 const Type *DestTy = $5->get();
1880 if (!CastInst::castIsValid($1, $3, DestTy))
1881 GEN_ERROR("invalid cast opcode for cast from '" +
1882 Val->getType()->getDescription() + "' to '" +
1883 DestTy->getDescription() + "'");
1884 $$ = ConstantExpr::getCast($1, $3, DestTy);
1885 delete $5;
1886 }
1887 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1888 if (!isa<PointerType>($3->getType()))
1889 GEN_ERROR("GetElementPtr requires a pointer operand");
1890
1891 const Type *IdxTy =
David Greene48556392007-09-04 18:46:50 +00001892 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 true);
1894 if (!IdxTy)
1895 GEN_ERROR("Index list invalid for constant getelementptr");
1896
1897 SmallVector<Constant*, 8> IdxVec;
1898 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1899 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1900 IdxVec.push_back(C);
1901 else
1902 GEN_ERROR("Indices to constant getelementptr must be constants");
1903
1904 delete $4;
1905
1906 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1907 CHECK_FOR_ERROR
1908 }
1909 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1910 if ($3->getType() != Type::Int1Ty)
1911 GEN_ERROR("Select condition must be of boolean type");
1912 if ($5->getType() != $7->getType())
1913 GEN_ERROR("Select operand types must match");
1914 $$ = ConstantExpr::getSelect($3, $5, $7);
1915 CHECK_FOR_ERROR
1916 }
1917 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1918 if ($3->getType() != $5->getType())
1919 GEN_ERROR("Binary operator types must match");
1920 CHECK_FOR_ERROR;
1921 $$ = ConstantExpr::get($1, $3, $5);
1922 }
1923 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1924 if ($3->getType() != $5->getType())
1925 GEN_ERROR("Logical operator types must match");
1926 if (!$3->getType()->isInteger()) {
1927 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1928 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1929 GEN_ERROR("Logical operator requires integral operands");
1930 }
1931 $$ = ConstantExpr::get($1, $3, $5);
1932 CHECK_FOR_ERROR
1933 }
1934 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1935 if ($4->getType() != $6->getType())
1936 GEN_ERROR("icmp operand types must match");
1937 $$ = ConstantExpr::getICmp($2, $4, $6);
1938 }
1939 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1940 if ($4->getType() != $6->getType())
1941 GEN_ERROR("fcmp operand types must match");
1942 $$ = ConstantExpr::getFCmp($2, $4, $6);
1943 }
1944 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1945 if (!ExtractElementInst::isValidOperands($3, $5))
1946 GEN_ERROR("Invalid extractelement operands");
1947 $$ = ConstantExpr::getExtractElement($3, $5);
1948 CHECK_FOR_ERROR
1949 }
1950 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1951 if (!InsertElementInst::isValidOperands($3, $5, $7))
1952 GEN_ERROR("Invalid insertelement operands");
1953 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1954 CHECK_FOR_ERROR
1955 }
1956 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1957 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1958 GEN_ERROR("Invalid shufflevector operands");
1959 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1960 CHECK_FOR_ERROR
1961 };
1962
1963
1964// ConstVector - A list of comma separated constants.
1965ConstVector : ConstVector ',' ConstVal {
1966 ($$ = $1)->push_back($3);
1967 CHECK_FOR_ERROR
1968 }
1969 | ConstVal {
1970 $$ = new std::vector<Constant*>();
1971 $$->push_back($1);
1972 CHECK_FOR_ERROR
1973 };
1974
1975
1976// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1977GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1978
1979// ThreadLocal
1980ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1981
1982// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1983AliaseeRef : ResultTypes SymbolicValueRef {
1984 const Type* VTy = $1->get();
1985 Value *V = getVal(VTy, $2);
Chris Lattnerbb856a32007-08-06 21:00:46 +00001986 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001987 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1988 if (!Aliasee)
1989 GEN_ERROR("Aliases can be created only to global values");
1990
1991 $$ = Aliasee;
1992 CHECK_FOR_ERROR
1993 delete $1;
1994 }
1995 | BITCAST '(' AliaseeRef TO Types ')' {
1996 Constant *Val = $3;
1997 const Type *DestTy = $5->get();
1998 if (!CastInst::castIsValid($1, $3, DestTy))
1999 GEN_ERROR("invalid cast opcode for cast from '" +
2000 Val->getType()->getDescription() + "' to '" +
2001 DestTy->getDescription() + "'");
2002
2003 $$ = ConstantExpr::getCast($1, $3, DestTy);
2004 CHECK_FOR_ERROR
2005 delete $5;
2006 };
2007
2008//===----------------------------------------------------------------------===//
2009// Rules to match Modules
2010//===----------------------------------------------------------------------===//
2011
2012// Module rule: Capture the result of parsing the whole file into a result
2013// variable...
2014//
2015Module
2016 : DefinitionList {
2017 $$ = ParserResult = CurModule.CurrentModule;
2018 CurModule.ModuleDone();
2019 CHECK_FOR_ERROR;
2020 }
2021 | /*empty*/ {
2022 $$ = ParserResult = CurModule.CurrentModule;
2023 CurModule.ModuleDone();
2024 CHECK_FOR_ERROR;
2025 }
2026 ;
2027
2028DefinitionList
2029 : Definition
2030 | DefinitionList Definition
2031 ;
2032
2033Definition
2034 : DEFINE { CurFun.isDeclare = false; } Function {
2035 CurFun.FunctionDone();
2036 CHECK_FOR_ERROR
2037 }
2038 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2039 CHECK_FOR_ERROR
2040 }
2041 | MODULE ASM_TOK AsmBlock {
2042 CHECK_FOR_ERROR
2043 }
2044 | OptLocalAssign TYPE Types {
2045 if (!UpRefs.empty())
2046 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2047 // Eagerly resolve types. This is not an optimization, this is a
2048 // requirement that is due to the fact that we could have this:
2049 //
2050 // %list = type { %list * }
2051 // %list = type { %list * } ; repeated type decl
2052 //
2053 // If types are not resolved eagerly, then the two types will not be
2054 // determined to be the same type!
2055 //
2056 ResolveTypeTo($1, *$3);
2057
2058 if (!setTypeName(*$3, $1) && !$1) {
2059 CHECK_FOR_ERROR
2060 // If this is a named type that is not a redefinition, add it to the slot
2061 // table.
2062 CurModule.Types.push_back(*$3);
2063 }
2064
2065 delete $3;
2066 CHECK_FOR_ERROR
2067 }
2068 | OptLocalAssign TYPE VOID {
2069 ResolveTypeTo($1, $3);
2070
2071 if (!setTypeName($3, $1) && !$1) {
2072 CHECK_FOR_ERROR
2073 // If this is a named type that is not a redefinition, add it to the slot
2074 // table.
2075 CurModule.Types.push_back($3);
2076 }
2077 CHECK_FOR_ERROR
2078 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00002079 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2080 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002081 /* "Externally Visible" Linkage */
2082 if ($5 == 0)
2083 GEN_ERROR("Global value initializer is not a constant");
2084 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb668d9a02007-12-12 08:45:45 +00002085 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb0a243582007-12-11 09:02:08 +00002086 CHECK_FOR_ERROR
2087 } GlobalVarAttributes {
2088 CurGV = 0;
2089 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002090 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002091 ConstVal OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 if ($6 == 0)
2093 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb668d9a02007-12-12 08:45:45 +00002094 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095 CHECK_FOR_ERROR
2096 } GlobalVarAttributes {
2097 CurGV = 0;
2098 }
2099 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002100 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002101 if (!UpRefs.empty())
2102 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb668d9a02007-12-12 08:45:45 +00002103 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 CHECK_FOR_ERROR
2105 delete $6;
2106 } GlobalVarAttributes {
2107 CurGV = 0;
2108 CHECK_FOR_ERROR
2109 }
2110 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2111 std::string Name;
2112 if ($1) {
2113 Name = *$1;
2114 delete $1;
2115 }
2116 if (Name.empty())
2117 GEN_ERROR("Alias name cannot be empty");
2118
2119 Constant* Aliasee = $5;
2120 if (Aliasee == 0)
2121 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2122
2123 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2124 CurModule.CurrentModule);
2125 GA->setVisibility($2);
2126 InsertValue(GA, CurModule.Values);
Chris Lattner5eefce32007-09-10 23:24:14 +00002127
2128
2129 // If there was a forward reference of this alias, resolve it now.
2130
2131 ValID ID;
2132 if (!Name.empty())
2133 ID = ValID::createGlobalName(Name);
2134 else
2135 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2136
2137 if (GlobalValue *FWGV =
2138 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2139 // Replace uses of the fwdref with the actual alias.
2140 FWGV->replaceAllUsesWith(GA);
2141 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2142 GV->eraseFromParent();
2143 else
2144 cast<Function>(FWGV)->eraseFromParent();
2145 }
2146 ID.destroy();
2147
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002148 CHECK_FOR_ERROR
2149 }
2150 | TARGET TargetDefinition {
2151 CHECK_FOR_ERROR
2152 }
2153 | DEPLIBS '=' LibrariesDefinition {
2154 CHECK_FOR_ERROR
2155 }
2156 ;
2157
2158
2159AsmBlock : STRINGCONSTANT {
2160 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2161 if (AsmSoFar.empty())
2162 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2163 else
2164 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2165 delete $1;
2166 CHECK_FOR_ERROR
2167};
2168
2169TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2170 CurModule.CurrentModule->setTargetTriple(*$3);
2171 delete $3;
2172 }
2173 | DATALAYOUT '=' STRINGCONSTANT {
2174 CurModule.CurrentModule->setDataLayout(*$3);
2175 delete $3;
2176 };
2177
2178LibrariesDefinition : '[' LibList ']';
2179
2180LibList : LibList ',' STRINGCONSTANT {
2181 CurModule.CurrentModule->addLibrary(*$3);
2182 delete $3;
2183 CHECK_FOR_ERROR
2184 }
2185 | STRINGCONSTANT {
2186 CurModule.CurrentModule->addLibrary(*$1);
2187 delete $1;
2188 CHECK_FOR_ERROR
2189 }
2190 | /* empty: end of list */ {
2191 CHECK_FOR_ERROR
2192 }
2193 ;
2194
2195//===----------------------------------------------------------------------===//
2196// Rules to match Function Headers
2197//===----------------------------------------------------------------------===//
2198
2199ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2200 if (!UpRefs.empty())
2201 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2202 if (*$3 == Type::VoidTy)
2203 GEN_ERROR("void typed arguments are invalid");
2204 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2205 $$ = $1;
2206 $1->push_back(E);
2207 CHECK_FOR_ERROR
2208 }
2209 | Types OptParamAttrs OptLocalName {
2210 if (!UpRefs.empty())
2211 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2212 if (*$1 == Type::VoidTy)
2213 GEN_ERROR("void typed arguments are invalid");
2214 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2215 $$ = new ArgListType;
2216 $$->push_back(E);
2217 CHECK_FOR_ERROR
2218 };
2219
2220ArgList : ArgListH {
2221 $$ = $1;
2222 CHECK_FOR_ERROR
2223 }
2224 | ArgListH ',' DOTDOTDOT {
2225 $$ = $1;
2226 struct ArgListEntry E;
2227 E.Ty = new PATypeHolder(Type::VoidTy);
2228 E.Name = 0;
2229 E.Attrs = ParamAttr::None;
2230 $$->push_back(E);
2231 CHECK_FOR_ERROR
2232 }
2233 | DOTDOTDOT {
2234 $$ = new ArgListType;
2235 struct ArgListEntry E;
2236 E.Ty = new PATypeHolder(Type::VoidTy);
2237 E.Name = 0;
2238 E.Attrs = ParamAttr::None;
2239 $$->push_back(E);
2240 CHECK_FOR_ERROR
2241 }
2242 | /* empty */ {
2243 $$ = 0;
2244 CHECK_FOR_ERROR
2245 };
2246
2247FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002248 OptFuncAttrs OptSection OptAlign OptGC {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249 std::string FunctionName(*$3);
2250 delete $3; // Free strdup'd memory!
2251
2252 // Check the function result for abstractness if this is a define. We should
2253 // have no abstract types at this point
2254 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2255 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2256
2257 std::vector<const Type*> ParamTypeList;
2258 ParamAttrsVector Attrs;
2259 if ($7 != ParamAttr::None) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002260 ParamAttrsWithIndex PAWI;
2261 PAWI.index = 0;
2262 PAWI.attrs = $7;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 Attrs.push_back(PAWI);
2264 }
2265 if ($5) { // If there are arguments...
2266 unsigned index = 1;
2267 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2268 const Type* Ty = I->Ty->get();
2269 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2270 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2271 ParamTypeList.push_back(Ty);
2272 if (Ty != Type::VoidTy)
2273 if (I->Attrs != ParamAttr::None) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002274 ParamAttrsWithIndex PAWI;
2275 PAWI.index = index;
2276 PAWI.attrs = I->Attrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277 Attrs.push_back(PAWI);
2278 }
2279 }
2280 }
2281
2282 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2283 if (isVarArg) ParamTypeList.pop_back();
2284
Duncan Sands637ec552007-11-28 17:07:01 +00002285 const ParamAttrsList *PAL = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286 if (!Attrs.empty())
2287 PAL = ParamAttrsList::get(Attrs);
2288
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002289 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambfb623c62007-12-17 01:17:35 +00002290 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 delete $2;
2292
2293 ValID ID;
2294 if (!FunctionName.empty()) {
2295 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2296 } else {
2297 ID = ValID::createGlobalID(CurModule.Values.size());
2298 }
2299
2300 Function *Fn = 0;
2301 // See if this function was forward referenced. If so, recycle the object.
2302 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2303 // Move the function to the end of the list, from whereever it was
2304 // previously inserted.
2305 Fn = cast<Function>(FWRef);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002306 assert(!Fn->getParamAttrs() && "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 CurModule.CurrentModule->getFunctionList().remove(Fn);
2308 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2309 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2310 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002311 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002312 // The existing function doesn't have the same type. This is an overload
2313 // error.
2314 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002315 } else if (Fn->getParamAttrs() != PAL) {
2316 // The existing function doesn't have the same parameter attributes.
2317 // This is an overload error.
2318 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2320 // Neither the existing or the current function is a declaration and they
2321 // have the same name and same type. Clearly this is a redefinition.
2322 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002323 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 // Make sure to strip off any argument names so we can't get conflicts.
2325 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2326 AI != AE; ++AI)
2327 AI->setName("");
2328 }
2329 } else { // Not already defined?
2330 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2331 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002332 InsertValue(Fn, CurModule.Values);
2333 }
2334
2335 CurFun.FunctionStart(Fn);
2336
2337 if (CurFun.isDeclare) {
2338 // If we have declaration, always overwrite linkage. This will allow us to
2339 // correctly handle cases, when pointer to function is passed as argument to
2340 // another function.
2341 Fn->setLinkage(CurFun.Linkage);
2342 Fn->setVisibility(CurFun.Visibility);
2343 }
2344 Fn->setCallingConv($1);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002345 Fn->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002346 Fn->setAlignment($9);
2347 if ($8) {
2348 Fn->setSection(*$8);
2349 delete $8;
2350 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002351 if ($10) {
2352 Fn->setCollector($10->c_str());
2353 delete $10;
2354 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355
2356 // Add all of the arguments we parsed to the function...
2357 if ($5) { // Is null if empty...
2358 if (isVarArg) { // Nuke the last entry
2359 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2360 "Not a varargs marker!");
2361 delete $5->back().Ty;
2362 $5->pop_back(); // Delete the last entry
2363 }
2364 Function::arg_iterator ArgIt = Fn->arg_begin();
2365 Function::arg_iterator ArgEnd = Fn->arg_end();
2366 unsigned Idx = 1;
2367 for (ArgListType::iterator I = $5->begin();
2368 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2369 delete I->Ty; // Delete the typeholder...
2370 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2371 CHECK_FOR_ERROR
2372 InsertValue(ArgIt);
2373 Idx++;
2374 }
2375
2376 delete $5; // We're now done with the argument list
2377 }
2378 CHECK_FOR_ERROR
2379};
2380
2381BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2382
2383FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2384 $$ = CurFun.CurrentFunction;
2385
2386 // Make sure that we keep track of the linkage type even if there was a
2387 // previous "declare".
2388 $$->setLinkage($1);
2389 $$->setVisibility($2);
2390};
2391
2392END : ENDTOK | '}'; // Allow end of '}' to end a function
2393
2394Function : BasicBlockList END {
2395 $$ = $1;
2396 CHECK_FOR_ERROR
2397};
2398
2399FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2400 CurFun.CurrentFunction->setLinkage($1);
2401 CurFun.CurrentFunction->setVisibility($2);
2402 $$ = CurFun.CurrentFunction;
2403 CurFun.FunctionDone();
2404 CHECK_FOR_ERROR
2405 };
2406
2407//===----------------------------------------------------------------------===//
2408// Rules to match Basic Blocks
2409//===----------------------------------------------------------------------===//
2410
2411OptSideEffect : /* empty */ {
2412 $$ = false;
2413 CHECK_FOR_ERROR
2414 }
2415 | SIDEEFFECT {
2416 $$ = true;
2417 CHECK_FOR_ERROR
2418 };
2419
2420ConstValueRef : ESINT64VAL { // A reference to a direct constant
2421 $$ = ValID::create($1);
2422 CHECK_FOR_ERROR
2423 }
2424 | EUINT64VAL {
2425 $$ = ValID::create($1);
2426 CHECK_FOR_ERROR
2427 }
2428 | FPVAL { // Perhaps it's an FP constant?
2429 $$ = ValID::create($1);
2430 CHECK_FOR_ERROR
2431 }
2432 | TRUETOK {
2433 $$ = ValID::create(ConstantInt::getTrue());
2434 CHECK_FOR_ERROR
2435 }
2436 | FALSETOK {
2437 $$ = ValID::create(ConstantInt::getFalse());
2438 CHECK_FOR_ERROR
2439 }
2440 | NULL_TOK {
2441 $$ = ValID::createNull();
2442 CHECK_FOR_ERROR
2443 }
2444 | UNDEF {
2445 $$ = ValID::createUndef();
2446 CHECK_FOR_ERROR
2447 }
2448 | ZEROINITIALIZER { // A vector zero constant.
2449 $$ = ValID::createZeroInit();
2450 CHECK_FOR_ERROR
2451 }
2452 | '<' ConstVector '>' { // Nonempty unsized packed vector
2453 const Type *ETy = (*$2)[0]->getType();
2454 int NumElements = $2->size();
2455
2456 VectorType* pt = VectorType::get(ETy, NumElements);
2457 PATypeHolder* PTy = new PATypeHolder(
2458 HandleUpRefs(
2459 VectorType::get(
2460 ETy,
2461 NumElements)
2462 )
2463 );
2464
2465 // Verify all elements are correct type!
2466 for (unsigned i = 0; i < $2->size(); i++) {
2467 if (ETy != (*$2)[i]->getType())
2468 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2469 ETy->getDescription() +"' as required!\nIt is of type '" +
2470 (*$2)[i]->getType()->getDescription() + "'.");
2471 }
2472
2473 $$ = ValID::create(ConstantVector::get(pt, *$2));
2474 delete PTy; delete $2;
2475 CHECK_FOR_ERROR
2476 }
2477 | ConstExpr {
2478 $$ = ValID::create($1);
2479 CHECK_FOR_ERROR
2480 }
2481 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2482 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2483 delete $3;
2484 delete $5;
2485 CHECK_FOR_ERROR
2486 };
2487
2488// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2489// another value.
2490//
2491SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2492 $$ = ValID::createLocalID($1);
2493 CHECK_FOR_ERROR
2494 }
2495 | GLOBALVAL_ID {
2496 $$ = ValID::createGlobalID($1);
2497 CHECK_FOR_ERROR
2498 }
2499 | LocalName { // Is it a named reference...?
2500 $$ = ValID::createLocalName(*$1);
2501 delete $1;
2502 CHECK_FOR_ERROR
2503 }
2504 | GlobalName { // Is it a named reference...?
2505 $$ = ValID::createGlobalName(*$1);
2506 delete $1;
2507 CHECK_FOR_ERROR
2508 };
2509
2510// ValueRef - A reference to a definition... either constant or symbolic
2511ValueRef : SymbolicValueRef | ConstValueRef;
2512
2513
2514// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2515// type immediately preceeds the value reference, and allows complex constant
2516// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2517ResolvedVal : Types ValueRef {
2518 if (!UpRefs.empty())
2519 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2520 $$ = getVal(*$1, $2);
2521 delete $1;
2522 CHECK_FOR_ERROR
2523 }
2524 ;
2525
2526BasicBlockList : BasicBlockList BasicBlock {
2527 $$ = $1;
2528 CHECK_FOR_ERROR
2529 }
2530 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2531 $$ = $1;
2532 CHECK_FOR_ERROR
2533 };
2534
2535
2536// Basic blocks are terminated by branching instructions:
2537// br, br/cc, switch, ret
2538//
2539BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2540 setValueName($3, $2);
2541 CHECK_FOR_ERROR
2542 InsertValue($3);
2543 $1->getInstList().push_back($3);
2544 $$ = $1;
2545 CHECK_FOR_ERROR
2546 };
2547
2548InstructionList : InstructionList Inst {
2549 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2550 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2551 if (CI2->getParent() == 0)
2552 $1->getInstList().push_back(CI2);
2553 $1->getInstList().push_back($2);
2554 $$ = $1;
2555 CHECK_FOR_ERROR
2556 }
2557 | /* empty */ { // Empty space between instruction lists
2558 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2559 CHECK_FOR_ERROR
2560 }
2561 | LABELSTR { // Labelled (named) basic block
2562 $$ = defineBBVal(ValID::createLocalName(*$1));
2563 delete $1;
2564 CHECK_FOR_ERROR
2565
2566 };
2567
2568BBTerminatorInst : RET ResolvedVal { // Return with a result...
2569 $$ = new ReturnInst($2);
2570 CHECK_FOR_ERROR
2571 }
2572 | RET VOID { // Return with no result...
2573 $$ = new ReturnInst();
2574 CHECK_FOR_ERROR
2575 }
2576 | BR LABEL ValueRef { // Unconditional Branch...
2577 BasicBlock* tmpBB = getBBVal($3);
2578 CHECK_FOR_ERROR
2579 $$ = new BranchInst(tmpBB);
2580 } // Conditional Branch...
2581 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2582 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2583 BasicBlock* tmpBBA = getBBVal($6);
2584 CHECK_FOR_ERROR
2585 BasicBlock* tmpBBB = getBBVal($9);
2586 CHECK_FOR_ERROR
2587 Value* tmpVal = getVal(Type::Int1Ty, $3);
2588 CHECK_FOR_ERROR
2589 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2590 }
2591 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2592 Value* tmpVal = getVal($2, $3);
2593 CHECK_FOR_ERROR
2594 BasicBlock* tmpBB = getBBVal($6);
2595 CHECK_FOR_ERROR
2596 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2597 $$ = S;
2598
2599 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2600 E = $8->end();
2601 for (; I != E; ++I) {
2602 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2603 S->addCase(CI, I->second);
2604 else
2605 GEN_ERROR("Switch case is constant, but not a simple integer");
2606 }
2607 delete $8;
2608 CHECK_FOR_ERROR
2609 }
2610 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2611 Value* tmpVal = getVal($2, $3);
2612 CHECK_FOR_ERROR
2613 BasicBlock* tmpBB = getBBVal($6);
2614 CHECK_FOR_ERROR
2615 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2616 $$ = S;
2617 CHECK_FOR_ERROR
2618 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002619 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002620 TO LABEL ValueRef UNWIND LABEL ValueRef {
2621
2622 // Handle the short syntax
2623 const PointerType *PFTy = 0;
2624 const FunctionType *Ty = 0;
2625 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2626 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2627 // Pull out the types of all of the arguments...
2628 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002629 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002630 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002631 const Type *Ty = I->Val->getType();
2632 if (Ty == Type::VoidTy)
2633 GEN_ERROR("Short call syntax cannot be used with varargs");
2634 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002635 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002636 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00002637 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 }
2639
2640 delete $3;
2641
2642 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2643 CHECK_FOR_ERROR
2644 BasicBlock *Normal = getBBVal($11);
2645 CHECK_FOR_ERROR
2646 BasicBlock *Except = getBBVal($14);
2647 CHECK_FOR_ERROR
2648
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002649 ParamAttrsVector Attrs;
2650 if ($8 != ParamAttr::None) {
2651 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2652 Attrs.push_back(PAWI);
2653 }
2654
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002655 // Check the arguments
2656 ValueList Args;
2657 if ($6->empty()) { // Has no arguments?
2658 // Make sure no arguments is a good thing!
2659 if (Ty->getNumParams() != 0)
2660 GEN_ERROR("No arguments passed to a function that "
2661 "expects arguments");
2662 } else { // Has arguments?
2663 // Loop through FunctionType's arguments and ensure they are specified
2664 // correctly!
2665 FunctionType::param_iterator I = Ty->param_begin();
2666 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002667 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002668 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002670 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002671 if (ArgI->Val->getType() != *I)
2672 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2673 (*I)->getDescription() + "'");
2674 Args.push_back(ArgI->Val);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002675 if (ArgI->Attrs != ParamAttr::None) {
2676 ParamAttrsWithIndex PAWI;
2677 PAWI.index = index;
2678 PAWI.attrs = ArgI->Attrs;
2679 Attrs.push_back(PAWI);
2680 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681 }
2682
2683 if (Ty->isVarArg()) {
2684 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00002685 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner59363a32008-02-19 04:36:25 +00002687 if (ArgI->Attrs != ParamAttr::None) {
2688 ParamAttrsWithIndex PAWI;
2689 PAWI.index = index;
2690 PAWI.attrs = ArgI->Attrs;
2691 Attrs.push_back(PAWI);
2692 }
2693 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002694 } 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);
Christopher Lambfb623c62007-12-17 01:17:35 +00002971 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002972 }
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)
Chris Lattner59363a32008-02-19 04:36:25 +00003023 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003024 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner59363a32008-02-19 04:36:25 +00003025 if (ArgI->Attrs != ParamAttr::None) {
3026 ParamAttrsWithIndex PAWI;
3027 PAWI.index = index;
3028 PAWI.attrs = ArgI->Attrs;
3029 Attrs.push_back(PAWI);
3030 }
3031 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003032 } else if (I != E || ArgI != ArgE)
3033 GEN_ERROR("Invalid number of parameters detected");
3034 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003035
3036 // Finish off the ParamAttrs and check them
Duncan Sands637ec552007-11-28 17:07:01 +00003037 const ParamAttrsList *PAL = 0;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003038 if (!Attrs.empty())
3039 PAL = ParamAttrsList::get(Attrs);
3040
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041 // Create the call node
David Greene9145dd22007-08-01 03:59:32 +00003042 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043 CI->setTailCall($1);
3044 CI->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003045 CI->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046 $$ = CI;
3047 delete $6;
3048 delete $3;
3049 CHECK_FOR_ERROR
3050 }
3051 | MemoryInst {
3052 $$ = $1;
3053 CHECK_FOR_ERROR
3054 };
3055
3056OptVolatile : VOLATILE {
3057 $$ = true;
3058 CHECK_FOR_ERROR
3059 }
3060 | /* empty */ {
3061 $$ = false;
3062 CHECK_FOR_ERROR
3063 };
3064
3065
3066
3067MemoryInst : MALLOC Types OptCAlign {
3068 if (!UpRefs.empty())
3069 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3070 $$ = new MallocInst(*$2, 0, $3);
3071 delete $2;
3072 CHECK_FOR_ERROR
3073 }
3074 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3075 if (!UpRefs.empty())
3076 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3077 Value* tmpVal = getVal($4, $5);
3078 CHECK_FOR_ERROR
3079 $$ = new MallocInst(*$2, tmpVal, $6);
3080 delete $2;
3081 }
3082 | ALLOCA Types OptCAlign {
3083 if (!UpRefs.empty())
3084 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3085 $$ = new AllocaInst(*$2, 0, $3);
3086 delete $2;
3087 CHECK_FOR_ERROR
3088 }
3089 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3090 if (!UpRefs.empty())
3091 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3092 Value* tmpVal = getVal($4, $5);
3093 CHECK_FOR_ERROR
3094 $$ = new AllocaInst(*$2, tmpVal, $6);
3095 delete $2;
3096 }
3097 | FREE ResolvedVal {
3098 if (!isa<PointerType>($2->getType()))
3099 GEN_ERROR("Trying to free nonpointer type " +
3100 $2->getType()->getDescription() + "");
3101 $$ = new FreeInst($2);
3102 CHECK_FOR_ERROR
3103 }
3104
3105 | OptVolatile LOAD Types ValueRef OptCAlign {
3106 if (!UpRefs.empty())
3107 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3108 if (!isa<PointerType>($3->get()))
3109 GEN_ERROR("Can't load from nonpointer type: " +
3110 (*$3)->getDescription());
3111 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3112 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3113 (*$3)->getDescription());
3114 Value* tmpVal = getVal(*$3, $4);
3115 CHECK_FOR_ERROR
3116 $$ = new LoadInst(tmpVal, "", $1, $5);
3117 delete $3;
3118 }
3119 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3120 if (!UpRefs.empty())
3121 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3122 const PointerType *PT = dyn_cast<PointerType>($5->get());
3123 if (!PT)
3124 GEN_ERROR("Can't store to a nonpointer type: " +
3125 (*$5)->getDescription());
3126 const Type *ElTy = PT->getElementType();
3127 if (ElTy != $3->getType())
3128 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3129 "' into space of type '" + ElTy->getDescription() + "'");
3130
3131 Value* tmpVal = getVal(*$5, $6);
3132 CHECK_FOR_ERROR
3133 $$ = new StoreInst($3, tmpVal, $1, $7);
3134 delete $5;
3135 }
Devang Pateleb293342008-02-20 19:13:10 +00003136| GETRESULT Types LocalName ',' EUINT64VAL {
Devang Patel3b8849c2008-02-19 22:27:01 +00003137 ValID TmpVID = ValID::createLocalName(*$3);
3138 Value *TmpVal = getVal($2->get(), TmpVID);
3139 if (!GetResultInst::isValidOperands(TmpVal, $5))
3140 GEN_ERROR("Invalid getresult operands");
3141 $$ = new GetResultInst(TmpVal, $5);
3142 CHECK_FOR_ERROR
3143 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003144 | GETELEMENTPTR Types ValueRef IndexList {
3145 if (!UpRefs.empty())
3146 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3147 if (!isa<PointerType>($2->get()))
3148 GEN_ERROR("getelementptr insn requires pointer operand");
3149
David Greene48556392007-09-04 18:46:50 +00003150 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151 GEN_ERROR("Invalid getelementptr indices for type '" +
3152 (*$2)->getDescription()+ "'");
3153 Value* tmpVal = getVal(*$2, $3);
3154 CHECK_FOR_ERROR
David Greene48556392007-09-04 18:46:50 +00003155 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 delete $2;
3157 delete $4;
3158 };
3159
3160
3161%%
3162
3163// common code from the two 'RunVMAsmParser' functions
3164static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003165 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003166 // Check to make sure the parser succeeded
3167 if (yyparse()) {
3168 if (ParserResult)
3169 delete ParserResult;
3170 return 0;
3171 }
3172
3173 // Emit an error if there are any unresolved types left.
3174 if (!CurModule.LateResolveTypes.empty()) {
3175 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3176 if (DID.Type == ValID::LocalName) {
3177 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3178 } else {
3179 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3180 }
3181 if (ParserResult)
3182 delete ParserResult;
3183 return 0;
3184 }
3185
3186 // Emit an error if there are any unresolved values left.
3187 if (!CurModule.LateResolveValues.empty()) {
3188 Value *V = CurModule.LateResolveValues.back();
3189 std::map<Value*, std::pair<ValID, int> >::iterator I =
3190 CurModule.PlaceHolderInfo.find(V);
3191
3192 if (I != CurModule.PlaceHolderInfo.end()) {
3193 ValID &DID = I->second.first;
3194 if (DID.Type == ValID::LocalName) {
3195 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3196 } else {
3197 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3198 }
3199 if (ParserResult)
3200 delete ParserResult;
3201 return 0;
3202 }
3203 }
3204
3205 // Check to make sure that parsing produced a result
3206 if (!ParserResult)
3207 return 0;
3208
3209 // Reset ParserResult variable while saving its value for the result.
3210 Module *Result = ParserResult;
3211 ParserResult = 0;
3212
3213 return Result;
3214}
3215
3216void llvm::GenerateError(const std::string &message, int LineNo) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003217 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 // TODO: column number in exception
3219 if (TheParseError)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003220 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 TriggerError = 1;
3222}
3223
3224int yyerror(const char *ErrorMsg) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003225 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003227 if (yychar != YYEMPTY && yychar != 0) {
3228 errMsg += " while reading token: '";
3229 errMsg += std::string(LLLgetTokenStart(),
3230 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3231 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003232 GenerateError(errMsg);
3233 return 0;
3234}