blob: d63e3c9ae8e0bbb1027c257d13f7ec4097c1ae69 [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 Carrutha228e392007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/Streams.h"
28#include <algorithm>
29#include <list>
30#include <map>
31#include <utility>
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 Carrutha228e392007-08-04 01:51:18 +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 Lattner97d8e5f2008-02-19 04:36:07 +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 Lattner97d8e5f2008-02-19 04:36:07 +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 Lattner97d8e5f2008-02-19 04:36:07 +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 Lattner97d8e5f2008-02-19 04:36:07 +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 Lattner97d8e5f2008-02-19 04:36:07 +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 }
Chris Lattner5e0610f2008-04-20 00:41:09 +0000411 // Lexer has no type info, so builds all float and double FP constants
Dale Johannesen1616e902007-09-11 18:32:33 +0000412 // 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);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000416 return ConstantFP::get(*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))
Gabor Greifd6da1d02008-04-06 20:25:17 +0000496 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 else
Christopher Lamb44d62f62007-12-11 08:59:05 +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,
Chris Lattner17e73c22007-11-18 08:46:26 +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.
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000520static BasicBlock *defineBBVal(const ValID &ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 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 }
Nick Lewycky31f5f242008-03-02 02:48:09 +0000550 } else {
551 // We haven't seen this BB before and its first mention is a definition.
552 // Just create it and return it.
553 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
Gabor Greifd6da1d02008-04-06 20:25:17 +0000554 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Nick Lewycky31f5f242008-03-02 02:48:09 +0000555 if (ID.Type == ValID::LocalID) {
556 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
557 InsertValue(BB);
558 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 }
560
Nick Lewycky31f5f242008-03-02 02:48:09 +0000561 ID.destroy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562 return BB;
563}
564
565/// getBBVal - get an existing BB value or create a forward reference for it.
566///
567static BasicBlock *getBBVal(const ValID &ID) {
568 assert(inFunctionScope() && "Can't get basic block at global scope!");
569
570 BasicBlock *BB = 0;
571
572 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
573 if (BBI != CurFun.BBForwardRefs.end()) {
574 BB = BBI->second;
575 } if (ID.Type == ValID::LocalName) {
576 std::string Name = ID.getName();
577 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000578 if (N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 if (N->getType()->getTypeID() == Type::LabelTyID)
580 BB = cast<BasicBlock>(N);
581 else
582 GenerateError("Reference to label '" + Name + "' is actually of type '"+
583 N->getType()->getDescription() + "'");
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000584 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 } else if (ID.Type == ValID::LocalID) {
586 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
587 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
588 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
589 else
590 GenerateError("Reference to label '%" + utostr(ID.Num) +
591 "' is actually of type '"+
592 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
593 }
594 } else {
595 GenerateError("Illegal label reference " + ID.getName());
596 return 0;
597 }
598
599 // If its already been defined, return it now.
600 if (BB) {
601 ID.destroy(); // Free strdup'd memory.
602 return BB;
603 }
604
605 // Otherwise, this block has not been seen before, create it.
606 std::string Name;
607 if (ID.Type == ValID::LocalName)
608 Name = ID.getName();
Gabor Greifd6da1d02008-04-06 20:25:17 +0000609 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610
611 // Insert it in the forward refs map.
612 CurFun.BBForwardRefs[ID] = BB;
613
614 return BB;
615}
616
617
618//===----------------------------------------------------------------------===//
619// Code to handle forward references in instructions
620//===----------------------------------------------------------------------===//
621//
622// This code handles the late binding needed with statements that reference
623// values not defined yet... for example, a forward branch, or the PHI node for
624// a loop body.
625//
626// This keeps a table (CurFun.LateResolveValues) of all such forward references
627// and back patchs after we are done.
628//
629
630// ResolveDefinitions - If we could not resolve some defs at parsing
631// time (forward branches, phi functions for loops, etc...) resolve the
632// defs now...
633//
634static void
635ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
636 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
637 while (!LateResolvers.empty()) {
638 Value *V = LateResolvers.back();
639 LateResolvers.pop_back();
640
641 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
642 CurModule.PlaceHolderInfo.find(V);
643 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
644
645 ValID &DID = PHI->second.first;
646
647 Value *TheRealValue = getExistingVal(V->getType(), DID);
648 if (TriggerError)
649 return;
650 if (TheRealValue) {
651 V->replaceAllUsesWith(TheRealValue);
652 delete V;
653 CurModule.PlaceHolderInfo.erase(PHI);
654 } else if (FutureLateResolvers) {
655 // Functions have their unresolved items forwarded to the module late
656 // resolver table
657 InsertValue(V, *FutureLateResolvers);
658 } else {
659 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
660 GenerateError("Reference to an invalid definition: '" +DID.getName()+
661 "' of type '" + V->getType()->getDescription() + "'",
662 PHI->second.second);
663 return;
664 } else {
665 GenerateError("Reference to an invalid definition: #" +
666 itostr(DID.Num) + " of type '" +
667 V->getType()->getDescription() + "'",
668 PHI->second.second);
669 return;
670 }
671 }
672 }
673 LateResolvers.clear();
674}
675
676// ResolveTypeTo - A brand new type was just declared. This means that (if
677// name is not null) things referencing Name can be resolved. Otherwise, things
678// refering to the number can be resolved. Do this now.
679//
680static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
681 ValID D;
682 if (Name)
683 D = ValID::createLocalName(*Name);
684 else
685 D = ValID::createLocalID(CurModule.Types.size());
686
687 std::map<ValID, PATypeHolder>::iterator I =
688 CurModule.LateResolveTypes.find(D);
689 if (I != CurModule.LateResolveTypes.end()) {
690 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
691 CurModule.LateResolveTypes.erase(I);
692 }
693}
694
695// setValueName - Set the specified value to the name given. The name may be
696// null potentially, in which case this is a noop. The string passed in is
697// assumed to be a malloc'd string buffer, and is free'd by this function.
698//
699static void setValueName(Value *V, std::string *NameStr) {
700 if (!NameStr) return;
701 std::string Name(*NameStr); // Copy string
702 delete NameStr; // Free old string
703
704 if (V->getType() == Type::VoidTy) {
705 GenerateError("Can't assign name '" + Name+"' to value with void type");
706 return;
707 }
708
709 assert(inFunctionScope() && "Must be in function scope!");
710 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
711 if (ST.lookup(Name)) {
712 GenerateError("Redefinition of value '" + Name + "' of type '" +
713 V->getType()->getDescription() + "'");
714 return;
715 }
716
717 // Set the name.
718 V->setName(Name);
719}
720
721/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
722/// this is a declaration, otherwise it is a definition.
723static GlobalVariable *
724ParseGlobalVariable(std::string *NameStr,
725 GlobalValue::LinkageTypes Linkage,
726 GlobalValue::VisibilityTypes Visibility,
727 bool isConstantGlobal, const Type *Ty,
Christopher Lamb44d62f62007-12-11 08:59:05 +0000728 Constant *Initializer, bool IsThreadLocal,
729 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 if (isa<FunctionType>(Ty)) {
731 GenerateError("Cannot declare global vars of function type");
732 return 0;
733 }
734
Christopher Lamb44d62f62007-12-11 08:59:05 +0000735 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736
737 std::string Name;
738 if (NameStr) {
739 Name = *NameStr; // Copy string
740 delete NameStr; // Free old string
741 }
742
743 // See if this global value was forward referenced. If so, recycle the
744 // object.
745 ValID ID;
746 if (!Name.empty()) {
747 ID = ValID::createGlobalName(Name);
748 } else {
749 ID = ValID::createGlobalID(CurModule.Values.size());
750 }
751
752 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
753 // Move the global to the end of the list, from whereever it was
754 // previously inserted.
755 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
756 CurModule.CurrentModule->getGlobalList().remove(GV);
757 CurModule.CurrentModule->getGlobalList().push_back(GV);
758 GV->setInitializer(Initializer);
759 GV->setLinkage(Linkage);
760 GV->setVisibility(Visibility);
761 GV->setConstant(isConstantGlobal);
762 GV->setThreadLocal(IsThreadLocal);
763 InsertValue(GV, CurModule.Values);
764 return GV;
765 }
766
767 // If this global has a name
768 if (!Name.empty()) {
769 // if the global we're parsing has an initializer (is a definition) and
770 // has external linkage.
771 if (Initializer && Linkage != GlobalValue::InternalLinkage)
772 // If there is already a global with external linkage with this name
773 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
774 // If we allow this GVar to get created, it will be renamed in the
775 // symbol table because it conflicts with an existing GVar. We can't
776 // allow redefinition of GVars whose linking indicates that their name
777 // must stay the same. Issue the error.
778 GenerateError("Redefinition of global variable named '" + Name +
779 "' of type '" + Ty->getDescription() + "'");
780 return 0;
781 }
782 }
783
784 // Otherwise there is no existing GV to use, create one now.
785 GlobalVariable *GV =
786 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb44d62f62007-12-11 08:59:05 +0000787 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 GV->setVisibility(Visibility);
789 InsertValue(GV, CurModule.Values);
790 return GV;
791}
792
793// setTypeName - Set the specified type to the name given. The name may be
794// null potentially, in which case this is a noop. The string passed in is
795// assumed to be a malloc'd string buffer, and is freed by this function.
796//
797// This function returns true if the type has already been defined, but is
798// allowed to be redefined in the specified context. If the name is a new name
799// for the type plane, it is inserted and false is returned.
800static bool setTypeName(const Type *T, std::string *NameStr) {
801 assert(!inFunctionScope() && "Can't give types function-local names!");
802 if (NameStr == 0) return false;
803
804 std::string Name(*NameStr); // Copy string
805 delete NameStr; // Free old string
806
807 // We don't allow assigning names to void type
808 if (T == Type::VoidTy) {
809 GenerateError("Can't assign name '" + Name + "' to the void type");
810 return false;
811 }
812
813 // Set the type name, checking for conflicts as we do so.
814 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
815
816 if (AlreadyExists) { // Inserting a name that is already defined???
817 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
818 assert(Existing && "Conflict but no matching type?!");
819
820 // There is only one case where this is allowed: when we are refining an
821 // opaque type. In this case, Existing will be an opaque type.
822 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
823 // We ARE replacing an opaque type!
824 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
825 return true;
826 }
827
828 // Otherwise, this is an attempt to redefine a type. That's okay if
829 // the redefinition is identical to the original. This will be so if
830 // Existing and T point to the same Type object. In this one case we
831 // allow the equivalent redefinition.
832 if (Existing == T) return true; // Yes, it's equal.
833
834 // Any other kind of (non-equivalent) redefinition is an error.
835 GenerateError("Redefinition of type named '" + Name + "' of type '" +
836 T->getDescription() + "'");
837 }
838
839 return false;
840}
841
842//===----------------------------------------------------------------------===//
843// Code for handling upreferences in type names...
844//
845
846// TypeContains - Returns true if Ty directly contains E in it.
847//
848static bool TypeContains(const Type *Ty, const Type *E) {
849 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
850 E) != Ty->subtype_end();
851}
852
853namespace {
854 struct UpRefRecord {
855 // NestingLevel - The number of nesting levels that need to be popped before
856 // this type is resolved.
857 unsigned NestingLevel;
858
859 // LastContainedTy - This is the type at the current binding level for the
860 // type. Every time we reduce the nesting level, this gets updated.
861 const Type *LastContainedTy;
862
863 // UpRefTy - This is the actual opaque type that the upreference is
864 // represented with.
865 OpaqueType *UpRefTy;
866
867 UpRefRecord(unsigned NL, OpaqueType *URTy)
868 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
869 };
870}
871
872// UpRefs - A list of the outstanding upreferences that need to be resolved.
873static std::vector<UpRefRecord> UpRefs;
874
875/// HandleUpRefs - Every time we finish a new layer of types, this function is
876/// called. It loops through the UpRefs vector, which is a list of the
877/// currently active types. For each type, if the up reference is contained in
878/// the newly completed type, we decrement the level count. When the level
879/// count reaches zero, the upreferenced type is the type that is passed in:
880/// thus we can complete the cycle.
881///
882static PATypeHolder HandleUpRefs(const Type *ty) {
883 // If Ty isn't abstract, or if there are no up-references in it, then there is
884 // nothing to resolve here.
885 if (!ty->isAbstract() || UpRefs.empty()) return ty;
886
887 PATypeHolder Ty(ty);
888 UR_OUT("Type '" << Ty->getDescription() <<
889 "' newly formed. Resolving upreferences.\n" <<
890 UpRefs.size() << " upreferences active!\n");
891
892 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
893 // to zero), we resolve them all together before we resolve them to Ty. At
894 // the end of the loop, if there is anything to resolve to Ty, it will be in
895 // this variable.
896 OpaqueType *TypeToResolve = 0;
897
898 for (unsigned i = 0; i != UpRefs.size(); ++i) {
899 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
900 << UpRefs[i].second->getDescription() << ") = "
901 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
902 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
903 // Decrement level of upreference
904 unsigned Level = --UpRefs[i].NestingLevel;
905 UpRefs[i].LastContainedTy = Ty;
906 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
907 if (Level == 0) { // Upreference should be resolved!
908 if (!TypeToResolve) {
909 TypeToResolve = UpRefs[i].UpRefTy;
910 } else {
911 UR_OUT(" * Resolving upreference for "
912 << UpRefs[i].second->getDescription() << "\n";
913 std::string OldName = UpRefs[i].UpRefTy->getDescription());
914 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
915 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
916 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
917 }
918 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
919 --i; // Do not skip the next element...
920 }
921 }
922 }
923
924 if (TypeToResolve) {
925 UR_OUT(" * Resolving upreference for "
926 << UpRefs[i].second->getDescription() << "\n";
927 std::string OldName = TypeToResolve->getDescription());
928 TypeToResolve->refineAbstractTypeTo(Ty);
929 }
930
931 return Ty;
932}
933
934//===----------------------------------------------------------------------===//
935// RunVMAsmParser - Define an interface to this parser
936//===----------------------------------------------------------------------===//
937//
938static Module* RunParser(Module * M);
939
Chris Lattner17e73c22007-11-18 08:46:26 +0000940Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
941 InitLLLexer(MB);
942 Module *M = RunParser(new Module(LLLgetFilename()));
943 FreeLexer();
944 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945}
946
947%}
948
949%union {
950 llvm::Module *ModuleVal;
951 llvm::Function *FunctionVal;
952 llvm::BasicBlock *BasicBlockVal;
953 llvm::TerminatorInst *TermInstVal;
954 llvm::Instruction *InstVal;
955 llvm::Constant *ConstVal;
956
957 const llvm::Type *PrimType;
958 std::list<llvm::PATypeHolder> *TypeList;
959 llvm::PATypeHolder *TypeVal;
960 llvm::Value *ValueVal;
961 std::vector<llvm::Value*> *ValueList;
962 llvm::ArgListType *ArgList;
963 llvm::TypeWithAttrs TypeWithAttrs;
964 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000965 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
967 // Represent the RHS of PHI node
968 std::list<std::pair<llvm::Value*,
969 llvm::BasicBlock*> > *PHIList;
970 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
971 std::vector<llvm::Constant*> *ConstVector;
972
973 llvm::GlobalValue::LinkageTypes Linkage;
974 llvm::GlobalValue::VisibilityTypes Visibility;
Dale Johannesenf4666f52008-02-19 21:38:47 +0000975 llvm::ParameterAttributes ParamAttrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 llvm::APInt *APIntVal;
977 int64_t SInt64Val;
978 uint64_t UInt64Val;
979 int SIntVal;
980 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000981 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 bool BoolVal;
983
984 std::string *StrVal; // This memory must be deleted
985 llvm::ValID ValIDVal;
986
987 llvm::Instruction::BinaryOps BinaryOpVal;
988 llvm::Instruction::TermOps TermOpVal;
989 llvm::Instruction::MemoryOps MemOpVal;
990 llvm::Instruction::CastOps CastOpVal;
991 llvm::Instruction::OtherOps OtherOpVal;
992 llvm::ICmpInst::Predicate IPredicate;
993 llvm::FCmpInst::Predicate FPredicate;
994}
995
996%type <ModuleVal> Module
997%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
998%type <BasicBlockVal> BasicBlock InstructionList
999%type <TermInstVal> BBTerminatorInst
1000%type <InstVal> Inst InstVal MemoryInst
1001%type <ConstVal> ConstVal ConstExpr AliaseeRef
1002%type <ConstVector> ConstVector
1003%type <ArgList> ArgList ArgListH
1004%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001005%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006%type <ValueList> IndexList // For GEP indices
1007%type <TypeList> TypeListI
1008%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1009%type <TypeWithAttrs> ArgType
1010%type <JumpTable> JumpTable
1011%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1012%type <BoolVal> ThreadLocal // 'thread_local' or not
1013%type <BoolVal> OptVolatile // 'volatile' or not
1014%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1015%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1016%type <Linkage> GVInternalLinkage GVExternalLinkage
1017%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1018%type <Linkage> AliasLinkage
1019%type <Visibility> GVVisibilityStyle
1020
1021// ValueRef - Unresolved reference to a definition or BB
1022%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1023%type <ValueVal> ResolvedVal // <type> <valref> pair
Devang Patel036f0382008-02-20 22:39:45 +00001024%type <ValueList> ReturnedVal
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025// Tokens and types for handling constant integer values
1026//
1027// ESINT64VAL - A negative number within long long range
1028%token <SInt64Val> ESINT64VAL
1029
1030// EUINT64VAL - A positive number within uns. long long range
1031%token <UInt64Val> EUINT64VAL
1032
1033// ESAPINTVAL - A negative number with arbitrary precision
1034%token <APIntVal> ESAPINTVAL
1035
1036// EUAPINTVAL - A positive number with arbitrary precision
1037%token <APIntVal> EUAPINTVAL
1038
1039%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1040%token <FPVal> FPVAL // Float or Double constant
1041
1042// Built in types...
1043%type <TypeVal> Types ResultTypes
1044%type <PrimType> IntType FPType PrimType // Classifications
1045%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001046%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047%token TYPE
1048
1049
1050%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1051%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1052%type <StrVal> LocalName OptLocalName OptLocalAssign
1053%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001054%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055
Christopher Lamb20a39e92007-12-12 08:44:39 +00001056%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057
1058%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1059%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1060%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
Dale Johannesen58562d32008-05-14 20:14:09 +00001061%token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
Christopher Lamb44d62f62007-12-11 08:59:05 +00001062%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1064%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00001065%token DATALAYOUT
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066%type <UIntVal> OptCallingConv
1067%type <ParamAttrs> OptParamAttrs ParamAttr
1068%type <ParamAttrs> OptFuncAttrs FuncAttr
1069
1070// Basic Block Terminating Operators
1071%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1072
1073// Binary Operators
1074%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1075%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1076%token <BinaryOpVal> SHL LSHR ASHR
1077
Nate Begeman646fa482008-05-12 19:01:56 +00001078%token <OtherOpVal> ICMP FCMP VICMP VFCMP
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079%type <IPredicate> IPredicates
1080%type <FPredicate> FPredicates
1081%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1082%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1083
1084// Memory Instructions
1085%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1086
1087// Cast Operators
1088%type <CastOpVal> CastOps
1089%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1090%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1091
1092// Other Operators
1093%token <OtherOpVal> PHI_TOK SELECT VAARG
1094%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Devang Patele5c806a2008-02-19 22:26:37 +00001095%token <OtherOpVal> GETRESULT
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096
1097// Function Attributes
Duncan Sands38947cd2007-07-27 12:58:54 +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 Lamb20a39e92007-12-12 08:44:39 +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; }
Dale Johannesen58562d32008-05-14 20:14:09 +00001177 | COMMON { $$ = GlobalValue::CommonLinkage; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178 ;
1179
1180GVExternalLinkage
1181 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1182 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1183 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1184 ;
1185
1186GVVisibilityStyle
1187 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1188 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1189 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1190 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1191 ;
1192
1193FunctionDeclareLinkage
1194 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1195 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1196 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1197 ;
1198
1199FunctionDefineLinkage
1200 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1201 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1202 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1203 | WEAK { $$ = GlobalValue::WeakLinkage; }
1204 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1205 ;
1206
1207AliasLinkage
1208 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1209 | WEAK { $$ = GlobalValue::WeakLinkage; }
1210 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1211 ;
1212
1213OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1214 CCC_TOK { $$ = CallingConv::C; } |
1215 FASTCC_TOK { $$ = CallingConv::Fast; } |
1216 COLDCC_TOK { $$ = CallingConv::Cold; } |
1217 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1218 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1219 CC_TOK EUINT64VAL {
1220 if ((unsigned)$2 != $2)
1221 GEN_ERROR("Calling conv too large");
1222 $$ = $2;
1223 CHECK_FOR_ERROR
1224 };
1225
Reid Spencerf234bed2007-07-19 23:13:04 +00001226ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001227 | ZEXT { $$ = ParamAttr::ZExt; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001228 | SIGNEXT { $$ = ParamAttr::SExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001229 | SEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 | INREG { $$ = ParamAttr::InReg; }
1231 | SRET { $$ = ParamAttr::StructRet; }
1232 | NOALIAS { $$ = ParamAttr::NoAlias; }
Duncan Sands38947cd2007-07-27 12:58:54 +00001233 | BYVAL { $$ = ParamAttr::ByVal; }
1234 | NEST { $$ = ParamAttr::Nest; }
Dale Johannesen9b398782008-02-22 17:49:45 +00001235 | ALIGN EUINT64VAL { $$ =
1236 ParamAttr::constructAlignmentFromInt($2); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 ;
1238
1239OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1240 | OptParamAttrs ParamAttr {
1241 $$ = $1 | $2;
1242 }
1243 ;
1244
1245FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1246 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001247 | ZEROEXT { $$ = ParamAttr::ZExt; }
1248 | SIGNEXT { $$ = ParamAttr::SExt; }
Duncan Sands13e13f82007-11-22 20:23:04 +00001249 | READNONE { $$ = ParamAttr::ReadNone; }
1250 | READONLY { $$ = ParamAttr::ReadOnly; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 ;
1252
1253OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1254 | OptFuncAttrs FuncAttr {
1255 $$ = $1 | $2;
1256 }
1257 ;
1258
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001259OptGC : /* empty */ { $$ = 0; }
1260 | GC STRINGCONSTANT {
1261 $$ = $2;
1262 }
1263 ;
1264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1266// a comma before it.
1267OptAlign : /*empty*/ { $$ = 0; } |
1268 ALIGN EUINT64VAL {
1269 $$ = $2;
1270 if ($$ != 0 && !isPowerOf2_32($$))
1271 GEN_ERROR("Alignment must be a power of two");
1272 CHECK_FOR_ERROR
1273};
1274OptCAlign : /*empty*/ { $$ = 0; } |
1275 ',' ALIGN EUINT64VAL {
1276 $$ = $3;
1277 if ($$ != 0 && !isPowerOf2_32($$))
1278 GEN_ERROR("Alignment must be a power of two");
1279 CHECK_FOR_ERROR
1280};
1281
1282
Christopher Lamb44d62f62007-12-11 08:59:05 +00001283
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284SectionString : SECTION STRINGCONSTANT {
1285 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1286 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1287 GEN_ERROR("Invalid character in section name");
1288 $$ = $2;
1289 CHECK_FOR_ERROR
1290};
1291
1292OptSection : /*empty*/ { $$ = 0; } |
1293 SectionString { $$ = $1; };
1294
1295// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1296// is set to be the global we are processing.
1297//
1298GlobalVarAttributes : /* empty */ {} |
1299 ',' GlobalVarAttribute GlobalVarAttributes {};
1300GlobalVarAttribute : SectionString {
1301 CurGV->setSection(*$1);
1302 delete $1;
1303 CHECK_FOR_ERROR
1304 }
1305 | ALIGN EUINT64VAL {
1306 if ($2 != 0 && !isPowerOf2_32($2))
1307 GEN_ERROR("Alignment must be a power of two");
1308 CurGV->setAlignment($2);
1309 CHECK_FOR_ERROR
1310 };
1311
1312//===----------------------------------------------------------------------===//
1313// Types includes all predefined types... except void, because it can only be
1314// used in specific contexts (function returning void for example).
1315
1316// Derived types are added later...
1317//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001318PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319
1320Types
1321 : OPAQUE {
1322 $$ = new PATypeHolder(OpaqueType::get());
1323 CHECK_FOR_ERROR
1324 }
1325 | PrimType {
1326 $$ = new PATypeHolder($1);
1327 CHECK_FOR_ERROR
1328 }
Christopher Lamb20a39e92007-12-12 08:44:39 +00001329 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 if (*$1 == Type::LabelTy)
1331 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb20a39e92007-12-12 08:44:39 +00001332 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb44d62f62007-12-11 08:59:05 +00001333 delete $1;
1334 CHECK_FOR_ERROR
1335 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 | SymbolicValueRef { // Named types are also simple types...
1337 const Type* tmp = getTypeVal($1);
1338 CHECK_FOR_ERROR
1339 $$ = new PATypeHolder(tmp);
1340 }
1341 | '\\' EUINT64VAL { // Type UpReference
1342 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1343 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1344 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1345 $$ = new PATypeHolder(OT);
1346 UR_OUT("New Upreference!\n");
1347 CHECK_FOR_ERROR
1348 }
1349 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001350 // Allow but ignore attributes on function types; this permits auto-upgrade.
1351 // FIXME: remove in LLVM 3.0.
Chris Lattner62de9332008-04-23 05:36:58 +00001352 const Type *RetTy = *$1;
1353 if (!FunctionType::isValidReturnType(RetTy))
1354 GEN_ERROR("Invalid result type for LLVM function");
1355
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001358 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 const Type *Ty = I->Ty->get();
1360 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001362
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1364 if (isVarArg) Params.pop_back();
1365
Anton Korobeynikov9ab58082007-12-03 21:00:45 +00001366 for (unsigned i = 0; i != Params.size(); ++i)
1367 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1368 GEN_ERROR("Function arguments must be value types!");
1369
1370 CHECK_FOR_ERROR
1371
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001372 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 delete $3; // Delete the argument list
1374 delete $1; // Delete the return type handle
1375 $$ = new PATypeHolder(HandleUpRefs(FT));
1376 CHECK_FOR_ERROR
1377 }
1378 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001379 // Allow but ignore attributes on function types; this permits auto-upgrade.
1380 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001383 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384 const Type* Ty = I->Ty->get();
1385 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001387
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1389 if (isVarArg) Params.pop_back();
1390
Anton Korobeynikov9ab58082007-12-03 21:00:45 +00001391 for (unsigned i = 0; i != Params.size(); ++i)
1392 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1393 GEN_ERROR("Function arguments must be value types!");
1394
1395 CHECK_FOR_ERROR
1396
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001397 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398 delete $3; // Delete the argument list
1399 $$ = new PATypeHolder(HandleUpRefs(FT));
1400 CHECK_FOR_ERROR
1401 }
1402
1403 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1404 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1405 delete $4;
1406 CHECK_FOR_ERROR
1407 }
1408 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1409 const llvm::Type* ElemTy = $4->get();
1410 if ((unsigned)$2 != $2)
1411 GEN_ERROR("Unsigned result not equal to signed result");
1412 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1413 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1415 delete $4;
1416 CHECK_FOR_ERROR
1417 }
1418 | '{' TypeListI '}' { // Structure type?
1419 std::vector<const Type*> Elements;
1420 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1421 E = $2->end(); I != E; ++I)
1422 Elements.push_back(*I);
1423
1424 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1425 delete $2;
1426 CHECK_FOR_ERROR
1427 }
1428 | '{' '}' { // Empty structure type?
1429 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1430 CHECK_FOR_ERROR
1431 }
1432 | '<' '{' TypeListI '}' '>' {
1433 std::vector<const Type*> Elements;
1434 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1435 E = $3->end(); I != E; ++I)
1436 Elements.push_back(*I);
1437
1438 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1439 delete $3;
1440 CHECK_FOR_ERROR
1441 }
1442 | '<' '{' '}' '>' { // Empty structure type?
1443 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1444 CHECK_FOR_ERROR
1445 }
1446 ;
1447
1448ArgType
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001449 : Types OptParamAttrs {
1450 // Allow but ignore attributes on function types; this permits auto-upgrade.
1451 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 $$.Ty = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001453 $$.Attrs = ParamAttr::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 }
1455 ;
1456
1457ResultTypes
1458 : Types {
1459 if (!UpRefs.empty())
1460 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Devang Patel62417142008-02-23 01:17:17 +00001461 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462 GEN_ERROR("LLVM functions cannot return aggregate types");
1463 $$ = $1;
1464 }
1465 | VOID {
1466 $$ = new PATypeHolder(Type::VoidTy);
1467 }
1468 ;
1469
1470ArgTypeList : ArgType {
1471 $$ = new TypeWithAttrsList();
1472 $$->push_back($1);
1473 CHECK_FOR_ERROR
1474 }
1475 | ArgTypeList ',' ArgType {
1476 ($$=$1)->push_back($3);
1477 CHECK_FOR_ERROR
1478 }
1479 ;
1480
1481ArgTypeListI
1482 : ArgTypeList
1483 | ArgTypeList ',' DOTDOTDOT {
1484 $$=$1;
1485 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1486 TWA.Ty = new PATypeHolder(Type::VoidTy);
1487 $$->push_back(TWA);
1488 CHECK_FOR_ERROR
1489 }
1490 | DOTDOTDOT {
1491 $$ = new TypeWithAttrsList;
1492 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1493 TWA.Ty = new PATypeHolder(Type::VoidTy);
1494 $$->push_back(TWA);
1495 CHECK_FOR_ERROR
1496 }
1497 | /*empty*/ {
1498 $$ = new TypeWithAttrsList();
1499 CHECK_FOR_ERROR
1500 };
1501
1502// TypeList - Used for struct declarations and as a basis for function type
1503// declaration type lists
1504//
1505TypeListI : Types {
1506 $$ = new std::list<PATypeHolder>();
1507 $$->push_back(*$1);
1508 delete $1;
1509 CHECK_FOR_ERROR
1510 }
1511 | TypeListI ',' Types {
1512 ($$=$1)->push_back(*$3);
1513 delete $3;
1514 CHECK_FOR_ERROR
1515 };
1516
1517// ConstVal - The various declarations that go into the constant pool. This
1518// production is used ONLY to represent constants that show up AFTER a 'const',
1519// 'constant' or 'global' token at global scope. Constants that can be inlined
1520// into other expressions (such as integers and constexprs) are handled by the
1521// ResolvedVal, ValueRef and ConstValueRef productions.
1522//
1523ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1524 if (!UpRefs.empty())
1525 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1526 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1527 if (ATy == 0)
1528 GEN_ERROR("Cannot make array constant with type: '" +
1529 (*$1)->getDescription() + "'");
1530 const Type *ETy = ATy->getElementType();
1531 int NumElements = ATy->getNumElements();
1532
1533 // Verify that we have the correct size...
1534 if (NumElements != -1 && NumElements != (int)$3->size())
1535 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1536 utostr($3->size()) + " arguments, but has size of " +
1537 itostr(NumElements) + "");
1538
1539 // Verify all elements are correct type!
1540 for (unsigned i = 0; i < $3->size(); i++) {
1541 if (ETy != (*$3)[i]->getType())
1542 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1543 ETy->getDescription() +"' as required!\nIt is of type '"+
1544 (*$3)[i]->getType()->getDescription() + "'.");
1545 }
1546
1547 $$ = ConstantArray::get(ATy, *$3);
1548 delete $1; delete $3;
1549 CHECK_FOR_ERROR
1550 }
1551 | Types '[' ']' {
1552 if (!UpRefs.empty())
1553 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1554 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1555 if (ATy == 0)
1556 GEN_ERROR("Cannot make array constant with type: '" +
1557 (*$1)->getDescription() + "'");
1558
1559 int NumElements = ATy->getNumElements();
1560 if (NumElements != -1 && NumElements != 0)
1561 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1562 " arguments, but has size of " + itostr(NumElements) +"");
1563 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1564 delete $1;
1565 CHECK_FOR_ERROR
1566 }
1567 | Types 'c' STRINGCONSTANT {
1568 if (!UpRefs.empty())
1569 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1570 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1571 if (ATy == 0)
1572 GEN_ERROR("Cannot make array constant with type: '" +
1573 (*$1)->getDescription() + "'");
1574
1575 int NumElements = ATy->getNumElements();
1576 const Type *ETy = ATy->getElementType();
1577 if (NumElements != -1 && NumElements != int($3->length()))
1578 GEN_ERROR("Can't build string constant of size " +
1579 itostr((int)($3->length())) +
1580 " when array has size " + itostr(NumElements) + "");
1581 std::vector<Constant*> Vals;
1582 if (ETy == Type::Int8Ty) {
1583 for (unsigned i = 0; i < $3->length(); ++i)
1584 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1585 } else {
1586 delete $3;
1587 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1588 }
1589 delete $3;
1590 $$ = ConstantArray::get(ATy, Vals);
1591 delete $1;
1592 CHECK_FOR_ERROR
1593 }
1594 | Types '<' ConstVector '>' { // Nonempty unsized arr
1595 if (!UpRefs.empty())
1596 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1597 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1598 if (PTy == 0)
1599 GEN_ERROR("Cannot make packed constant with type: '" +
1600 (*$1)->getDescription() + "'");
1601 const Type *ETy = PTy->getElementType();
1602 int NumElements = PTy->getNumElements();
1603
1604 // Verify that we have the correct size...
1605 if (NumElements != -1 && NumElements != (int)$3->size())
1606 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1607 utostr($3->size()) + " arguments, but has size of " +
1608 itostr(NumElements) + "");
1609
1610 // Verify all elements are correct type!
1611 for (unsigned i = 0; i < $3->size(); i++) {
1612 if (ETy != (*$3)[i]->getType())
1613 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1614 ETy->getDescription() +"' as required!\nIt is of type '"+
1615 (*$3)[i]->getType()->getDescription() + "'.");
1616 }
1617
1618 $$ = ConstantVector::get(PTy, *$3);
1619 delete $1; delete $3;
1620 CHECK_FOR_ERROR
1621 }
1622 | Types '{' ConstVector '}' {
1623 const StructType *STy = dyn_cast<StructType>($1->get());
1624 if (STy == 0)
1625 GEN_ERROR("Cannot make struct constant with type: '" +
1626 (*$1)->getDescription() + "'");
1627
1628 if ($3->size() != STy->getNumContainedTypes())
1629 GEN_ERROR("Illegal number of initializers for structure type");
1630
1631 // Check to ensure that constants are compatible with the type initializer!
1632 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1633 if ((*$3)[i]->getType() != STy->getElementType(i))
1634 GEN_ERROR("Expected type '" +
1635 STy->getElementType(i)->getDescription() +
1636 "' for element #" + utostr(i) +
1637 " of structure initializer");
1638
1639 // Check to ensure that Type is not packed
1640 if (STy->isPacked())
1641 GEN_ERROR("Unpacked Initializer to vector type '" +
1642 STy->getDescription() + "'");
1643
1644 $$ = ConstantStruct::get(STy, *$3);
1645 delete $1; delete $3;
1646 CHECK_FOR_ERROR
1647 }
1648 | Types '{' '}' {
1649 if (!UpRefs.empty())
1650 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1651 const StructType *STy = dyn_cast<StructType>($1->get());
1652 if (STy == 0)
1653 GEN_ERROR("Cannot make struct constant with type: '" +
1654 (*$1)->getDescription() + "'");
1655
1656 if (STy->getNumContainedTypes() != 0)
1657 GEN_ERROR("Illegal number of initializers for structure type");
1658
1659 // Check to ensure that Type is not packed
1660 if (STy->isPacked())
1661 GEN_ERROR("Unpacked Initializer to vector type '" +
1662 STy->getDescription() + "'");
1663
1664 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1665 delete $1;
1666 CHECK_FOR_ERROR
1667 }
1668 | Types '<' '{' ConstVector '}' '>' {
1669 const StructType *STy = dyn_cast<StructType>($1->get());
1670 if (STy == 0)
1671 GEN_ERROR("Cannot make struct constant with type: '" +
1672 (*$1)->getDescription() + "'");
1673
1674 if ($4->size() != STy->getNumContainedTypes())
1675 GEN_ERROR("Illegal number of initializers for structure type");
1676
1677 // Check to ensure that constants are compatible with the type initializer!
1678 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1679 if ((*$4)[i]->getType() != STy->getElementType(i))
1680 GEN_ERROR("Expected type '" +
1681 STy->getElementType(i)->getDescription() +
1682 "' for element #" + utostr(i) +
1683 " of structure initializer");
1684
1685 // Check to ensure that Type is packed
1686 if (!STy->isPacked())
1687 GEN_ERROR("Vector initializer to non-vector type '" +
1688 STy->getDescription() + "'");
1689
1690 $$ = ConstantStruct::get(STy, *$4);
1691 delete $1; delete $4;
1692 CHECK_FOR_ERROR
1693 }
1694 | Types '<' '{' '}' '>' {
1695 if (!UpRefs.empty())
1696 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1697 const StructType *STy = dyn_cast<StructType>($1->get());
1698 if (STy == 0)
1699 GEN_ERROR("Cannot make struct constant with type: '" +
1700 (*$1)->getDescription() + "'");
1701
1702 if (STy->getNumContainedTypes() != 0)
1703 GEN_ERROR("Illegal number of initializers for structure type");
1704
1705 // Check to ensure that Type is packed
1706 if (!STy->isPacked())
1707 GEN_ERROR("Vector initializer to non-vector type '" +
1708 STy->getDescription() + "'");
1709
1710 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1711 delete $1;
1712 CHECK_FOR_ERROR
1713 }
1714 | Types NULL_TOK {
1715 if (!UpRefs.empty())
1716 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1717 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1718 if (PTy == 0)
1719 GEN_ERROR("Cannot make null pointer constant with type: '" +
1720 (*$1)->getDescription() + "'");
1721
1722 $$ = ConstantPointerNull::get(PTy);
1723 delete $1;
1724 CHECK_FOR_ERROR
1725 }
1726 | Types UNDEF {
1727 if (!UpRefs.empty())
1728 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1729 $$ = UndefValue::get($1->get());
1730 delete $1;
1731 CHECK_FOR_ERROR
1732 }
1733 | Types SymbolicValueRef {
1734 if (!UpRefs.empty())
1735 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1736 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1737 if (Ty == 0)
Devang Patele5c806a2008-02-19 22:26:37 +00001738 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739
1740 // ConstExprs can exist in the body of a function, thus creating
1741 // GlobalValues whenever they refer to a variable. Because we are in
1742 // the context of a function, getExistingVal will search the functions
1743 // symbol table instead of the module symbol table for the global symbol,
1744 // which throws things all off. To get around this, we just tell
1745 // getExistingVal that we are at global scope here.
1746 //
1747 Function *SavedCurFn = CurFun.CurrentFunction;
1748 CurFun.CurrentFunction = 0;
1749
1750 Value *V = getExistingVal(Ty, $2);
1751 CHECK_FOR_ERROR
1752
1753 CurFun.CurrentFunction = SavedCurFn;
1754
1755 // If this is an initializer for a constant pointer, which is referencing a
1756 // (currently) undefined variable, create a stub now that shall be replaced
1757 // in the future with the right type of variable.
1758 //
1759 if (V == 0) {
1760 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1761 const PointerType *PT = cast<PointerType>(Ty);
1762
1763 // First check to see if the forward references value is already created!
1764 PerModuleInfo::GlobalRefsType::iterator I =
1765 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1766
1767 if (I != CurModule.GlobalRefs.end()) {
1768 V = I->second; // Placeholder already exists, use it...
1769 $2.destroy();
1770 } else {
1771 std::string Name;
1772 if ($2.Type == ValID::GlobalName)
1773 Name = $2.getName();
1774 else if ($2.Type != ValID::GlobalID)
1775 GEN_ERROR("Invalid reference to global");
1776
1777 // Create the forward referenced global.
1778 GlobalValue *GV;
1779 if (const FunctionType *FTy =
1780 dyn_cast<FunctionType>(PT->getElementType())) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00001781 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1782 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001783 } else {
1784 GV = new GlobalVariable(PT->getElementType(), false,
1785 GlobalValue::ExternalWeakLinkage, 0,
1786 Name, CurModule.CurrentModule);
1787 }
1788
1789 // Keep track of the fact that we have a forward ref to recycle it
1790 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1791 V = GV;
1792 }
1793 }
1794
1795 $$ = cast<GlobalValue>(V);
1796 delete $1; // Free the type handle
1797 CHECK_FOR_ERROR
1798 }
1799 | Types ConstExpr {
1800 if (!UpRefs.empty())
1801 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1802 if ($1->get() != $2->getType())
1803 GEN_ERROR("Mismatched types for constant expression: " +
1804 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1805 $$ = $2;
1806 delete $1;
1807 CHECK_FOR_ERROR
1808 }
1809 | Types ZEROINITIALIZER {
1810 if (!UpRefs.empty())
1811 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1812 const Type *Ty = $1->get();
1813 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1814 GEN_ERROR("Cannot create a null initialized value of this type");
1815 $$ = Constant::getNullValue(Ty);
1816 delete $1;
1817 CHECK_FOR_ERROR
1818 }
1819 | IntType ESINT64VAL { // integral constants
1820 if (!ConstantInt::isValueValidForType($1, $2))
1821 GEN_ERROR("Constant value doesn't fit in type");
1822 $$ = ConstantInt::get($1, $2, true);
1823 CHECK_FOR_ERROR
1824 }
1825 | IntType ESAPINTVAL { // arbitrary precision integer constants
1826 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1827 if ($2->getBitWidth() > BitWidth) {
1828 GEN_ERROR("Constant value does not fit in type");
1829 }
1830 $2->sextOrTrunc(BitWidth);
1831 $$ = ConstantInt::get(*$2);
1832 delete $2;
1833 CHECK_FOR_ERROR
1834 }
1835 | IntType EUINT64VAL { // integral constants
1836 if (!ConstantInt::isValueValidForType($1, $2))
1837 GEN_ERROR("Constant value doesn't fit in type");
1838 $$ = ConstantInt::get($1, $2, false);
1839 CHECK_FOR_ERROR
1840 }
1841 | IntType EUAPINTVAL { // arbitrary precision integer constants
1842 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1843 if ($2->getBitWidth() > BitWidth) {
1844 GEN_ERROR("Constant value does not fit in type");
1845 }
1846 $2->zextOrTrunc(BitWidth);
1847 $$ = ConstantInt::get(*$2);
1848 delete $2;
1849 CHECK_FOR_ERROR
1850 }
1851 | INTTYPE TRUETOK { // Boolean constants
1852 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1853 $$ = ConstantInt::getTrue();
1854 CHECK_FOR_ERROR
1855 }
1856 | INTTYPE FALSETOK { // Boolean constants
1857 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1858 $$ = ConstantInt::getFalse();
1859 CHECK_FOR_ERROR
1860 }
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00001861 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001862 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen1616e902007-09-11 18:32:33 +00001864 // Lexer has no type info, so builds all float and double FP constants
1865 // as double. Fix this here. Long double is done right.
1866 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001867 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner5e0610f2008-04-20 00:41:09 +00001868 $$ = ConstantFP::get(*$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001869 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870 CHECK_FOR_ERROR
1871 };
1872
1873
1874ConstExpr: CastOps '(' ConstVal TO Types ')' {
1875 if (!UpRefs.empty())
1876 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1877 Constant *Val = $3;
1878 const Type *DestTy = $5->get();
1879 if (!CastInst::castIsValid($1, $3, DestTy))
1880 GEN_ERROR("invalid cast opcode for cast from '" +
1881 Val->getType()->getDescription() + "' to '" +
1882 DestTy->getDescription() + "'");
1883 $$ = ConstantExpr::getCast($1, $3, DestTy);
1884 delete $5;
1885 }
1886 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1887 if (!isa<PointerType>($3->getType()))
1888 GEN_ERROR("GetElementPtr requires a pointer operand");
1889
1890 const Type *IdxTy =
David Greene393be882007-09-04 15:46:09 +00001891 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 true);
1893 if (!IdxTy)
1894 GEN_ERROR("Index list invalid for constant getelementptr");
1895
1896 SmallVector<Constant*, 8> IdxVec;
1897 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1898 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1899 IdxVec.push_back(C);
1900 else
1901 GEN_ERROR("Indices to constant getelementptr must be constants");
1902
1903 delete $4;
1904
1905 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1906 CHECK_FOR_ERROR
1907 }
1908 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1909 if ($3->getType() != Type::Int1Ty)
1910 GEN_ERROR("Select condition must be of boolean type");
1911 if ($5->getType() != $7->getType())
1912 GEN_ERROR("Select operand types must match");
1913 $$ = ConstantExpr::getSelect($3, $5, $7);
1914 CHECK_FOR_ERROR
1915 }
1916 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1917 if ($3->getType() != $5->getType())
1918 GEN_ERROR("Binary operator types must match");
1919 CHECK_FOR_ERROR;
1920 $$ = ConstantExpr::get($1, $3, $5);
1921 }
1922 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1923 if ($3->getType() != $5->getType())
1924 GEN_ERROR("Logical operator types must match");
1925 if (!$3->getType()->isInteger()) {
1926 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1927 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1928 GEN_ERROR("Logical operator requires integral operands");
1929 }
1930 $$ = ConstantExpr::get($1, $3, $5);
1931 CHECK_FOR_ERROR
1932 }
1933 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1934 if ($4->getType() != $6->getType())
1935 GEN_ERROR("icmp operand types must match");
1936 $$ = ConstantExpr::getICmp($2, $4, $6);
1937 }
1938 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1939 if ($4->getType() != $6->getType())
1940 GEN_ERROR("fcmp operand types must match");
1941 $$ = ConstantExpr::getFCmp($2, $4, $6);
1942 }
Nate Begeman646fa482008-05-12 19:01:56 +00001943 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1944 if ($4->getType() != $6->getType())
1945 GEN_ERROR("vicmp operand types must match");
1946 $$ = ConstantExpr::getVICmp($2, $4, $6);
1947 }
1948 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1949 if ($4->getType() != $6->getType())
1950 GEN_ERROR("vfcmp operand types must match");
1951 $$ = ConstantExpr::getVFCmp($2, $4, $6);
1952 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001953 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1954 if (!ExtractElementInst::isValidOperands($3, $5))
1955 GEN_ERROR("Invalid extractelement operands");
1956 $$ = ConstantExpr::getExtractElement($3, $5);
1957 CHECK_FOR_ERROR
1958 }
1959 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1960 if (!InsertElementInst::isValidOperands($3, $5, $7))
1961 GEN_ERROR("Invalid insertelement operands");
1962 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1963 CHECK_FOR_ERROR
1964 }
1965 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1966 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1967 GEN_ERROR("Invalid shufflevector operands");
1968 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1969 CHECK_FOR_ERROR
1970 };
1971
1972
1973// ConstVector - A list of comma separated constants.
1974ConstVector : ConstVector ',' ConstVal {
1975 ($$ = $1)->push_back($3);
1976 CHECK_FOR_ERROR
1977 }
1978 | ConstVal {
1979 $$ = new std::vector<Constant*>();
1980 $$->push_back($1);
1981 CHECK_FOR_ERROR
1982 };
1983
1984
1985// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1986GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1987
1988// ThreadLocal
1989ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1990
1991// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1992AliaseeRef : ResultTypes SymbolicValueRef {
1993 const Type* VTy = $1->get();
1994 Value *V = getVal(VTy, $2);
Chris Lattner0f800522007-08-06 21:00:37 +00001995 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1997 if (!Aliasee)
1998 GEN_ERROR("Aliases can be created only to global values");
1999
2000 $$ = Aliasee;
2001 CHECK_FOR_ERROR
2002 delete $1;
2003 }
2004 | BITCAST '(' AliaseeRef TO Types ')' {
2005 Constant *Val = $3;
2006 const Type *DestTy = $5->get();
2007 if (!CastInst::castIsValid($1, $3, DestTy))
2008 GEN_ERROR("invalid cast opcode for cast from '" +
2009 Val->getType()->getDescription() + "' to '" +
2010 DestTy->getDescription() + "'");
2011
2012 $$ = ConstantExpr::getCast($1, $3, DestTy);
2013 CHECK_FOR_ERROR
2014 delete $5;
2015 };
2016
2017//===----------------------------------------------------------------------===//
2018// Rules to match Modules
2019//===----------------------------------------------------------------------===//
2020
2021// Module rule: Capture the result of parsing the whole file into a result
2022// variable...
2023//
2024Module
2025 : DefinitionList {
2026 $$ = ParserResult = CurModule.CurrentModule;
2027 CurModule.ModuleDone();
2028 CHECK_FOR_ERROR;
2029 }
2030 | /*empty*/ {
2031 $$ = ParserResult = CurModule.CurrentModule;
2032 CurModule.ModuleDone();
2033 CHECK_FOR_ERROR;
2034 }
2035 ;
2036
2037DefinitionList
2038 : Definition
2039 | DefinitionList Definition
2040 ;
2041
2042Definition
2043 : DEFINE { CurFun.isDeclare = false; } Function {
2044 CurFun.FunctionDone();
2045 CHECK_FOR_ERROR
2046 }
2047 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2048 CHECK_FOR_ERROR
2049 }
2050 | MODULE ASM_TOK AsmBlock {
2051 CHECK_FOR_ERROR
2052 }
2053 | OptLocalAssign TYPE Types {
2054 if (!UpRefs.empty())
2055 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2056 // Eagerly resolve types. This is not an optimization, this is a
2057 // requirement that is due to the fact that we could have this:
2058 //
2059 // %list = type { %list * }
2060 // %list = type { %list * } ; repeated type decl
2061 //
2062 // If types are not resolved eagerly, then the two types will not be
2063 // determined to be the same type!
2064 //
2065 ResolveTypeTo($1, *$3);
2066
2067 if (!setTypeName(*$3, $1) && !$1) {
2068 CHECK_FOR_ERROR
2069 // If this is a named type that is not a redefinition, add it to the slot
2070 // table.
2071 CurModule.Types.push_back(*$3);
2072 }
2073
2074 delete $3;
2075 CHECK_FOR_ERROR
2076 }
2077 | OptLocalAssign TYPE VOID {
2078 ResolveTypeTo($1, $3);
2079
2080 if (!setTypeName($3, $1) && !$1) {
2081 CHECK_FOR_ERROR
2082 // If this is a named type that is not a redefinition, add it to the slot
2083 // table.
2084 CurModule.Types.push_back($3);
2085 }
2086 CHECK_FOR_ERROR
2087 }
Christopher Lamb20a39e92007-12-12 08:44:39 +00002088 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2089 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002090 /* "Externally Visible" Linkage */
2091 if ($5 == 0)
2092 GEN_ERROR("Global value initializer is not a constant");
2093 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb20a39e92007-12-12 08:44:39 +00002094 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb44d62f62007-12-11 08:59:05 +00002095 CHECK_FOR_ERROR
2096 } GlobalVarAttributes {
2097 CurGV = 0;
2098 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb20a39e92007-12-12 08:44:39 +00002100 ConstVal OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002101 if ($6 == 0)
2102 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb20a39e92007-12-12 08:44:39 +00002103 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 CHECK_FOR_ERROR
2105 } GlobalVarAttributes {
2106 CurGV = 0;
2107 }
2108 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb20a39e92007-12-12 08:44:39 +00002109 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002110 if (!UpRefs.empty())
2111 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb20a39e92007-12-12 08:44:39 +00002112 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002113 CHECK_FOR_ERROR
2114 delete $6;
2115 } GlobalVarAttributes {
2116 CurGV = 0;
2117 CHECK_FOR_ERROR
2118 }
2119 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2120 std::string Name;
2121 if ($1) {
2122 Name = *$1;
2123 delete $1;
2124 }
2125 if (Name.empty())
2126 GEN_ERROR("Alias name cannot be empty");
2127
2128 Constant* Aliasee = $5;
2129 if (Aliasee == 0)
2130 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2131
2132 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2133 CurModule.CurrentModule);
2134 GA->setVisibility($2);
2135 InsertValue(GA, CurModule.Values);
Chris Lattner9d99b312007-09-10 23:23:53 +00002136
2137
2138 // If there was a forward reference of this alias, resolve it now.
2139
2140 ValID ID;
2141 if (!Name.empty())
2142 ID = ValID::createGlobalName(Name);
2143 else
2144 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2145
2146 if (GlobalValue *FWGV =
2147 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2148 // Replace uses of the fwdref with the actual alias.
2149 FWGV->replaceAllUsesWith(GA);
2150 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2151 GV->eraseFromParent();
2152 else
2153 cast<Function>(FWGV)->eraseFromParent();
2154 }
2155 ID.destroy();
2156
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157 CHECK_FOR_ERROR
2158 }
2159 | TARGET TargetDefinition {
2160 CHECK_FOR_ERROR
2161 }
2162 | DEPLIBS '=' LibrariesDefinition {
2163 CHECK_FOR_ERROR
2164 }
2165 ;
2166
2167
2168AsmBlock : STRINGCONSTANT {
2169 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2170 if (AsmSoFar.empty())
2171 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2172 else
2173 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2174 delete $1;
2175 CHECK_FOR_ERROR
2176};
2177
2178TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2179 CurModule.CurrentModule->setTargetTriple(*$3);
2180 delete $3;
2181 }
2182 | DATALAYOUT '=' STRINGCONSTANT {
2183 CurModule.CurrentModule->setDataLayout(*$3);
2184 delete $3;
2185 };
2186
2187LibrariesDefinition : '[' LibList ']';
2188
2189LibList : LibList ',' STRINGCONSTANT {
2190 CurModule.CurrentModule->addLibrary(*$3);
2191 delete $3;
2192 CHECK_FOR_ERROR
2193 }
2194 | STRINGCONSTANT {
2195 CurModule.CurrentModule->addLibrary(*$1);
2196 delete $1;
2197 CHECK_FOR_ERROR
2198 }
2199 | /* empty: end of list */ {
2200 CHECK_FOR_ERROR
2201 }
2202 ;
2203
2204//===----------------------------------------------------------------------===//
2205// Rules to match Function Headers
2206//===----------------------------------------------------------------------===//
2207
2208ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2209 if (!UpRefs.empty())
2210 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2211 if (*$3 == Type::VoidTy)
2212 GEN_ERROR("void typed arguments are invalid");
2213 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2214 $$ = $1;
2215 $1->push_back(E);
2216 CHECK_FOR_ERROR
2217 }
2218 | Types OptParamAttrs OptLocalName {
2219 if (!UpRefs.empty())
2220 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2221 if (*$1 == Type::VoidTy)
2222 GEN_ERROR("void typed arguments are invalid");
2223 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2224 $$ = new ArgListType;
2225 $$->push_back(E);
2226 CHECK_FOR_ERROR
2227 };
2228
2229ArgList : ArgListH {
2230 $$ = $1;
2231 CHECK_FOR_ERROR
2232 }
2233 | ArgListH ',' DOTDOTDOT {
2234 $$ = $1;
2235 struct ArgListEntry E;
2236 E.Ty = new PATypeHolder(Type::VoidTy);
2237 E.Name = 0;
2238 E.Attrs = ParamAttr::None;
2239 $$->push_back(E);
2240 CHECK_FOR_ERROR
2241 }
2242 | DOTDOTDOT {
2243 $$ = new ArgListType;
2244 struct ArgListEntry E;
2245 E.Ty = new PATypeHolder(Type::VoidTy);
2246 E.Name = 0;
2247 E.Attrs = ParamAttr::None;
2248 $$->push_back(E);
2249 CHECK_FOR_ERROR
2250 }
2251 | /* empty */ {
2252 $$ = 0;
2253 CHECK_FOR_ERROR
2254 };
2255
2256FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002257 OptFuncAttrs OptSection OptAlign OptGC {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 std::string FunctionName(*$3);
2259 delete $3; // Free strdup'd memory!
2260
2261 // Check the function result for abstractness if this is a define. We should
2262 // have no abstract types at this point
2263 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2264 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2265
Chris Lattner62de9332008-04-23 05:36:58 +00002266 if (!FunctionType::isValidReturnType(*$2))
2267 GEN_ERROR("Invalid result type for LLVM function");
2268
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 std::vector<const Type*> ParamTypeList;
Chris Lattner1c8733e2008-03-12 17:45:29 +00002270 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2271 if ($7 != ParamAttr::None)
2272 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002273 if ($5) { // If there are arguments...
2274 unsigned index = 1;
2275 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2276 const Type* Ty = I->Ty->get();
2277 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2278 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2279 ParamTypeList.push_back(Ty);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002280 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2281 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002282 }
2283 }
2284
2285 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2286 if (isVarArg) ParamTypeList.pop_back();
2287
Chris Lattner1c8733e2008-03-12 17:45:29 +00002288 PAListPtr PAL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002289 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002290 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002292 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambbb2f2222007-12-17 01:12:55 +00002293 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294 delete $2;
2295
2296 ValID ID;
2297 if (!FunctionName.empty()) {
2298 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2299 } else {
2300 ID = ValID::createGlobalID(CurModule.Values.size());
2301 }
2302
2303 Function *Fn = 0;
2304 // See if this function was forward referenced. If so, recycle the object.
2305 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2306 // Move the function to the end of the list, from whereever it was
2307 // previously inserted.
2308 Fn = cast<Function>(FWRef);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002309 assert(Fn->getParamAttrs().isEmpty() &&
2310 "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311 CurModule.CurrentModule->getFunctionList().remove(Fn);
2312 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2313 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2314 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002315 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 // The existing function doesn't have the same type. This is an overload
2317 // error.
2318 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002319 } else if (Fn->getParamAttrs() != PAL) {
2320 // The existing function doesn't have the same parameter attributes.
2321 // This is an overload error.
2322 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002323 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2324 // Neither the existing or the current function is a declaration and they
2325 // have the same name and same type. Clearly this is a redefinition.
2326 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002327 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002328 // Make sure to strip off any argument names so we can't get conflicts.
2329 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2330 AI != AE; ++AI)
2331 AI->setName("");
2332 }
2333 } else { // Not already defined?
Gabor Greifd6da1d02008-04-06 20:25:17 +00002334 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2335 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002336 InsertValue(Fn, CurModule.Values);
2337 }
2338
2339 CurFun.FunctionStart(Fn);
2340
2341 if (CurFun.isDeclare) {
2342 // If we have declaration, always overwrite linkage. This will allow us to
2343 // correctly handle cases, when pointer to function is passed as argument to
2344 // another function.
2345 Fn->setLinkage(CurFun.Linkage);
2346 Fn->setVisibility(CurFun.Visibility);
2347 }
2348 Fn->setCallingConv($1);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002349 Fn->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 Fn->setAlignment($9);
2351 if ($8) {
2352 Fn->setSection(*$8);
2353 delete $8;
2354 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002355 if ($10) {
2356 Fn->setCollector($10->c_str());
2357 delete $10;
2358 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002359
2360 // Add all of the arguments we parsed to the function...
2361 if ($5) { // Is null if empty...
2362 if (isVarArg) { // Nuke the last entry
2363 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2364 "Not a varargs marker!");
2365 delete $5->back().Ty;
2366 $5->pop_back(); // Delete the last entry
2367 }
2368 Function::arg_iterator ArgIt = Fn->arg_begin();
2369 Function::arg_iterator ArgEnd = Fn->arg_end();
2370 unsigned Idx = 1;
2371 for (ArgListType::iterator I = $5->begin();
2372 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2373 delete I->Ty; // Delete the typeholder...
2374 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2375 CHECK_FOR_ERROR
2376 InsertValue(ArgIt);
2377 Idx++;
2378 }
2379
2380 delete $5; // We're now done with the argument list
2381 }
2382 CHECK_FOR_ERROR
2383};
2384
2385BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2386
2387FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2388 $$ = CurFun.CurrentFunction;
2389
2390 // Make sure that we keep track of the linkage type even if there was a
2391 // previous "declare".
2392 $$->setLinkage($1);
2393 $$->setVisibility($2);
2394};
2395
2396END : ENDTOK | '}'; // Allow end of '}' to end a function
2397
2398Function : BasicBlockList END {
2399 $$ = $1;
2400 CHECK_FOR_ERROR
2401};
2402
2403FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2404 CurFun.CurrentFunction->setLinkage($1);
2405 CurFun.CurrentFunction->setVisibility($2);
2406 $$ = CurFun.CurrentFunction;
2407 CurFun.FunctionDone();
2408 CHECK_FOR_ERROR
2409 };
2410
2411//===----------------------------------------------------------------------===//
2412// Rules to match Basic Blocks
2413//===----------------------------------------------------------------------===//
2414
2415OptSideEffect : /* empty */ {
2416 $$ = false;
2417 CHECK_FOR_ERROR
2418 }
2419 | SIDEEFFECT {
2420 $$ = true;
2421 CHECK_FOR_ERROR
2422 };
2423
2424ConstValueRef : ESINT64VAL { // A reference to a direct constant
2425 $$ = ValID::create($1);
2426 CHECK_FOR_ERROR
2427 }
2428 | EUINT64VAL {
2429 $$ = ValID::create($1);
2430 CHECK_FOR_ERROR
2431 }
2432 | FPVAL { // Perhaps it's an FP constant?
2433 $$ = ValID::create($1);
2434 CHECK_FOR_ERROR
2435 }
2436 | TRUETOK {
2437 $$ = ValID::create(ConstantInt::getTrue());
2438 CHECK_FOR_ERROR
2439 }
2440 | FALSETOK {
2441 $$ = ValID::create(ConstantInt::getFalse());
2442 CHECK_FOR_ERROR
2443 }
2444 | NULL_TOK {
2445 $$ = ValID::createNull();
2446 CHECK_FOR_ERROR
2447 }
2448 | UNDEF {
2449 $$ = ValID::createUndef();
2450 CHECK_FOR_ERROR
2451 }
2452 | ZEROINITIALIZER { // A vector zero constant.
2453 $$ = ValID::createZeroInit();
2454 CHECK_FOR_ERROR
2455 }
2456 | '<' ConstVector '>' { // Nonempty unsized packed vector
2457 const Type *ETy = (*$2)[0]->getType();
2458 int NumElements = $2->size();
2459
2460 VectorType* pt = VectorType::get(ETy, NumElements);
2461 PATypeHolder* PTy = new PATypeHolder(
2462 HandleUpRefs(
2463 VectorType::get(
2464 ETy,
2465 NumElements)
2466 )
2467 );
2468
2469 // Verify all elements are correct type!
2470 for (unsigned i = 0; i < $2->size(); i++) {
2471 if (ETy != (*$2)[i]->getType())
2472 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2473 ETy->getDescription() +"' as required!\nIt is of type '" +
2474 (*$2)[i]->getType()->getDescription() + "'.");
2475 }
2476
2477 $$ = ValID::create(ConstantVector::get(pt, *$2));
2478 delete PTy; delete $2;
2479 CHECK_FOR_ERROR
2480 }
2481 | ConstExpr {
2482 $$ = ValID::create($1);
2483 CHECK_FOR_ERROR
2484 }
2485 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2486 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2487 delete $3;
2488 delete $5;
2489 CHECK_FOR_ERROR
2490 };
2491
2492// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2493// another value.
2494//
2495SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2496 $$ = ValID::createLocalID($1);
2497 CHECK_FOR_ERROR
2498 }
2499 | GLOBALVAL_ID {
2500 $$ = ValID::createGlobalID($1);
2501 CHECK_FOR_ERROR
2502 }
2503 | LocalName { // Is it a named reference...?
2504 $$ = ValID::createLocalName(*$1);
2505 delete $1;
2506 CHECK_FOR_ERROR
2507 }
2508 | GlobalName { // Is it a named reference...?
2509 $$ = ValID::createGlobalName(*$1);
2510 delete $1;
2511 CHECK_FOR_ERROR
2512 };
2513
2514// ValueRef - A reference to a definition... either constant or symbolic
2515ValueRef : SymbolicValueRef | ConstValueRef;
2516
2517
2518// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2519// type immediately preceeds the value reference, and allows complex constant
2520// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2521ResolvedVal : Types ValueRef {
2522 if (!UpRefs.empty())
2523 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2524 $$ = getVal(*$1, $2);
2525 delete $1;
2526 CHECK_FOR_ERROR
2527 }
2528 ;
2529
Devang Patel036f0382008-02-20 22:39:45 +00002530ReturnedVal : ResolvedVal {
2531 $$ = new std::vector<Value *>();
2532 $$->push_back($1);
2533 CHECK_FOR_ERROR
2534 }
Devang Patel1a932fc2008-02-23 00:35:18 +00002535 | ReturnedVal ',' ResolvedVal {
Devang Patel036f0382008-02-20 22:39:45 +00002536 ($$=$1)->push_back($3);
2537 CHECK_FOR_ERROR
2538 };
2539
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002540BasicBlockList : BasicBlockList BasicBlock {
2541 $$ = $1;
2542 CHECK_FOR_ERROR
2543 }
2544 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2545 $$ = $1;
2546 CHECK_FOR_ERROR
2547 };
2548
2549
2550// Basic blocks are terminated by branching instructions:
2551// br, br/cc, switch, ret
2552//
2553BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2554 setValueName($3, $2);
2555 CHECK_FOR_ERROR
2556 InsertValue($3);
2557 $1->getInstList().push_back($3);
2558 $$ = $1;
2559 CHECK_FOR_ERROR
2560 };
2561
2562InstructionList : InstructionList Inst {
2563 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2564 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2565 if (CI2->getParent() == 0)
2566 $1->getInstList().push_back(CI2);
2567 $1->getInstList().push_back($2);
2568 $$ = $1;
2569 CHECK_FOR_ERROR
2570 }
2571 | /* empty */ { // Empty space between instruction lists
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002572 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002573 CHECK_FOR_ERROR
2574 }
2575 | LABELSTR { // Labelled (named) basic block
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002576 $$ = defineBBVal(ValID::createLocalName(*$1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577 delete $1;
2578 CHECK_FOR_ERROR
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002579
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002580 };
2581
Devang Patel036f0382008-02-20 22:39:45 +00002582BBTerminatorInst :
2583 RET ReturnedVal { // Return with a result...
Devang Patelbbbb8202008-02-26 22:12:58 +00002584 ValueList &VL = *$2;
Devang Patel202ec472008-02-26 23:17:50 +00002585 assert(!VL.empty() && "Invalid ret operands!");
Gabor Greifd6da1d02008-04-06 20:25:17 +00002586 $$ = ReturnInst::Create(&VL[0], VL.size());
Devang Patel036f0382008-02-20 22:39:45 +00002587 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002588 CHECK_FOR_ERROR
2589 }
2590 | RET VOID { // Return with no result...
Gabor Greifd6da1d02008-04-06 20:25:17 +00002591 $$ = ReturnInst::Create();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002592 CHECK_FOR_ERROR
2593 }
2594 | BR LABEL ValueRef { // Unconditional Branch...
2595 BasicBlock* tmpBB = getBBVal($3);
2596 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002597 $$ = BranchInst::Create(tmpBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 } // Conditional Branch...
2599 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2600 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2601 BasicBlock* tmpBBA = getBBVal($6);
2602 CHECK_FOR_ERROR
2603 BasicBlock* tmpBBB = getBBVal($9);
2604 CHECK_FOR_ERROR
2605 Value* tmpVal = getVal(Type::Int1Ty, $3);
2606 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002607 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002608 }
2609 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2610 Value* tmpVal = getVal($2, $3);
2611 CHECK_FOR_ERROR
2612 BasicBlock* tmpBB = getBBVal($6);
2613 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002614 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002615 $$ = S;
2616
2617 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2618 E = $8->end();
2619 for (; I != E; ++I) {
2620 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2621 S->addCase(CI, I->second);
2622 else
2623 GEN_ERROR("Switch case is constant, but not a simple integer");
2624 }
2625 delete $8;
2626 CHECK_FOR_ERROR
2627 }
2628 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2629 Value* tmpVal = getVal($2, $3);
2630 CHECK_FOR_ERROR
2631 BasicBlock* tmpBB = getBBVal($6);
2632 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002633 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002634 $$ = S;
2635 CHECK_FOR_ERROR
2636 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002637 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 TO LABEL ValueRef UNWIND LABEL ValueRef {
2639
2640 // Handle the short syntax
2641 const PointerType *PFTy = 0;
2642 const FunctionType *Ty = 0;
2643 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2644 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2645 // Pull out the types of all of the arguments...
2646 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002647 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002648 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002649 const Type *Ty = I->Val->getType();
2650 if (Ty == Type::VoidTy)
2651 GEN_ERROR("Short call syntax cannot be used with varargs");
2652 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002653 }
Chris Lattner62de9332008-04-23 05:36:58 +00002654
2655 if (!FunctionType::isValidReturnType(*$3))
2656 GEN_ERROR("Invalid result type for LLVM function");
2657
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002658 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambbb2f2222007-12-17 01:12:55 +00002659 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002660 }
2661
2662 delete $3;
2663
2664 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2665 CHECK_FOR_ERROR
2666 BasicBlock *Normal = getBBVal($11);
2667 CHECK_FOR_ERROR
2668 BasicBlock *Except = getBBVal($14);
2669 CHECK_FOR_ERROR
2670
Chris Lattner1c8733e2008-03-12 17:45:29 +00002671 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2672 if ($8 != ParamAttr::None)
2673 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002674
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002675 // Check the arguments
2676 ValueList Args;
2677 if ($6->empty()) { // Has no arguments?
2678 // Make sure no arguments is a good thing!
2679 if (Ty->getNumParams() != 0)
2680 GEN_ERROR("No arguments passed to a function that "
2681 "expects arguments");
2682 } else { // Has arguments?
2683 // Loop through FunctionType's arguments and ensure they are specified
2684 // correctly!
2685 FunctionType::param_iterator I = Ty->param_begin();
2686 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002687 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002688 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002689
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002690 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002691 if (ArgI->Val->getType() != *I)
2692 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2693 (*I)->getDescription() + "'");
2694 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002695 if (ArgI->Attrs != ParamAttr::None)
2696 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 }
2698
2699 if (Ty->isVarArg()) {
2700 if (I == E)
Duncan Sands6c3314b2008-01-11 21:23:39 +00002701 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002702 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00002703 if (ArgI->Attrs != ParamAttr::None)
2704 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Duncan Sands6c3314b2008-01-11 21:23:39 +00002705 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002706 } else if (I != E || ArgI != ArgE)
2707 GEN_ERROR("Invalid number of parameters detected");
2708 }
2709
Chris Lattner1c8733e2008-03-12 17:45:29 +00002710 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002711 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002712 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002713
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714 // Create the InvokeInst
Gabor Greifb91ea9d2008-05-15 10:04:30 +00002715 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2716 Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717 II->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002718 II->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719 $$ = II;
2720 delete $6;
2721 CHECK_FOR_ERROR
2722 }
2723 | UNWIND {
2724 $$ = new UnwindInst();
2725 CHECK_FOR_ERROR
2726 }
2727 | UNREACHABLE {
2728 $$ = new UnreachableInst();
2729 CHECK_FOR_ERROR
2730 };
2731
2732
2733
2734JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2735 $$ = $1;
2736 Constant *V = cast<Constant>(getExistingVal($2, $3));
2737 CHECK_FOR_ERROR
2738 if (V == 0)
2739 GEN_ERROR("May only switch on a constant pool value");
2740
2741 BasicBlock* tmpBB = getBBVal($6);
2742 CHECK_FOR_ERROR
2743 $$->push_back(std::make_pair(V, tmpBB));
2744 }
2745 | IntType ConstValueRef ',' LABEL ValueRef {
2746 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2747 Constant *V = cast<Constant>(getExistingVal($1, $2));
2748 CHECK_FOR_ERROR
2749
2750 if (V == 0)
2751 GEN_ERROR("May only switch on a constant pool value");
2752
2753 BasicBlock* tmpBB = getBBVal($5);
2754 CHECK_FOR_ERROR
2755 $$->push_back(std::make_pair(V, tmpBB));
2756 };
2757
2758Inst : OptLocalAssign InstVal {
2759 // Is this definition named?? if so, assign the name...
2760 setValueName($2, $1);
2761 CHECK_FOR_ERROR
2762 InsertValue($2);
2763 $$ = $2;
2764 CHECK_FOR_ERROR
2765 };
2766
2767
2768PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2769 if (!UpRefs.empty())
2770 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2771 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2772 Value* tmpVal = getVal(*$1, $3);
2773 CHECK_FOR_ERROR
2774 BasicBlock* tmpBB = getBBVal($5);
2775 CHECK_FOR_ERROR
2776 $$->push_back(std::make_pair(tmpVal, tmpBB));
2777 delete $1;
2778 }
2779 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2780 $$ = $1;
2781 Value* tmpVal = getVal($1->front().first->getType(), $4);
2782 CHECK_FOR_ERROR
2783 BasicBlock* tmpBB = getBBVal($6);
2784 CHECK_FOR_ERROR
2785 $1->push_back(std::make_pair(tmpVal, tmpBB));
2786 };
2787
2788
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002789ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2790 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002791 if (!UpRefs.empty())
2792 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2793 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00002794 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002795 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002796 $$->push_back(E);
2797 delete $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002798 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002800 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2801 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002802 // Labels are only valid in ASMs
2803 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002804 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002805 $$->push_back(E);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002806 CHECK_FOR_ERROR
Dale Johannesencfb19e62007-11-05 21:20:28 +00002807 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002808 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2809 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002810 if (!UpRefs.empty())
2811 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2812 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002813 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002814 $$->push_back(E);
2815 delete $3;
2816 CHECK_FOR_ERROR
2817 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002818 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2819 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002820 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002821 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002822 $$->push_back(E);
2823 CHECK_FOR_ERROR
2824 }
2825 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002826
2827IndexList // Used for gep instructions and constant expressions
2828 : /*empty*/ { $$ = new std::vector<Value*>(); }
2829 | IndexList ',' ResolvedVal {
2830 $$ = $1;
2831 $$->push_back($3);
2832 CHECK_FOR_ERROR
2833 }
2834 ;
2835
2836OptTailCall : TAIL CALL {
2837 $$ = true;
2838 CHECK_FOR_ERROR
2839 }
2840 | CALL {
2841 $$ = false;
2842 CHECK_FOR_ERROR
2843 };
2844
2845InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2846 if (!UpRefs.empty())
2847 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2848 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2849 !isa<VectorType>((*$2).get()))
2850 GEN_ERROR(
2851 "Arithmetic operator requires integer, FP, or packed operands");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002852 Value* val1 = getVal(*$2, $3);
2853 CHECK_FOR_ERROR
2854 Value* val2 = getVal(*$2, $5);
2855 CHECK_FOR_ERROR
2856 $$ = BinaryOperator::create($1, val1, val2);
2857 if ($$ == 0)
2858 GEN_ERROR("binary operator returned null");
2859 delete $2;
2860 }
2861 | LogicalOps Types ValueRef ',' ValueRef {
2862 if (!UpRefs.empty())
2863 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2864 if (!(*$2)->isInteger()) {
2865 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2866 !cast<VectorType>($2->get())->getElementType()->isInteger())
2867 GEN_ERROR("Logical operator requires integral operands");
2868 }
2869 Value* tmpVal1 = getVal(*$2, $3);
2870 CHECK_FOR_ERROR
2871 Value* tmpVal2 = getVal(*$2, $5);
2872 CHECK_FOR_ERROR
2873 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2874 if ($$ == 0)
2875 GEN_ERROR("binary operator returned null");
2876 delete $2;
2877 }
2878 | ICMP IPredicates Types ValueRef ',' ValueRef {
2879 if (!UpRefs.empty())
2880 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2881 if (isa<VectorType>((*$3).get()))
2882 GEN_ERROR("Vector types not supported by icmp instruction");
2883 Value* tmpVal1 = getVal(*$3, $4);
2884 CHECK_FOR_ERROR
2885 Value* tmpVal2 = getVal(*$3, $6);
2886 CHECK_FOR_ERROR
2887 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2888 if ($$ == 0)
2889 GEN_ERROR("icmp operator returned null");
2890 delete $3;
2891 }
2892 | FCMP FPredicates Types ValueRef ',' ValueRef {
2893 if (!UpRefs.empty())
2894 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2895 if (isa<VectorType>((*$3).get()))
2896 GEN_ERROR("Vector types not supported by fcmp instruction");
2897 Value* tmpVal1 = getVal(*$3, $4);
2898 CHECK_FOR_ERROR
2899 Value* tmpVal2 = getVal(*$3, $6);
2900 CHECK_FOR_ERROR
2901 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2902 if ($$ == 0)
2903 GEN_ERROR("fcmp operator returned null");
2904 delete $3;
2905 }
Nate Begeman646fa482008-05-12 19:01:56 +00002906 | VICMP IPredicates Types ValueRef ',' ValueRef {
2907 if (!UpRefs.empty())
2908 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2909 if (!isa<VectorType>((*$3).get()))
2910 GEN_ERROR("Scalar types not supported by vicmp instruction");
2911 Value* tmpVal1 = getVal(*$3, $4);
2912 CHECK_FOR_ERROR
2913 Value* tmpVal2 = getVal(*$3, $6);
2914 CHECK_FOR_ERROR
2915 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2916 if ($$ == 0)
2917 GEN_ERROR("icmp operator returned null");
2918 delete $3;
2919 }
2920 | VFCMP FPredicates Types ValueRef ',' ValueRef {
2921 if (!UpRefs.empty())
2922 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2923 if (!isa<VectorType>((*$3).get()))
2924 GEN_ERROR("Scalar types not supported by vfcmp instruction");
2925 Value* tmpVal1 = getVal(*$3, $4);
2926 CHECK_FOR_ERROR
2927 Value* tmpVal2 = getVal(*$3, $6);
2928 CHECK_FOR_ERROR
2929 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2930 if ($$ == 0)
2931 GEN_ERROR("fcmp operator returned null");
2932 delete $3;
2933 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002934 | CastOps ResolvedVal TO Types {
2935 if (!UpRefs.empty())
2936 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2937 Value* Val = $2;
2938 const Type* DestTy = $4->get();
2939 if (!CastInst::castIsValid($1, Val, DestTy))
2940 GEN_ERROR("invalid cast opcode for cast from '" +
2941 Val->getType()->getDescription() + "' to '" +
2942 DestTy->getDescription() + "'");
2943 $$ = CastInst::create($1, Val, DestTy);
2944 delete $4;
2945 }
2946 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2947 if ($2->getType() != Type::Int1Ty)
2948 GEN_ERROR("select condition must be boolean");
2949 if ($4->getType() != $6->getType())
2950 GEN_ERROR("select value types should match");
Gabor Greifd6da1d02008-04-06 20:25:17 +00002951 $$ = SelectInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952 CHECK_FOR_ERROR
2953 }
2954 | VAARG ResolvedVal ',' Types {
2955 if (!UpRefs.empty())
2956 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2957 $$ = new VAArgInst($2, *$4);
2958 delete $4;
2959 CHECK_FOR_ERROR
2960 }
2961 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2962 if (!ExtractElementInst::isValidOperands($2, $4))
2963 GEN_ERROR("Invalid extractelement operands");
2964 $$ = new ExtractElementInst($2, $4);
2965 CHECK_FOR_ERROR
2966 }
2967 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2968 if (!InsertElementInst::isValidOperands($2, $4, $6))
2969 GEN_ERROR("Invalid insertelement operands");
Gabor Greifd6da1d02008-04-06 20:25:17 +00002970 $$ = InsertElementInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971 CHECK_FOR_ERROR
2972 }
2973 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2974 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2975 GEN_ERROR("Invalid shufflevector operands");
2976 $$ = new ShuffleVectorInst($2, $4, $6);
2977 CHECK_FOR_ERROR
2978 }
2979 | PHI_TOK PHIList {
2980 const Type *Ty = $2->front().first->getType();
2981 if (!Ty->isFirstClassType())
2982 GEN_ERROR("PHI node operands must be of first class type");
Gabor Greifd6da1d02008-04-06 20:25:17 +00002983 $$ = PHINode::Create(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002984 ((PHINode*)$$)->reserveOperandSpace($2->size());
2985 while ($2->begin() != $2->end()) {
2986 if ($2->front().first->getType() != Ty)
2987 GEN_ERROR("All elements of a PHI node must be of the same type");
2988 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2989 $2->pop_front();
2990 }
2991 delete $2; // Free the list...
2992 CHECK_FOR_ERROR
2993 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002994 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 OptFuncAttrs {
2996
2997 // Handle the short syntax
2998 const PointerType *PFTy = 0;
2999 const FunctionType *Ty = 0;
3000 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3001 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3002 // Pull out the types of all of the arguments...
3003 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00003004 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003005 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003006 const Type *Ty = I->Val->getType();
3007 if (Ty == Type::VoidTy)
3008 GEN_ERROR("Short call syntax cannot be used with varargs");
3009 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010 }
Chris Lattner62de9332008-04-23 05:36:58 +00003011
3012 if (!FunctionType::isValidReturnType(*$3))
3013 GEN_ERROR("Invalid result type for LLVM function");
3014
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003015 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambbb2f2222007-12-17 01:12:55 +00003016 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 }
3018
3019 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3020 CHECK_FOR_ERROR
3021
3022 // Check for call to invalid intrinsic to avoid crashing later.
3023 if (Function *theF = dyn_cast<Function>(V)) {
3024 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3025 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3026 !theF->getIntrinsicID(true))
3027 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3028 theF->getName() + "'");
3029 }
3030
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003031 // Set up the ParamAttrs for the function
Chris Lattner1c8733e2008-03-12 17:45:29 +00003032 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3033 if ($8 != ParamAttr::None)
3034 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 // Check the arguments
3036 ValueList Args;
3037 if ($6->empty()) { // Has no arguments?
3038 // Make sure no arguments is a good thing!
3039 if (Ty->getNumParams() != 0)
3040 GEN_ERROR("No arguments passed to a function that "
3041 "expects arguments");
3042 } else { // Has arguments?
3043 // Loop through FunctionType's arguments and ensure they are specified
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003044 // correctly. Also, gather any parameter attributes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003045 FunctionType::param_iterator I = Ty->param_begin();
3046 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00003047 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003048 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003049
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003050 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 if (ArgI->Val->getType() != *I)
3052 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3053 (*I)->getDescription() + "'");
3054 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00003055 if (ArgI->Attrs != ParamAttr::None)
3056 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003057 }
3058 if (Ty->isVarArg()) {
3059 if (I == E)
Duncan Sands6c3314b2008-01-11 21:23:39 +00003060 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003061 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00003062 if (ArgI->Attrs != ParamAttr::None)
3063 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Duncan Sands6c3314b2008-01-11 21:23:39 +00003064 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003065 } else if (I != E || ArgI != ArgE)
3066 GEN_ERROR("Invalid number of parameters detected");
3067 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003068
3069 // Finish off the ParamAttrs and check them
Chris Lattner1c8733e2008-03-12 17:45:29 +00003070 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003071 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00003072 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003073
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074 // Create the call node
Gabor Greifd6da1d02008-04-06 20:25:17 +00003075 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003076 CI->setTailCall($1);
3077 CI->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003078 CI->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003079 $$ = CI;
3080 delete $6;
3081 delete $3;
3082 CHECK_FOR_ERROR
3083 }
3084 | MemoryInst {
3085 $$ = $1;
3086 CHECK_FOR_ERROR
3087 };
3088
3089OptVolatile : VOLATILE {
3090 $$ = true;
3091 CHECK_FOR_ERROR
3092 }
3093 | /* empty */ {
3094 $$ = false;
3095 CHECK_FOR_ERROR
3096 };
3097
3098
3099
3100MemoryInst : MALLOC Types OptCAlign {
3101 if (!UpRefs.empty())
3102 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3103 $$ = new MallocInst(*$2, 0, $3);
3104 delete $2;
3105 CHECK_FOR_ERROR
3106 }
3107 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3108 if (!UpRefs.empty())
3109 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3110 Value* tmpVal = getVal($4, $5);
3111 CHECK_FOR_ERROR
3112 $$ = new MallocInst(*$2, tmpVal, $6);
3113 delete $2;
3114 }
3115 | ALLOCA Types OptCAlign {
3116 if (!UpRefs.empty())
3117 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3118 $$ = new AllocaInst(*$2, 0, $3);
3119 delete $2;
3120 CHECK_FOR_ERROR
3121 }
3122 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3123 if (!UpRefs.empty())
3124 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3125 Value* tmpVal = getVal($4, $5);
3126 CHECK_FOR_ERROR
3127 $$ = new AllocaInst(*$2, tmpVal, $6);
3128 delete $2;
3129 }
3130 | FREE ResolvedVal {
3131 if (!isa<PointerType>($2->getType()))
3132 GEN_ERROR("Trying to free nonpointer type " +
3133 $2->getType()->getDescription() + "");
3134 $$ = new FreeInst($2);
3135 CHECK_FOR_ERROR
3136 }
3137
3138 | OptVolatile LOAD Types ValueRef OptCAlign {
3139 if (!UpRefs.empty())
3140 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3141 if (!isa<PointerType>($3->get()))
3142 GEN_ERROR("Can't load from nonpointer type: " +
3143 (*$3)->getDescription());
3144 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3145 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3146 (*$3)->getDescription());
3147 Value* tmpVal = getVal(*$3, $4);
3148 CHECK_FOR_ERROR
3149 $$ = new LoadInst(tmpVal, "", $1, $5);
3150 delete $3;
3151 }
3152 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3153 if (!UpRefs.empty())
3154 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3155 const PointerType *PT = dyn_cast<PointerType>($5->get());
3156 if (!PT)
3157 GEN_ERROR("Can't store to a nonpointer type: " +
3158 (*$5)->getDescription());
3159 const Type *ElTy = PT->getElementType();
3160 if (ElTy != $3->getType())
3161 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3162 "' into space of type '" + ElTy->getDescription() + "'");
3163
3164 Value* tmpVal = getVal(*$5, $6);
3165 CHECK_FOR_ERROR
3166 $$ = new StoreInst($3, tmpVal, $1, $7);
3167 delete $5;
3168 }
Dan Gohmandecb8c02008-04-23 20:11:27 +00003169| GETRESULT Types ValueRef ',' EUINT64VAL {
Devang Patel89c3d672008-02-22 19:31:15 +00003170 Value *TmpVal = getVal($2->get(), $3);
Devang Patele5c806a2008-02-19 22:26:37 +00003171 if (!GetResultInst::isValidOperands(TmpVal, $5))
3172 GEN_ERROR("Invalid getresult operands");
3173 $$ = new GetResultInst(TmpVal, $5);
Devang Patel1a932fc2008-02-23 00:35:18 +00003174 delete $2;
Devang Patele5c806a2008-02-19 22:26:37 +00003175 CHECK_FOR_ERROR
3176 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 | GETELEMENTPTR Types ValueRef IndexList {
3178 if (!UpRefs.empty())
3179 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3180 if (!isa<PointerType>($2->get()))
3181 GEN_ERROR("getelementptr insn requires pointer operand");
3182
David Greene393be882007-09-04 15:46:09 +00003183 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 GEN_ERROR("Invalid getelementptr indices for type '" +
3185 (*$2)->getDescription()+ "'");
3186 Value* tmpVal = getVal(*$2, $3);
3187 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00003188 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189 delete $2;
3190 delete $4;
3191 };
3192
3193
3194%%
3195
3196// common code from the two 'RunVMAsmParser' functions
3197static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199 // Check to make sure the parser succeeded
3200 if (yyparse()) {
3201 if (ParserResult)
3202 delete ParserResult;
3203 return 0;
3204 }
3205
3206 // Emit an error if there are any unresolved types left.
3207 if (!CurModule.LateResolveTypes.empty()) {
3208 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3209 if (DID.Type == ValID::LocalName) {
3210 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3211 } else {
3212 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3213 }
3214 if (ParserResult)
3215 delete ParserResult;
3216 return 0;
3217 }
3218
3219 // Emit an error if there are any unresolved values left.
3220 if (!CurModule.LateResolveValues.empty()) {
3221 Value *V = CurModule.LateResolveValues.back();
3222 std::map<Value*, std::pair<ValID, int> >::iterator I =
3223 CurModule.PlaceHolderInfo.find(V);
3224
3225 if (I != CurModule.PlaceHolderInfo.end()) {
3226 ValID &DID = I->second.first;
3227 if (DID.Type == ValID::LocalName) {
3228 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3229 } else {
3230 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3231 }
3232 if (ParserResult)
3233 delete ParserResult;
3234 return 0;
3235 }
3236 }
3237
3238 // Check to make sure that parsing produced a result
3239 if (!ParserResult)
3240 return 0;
3241
3242 // Reset ParserResult variable while saving its value for the result.
3243 Module *Result = ParserResult;
3244 ParserResult = 0;
3245
3246 return Result;
3247}
3248
3249void llvm::GenerateError(const std::string &message, int LineNo) {
Chris Lattner17e73c22007-11-18 08:46:26 +00003250 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003251 // TODO: column number in exception
3252 if (TheParseError)
Chris Lattner17e73c22007-11-18 08:46:26 +00003253 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 TriggerError = 1;
3255}
3256
3257int yyerror(const char *ErrorMsg) {
Chris Lattner17e73c22007-11-18 08:46:26 +00003258 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Chris Lattner17e73c22007-11-18 08:46:26 +00003260 if (yychar != YYEMPTY && yychar != 0) {
3261 errMsg += " while reading token: '";
3262 errMsg += std::string(LLLgetTokenStart(),
3263 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3264 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003265 GenerateError(errMsg);
3266 return 0;
3267}