blob: ccfe44ab82f32ae7e056271a1c59e6c16ad7f97f [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);
581 if (N)
582 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() + "'");
587 } else if (ID.Type == ValID::LocalID) {
588 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
589 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
590 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
591 else
592 GenerateError("Reference to label '%" + utostr(ID.Num) +
593 "' is actually of type '"+
594 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
595 }
596 } else {
597 GenerateError("Illegal label reference " + ID.getName());
598 return 0;
599 }
600
601 // If its already been defined, return it now.
602 if (BB) {
603 ID.destroy(); // Free strdup'd memory.
604 return BB;
605 }
606
607 // Otherwise, this block has not been seen before, create it.
608 std::string Name;
609 if (ID.Type == ValID::LocalName)
610 Name = ID.getName();
611 BB = new BasicBlock(Name, CurFun.CurrentFunction);
612
613 // Insert it in the forward refs map.
614 CurFun.BBForwardRefs[ID] = BB;
615
616 return BB;
617}
618
619
620//===----------------------------------------------------------------------===//
621// Code to handle forward references in instructions
622//===----------------------------------------------------------------------===//
623//
624// This code handles the late binding needed with statements that reference
625// values not defined yet... for example, a forward branch, or the PHI node for
626// a loop body.
627//
628// This keeps a table (CurFun.LateResolveValues) of all such forward references
629// and back patchs after we are done.
630//
631
632// ResolveDefinitions - If we could not resolve some defs at parsing
633// time (forward branches, phi functions for loops, etc...) resolve the
634// defs now...
635//
636static void
637ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
638 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
639 while (!LateResolvers.empty()) {
640 Value *V = LateResolvers.back();
641 LateResolvers.pop_back();
642
643 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
644 CurModule.PlaceHolderInfo.find(V);
645 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
646
647 ValID &DID = PHI->second.first;
648
649 Value *TheRealValue = getExistingVal(V->getType(), DID);
650 if (TriggerError)
651 return;
652 if (TheRealValue) {
653 V->replaceAllUsesWith(TheRealValue);
654 delete V;
655 CurModule.PlaceHolderInfo.erase(PHI);
656 } else if (FutureLateResolvers) {
657 // Functions have their unresolved items forwarded to the module late
658 // resolver table
659 InsertValue(V, *FutureLateResolvers);
660 } else {
661 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
662 GenerateError("Reference to an invalid definition: '" +DID.getName()+
663 "' of type '" + V->getType()->getDescription() + "'",
664 PHI->second.second);
665 return;
666 } else {
667 GenerateError("Reference to an invalid definition: #" +
668 itostr(DID.Num) + " of type '" +
669 V->getType()->getDescription() + "'",
670 PHI->second.second);
671 return;
672 }
673 }
674 }
675 LateResolvers.clear();
676}
677
678// ResolveTypeTo - A brand new type was just declared. This means that (if
679// name is not null) things referencing Name can be resolved. Otherwise, things
680// refering to the number can be resolved. Do this now.
681//
682static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
683 ValID D;
684 if (Name)
685 D = ValID::createLocalName(*Name);
686 else
687 D = ValID::createLocalID(CurModule.Types.size());
688
689 std::map<ValID, PATypeHolder>::iterator I =
690 CurModule.LateResolveTypes.find(D);
691 if (I != CurModule.LateResolveTypes.end()) {
692 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
693 CurModule.LateResolveTypes.erase(I);
694 }
695}
696
697// setValueName - Set the specified value to the name given. The name may be
698// null potentially, in which case this is a noop. The string passed in is
699// assumed to be a malloc'd string buffer, and is free'd by this function.
700//
701static void setValueName(Value *V, std::string *NameStr) {
702 if (!NameStr) return;
703 std::string Name(*NameStr); // Copy string
704 delete NameStr; // Free old string
705
706 if (V->getType() == Type::VoidTy) {
707 GenerateError("Can't assign name '" + Name+"' to value with void type");
708 return;
709 }
710
711 assert(inFunctionScope() && "Must be in function scope!");
712 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
713 if (ST.lookup(Name)) {
714 GenerateError("Redefinition of value '" + Name + "' of type '" +
715 V->getType()->getDescription() + "'");
716 return;
717 }
718
719 // Set the name.
720 V->setName(Name);
721}
722
723/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
724/// this is a declaration, otherwise it is a definition.
725static GlobalVariable *
726ParseGlobalVariable(std::string *NameStr,
727 GlobalValue::LinkageTypes Linkage,
728 GlobalValue::VisibilityTypes Visibility,
729 bool isConstantGlobal, const Type *Ty,
Christopher Lamb0a243582007-12-11 09:02:08 +0000730 Constant *Initializer, bool IsThreadLocal,
731 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 if (isa<FunctionType>(Ty)) {
733 GenerateError("Cannot declare global vars of function type");
734 return 0;
735 }
736
Christopher Lamb0a243582007-12-11 09:02:08 +0000737 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738
739 std::string Name;
740 if (NameStr) {
741 Name = *NameStr; // Copy string
742 delete NameStr; // Free old string
743 }
744
745 // See if this global value was forward referenced. If so, recycle the
746 // object.
747 ValID ID;
748 if (!Name.empty()) {
749 ID = ValID::createGlobalName(Name);
750 } else {
751 ID = ValID::createGlobalID(CurModule.Values.size());
752 }
753
754 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
755 // Move the global to the end of the list, from whereever it was
756 // previously inserted.
757 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
758 CurModule.CurrentModule->getGlobalList().remove(GV);
759 CurModule.CurrentModule->getGlobalList().push_back(GV);
760 GV->setInitializer(Initializer);
761 GV->setLinkage(Linkage);
762 GV->setVisibility(Visibility);
763 GV->setConstant(isConstantGlobal);
764 GV->setThreadLocal(IsThreadLocal);
765 InsertValue(GV, CurModule.Values);
766 return GV;
767 }
768
769 // If this global has a name
770 if (!Name.empty()) {
771 // if the global we're parsing has an initializer (is a definition) and
772 // has external linkage.
773 if (Initializer && Linkage != GlobalValue::InternalLinkage)
774 // If there is already a global with external linkage with this name
775 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
776 // If we allow this GVar to get created, it will be renamed in the
777 // symbol table because it conflicts with an existing GVar. We can't
778 // allow redefinition of GVars whose linking indicates that their name
779 // must stay the same. Issue the error.
780 GenerateError("Redefinition of global variable named '" + Name +
781 "' of type '" + Ty->getDescription() + "'");
782 return 0;
783 }
784 }
785
786 // Otherwise there is no existing GV to use, create one now.
787 GlobalVariable *GV =
788 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb0a243582007-12-11 09:02:08 +0000789 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000790 GV->setVisibility(Visibility);
791 InsertValue(GV, CurModule.Values);
792 return GV;
793}
794
795// setTypeName - Set the specified type to the name given. The name may be
796// null potentially, in which case this is a noop. The string passed in is
797// assumed to be a malloc'd string buffer, and is freed by this function.
798//
799// This function returns true if the type has already been defined, but is
800// allowed to be redefined in the specified context. If the name is a new name
801// for the type plane, it is inserted and false is returned.
802static bool setTypeName(const Type *T, std::string *NameStr) {
803 assert(!inFunctionScope() && "Can't give types function-local names!");
804 if (NameStr == 0) return false;
805
806 std::string Name(*NameStr); // Copy string
807 delete NameStr; // Free old string
808
809 // We don't allow assigning names to void type
810 if (T == Type::VoidTy) {
811 GenerateError("Can't assign name '" + Name + "' to the void type");
812 return false;
813 }
814
815 // Set the type name, checking for conflicts as we do so.
816 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
817
818 if (AlreadyExists) { // Inserting a name that is already defined???
819 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
820 assert(Existing && "Conflict but no matching type?!");
821
822 // There is only one case where this is allowed: when we are refining an
823 // opaque type. In this case, Existing will be an opaque type.
824 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
825 // We ARE replacing an opaque type!
826 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
827 return true;
828 }
829
830 // Otherwise, this is an attempt to redefine a type. That's okay if
831 // the redefinition is identical to the original. This will be so if
832 // Existing and T point to the same Type object. In this one case we
833 // allow the equivalent redefinition.
834 if (Existing == T) return true; // Yes, it's equal.
835
836 // Any other kind of (non-equivalent) redefinition is an error.
837 GenerateError("Redefinition of type named '" + Name + "' of type '" +
838 T->getDescription() + "'");
839 }
840
841 return false;
842}
843
844//===----------------------------------------------------------------------===//
845// Code for handling upreferences in type names...
846//
847
848// TypeContains - Returns true if Ty directly contains E in it.
849//
850static bool TypeContains(const Type *Ty, const Type *E) {
851 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
852 E) != Ty->subtype_end();
853}
854
855namespace {
856 struct UpRefRecord {
857 // NestingLevel - The number of nesting levels that need to be popped before
858 // this type is resolved.
859 unsigned NestingLevel;
860
861 // LastContainedTy - This is the type at the current binding level for the
862 // type. Every time we reduce the nesting level, this gets updated.
863 const Type *LastContainedTy;
864
865 // UpRefTy - This is the actual opaque type that the upreference is
866 // represented with.
867 OpaqueType *UpRefTy;
868
869 UpRefRecord(unsigned NL, OpaqueType *URTy)
870 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
871 };
872}
873
874// UpRefs - A list of the outstanding upreferences that need to be resolved.
875static std::vector<UpRefRecord> UpRefs;
876
877/// HandleUpRefs - Every time we finish a new layer of types, this function is
878/// called. It loops through the UpRefs vector, which is a list of the
879/// currently active types. For each type, if the up reference is contained in
880/// the newly completed type, we decrement the level count. When the level
881/// count reaches zero, the upreferenced type is the type that is passed in:
882/// thus we can complete the cycle.
883///
884static PATypeHolder HandleUpRefs(const Type *ty) {
885 // If Ty isn't abstract, or if there are no up-references in it, then there is
886 // nothing to resolve here.
887 if (!ty->isAbstract() || UpRefs.empty()) return ty;
888
889 PATypeHolder Ty(ty);
890 UR_OUT("Type '" << Ty->getDescription() <<
891 "' newly formed. Resolving upreferences.\n" <<
892 UpRefs.size() << " upreferences active!\n");
893
894 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
895 // to zero), we resolve them all together before we resolve them to Ty. At
896 // the end of the loop, if there is anything to resolve to Ty, it will be in
897 // this variable.
898 OpaqueType *TypeToResolve = 0;
899
900 for (unsigned i = 0; i != UpRefs.size(); ++i) {
901 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
902 << UpRefs[i].second->getDescription() << ") = "
903 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
904 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
905 // Decrement level of upreference
906 unsigned Level = --UpRefs[i].NestingLevel;
907 UpRefs[i].LastContainedTy = Ty;
908 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
909 if (Level == 0) { // Upreference should be resolved!
910 if (!TypeToResolve) {
911 TypeToResolve = UpRefs[i].UpRefTy;
912 } else {
913 UR_OUT(" * Resolving upreference for "
914 << UpRefs[i].second->getDescription() << "\n";
915 std::string OldName = UpRefs[i].UpRefTy->getDescription());
916 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
917 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
918 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
919 }
920 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
921 --i; // Do not skip the next element...
922 }
923 }
924 }
925
926 if (TypeToResolve) {
927 UR_OUT(" * Resolving upreference for "
928 << UpRefs[i].second->getDescription() << "\n";
929 std::string OldName = TypeToResolve->getDescription());
930 TypeToResolve->refineAbstractTypeTo(Ty);
931 }
932
933 return Ty;
934}
935
936//===----------------------------------------------------------------------===//
937// RunVMAsmParser - Define an interface to this parser
938//===----------------------------------------------------------------------===//
939//
940static Module* RunParser(Module * M);
941
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000942Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
943 InitLLLexer(MB);
944 Module *M = RunParser(new Module(LLLgetFilename()));
945 FreeLexer();
946 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947}
948
949%}
950
951%union {
952 llvm::Module *ModuleVal;
953 llvm::Function *FunctionVal;
954 llvm::BasicBlock *BasicBlockVal;
955 llvm::TerminatorInst *TermInstVal;
956 llvm::Instruction *InstVal;
957 llvm::Constant *ConstVal;
958
959 const llvm::Type *PrimType;
960 std::list<llvm::PATypeHolder> *TypeList;
961 llvm::PATypeHolder *TypeVal;
962 llvm::Value *ValueVal;
963 std::vector<llvm::Value*> *ValueList;
964 llvm::ArgListType *ArgList;
965 llvm::TypeWithAttrs TypeWithAttrs;
966 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000967 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000968
969 // Represent the RHS of PHI node
970 std::list<std::pair<llvm::Value*,
971 llvm::BasicBlock*> > *PHIList;
972 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
973 std::vector<llvm::Constant*> *ConstVector;
974
975 llvm::GlobalValue::LinkageTypes Linkage;
976 llvm::GlobalValue::VisibilityTypes Visibility;
977 uint16_t ParamAttrs;
978 llvm::APInt *APIntVal;
979 int64_t SInt64Val;
980 uint64_t UInt64Val;
981 int SIntVal;
982 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000983 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 bool BoolVal;
985
986 std::string *StrVal; // This memory must be deleted
987 llvm::ValID ValIDVal;
988
989 llvm::Instruction::BinaryOps BinaryOpVal;
990 llvm::Instruction::TermOps TermOpVal;
991 llvm::Instruction::MemoryOps MemOpVal;
992 llvm::Instruction::CastOps CastOpVal;
993 llvm::Instruction::OtherOps OtherOpVal;
994 llvm::ICmpInst::Predicate IPredicate;
995 llvm::FCmpInst::Predicate FPredicate;
996}
997
998%type <ModuleVal> Module
999%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1000%type <BasicBlockVal> BasicBlock InstructionList
1001%type <TermInstVal> BBTerminatorInst
1002%type <InstVal> Inst InstVal MemoryInst
1003%type <ConstVal> ConstVal ConstExpr AliaseeRef
1004%type <ConstVector> ConstVector
1005%type <ArgList> ArgList ArgListH
1006%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001007%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008%type <ValueList> IndexList // For GEP indices
1009%type <TypeList> TypeListI
1010%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1011%type <TypeWithAttrs> ArgType
1012%type <JumpTable> JumpTable
1013%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1014%type <BoolVal> ThreadLocal // 'thread_local' or not
1015%type <BoolVal> OptVolatile // 'volatile' or not
1016%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1017%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1018%type <Linkage> GVInternalLinkage GVExternalLinkage
1019%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1020%type <Linkage> AliasLinkage
1021%type <Visibility> GVVisibilityStyle
1022
1023// ValueRef - Unresolved reference to a definition or BB
1024%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1025%type <ValueVal> ResolvedVal // <type> <valref> pair
1026// Tokens and types for handling constant integer values
1027//
1028// ESINT64VAL - A negative number within long long range
1029%token <SInt64Val> ESINT64VAL
1030
1031// EUINT64VAL - A positive number within uns. long long range
1032%token <UInt64Val> EUINT64VAL
1033
1034// ESAPINTVAL - A negative number with arbitrary precision
1035%token <APIntVal> ESAPINTVAL
1036
1037// EUAPINTVAL - A positive number with arbitrary precision
1038%token <APIntVal> EUAPINTVAL
1039
1040%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1041%token <FPVal> FPVAL // Float or Double constant
1042
1043// Built in types...
1044%type <TypeVal> Types ResultTypes
1045%type <PrimType> IntType FPType PrimType // Classifications
1046%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001047%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048%token TYPE
1049
1050
1051%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1052%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1053%type <StrVal> LocalName OptLocalName OptLocalAssign
1054%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001055%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056
Christopher Lamb668d9a02007-12-12 08:45:45 +00001057%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058
1059%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1060%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1061%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1062%token DLLIMPORT DLLEXPORT EXTERN_WEAK
Christopher Lamb0a243582007-12-11 09:02:08 +00001063%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1065%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1066%token DATALAYOUT
1067%type <UIntVal> OptCallingConv
1068%type <ParamAttrs> OptParamAttrs ParamAttr
1069%type <ParamAttrs> OptFuncAttrs FuncAttr
1070
1071// Basic Block Terminating Operators
1072%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1073
1074// Binary Operators
1075%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1076%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1077%token <BinaryOpVal> SHL LSHR ASHR
1078
1079%token <OtherOpVal> ICMP FCMP
1080%type <IPredicate> IPredicates
1081%type <FPredicate> FPredicates
1082%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1083%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1084
1085// Memory Instructions
1086%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1087
1088// Cast Operators
1089%type <CastOpVal> CastOps
1090%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1091%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1092
1093// Other Operators
1094%token <OtherOpVal> PHI_TOK SELECT VAARG
1095%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1096
1097// Function Attributes
Reid Spenceraa8ae282007-07-31 03:50:36 +00001098%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001099%token READNONE READONLY GC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100
1101// Visibility Styles
1102%token DEFAULT HIDDEN PROTECTED
1103
1104%start Module
1105%%
1106
1107
1108// Operations that are notably excluded from this list include:
1109// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1110//
1111ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1112LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1113CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1114 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1115
1116IPredicates
1117 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1118 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1119 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1120 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1121 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1122 ;
1123
1124FPredicates
1125 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1126 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1127 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1128 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1129 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1130 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1131 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1132 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1133 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1134 ;
1135
1136// These are some types that allow classification if we only want a particular
1137// thing... for example, only a signed, unsigned, or integral type.
1138IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001139FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140
1141LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1142OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1143
Christopher Lamb668d9a02007-12-12 08:45:45 +00001144OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1145 | /*empty*/ { $$=0; };
1146
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147/// OptLocalAssign - Value producing statements have an optional assignment
1148/// component.
1149OptLocalAssign : LocalName '=' {
1150 $$ = $1;
1151 CHECK_FOR_ERROR
1152 }
1153 | /*empty*/ {
1154 $$ = 0;
1155 CHECK_FOR_ERROR
1156 };
1157
1158GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1159
1160OptGlobalAssign : GlobalAssign
1161 | /*empty*/ {
1162 $$ = 0;
1163 CHECK_FOR_ERROR
1164 };
1165
1166GlobalAssign : GlobalName '=' {
1167 $$ = $1;
1168 CHECK_FOR_ERROR
1169 };
1170
1171GVInternalLinkage
1172 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1173 | WEAK { $$ = GlobalValue::WeakLinkage; }
1174 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1175 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1176 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1177 ;
1178
1179GVExternalLinkage
1180 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1181 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1182 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1183 ;
1184
1185GVVisibilityStyle
1186 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1187 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1188 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1189 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1190 ;
1191
1192FunctionDeclareLinkage
1193 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1194 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1195 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1196 ;
1197
1198FunctionDefineLinkage
1199 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1200 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1201 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1202 | WEAK { $$ = GlobalValue::WeakLinkage; }
1203 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1204 ;
1205
1206AliasLinkage
1207 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1208 | WEAK { $$ = GlobalValue::WeakLinkage; }
1209 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1210 ;
1211
1212OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1213 CCC_TOK { $$ = CallingConv::C; } |
1214 FASTCC_TOK { $$ = CallingConv::Fast; } |
1215 COLDCC_TOK { $$ = CallingConv::Cold; } |
1216 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1217 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1218 CC_TOK EUINT64VAL {
1219 if ((unsigned)$2 != $2)
1220 GEN_ERROR("Calling conv too large");
1221 $$ = $2;
1222 CHECK_FOR_ERROR
1223 };
1224
Reid Spenceraa8ae282007-07-31 03:50:36 +00001225ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1226 | ZEXT { $$ = ParamAttr::ZExt; }
1227 | SIGNEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 | SEXT { $$ = ParamAttr::SExt; }
1229 | INREG { $$ = ParamAttr::InReg; }
1230 | SRET { $$ = ParamAttr::StructRet; }
1231 | NOALIAS { $$ = ParamAttr::NoAlias; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001232 | BYVAL { $$ = ParamAttr::ByVal; }
1233 | NEST { $$ = ParamAttr::Nest; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 ;
1235
1236OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1237 | OptParamAttrs ParamAttr {
1238 $$ = $1 | $2;
1239 }
1240 ;
1241
1242FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1243 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001244 | ZEROEXT { $$ = ParamAttr::ZExt; }
1245 | SIGNEXT { $$ = ParamAttr::SExt; }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001246 | READNONE { $$ = ParamAttr::ReadNone; }
1247 | READONLY { $$ = ParamAttr::ReadOnly; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 ;
1249
1250OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1251 | OptFuncAttrs FuncAttr {
1252 $$ = $1 | $2;
1253 }
1254 ;
1255
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001256OptGC : /* empty */ { $$ = 0; }
1257 | GC STRINGCONSTANT {
1258 $$ = $2;
1259 }
1260 ;
1261
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1263// a comma before it.
1264OptAlign : /*empty*/ { $$ = 0; } |
1265 ALIGN EUINT64VAL {
1266 $$ = $2;
1267 if ($$ != 0 && !isPowerOf2_32($$))
1268 GEN_ERROR("Alignment must be a power of two");
1269 CHECK_FOR_ERROR
1270};
1271OptCAlign : /*empty*/ { $$ = 0; } |
1272 ',' ALIGN EUINT64VAL {
1273 $$ = $3;
1274 if ($$ != 0 && !isPowerOf2_32($$))
1275 GEN_ERROR("Alignment must be a power of two");
1276 CHECK_FOR_ERROR
1277};
1278
1279
Christopher Lamb0a243582007-12-11 09:02:08 +00001280
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281SectionString : SECTION STRINGCONSTANT {
1282 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1283 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1284 GEN_ERROR("Invalid character in section name");
1285 $$ = $2;
1286 CHECK_FOR_ERROR
1287};
1288
1289OptSection : /*empty*/ { $$ = 0; } |
1290 SectionString { $$ = $1; };
1291
1292// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1293// is set to be the global we are processing.
1294//
1295GlobalVarAttributes : /* empty */ {} |
1296 ',' GlobalVarAttribute GlobalVarAttributes {};
1297GlobalVarAttribute : SectionString {
1298 CurGV->setSection(*$1);
1299 delete $1;
1300 CHECK_FOR_ERROR
1301 }
1302 | ALIGN EUINT64VAL {
1303 if ($2 != 0 && !isPowerOf2_32($2))
1304 GEN_ERROR("Alignment must be a power of two");
1305 CurGV->setAlignment($2);
1306 CHECK_FOR_ERROR
1307 };
1308
1309//===----------------------------------------------------------------------===//
1310// Types includes all predefined types... except void, because it can only be
1311// used in specific contexts (function returning void for example).
1312
1313// Derived types are added later...
1314//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001315PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316
1317Types
1318 : OPAQUE {
1319 $$ = new PATypeHolder(OpaqueType::get());
1320 CHECK_FOR_ERROR
1321 }
1322 | PrimType {
1323 $$ = new PATypeHolder($1);
1324 CHECK_FOR_ERROR
1325 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00001326 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 if (*$1 == Type::LabelTy)
1328 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb668d9a02007-12-12 08:45:45 +00001329 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb0a243582007-12-11 09:02:08 +00001330 delete $1;
1331 CHECK_FOR_ERROR
1332 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 | SymbolicValueRef { // Named types are also simple types...
1334 const Type* tmp = getTypeVal($1);
1335 CHECK_FOR_ERROR
1336 $$ = new PATypeHolder(tmp);
1337 }
1338 | '\\' EUINT64VAL { // Type UpReference
1339 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1340 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1341 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1342 $$ = new PATypeHolder(OT);
1343 UR_OUT("New Upreference!\n");
1344 CHECK_FOR_ERROR
1345 }
1346 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001347 // Allow but ignore attributes on function types; this permits auto-upgrade.
1348 // FIXME: remove in LLVM 3.0.
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001349 const Type* RetTy = *$1;
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001350 if (!(RetTy->isFirstClassType() || RetTy == Type::VoidTy ||
1351 isa<OpaqueType>(RetTy)))
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001352 GEN_ERROR("LLVM Functions cannot return aggregates");
1353
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001356 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 const Type *Ty = I->Ty->get();
1358 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001360
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1362 if (isVarArg) Params.pop_back();
1363
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001364 for (unsigned i = 0; i != Params.size(); ++i)
1365 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1366 GEN_ERROR("Function arguments must be value types!");
1367
1368 CHECK_FOR_ERROR
1369
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001370 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 delete $3; // Delete the argument list
1372 delete $1; // Delete the return type handle
1373 $$ = new PATypeHolder(HandleUpRefs(FT));
1374 CHECK_FOR_ERROR
1375 }
1376 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001377 // Allow but ignore attributes on function types; this permits auto-upgrade.
1378 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001381 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 const Type* Ty = I->Ty->get();
1383 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001385
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1387 if (isVarArg) Params.pop_back();
1388
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001389 for (unsigned i = 0; i != Params.size(); ++i)
1390 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1391 GEN_ERROR("Function arguments must be value types!");
1392
1393 CHECK_FOR_ERROR
1394
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001395 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396 delete $3; // Delete the argument list
1397 $$ = new PATypeHolder(HandleUpRefs(FT));
1398 CHECK_FOR_ERROR
1399 }
1400
1401 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1402 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1403 delete $4;
1404 CHECK_FOR_ERROR
1405 }
1406 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1407 const llvm::Type* ElemTy = $4->get();
1408 if ((unsigned)$2 != $2)
1409 GEN_ERROR("Unsigned result not equal to signed result");
1410 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1411 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1413 delete $4;
1414 CHECK_FOR_ERROR
1415 }
1416 | '{' TypeListI '}' { // Structure type?
1417 std::vector<const Type*> Elements;
1418 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1419 E = $2->end(); I != E; ++I)
1420 Elements.push_back(*I);
1421
1422 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1423 delete $2;
1424 CHECK_FOR_ERROR
1425 }
1426 | '{' '}' { // Empty structure type?
1427 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1428 CHECK_FOR_ERROR
1429 }
1430 | '<' '{' TypeListI '}' '>' {
1431 std::vector<const Type*> Elements;
1432 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1433 E = $3->end(); I != E; ++I)
1434 Elements.push_back(*I);
1435
1436 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1437 delete $3;
1438 CHECK_FOR_ERROR
1439 }
1440 | '<' '{' '}' '>' { // Empty structure type?
1441 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1442 CHECK_FOR_ERROR
1443 }
1444 ;
1445
1446ArgType
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001447 : Types OptParamAttrs {
1448 // Allow but ignore attributes on function types; this permits auto-upgrade.
1449 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 $$.Ty = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001451 $$.Attrs = ParamAttr::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 }
1453 ;
1454
1455ResultTypes
1456 : Types {
1457 if (!UpRefs.empty())
1458 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1459 if (!(*$1)->isFirstClassType())
1460 GEN_ERROR("LLVM functions cannot return aggregate types");
1461 $$ = $1;
1462 }
1463 | VOID {
1464 $$ = new PATypeHolder(Type::VoidTy);
1465 }
1466 ;
1467
1468ArgTypeList : ArgType {
1469 $$ = new TypeWithAttrsList();
1470 $$->push_back($1);
1471 CHECK_FOR_ERROR
1472 }
1473 | ArgTypeList ',' ArgType {
1474 ($$=$1)->push_back($3);
1475 CHECK_FOR_ERROR
1476 }
1477 ;
1478
1479ArgTypeListI
1480 : ArgTypeList
1481 | ArgTypeList ',' DOTDOTDOT {
1482 $$=$1;
1483 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1484 TWA.Ty = new PATypeHolder(Type::VoidTy);
1485 $$->push_back(TWA);
1486 CHECK_FOR_ERROR
1487 }
1488 | DOTDOTDOT {
1489 $$ = new TypeWithAttrsList;
1490 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1491 TWA.Ty = new PATypeHolder(Type::VoidTy);
1492 $$->push_back(TWA);
1493 CHECK_FOR_ERROR
1494 }
1495 | /*empty*/ {
1496 $$ = new TypeWithAttrsList();
1497 CHECK_FOR_ERROR
1498 };
1499
1500// TypeList - Used for struct declarations and as a basis for function type
1501// declaration type lists
1502//
1503TypeListI : Types {
1504 $$ = new std::list<PATypeHolder>();
1505 $$->push_back(*$1);
1506 delete $1;
1507 CHECK_FOR_ERROR
1508 }
1509 | TypeListI ',' Types {
1510 ($$=$1)->push_back(*$3);
1511 delete $3;
1512 CHECK_FOR_ERROR
1513 };
1514
1515// ConstVal - The various declarations that go into the constant pool. This
1516// production is used ONLY to represent constants that show up AFTER a 'const',
1517// 'constant' or 'global' token at global scope. Constants that can be inlined
1518// into other expressions (such as integers and constexprs) are handled by the
1519// ResolvedVal, ValueRef and ConstValueRef productions.
1520//
1521ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1522 if (!UpRefs.empty())
1523 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1524 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1525 if (ATy == 0)
1526 GEN_ERROR("Cannot make array constant with type: '" +
1527 (*$1)->getDescription() + "'");
1528 const Type *ETy = ATy->getElementType();
1529 int NumElements = ATy->getNumElements();
1530
1531 // Verify that we have the correct size...
1532 if (NumElements != -1 && NumElements != (int)$3->size())
1533 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1534 utostr($3->size()) + " arguments, but has size of " +
1535 itostr(NumElements) + "");
1536
1537 // Verify all elements are correct type!
1538 for (unsigned i = 0; i < $3->size(); i++) {
1539 if (ETy != (*$3)[i]->getType())
1540 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1541 ETy->getDescription() +"' as required!\nIt is of type '"+
1542 (*$3)[i]->getType()->getDescription() + "'.");
1543 }
1544
1545 $$ = ConstantArray::get(ATy, *$3);
1546 delete $1; delete $3;
1547 CHECK_FOR_ERROR
1548 }
1549 | Types '[' ']' {
1550 if (!UpRefs.empty())
1551 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1552 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1553 if (ATy == 0)
1554 GEN_ERROR("Cannot make array constant with type: '" +
1555 (*$1)->getDescription() + "'");
1556
1557 int NumElements = ATy->getNumElements();
1558 if (NumElements != -1 && NumElements != 0)
1559 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1560 " arguments, but has size of " + itostr(NumElements) +"");
1561 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1562 delete $1;
1563 CHECK_FOR_ERROR
1564 }
1565 | Types 'c' STRINGCONSTANT {
1566 if (!UpRefs.empty())
1567 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1568 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1569 if (ATy == 0)
1570 GEN_ERROR("Cannot make array constant with type: '" +
1571 (*$1)->getDescription() + "'");
1572
1573 int NumElements = ATy->getNumElements();
1574 const Type *ETy = ATy->getElementType();
1575 if (NumElements != -1 && NumElements != int($3->length()))
1576 GEN_ERROR("Can't build string constant of size " +
1577 itostr((int)($3->length())) +
1578 " when array has size " + itostr(NumElements) + "");
1579 std::vector<Constant*> Vals;
1580 if (ETy == Type::Int8Ty) {
1581 for (unsigned i = 0; i < $3->length(); ++i)
1582 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1583 } else {
1584 delete $3;
1585 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1586 }
1587 delete $3;
1588 $$ = ConstantArray::get(ATy, Vals);
1589 delete $1;
1590 CHECK_FOR_ERROR
1591 }
1592 | Types '<' ConstVector '>' { // Nonempty unsized arr
1593 if (!UpRefs.empty())
1594 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1595 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1596 if (PTy == 0)
1597 GEN_ERROR("Cannot make packed constant with type: '" +
1598 (*$1)->getDescription() + "'");
1599 const Type *ETy = PTy->getElementType();
1600 int NumElements = PTy->getNumElements();
1601
1602 // Verify that we have the correct size...
1603 if (NumElements != -1 && NumElements != (int)$3->size())
1604 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1605 utostr($3->size()) + " arguments, but has size of " +
1606 itostr(NumElements) + "");
1607
1608 // Verify all elements are correct type!
1609 for (unsigned i = 0; i < $3->size(); i++) {
1610 if (ETy != (*$3)[i]->getType())
1611 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1612 ETy->getDescription() +"' as required!\nIt is of type '"+
1613 (*$3)[i]->getType()->getDescription() + "'.");
1614 }
1615
1616 $$ = ConstantVector::get(PTy, *$3);
1617 delete $1; delete $3;
1618 CHECK_FOR_ERROR
1619 }
1620 | Types '{' ConstVector '}' {
1621 const StructType *STy = dyn_cast<StructType>($1->get());
1622 if (STy == 0)
1623 GEN_ERROR("Cannot make struct constant with type: '" +
1624 (*$1)->getDescription() + "'");
1625
1626 if ($3->size() != STy->getNumContainedTypes())
1627 GEN_ERROR("Illegal number of initializers for structure type");
1628
1629 // Check to ensure that constants are compatible with the type initializer!
1630 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1631 if ((*$3)[i]->getType() != STy->getElementType(i))
1632 GEN_ERROR("Expected type '" +
1633 STy->getElementType(i)->getDescription() +
1634 "' for element #" + utostr(i) +
1635 " of structure initializer");
1636
1637 // Check to ensure that Type is not packed
1638 if (STy->isPacked())
1639 GEN_ERROR("Unpacked Initializer to vector type '" +
1640 STy->getDescription() + "'");
1641
1642 $$ = ConstantStruct::get(STy, *$3);
1643 delete $1; delete $3;
1644 CHECK_FOR_ERROR
1645 }
1646 | Types '{' '}' {
1647 if (!UpRefs.empty())
1648 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1649 const StructType *STy = dyn_cast<StructType>($1->get());
1650 if (STy == 0)
1651 GEN_ERROR("Cannot make struct constant with type: '" +
1652 (*$1)->getDescription() + "'");
1653
1654 if (STy->getNumContainedTypes() != 0)
1655 GEN_ERROR("Illegal number of initializers for structure type");
1656
1657 // Check to ensure that Type is not packed
1658 if (STy->isPacked())
1659 GEN_ERROR("Unpacked Initializer to vector type '" +
1660 STy->getDescription() + "'");
1661
1662 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1663 delete $1;
1664 CHECK_FOR_ERROR
1665 }
1666 | Types '<' '{' ConstVector '}' '>' {
1667 const StructType *STy = dyn_cast<StructType>($1->get());
1668 if (STy == 0)
1669 GEN_ERROR("Cannot make struct constant with type: '" +
1670 (*$1)->getDescription() + "'");
1671
1672 if ($4->size() != STy->getNumContainedTypes())
1673 GEN_ERROR("Illegal number of initializers for structure type");
1674
1675 // Check to ensure that constants are compatible with the type initializer!
1676 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1677 if ((*$4)[i]->getType() != STy->getElementType(i))
1678 GEN_ERROR("Expected type '" +
1679 STy->getElementType(i)->getDescription() +
1680 "' for element #" + utostr(i) +
1681 " of structure initializer");
1682
1683 // Check to ensure that Type is packed
1684 if (!STy->isPacked())
1685 GEN_ERROR("Vector initializer to non-vector type '" +
1686 STy->getDescription() + "'");
1687
1688 $$ = ConstantStruct::get(STy, *$4);
1689 delete $1; delete $4;
1690 CHECK_FOR_ERROR
1691 }
1692 | Types '<' '{' '}' '>' {
1693 if (!UpRefs.empty())
1694 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1695 const StructType *STy = dyn_cast<StructType>($1->get());
1696 if (STy == 0)
1697 GEN_ERROR("Cannot make struct constant with type: '" +
1698 (*$1)->getDescription() + "'");
1699
1700 if (STy->getNumContainedTypes() != 0)
1701 GEN_ERROR("Illegal number of initializers for structure type");
1702
1703 // Check to ensure that Type is packed
1704 if (!STy->isPacked())
1705 GEN_ERROR("Vector initializer to non-vector type '" +
1706 STy->getDescription() + "'");
1707
1708 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1709 delete $1;
1710 CHECK_FOR_ERROR
1711 }
1712 | Types NULL_TOK {
1713 if (!UpRefs.empty())
1714 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1715 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1716 if (PTy == 0)
1717 GEN_ERROR("Cannot make null pointer constant with type: '" +
1718 (*$1)->getDescription() + "'");
1719
1720 $$ = ConstantPointerNull::get(PTy);
1721 delete $1;
1722 CHECK_FOR_ERROR
1723 }
1724 | Types UNDEF {
1725 if (!UpRefs.empty())
1726 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1727 $$ = UndefValue::get($1->get());
1728 delete $1;
1729 CHECK_FOR_ERROR
1730 }
1731 | Types SymbolicValueRef {
1732 if (!UpRefs.empty())
1733 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1734 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1735 if (Ty == 0)
1736 GEN_ERROR("Global const reference must be a pointer type");
1737
1738 // ConstExprs can exist in the body of a function, thus creating
1739 // GlobalValues whenever they refer to a variable. Because we are in
1740 // the context of a function, getExistingVal will search the functions
1741 // symbol table instead of the module symbol table for the global symbol,
1742 // which throws things all off. To get around this, we just tell
1743 // getExistingVal that we are at global scope here.
1744 //
1745 Function *SavedCurFn = CurFun.CurrentFunction;
1746 CurFun.CurrentFunction = 0;
1747
1748 Value *V = getExistingVal(Ty, $2);
1749 CHECK_FOR_ERROR
1750
1751 CurFun.CurrentFunction = SavedCurFn;
1752
1753 // If this is an initializer for a constant pointer, which is referencing a
1754 // (currently) undefined variable, create a stub now that shall be replaced
1755 // in the future with the right type of variable.
1756 //
1757 if (V == 0) {
1758 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1759 const PointerType *PT = cast<PointerType>(Ty);
1760
1761 // First check to see if the forward references value is already created!
1762 PerModuleInfo::GlobalRefsType::iterator I =
1763 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1764
1765 if (I != CurModule.GlobalRefs.end()) {
1766 V = I->second; // Placeholder already exists, use it...
1767 $2.destroy();
1768 } else {
1769 std::string Name;
1770 if ($2.Type == ValID::GlobalName)
1771 Name = $2.getName();
1772 else if ($2.Type != ValID::GlobalID)
1773 GEN_ERROR("Invalid reference to global");
1774
1775 // Create the forward referenced global.
1776 GlobalValue *GV;
1777 if (const FunctionType *FTy =
1778 dyn_cast<FunctionType>(PT->getElementType())) {
1779 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1780 CurModule.CurrentModule);
1781 } else {
1782 GV = new GlobalVariable(PT->getElementType(), false,
1783 GlobalValue::ExternalWeakLinkage, 0,
1784 Name, CurModule.CurrentModule);
1785 }
1786
1787 // Keep track of the fact that we have a forward ref to recycle it
1788 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1789 V = GV;
1790 }
1791 }
1792
1793 $$ = cast<GlobalValue>(V);
1794 delete $1; // Free the type handle
1795 CHECK_FOR_ERROR
1796 }
1797 | Types ConstExpr {
1798 if (!UpRefs.empty())
1799 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1800 if ($1->get() != $2->getType())
1801 GEN_ERROR("Mismatched types for constant expression: " +
1802 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1803 $$ = $2;
1804 delete $1;
1805 CHECK_FOR_ERROR
1806 }
1807 | Types ZEROINITIALIZER {
1808 if (!UpRefs.empty())
1809 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1810 const Type *Ty = $1->get();
1811 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1812 GEN_ERROR("Cannot create a null initialized value of this type");
1813 $$ = Constant::getNullValue(Ty);
1814 delete $1;
1815 CHECK_FOR_ERROR
1816 }
1817 | IntType ESINT64VAL { // integral constants
1818 if (!ConstantInt::isValueValidForType($1, $2))
1819 GEN_ERROR("Constant value doesn't fit in type");
1820 $$ = ConstantInt::get($1, $2, true);
1821 CHECK_FOR_ERROR
1822 }
1823 | IntType ESAPINTVAL { // arbitrary precision integer constants
1824 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1825 if ($2->getBitWidth() > BitWidth) {
1826 GEN_ERROR("Constant value does not fit in type");
1827 }
1828 $2->sextOrTrunc(BitWidth);
1829 $$ = ConstantInt::get(*$2);
1830 delete $2;
1831 CHECK_FOR_ERROR
1832 }
1833 | IntType EUINT64VAL { // integral constants
1834 if (!ConstantInt::isValueValidForType($1, $2))
1835 GEN_ERROR("Constant value doesn't fit in type");
1836 $$ = ConstantInt::get($1, $2, false);
1837 CHECK_FOR_ERROR
1838 }
1839 | IntType EUAPINTVAL { // arbitrary precision integer constants
1840 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1841 if ($2->getBitWidth() > BitWidth) {
1842 GEN_ERROR("Constant value does not fit in type");
1843 }
1844 $2->zextOrTrunc(BitWidth);
1845 $$ = ConstantInt::get(*$2);
1846 delete $2;
1847 CHECK_FOR_ERROR
1848 }
1849 | INTTYPE TRUETOK { // Boolean constants
1850 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1851 $$ = ConstantInt::getTrue();
1852 CHECK_FOR_ERROR
1853 }
1854 | INTTYPE FALSETOK { // Boolean constants
1855 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1856 $$ = ConstantInt::getFalse();
1857 CHECK_FOR_ERROR
1858 }
Dale Johannesen043064d2007-09-12 03:31:28 +00001859 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001860 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen255b8fe2007-09-11 18:33:39 +00001862 // Lexer has no type info, so builds all float and double FP constants
1863 // as double. Fix this here. Long double is done right.
1864 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001865 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1866 $$ = ConstantFP::get($1, *$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001867 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001868 CHECK_FOR_ERROR
1869 };
1870
1871
1872ConstExpr: CastOps '(' ConstVal TO Types ')' {
1873 if (!UpRefs.empty())
1874 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1875 Constant *Val = $3;
1876 const Type *DestTy = $5->get();
1877 if (!CastInst::castIsValid($1, $3, DestTy))
1878 GEN_ERROR("invalid cast opcode for cast from '" +
1879 Val->getType()->getDescription() + "' to '" +
1880 DestTy->getDescription() + "'");
1881 $$ = ConstantExpr::getCast($1, $3, DestTy);
1882 delete $5;
1883 }
1884 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1885 if (!isa<PointerType>($3->getType()))
1886 GEN_ERROR("GetElementPtr requires a pointer operand");
1887
1888 const Type *IdxTy =
David Greene48556392007-09-04 18:46:50 +00001889 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001890 true);
1891 if (!IdxTy)
1892 GEN_ERROR("Index list invalid for constant getelementptr");
1893
1894 SmallVector<Constant*, 8> IdxVec;
1895 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1896 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1897 IdxVec.push_back(C);
1898 else
1899 GEN_ERROR("Indices to constant getelementptr must be constants");
1900
1901 delete $4;
1902
1903 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1904 CHECK_FOR_ERROR
1905 }
1906 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1907 if ($3->getType() != Type::Int1Ty)
1908 GEN_ERROR("Select condition must be of boolean type");
1909 if ($5->getType() != $7->getType())
1910 GEN_ERROR("Select operand types must match");
1911 $$ = ConstantExpr::getSelect($3, $5, $7);
1912 CHECK_FOR_ERROR
1913 }
1914 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1915 if ($3->getType() != $5->getType())
1916 GEN_ERROR("Binary operator types must match");
1917 CHECK_FOR_ERROR;
1918 $$ = ConstantExpr::get($1, $3, $5);
1919 }
1920 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1921 if ($3->getType() != $5->getType())
1922 GEN_ERROR("Logical operator types must match");
1923 if (!$3->getType()->isInteger()) {
1924 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1925 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1926 GEN_ERROR("Logical operator requires integral operands");
1927 }
1928 $$ = ConstantExpr::get($1, $3, $5);
1929 CHECK_FOR_ERROR
1930 }
1931 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1932 if ($4->getType() != $6->getType())
1933 GEN_ERROR("icmp operand types must match");
1934 $$ = ConstantExpr::getICmp($2, $4, $6);
1935 }
1936 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1937 if ($4->getType() != $6->getType())
1938 GEN_ERROR("fcmp operand types must match");
1939 $$ = ConstantExpr::getFCmp($2, $4, $6);
1940 }
1941 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1942 if (!ExtractElementInst::isValidOperands($3, $5))
1943 GEN_ERROR("Invalid extractelement operands");
1944 $$ = ConstantExpr::getExtractElement($3, $5);
1945 CHECK_FOR_ERROR
1946 }
1947 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1948 if (!InsertElementInst::isValidOperands($3, $5, $7))
1949 GEN_ERROR("Invalid insertelement operands");
1950 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1951 CHECK_FOR_ERROR
1952 }
1953 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1954 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1955 GEN_ERROR("Invalid shufflevector operands");
1956 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1957 CHECK_FOR_ERROR
1958 };
1959
1960
1961// ConstVector - A list of comma separated constants.
1962ConstVector : ConstVector ',' ConstVal {
1963 ($$ = $1)->push_back($3);
1964 CHECK_FOR_ERROR
1965 }
1966 | ConstVal {
1967 $$ = new std::vector<Constant*>();
1968 $$->push_back($1);
1969 CHECK_FOR_ERROR
1970 };
1971
1972
1973// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1974GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1975
1976// ThreadLocal
1977ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1978
1979// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1980AliaseeRef : ResultTypes SymbolicValueRef {
1981 const Type* VTy = $1->get();
1982 Value *V = getVal(VTy, $2);
Chris Lattnerbb856a32007-08-06 21:00:46 +00001983 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1985 if (!Aliasee)
1986 GEN_ERROR("Aliases can be created only to global values");
1987
1988 $$ = Aliasee;
1989 CHECK_FOR_ERROR
1990 delete $1;
1991 }
1992 | BITCAST '(' AliaseeRef TO Types ')' {
1993 Constant *Val = $3;
1994 const Type *DestTy = $5->get();
1995 if (!CastInst::castIsValid($1, $3, DestTy))
1996 GEN_ERROR("invalid cast opcode for cast from '" +
1997 Val->getType()->getDescription() + "' to '" +
1998 DestTy->getDescription() + "'");
1999
2000 $$ = ConstantExpr::getCast($1, $3, DestTy);
2001 CHECK_FOR_ERROR
2002 delete $5;
2003 };
2004
2005//===----------------------------------------------------------------------===//
2006// Rules to match Modules
2007//===----------------------------------------------------------------------===//
2008
2009// Module rule: Capture the result of parsing the whole file into a result
2010// variable...
2011//
2012Module
2013 : DefinitionList {
2014 $$ = ParserResult = CurModule.CurrentModule;
2015 CurModule.ModuleDone();
2016 CHECK_FOR_ERROR;
2017 }
2018 | /*empty*/ {
2019 $$ = ParserResult = CurModule.CurrentModule;
2020 CurModule.ModuleDone();
2021 CHECK_FOR_ERROR;
2022 }
2023 ;
2024
2025DefinitionList
2026 : Definition
2027 | DefinitionList Definition
2028 ;
2029
2030Definition
2031 : DEFINE { CurFun.isDeclare = false; } Function {
2032 CurFun.FunctionDone();
2033 CHECK_FOR_ERROR
2034 }
2035 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2036 CHECK_FOR_ERROR
2037 }
2038 | MODULE ASM_TOK AsmBlock {
2039 CHECK_FOR_ERROR
2040 }
2041 | OptLocalAssign TYPE Types {
2042 if (!UpRefs.empty())
2043 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2044 // Eagerly resolve types. This is not an optimization, this is a
2045 // requirement that is due to the fact that we could have this:
2046 //
2047 // %list = type { %list * }
2048 // %list = type { %list * } ; repeated type decl
2049 //
2050 // If types are not resolved eagerly, then the two types will not be
2051 // determined to be the same type!
2052 //
2053 ResolveTypeTo($1, *$3);
2054
2055 if (!setTypeName(*$3, $1) && !$1) {
2056 CHECK_FOR_ERROR
2057 // If this is a named type that is not a redefinition, add it to the slot
2058 // table.
2059 CurModule.Types.push_back(*$3);
2060 }
2061
2062 delete $3;
2063 CHECK_FOR_ERROR
2064 }
2065 | OptLocalAssign TYPE VOID {
2066 ResolveTypeTo($1, $3);
2067
2068 if (!setTypeName($3, $1) && !$1) {
2069 CHECK_FOR_ERROR
2070 // If this is a named type that is not a redefinition, add it to the slot
2071 // table.
2072 CurModule.Types.push_back($3);
2073 }
2074 CHECK_FOR_ERROR
2075 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00002076 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2077 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078 /* "Externally Visible" Linkage */
2079 if ($5 == 0)
2080 GEN_ERROR("Global value initializer is not a constant");
2081 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb668d9a02007-12-12 08:45:45 +00002082 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb0a243582007-12-11 09:02:08 +00002083 CHECK_FOR_ERROR
2084 } GlobalVarAttributes {
2085 CurGV = 0;
2086 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002087 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002088 ConstVal OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002089 if ($6 == 0)
2090 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb668d9a02007-12-12 08:45:45 +00002091 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 CHECK_FOR_ERROR
2093 } GlobalVarAttributes {
2094 CurGV = 0;
2095 }
2096 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002097 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098 if (!UpRefs.empty())
2099 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb668d9a02007-12-12 08:45:45 +00002100 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002101 CHECK_FOR_ERROR
2102 delete $6;
2103 } GlobalVarAttributes {
2104 CurGV = 0;
2105 CHECK_FOR_ERROR
2106 }
2107 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2108 std::string Name;
2109 if ($1) {
2110 Name = *$1;
2111 delete $1;
2112 }
2113 if (Name.empty())
2114 GEN_ERROR("Alias name cannot be empty");
2115
2116 Constant* Aliasee = $5;
2117 if (Aliasee == 0)
2118 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2119
2120 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2121 CurModule.CurrentModule);
2122 GA->setVisibility($2);
2123 InsertValue(GA, CurModule.Values);
Chris Lattner5eefce32007-09-10 23:24:14 +00002124
2125
2126 // If there was a forward reference of this alias, resolve it now.
2127
2128 ValID ID;
2129 if (!Name.empty())
2130 ID = ValID::createGlobalName(Name);
2131 else
2132 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2133
2134 if (GlobalValue *FWGV =
2135 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2136 // Replace uses of the fwdref with the actual alias.
2137 FWGV->replaceAllUsesWith(GA);
2138 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2139 GV->eraseFromParent();
2140 else
2141 cast<Function>(FWGV)->eraseFromParent();
2142 }
2143 ID.destroy();
2144
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002145 CHECK_FOR_ERROR
2146 }
2147 | TARGET TargetDefinition {
2148 CHECK_FOR_ERROR
2149 }
2150 | DEPLIBS '=' LibrariesDefinition {
2151 CHECK_FOR_ERROR
2152 }
2153 ;
2154
2155
2156AsmBlock : STRINGCONSTANT {
2157 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2158 if (AsmSoFar.empty())
2159 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2160 else
2161 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2162 delete $1;
2163 CHECK_FOR_ERROR
2164};
2165
2166TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2167 CurModule.CurrentModule->setTargetTriple(*$3);
2168 delete $3;
2169 }
2170 | DATALAYOUT '=' STRINGCONSTANT {
2171 CurModule.CurrentModule->setDataLayout(*$3);
2172 delete $3;
2173 };
2174
2175LibrariesDefinition : '[' LibList ']';
2176
2177LibList : LibList ',' STRINGCONSTANT {
2178 CurModule.CurrentModule->addLibrary(*$3);
2179 delete $3;
2180 CHECK_FOR_ERROR
2181 }
2182 | STRINGCONSTANT {
2183 CurModule.CurrentModule->addLibrary(*$1);
2184 delete $1;
2185 CHECK_FOR_ERROR
2186 }
2187 | /* empty: end of list */ {
2188 CHECK_FOR_ERROR
2189 }
2190 ;
2191
2192//===----------------------------------------------------------------------===//
2193// Rules to match Function Headers
2194//===----------------------------------------------------------------------===//
2195
2196ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2197 if (!UpRefs.empty())
2198 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2199 if (*$3 == Type::VoidTy)
2200 GEN_ERROR("void typed arguments are invalid");
2201 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2202 $$ = $1;
2203 $1->push_back(E);
2204 CHECK_FOR_ERROR
2205 }
2206 | Types OptParamAttrs OptLocalName {
2207 if (!UpRefs.empty())
2208 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2209 if (*$1 == Type::VoidTy)
2210 GEN_ERROR("void typed arguments are invalid");
2211 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2212 $$ = new ArgListType;
2213 $$->push_back(E);
2214 CHECK_FOR_ERROR
2215 };
2216
2217ArgList : ArgListH {
2218 $$ = $1;
2219 CHECK_FOR_ERROR
2220 }
2221 | ArgListH ',' DOTDOTDOT {
2222 $$ = $1;
2223 struct ArgListEntry E;
2224 E.Ty = new PATypeHolder(Type::VoidTy);
2225 E.Name = 0;
2226 E.Attrs = ParamAttr::None;
2227 $$->push_back(E);
2228 CHECK_FOR_ERROR
2229 }
2230 | DOTDOTDOT {
2231 $$ = new ArgListType;
2232 struct ArgListEntry E;
2233 E.Ty = new PATypeHolder(Type::VoidTy);
2234 E.Name = 0;
2235 E.Attrs = ParamAttr::None;
2236 $$->push_back(E);
2237 CHECK_FOR_ERROR
2238 }
2239 | /* empty */ {
2240 $$ = 0;
2241 CHECK_FOR_ERROR
2242 };
2243
2244FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002245 OptFuncAttrs OptSection OptAlign OptGC {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002246 std::string FunctionName(*$3);
2247 delete $3; // Free strdup'd memory!
2248
2249 // Check the function result for abstractness if this is a define. We should
2250 // have no abstract types at this point
2251 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2252 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2253
2254 std::vector<const Type*> ParamTypeList;
2255 ParamAttrsVector Attrs;
2256 if ($7 != ParamAttr::None) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002257 ParamAttrsWithIndex PAWI;
2258 PAWI.index = 0;
2259 PAWI.attrs = $7;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 Attrs.push_back(PAWI);
2261 }
2262 if ($5) { // If there are arguments...
2263 unsigned index = 1;
2264 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2265 const Type* Ty = I->Ty->get();
2266 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2267 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2268 ParamTypeList.push_back(Ty);
2269 if (Ty != Type::VoidTy)
2270 if (I->Attrs != ParamAttr::None) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002271 ParamAttrsWithIndex PAWI;
2272 PAWI.index = index;
2273 PAWI.attrs = I->Attrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 Attrs.push_back(PAWI);
2275 }
2276 }
2277 }
2278
2279 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2280 if (isVarArg) ParamTypeList.pop_back();
2281
Duncan Sands637ec552007-11-28 17:07:01 +00002282 const ParamAttrsList *PAL = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283 if (!Attrs.empty())
2284 PAL = ParamAttrsList::get(Attrs);
2285
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002286 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambfb623c62007-12-17 01:17:35 +00002287 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288 delete $2;
2289
2290 ValID ID;
2291 if (!FunctionName.empty()) {
2292 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2293 } else {
2294 ID = ValID::createGlobalID(CurModule.Values.size());
2295 }
2296
2297 Function *Fn = 0;
2298 // See if this function was forward referenced. If so, recycle the object.
2299 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2300 // Move the function to the end of the list, from whereever it was
2301 // previously inserted.
2302 Fn = cast<Function>(FWRef);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002303 assert(!Fn->getParamAttrs() && "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002304 CurModule.CurrentModule->getFunctionList().remove(Fn);
2305 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2306 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2307 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002308 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309 // The existing function doesn't have the same type. This is an overload
2310 // error.
2311 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002312 } else if (Fn->getParamAttrs() != PAL) {
2313 // The existing function doesn't have the same parameter attributes.
2314 // This is an overload error.
2315 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2317 // Neither the existing or the current function is a declaration and they
2318 // have the same name and same type. Clearly this is a redefinition.
2319 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002320 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321 // Make sure to strip off any argument names so we can't get conflicts.
2322 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2323 AI != AE; ++AI)
2324 AI->setName("");
2325 }
2326 } else { // Not already defined?
2327 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2328 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002329 InsertValue(Fn, CurModule.Values);
2330 }
2331
2332 CurFun.FunctionStart(Fn);
2333
2334 if (CurFun.isDeclare) {
2335 // If we have declaration, always overwrite linkage. This will allow us to
2336 // correctly handle cases, when pointer to function is passed as argument to
2337 // another function.
2338 Fn->setLinkage(CurFun.Linkage);
2339 Fn->setVisibility(CurFun.Visibility);
2340 }
2341 Fn->setCallingConv($1);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002342 Fn->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002343 Fn->setAlignment($9);
2344 if ($8) {
2345 Fn->setSection(*$8);
2346 delete $8;
2347 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002348 if ($10) {
2349 Fn->setCollector($10->c_str());
2350 delete $10;
2351 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002352
2353 // Add all of the arguments we parsed to the function...
2354 if ($5) { // Is null if empty...
2355 if (isVarArg) { // Nuke the last entry
2356 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2357 "Not a varargs marker!");
2358 delete $5->back().Ty;
2359 $5->pop_back(); // Delete the last entry
2360 }
2361 Function::arg_iterator ArgIt = Fn->arg_begin();
2362 Function::arg_iterator ArgEnd = Fn->arg_end();
2363 unsigned Idx = 1;
2364 for (ArgListType::iterator I = $5->begin();
2365 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2366 delete I->Ty; // Delete the typeholder...
2367 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2368 CHECK_FOR_ERROR
2369 InsertValue(ArgIt);
2370 Idx++;
2371 }
2372
2373 delete $5; // We're now done with the argument list
2374 }
2375 CHECK_FOR_ERROR
2376};
2377
2378BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2379
2380FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2381 $$ = CurFun.CurrentFunction;
2382
2383 // Make sure that we keep track of the linkage type even if there was a
2384 // previous "declare".
2385 $$->setLinkage($1);
2386 $$->setVisibility($2);
2387};
2388
2389END : ENDTOK | '}'; // Allow end of '}' to end a function
2390
2391Function : BasicBlockList END {
2392 $$ = $1;
2393 CHECK_FOR_ERROR
2394};
2395
2396FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2397 CurFun.CurrentFunction->setLinkage($1);
2398 CurFun.CurrentFunction->setVisibility($2);
2399 $$ = CurFun.CurrentFunction;
2400 CurFun.FunctionDone();
2401 CHECK_FOR_ERROR
2402 };
2403
2404//===----------------------------------------------------------------------===//
2405// Rules to match Basic Blocks
2406//===----------------------------------------------------------------------===//
2407
2408OptSideEffect : /* empty */ {
2409 $$ = false;
2410 CHECK_FOR_ERROR
2411 }
2412 | SIDEEFFECT {
2413 $$ = true;
2414 CHECK_FOR_ERROR
2415 };
2416
2417ConstValueRef : ESINT64VAL { // A reference to a direct constant
2418 $$ = ValID::create($1);
2419 CHECK_FOR_ERROR
2420 }
2421 | EUINT64VAL {
2422 $$ = ValID::create($1);
2423 CHECK_FOR_ERROR
2424 }
2425 | FPVAL { // Perhaps it's an FP constant?
2426 $$ = ValID::create($1);
2427 CHECK_FOR_ERROR
2428 }
2429 | TRUETOK {
2430 $$ = ValID::create(ConstantInt::getTrue());
2431 CHECK_FOR_ERROR
2432 }
2433 | FALSETOK {
2434 $$ = ValID::create(ConstantInt::getFalse());
2435 CHECK_FOR_ERROR
2436 }
2437 | NULL_TOK {
2438 $$ = ValID::createNull();
2439 CHECK_FOR_ERROR
2440 }
2441 | UNDEF {
2442 $$ = ValID::createUndef();
2443 CHECK_FOR_ERROR
2444 }
2445 | ZEROINITIALIZER { // A vector zero constant.
2446 $$ = ValID::createZeroInit();
2447 CHECK_FOR_ERROR
2448 }
2449 | '<' ConstVector '>' { // Nonempty unsized packed vector
2450 const Type *ETy = (*$2)[0]->getType();
2451 int NumElements = $2->size();
2452
2453 VectorType* pt = VectorType::get(ETy, NumElements);
2454 PATypeHolder* PTy = new PATypeHolder(
2455 HandleUpRefs(
2456 VectorType::get(
2457 ETy,
2458 NumElements)
2459 )
2460 );
2461
2462 // Verify all elements are correct type!
2463 for (unsigned i = 0; i < $2->size(); i++) {
2464 if (ETy != (*$2)[i]->getType())
2465 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2466 ETy->getDescription() +"' as required!\nIt is of type '" +
2467 (*$2)[i]->getType()->getDescription() + "'.");
2468 }
2469
2470 $$ = ValID::create(ConstantVector::get(pt, *$2));
2471 delete PTy; delete $2;
2472 CHECK_FOR_ERROR
2473 }
2474 | ConstExpr {
2475 $$ = ValID::create($1);
2476 CHECK_FOR_ERROR
2477 }
2478 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2479 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2480 delete $3;
2481 delete $5;
2482 CHECK_FOR_ERROR
2483 };
2484
2485// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2486// another value.
2487//
2488SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2489 $$ = ValID::createLocalID($1);
2490 CHECK_FOR_ERROR
2491 }
2492 | GLOBALVAL_ID {
2493 $$ = ValID::createGlobalID($1);
2494 CHECK_FOR_ERROR
2495 }
2496 | LocalName { // Is it a named reference...?
2497 $$ = ValID::createLocalName(*$1);
2498 delete $1;
2499 CHECK_FOR_ERROR
2500 }
2501 | GlobalName { // Is it a named reference...?
2502 $$ = ValID::createGlobalName(*$1);
2503 delete $1;
2504 CHECK_FOR_ERROR
2505 };
2506
2507// ValueRef - A reference to a definition... either constant or symbolic
2508ValueRef : SymbolicValueRef | ConstValueRef;
2509
2510
2511// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2512// type immediately preceeds the value reference, and allows complex constant
2513// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2514ResolvedVal : Types ValueRef {
2515 if (!UpRefs.empty())
2516 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2517 $$ = getVal(*$1, $2);
2518 delete $1;
2519 CHECK_FOR_ERROR
2520 }
2521 ;
2522
2523BasicBlockList : BasicBlockList BasicBlock {
2524 $$ = $1;
2525 CHECK_FOR_ERROR
2526 }
2527 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2528 $$ = $1;
2529 CHECK_FOR_ERROR
2530 };
2531
2532
2533// Basic blocks are terminated by branching instructions:
2534// br, br/cc, switch, ret
2535//
2536BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2537 setValueName($3, $2);
2538 CHECK_FOR_ERROR
2539 InsertValue($3);
2540 $1->getInstList().push_back($3);
2541 $$ = $1;
2542 CHECK_FOR_ERROR
2543 };
2544
2545InstructionList : InstructionList Inst {
2546 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2547 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2548 if (CI2->getParent() == 0)
2549 $1->getInstList().push_back(CI2);
2550 $1->getInstList().push_back($2);
2551 $$ = $1;
2552 CHECK_FOR_ERROR
2553 }
2554 | /* empty */ { // Empty space between instruction lists
2555 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2556 CHECK_FOR_ERROR
2557 }
2558 | LABELSTR { // Labelled (named) basic block
2559 $$ = defineBBVal(ValID::createLocalName(*$1));
2560 delete $1;
2561 CHECK_FOR_ERROR
2562
2563 };
2564
2565BBTerminatorInst : RET ResolvedVal { // Return with a result...
2566 $$ = new ReturnInst($2);
2567 CHECK_FOR_ERROR
2568 }
2569 | RET VOID { // Return with no result...
2570 $$ = new ReturnInst();
2571 CHECK_FOR_ERROR
2572 }
2573 | BR LABEL ValueRef { // Unconditional Branch...
2574 BasicBlock* tmpBB = getBBVal($3);
2575 CHECK_FOR_ERROR
2576 $$ = new BranchInst(tmpBB);
2577 } // Conditional Branch...
2578 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2579 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2580 BasicBlock* tmpBBA = getBBVal($6);
2581 CHECK_FOR_ERROR
2582 BasicBlock* tmpBBB = getBBVal($9);
2583 CHECK_FOR_ERROR
2584 Value* tmpVal = getVal(Type::Int1Ty, $3);
2585 CHECK_FOR_ERROR
2586 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2587 }
2588 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2589 Value* tmpVal = getVal($2, $3);
2590 CHECK_FOR_ERROR
2591 BasicBlock* tmpBB = getBBVal($6);
2592 CHECK_FOR_ERROR
2593 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2594 $$ = S;
2595
2596 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2597 E = $8->end();
2598 for (; I != E; ++I) {
2599 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2600 S->addCase(CI, I->second);
2601 else
2602 GEN_ERROR("Switch case is constant, but not a simple integer");
2603 }
2604 delete $8;
2605 CHECK_FOR_ERROR
2606 }
2607 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2608 Value* tmpVal = getVal($2, $3);
2609 CHECK_FOR_ERROR
2610 BasicBlock* tmpBB = getBBVal($6);
2611 CHECK_FOR_ERROR
2612 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2613 $$ = S;
2614 CHECK_FOR_ERROR
2615 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002616 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002617 TO LABEL ValueRef UNWIND LABEL ValueRef {
2618
2619 // Handle the short syntax
2620 const PointerType *PFTy = 0;
2621 const FunctionType *Ty = 0;
2622 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2623 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2624 // Pull out the types of all of the arguments...
2625 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002626 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002627 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002628 const Type *Ty = I->Val->getType();
2629 if (Ty == Type::VoidTy)
2630 GEN_ERROR("Short call syntax cannot be used with varargs");
2631 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002632 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002633 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00002634 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002635 }
2636
2637 delete $3;
2638
2639 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2640 CHECK_FOR_ERROR
2641 BasicBlock *Normal = getBBVal($11);
2642 CHECK_FOR_ERROR
2643 BasicBlock *Except = getBBVal($14);
2644 CHECK_FOR_ERROR
2645
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002646 ParamAttrsVector Attrs;
2647 if ($8 != ParamAttr::None) {
2648 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2649 Attrs.push_back(PAWI);
2650 }
2651
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002652 // Check the arguments
2653 ValueList Args;
2654 if ($6->empty()) { // Has no arguments?
2655 // Make sure no arguments is a good thing!
2656 if (Ty->getNumParams() != 0)
2657 GEN_ERROR("No arguments passed to a function that "
2658 "expects arguments");
2659 } else { // Has arguments?
2660 // Loop through FunctionType's arguments and ensure they are specified
2661 // correctly!
2662 FunctionType::param_iterator I = Ty->param_begin();
2663 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002664 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002665 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002666
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002667 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002668 if (ArgI->Val->getType() != *I)
2669 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2670 (*I)->getDescription() + "'");
2671 Args.push_back(ArgI->Val);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002672 if (ArgI->Attrs != ParamAttr::None) {
2673 ParamAttrsWithIndex PAWI;
2674 PAWI.index = index;
2675 PAWI.attrs = ArgI->Attrs;
2676 Attrs.push_back(PAWI);
2677 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 }
2679
2680 if (Ty->isVarArg()) {
2681 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00002682 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002683 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner59363a32008-02-19 04:36:25 +00002684 if (ArgI->Attrs != ParamAttr::None) {
2685 ParamAttrsWithIndex PAWI;
2686 PAWI.index = index;
2687 PAWI.attrs = ArgI->Attrs;
2688 Attrs.push_back(PAWI);
2689 }
2690 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002691 } else if (I != E || ArgI != ArgE)
2692 GEN_ERROR("Invalid number of parameters detected");
2693 }
2694
Duncan Sands637ec552007-11-28 17:07:01 +00002695 const ParamAttrsList *PAL = 0;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002696 if (!Attrs.empty())
2697 PAL = ParamAttrsList::get(Attrs);
2698
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002699 // Create the InvokeInst
Chris Lattnerd140ada2007-08-29 16:15:23 +00002700 InvokeInst *II = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002701 II->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002702 II->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 $$ = II;
2704 delete $6;
2705 CHECK_FOR_ERROR
2706 }
2707 | UNWIND {
2708 $$ = new UnwindInst();
2709 CHECK_FOR_ERROR
2710 }
2711 | UNREACHABLE {
2712 $$ = new UnreachableInst();
2713 CHECK_FOR_ERROR
2714 };
2715
2716
2717
2718JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2719 $$ = $1;
2720 Constant *V = cast<Constant>(getExistingVal($2, $3));
2721 CHECK_FOR_ERROR
2722 if (V == 0)
2723 GEN_ERROR("May only switch on a constant pool value");
2724
2725 BasicBlock* tmpBB = getBBVal($6);
2726 CHECK_FOR_ERROR
2727 $$->push_back(std::make_pair(V, tmpBB));
2728 }
2729 | IntType ConstValueRef ',' LABEL ValueRef {
2730 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2731 Constant *V = cast<Constant>(getExistingVal($1, $2));
2732 CHECK_FOR_ERROR
2733
2734 if (V == 0)
2735 GEN_ERROR("May only switch on a constant pool value");
2736
2737 BasicBlock* tmpBB = getBBVal($5);
2738 CHECK_FOR_ERROR
2739 $$->push_back(std::make_pair(V, tmpBB));
2740 };
2741
2742Inst : OptLocalAssign InstVal {
2743 // Is this definition named?? if so, assign the name...
2744 setValueName($2, $1);
2745 CHECK_FOR_ERROR
2746 InsertValue($2);
2747 $$ = $2;
2748 CHECK_FOR_ERROR
2749 };
2750
2751
2752PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2753 if (!UpRefs.empty())
2754 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2755 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2756 Value* tmpVal = getVal(*$1, $3);
2757 CHECK_FOR_ERROR
2758 BasicBlock* tmpBB = getBBVal($5);
2759 CHECK_FOR_ERROR
2760 $$->push_back(std::make_pair(tmpVal, tmpBB));
2761 delete $1;
2762 }
2763 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2764 $$ = $1;
2765 Value* tmpVal = getVal($1->front().first->getType(), $4);
2766 CHECK_FOR_ERROR
2767 BasicBlock* tmpBB = getBBVal($6);
2768 CHECK_FOR_ERROR
2769 $1->push_back(std::make_pair(tmpVal, tmpBB));
2770 };
2771
2772
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002773ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2774 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 if (!UpRefs.empty())
2776 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2777 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00002778 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002779 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 $$->push_back(E);
2781 delete $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002782 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002783 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002784 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2785 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002786 // Labels are only valid in ASMs
2787 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002788 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002789 $$->push_back(E);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002790 CHECK_FOR_ERROR
Dale Johannesencfb19e62007-11-05 21:20:28 +00002791 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002792 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2793 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002794 if (!UpRefs.empty())
2795 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2796 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002797 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 $$->push_back(E);
2799 delete $3;
2800 CHECK_FOR_ERROR
2801 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002802 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2803 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002804 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002805 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002806 $$->push_back(E);
2807 CHECK_FOR_ERROR
2808 }
2809 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002810
2811IndexList // Used for gep instructions and constant expressions
2812 : /*empty*/ { $$ = new std::vector<Value*>(); }
2813 | IndexList ',' ResolvedVal {
2814 $$ = $1;
2815 $$->push_back($3);
2816 CHECK_FOR_ERROR
2817 }
2818 ;
2819
2820OptTailCall : TAIL CALL {
2821 $$ = true;
2822 CHECK_FOR_ERROR
2823 }
2824 | CALL {
2825 $$ = false;
2826 CHECK_FOR_ERROR
2827 };
2828
2829InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2830 if (!UpRefs.empty())
2831 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2832 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2833 !isa<VectorType>((*$2).get()))
2834 GEN_ERROR(
2835 "Arithmetic operator requires integer, FP, or packed operands");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002836 Value* val1 = getVal(*$2, $3);
2837 CHECK_FOR_ERROR
2838 Value* val2 = getVal(*$2, $5);
2839 CHECK_FOR_ERROR
2840 $$ = BinaryOperator::create($1, val1, val2);
2841 if ($$ == 0)
2842 GEN_ERROR("binary operator returned null");
2843 delete $2;
2844 }
2845 | LogicalOps Types ValueRef ',' ValueRef {
2846 if (!UpRefs.empty())
2847 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2848 if (!(*$2)->isInteger()) {
2849 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2850 !cast<VectorType>($2->get())->getElementType()->isInteger())
2851 GEN_ERROR("Logical operator requires integral operands");
2852 }
2853 Value* tmpVal1 = getVal(*$2, $3);
2854 CHECK_FOR_ERROR
2855 Value* tmpVal2 = getVal(*$2, $5);
2856 CHECK_FOR_ERROR
2857 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2858 if ($$ == 0)
2859 GEN_ERROR("binary operator returned null");
2860 delete $2;
2861 }
2862 | ICMP IPredicates Types ValueRef ',' ValueRef {
2863 if (!UpRefs.empty())
2864 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2865 if (isa<VectorType>((*$3).get()))
2866 GEN_ERROR("Vector types not supported by icmp instruction");
2867 Value* tmpVal1 = getVal(*$3, $4);
2868 CHECK_FOR_ERROR
2869 Value* tmpVal2 = getVal(*$3, $6);
2870 CHECK_FOR_ERROR
2871 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2872 if ($$ == 0)
2873 GEN_ERROR("icmp operator returned null");
2874 delete $3;
2875 }
2876 | FCMP FPredicates Types ValueRef ',' ValueRef {
2877 if (!UpRefs.empty())
2878 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2879 if (isa<VectorType>((*$3).get()))
2880 GEN_ERROR("Vector types not supported by fcmp instruction");
2881 Value* tmpVal1 = getVal(*$3, $4);
2882 CHECK_FOR_ERROR
2883 Value* tmpVal2 = getVal(*$3, $6);
2884 CHECK_FOR_ERROR
2885 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2886 if ($$ == 0)
2887 GEN_ERROR("fcmp operator returned null");
2888 delete $3;
2889 }
2890 | CastOps ResolvedVal TO Types {
2891 if (!UpRefs.empty())
2892 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2893 Value* Val = $2;
2894 const Type* DestTy = $4->get();
2895 if (!CastInst::castIsValid($1, Val, DestTy))
2896 GEN_ERROR("invalid cast opcode for cast from '" +
2897 Val->getType()->getDescription() + "' to '" +
2898 DestTy->getDescription() + "'");
2899 $$ = CastInst::create($1, Val, DestTy);
2900 delete $4;
2901 }
2902 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2903 if ($2->getType() != Type::Int1Ty)
2904 GEN_ERROR("select condition must be boolean");
2905 if ($4->getType() != $6->getType())
2906 GEN_ERROR("select value types should match");
2907 $$ = new SelectInst($2, $4, $6);
2908 CHECK_FOR_ERROR
2909 }
2910 | VAARG ResolvedVal ',' Types {
2911 if (!UpRefs.empty())
2912 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2913 $$ = new VAArgInst($2, *$4);
2914 delete $4;
2915 CHECK_FOR_ERROR
2916 }
2917 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2918 if (!ExtractElementInst::isValidOperands($2, $4))
2919 GEN_ERROR("Invalid extractelement operands");
2920 $$ = new ExtractElementInst($2, $4);
2921 CHECK_FOR_ERROR
2922 }
2923 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2924 if (!InsertElementInst::isValidOperands($2, $4, $6))
2925 GEN_ERROR("Invalid insertelement operands");
2926 $$ = new InsertElementInst($2, $4, $6);
2927 CHECK_FOR_ERROR
2928 }
2929 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2930 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2931 GEN_ERROR("Invalid shufflevector operands");
2932 $$ = new ShuffleVectorInst($2, $4, $6);
2933 CHECK_FOR_ERROR
2934 }
2935 | PHI_TOK PHIList {
2936 const Type *Ty = $2->front().first->getType();
2937 if (!Ty->isFirstClassType())
2938 GEN_ERROR("PHI node operands must be of first class type");
2939 $$ = new PHINode(Ty);
2940 ((PHINode*)$$)->reserveOperandSpace($2->size());
2941 while ($2->begin() != $2->end()) {
2942 if ($2->front().first->getType() != Ty)
2943 GEN_ERROR("All elements of a PHI node must be of the same type");
2944 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2945 $2->pop_front();
2946 }
2947 delete $2; // Free the list...
2948 CHECK_FOR_ERROR
2949 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002950 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951 OptFuncAttrs {
2952
2953 // Handle the short syntax
2954 const PointerType *PFTy = 0;
2955 const FunctionType *Ty = 0;
2956 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2957 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2958 // Pull out the types of all of the arguments...
2959 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002960 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002961 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002962 const Type *Ty = I->Val->getType();
2963 if (Ty == Type::VoidTy)
2964 GEN_ERROR("Short call syntax cannot be used with varargs");
2965 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002967 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00002968 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 }
2970
2971 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2972 CHECK_FOR_ERROR
2973
2974 // Check for call to invalid intrinsic to avoid crashing later.
2975 if (Function *theF = dyn_cast<Function>(V)) {
2976 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2977 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2978 !theF->getIntrinsicID(true))
2979 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2980 theF->getName() + "'");
2981 }
2982
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002983 // Set up the ParamAttrs for the function
2984 ParamAttrsVector Attrs;
2985 if ($8 != ParamAttr::None) {
2986 ParamAttrsWithIndex PAWI;
2987 PAWI.index = 0;
2988 PAWI.attrs = $8;
2989 Attrs.push_back(PAWI);
2990 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002991 // Check the arguments
2992 ValueList Args;
2993 if ($6->empty()) { // Has no arguments?
2994 // Make sure no arguments is a good thing!
2995 if (Ty->getNumParams() != 0)
2996 GEN_ERROR("No arguments passed to a function that "
2997 "expects arguments");
2998 } else { // Has arguments?
2999 // Loop through FunctionType's arguments and ensure they are specified
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003000 // correctly. Also, gather any parameter attributes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001 FunctionType::param_iterator I = Ty->param_begin();
3002 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00003003 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003004 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003006 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007 if (ArgI->Val->getType() != *I)
3008 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3009 (*I)->getDescription() + "'");
3010 Args.push_back(ArgI->Val);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003011 if (ArgI->Attrs != ParamAttr::None) {
3012 ParamAttrsWithIndex PAWI;
3013 PAWI.index = index;
3014 PAWI.attrs = ArgI->Attrs;
3015 Attrs.push_back(PAWI);
3016 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 }
3018 if (Ty->isVarArg()) {
3019 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00003020 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner59363a32008-02-19 04:36:25 +00003022 if (ArgI->Attrs != ParamAttr::None) {
3023 ParamAttrsWithIndex PAWI;
3024 PAWI.index = index;
3025 PAWI.attrs = ArgI->Attrs;
3026 Attrs.push_back(PAWI);
3027 }
3028 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 } else if (I != E || ArgI != ArgE)
3030 GEN_ERROR("Invalid number of parameters detected");
3031 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003032
3033 // Finish off the ParamAttrs and check them
Duncan Sands637ec552007-11-28 17:07:01 +00003034 const ParamAttrsList *PAL = 0;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003035 if (!Attrs.empty())
3036 PAL = ParamAttrsList::get(Attrs);
3037
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038 // Create the call node
David Greene9145dd22007-08-01 03:59:32 +00003039 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003040 CI->setTailCall($1);
3041 CI->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003042 CI->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043 $$ = CI;
3044 delete $6;
3045 delete $3;
3046 CHECK_FOR_ERROR
3047 }
3048 | MemoryInst {
3049 $$ = $1;
3050 CHECK_FOR_ERROR
3051 };
3052
3053OptVolatile : VOLATILE {
3054 $$ = true;
3055 CHECK_FOR_ERROR
3056 }
3057 | /* empty */ {
3058 $$ = false;
3059 CHECK_FOR_ERROR
3060 };
3061
3062
3063
3064MemoryInst : MALLOC Types OptCAlign {
3065 if (!UpRefs.empty())
3066 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3067 $$ = new MallocInst(*$2, 0, $3);
3068 delete $2;
3069 CHECK_FOR_ERROR
3070 }
3071 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3072 if (!UpRefs.empty())
3073 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3074 Value* tmpVal = getVal($4, $5);
3075 CHECK_FOR_ERROR
3076 $$ = new MallocInst(*$2, tmpVal, $6);
3077 delete $2;
3078 }
3079 | ALLOCA Types OptCAlign {
3080 if (!UpRefs.empty())
3081 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3082 $$ = new AllocaInst(*$2, 0, $3);
3083 delete $2;
3084 CHECK_FOR_ERROR
3085 }
3086 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3087 if (!UpRefs.empty())
3088 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3089 Value* tmpVal = getVal($4, $5);
3090 CHECK_FOR_ERROR
3091 $$ = new AllocaInst(*$2, tmpVal, $6);
3092 delete $2;
3093 }
3094 | FREE ResolvedVal {
3095 if (!isa<PointerType>($2->getType()))
3096 GEN_ERROR("Trying to free nonpointer type " +
3097 $2->getType()->getDescription() + "");
3098 $$ = new FreeInst($2);
3099 CHECK_FOR_ERROR
3100 }
3101
3102 | OptVolatile LOAD Types ValueRef OptCAlign {
3103 if (!UpRefs.empty())
3104 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3105 if (!isa<PointerType>($3->get()))
3106 GEN_ERROR("Can't load from nonpointer type: " +
3107 (*$3)->getDescription());
3108 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3109 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3110 (*$3)->getDescription());
3111 Value* tmpVal = getVal(*$3, $4);
3112 CHECK_FOR_ERROR
3113 $$ = new LoadInst(tmpVal, "", $1, $5);
3114 delete $3;
3115 }
3116 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3117 if (!UpRefs.empty())
3118 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3119 const PointerType *PT = dyn_cast<PointerType>($5->get());
3120 if (!PT)
3121 GEN_ERROR("Can't store to a nonpointer type: " +
3122 (*$5)->getDescription());
3123 const Type *ElTy = PT->getElementType();
3124 if (ElTy != $3->getType())
3125 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3126 "' into space of type '" + ElTy->getDescription() + "'");
3127
3128 Value* tmpVal = getVal(*$5, $6);
3129 CHECK_FOR_ERROR
3130 $$ = new StoreInst($3, tmpVal, $1, $7);
3131 delete $5;
3132 }
3133 | GETELEMENTPTR Types ValueRef IndexList {
3134 if (!UpRefs.empty())
3135 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3136 if (!isa<PointerType>($2->get()))
3137 GEN_ERROR("getelementptr insn requires pointer operand");
3138
David Greene48556392007-09-04 18:46:50 +00003139 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140 GEN_ERROR("Invalid getelementptr indices for type '" +
3141 (*$2)->getDescription()+ "'");
3142 Value* tmpVal = getVal(*$2, $3);
3143 CHECK_FOR_ERROR
David Greene48556392007-09-04 18:46:50 +00003144 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145 delete $2;
3146 delete $4;
3147 };
3148
3149
3150%%
3151
3152// common code from the two 'RunVMAsmParser' functions
3153static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 // Check to make sure the parser succeeded
3156 if (yyparse()) {
3157 if (ParserResult)
3158 delete ParserResult;
3159 return 0;
3160 }
3161
3162 // Emit an error if there are any unresolved types left.
3163 if (!CurModule.LateResolveTypes.empty()) {
3164 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3165 if (DID.Type == ValID::LocalName) {
3166 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3167 } else {
3168 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3169 }
3170 if (ParserResult)
3171 delete ParserResult;
3172 return 0;
3173 }
3174
3175 // Emit an error if there are any unresolved values left.
3176 if (!CurModule.LateResolveValues.empty()) {
3177 Value *V = CurModule.LateResolveValues.back();
3178 std::map<Value*, std::pair<ValID, int> >::iterator I =
3179 CurModule.PlaceHolderInfo.find(V);
3180
3181 if (I != CurModule.PlaceHolderInfo.end()) {
3182 ValID &DID = I->second.first;
3183 if (DID.Type == ValID::LocalName) {
3184 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3185 } else {
3186 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3187 }
3188 if (ParserResult)
3189 delete ParserResult;
3190 return 0;
3191 }
3192 }
3193
3194 // Check to make sure that parsing produced a result
3195 if (!ParserResult)
3196 return 0;
3197
3198 // Reset ParserResult variable while saving its value for the result.
3199 Module *Result = ParserResult;
3200 ParserResult = 0;
3201
3202 return Result;
3203}
3204
3205void llvm::GenerateError(const std::string &message, int LineNo) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003206 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 // TODO: column number in exception
3208 if (TheParseError)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003209 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003210 TriggerError = 1;
3211}
3212
3213int yyerror(const char *ErrorMsg) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003214 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003216 if (yychar != YYEMPTY && yychar != 0) {
3217 errMsg += " while reading token: '";
3218 errMsg += std::string(LLLgetTokenStart(),
3219 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3220 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 GenerateError(errMsg);
3222 return 0;
3223}