blob: d004a4e399f57aa32c98eb392849dbe1a6ec0c46 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the bison parser for LLVM assembly languages files.
11//
12//===----------------------------------------------------------------------===//
13
14%{
15#include "ParserInternals.h"
16#include "llvm/CallingConv.h"
17#include "llvm/InlineAsm.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/ValueSymbolTable.h"
Chandler Carruth563d4a42007-08-04 01:56:21 +000021#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/Streams.h"
28#include <algorithm>
29#include <list>
30#include <map>
31#include <utility>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032
33// The following is a gross hack. In order to rid the libAsmParser library of
34// exceptions, we have to have a way of getting the yyparse function to go into
35// an error situation. So, whenever we want an error to occur, the GenerateError
36// function (see bottom of file) sets TriggerError. Then, at the end of each
37// production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38// (a goto) to put YACC in error state. Furthermore, several calls to
39// GenerateError are made from inside productions and they must simulate the
40// previous exception behavior by exiting the production immediately. We have
41// replaced these with the GEN_ERROR macro which calls GeneratError and then
42// immediately invokes YYERROR. This would be so much cleaner if it was a
43// recursive descent parser.
44static bool TriggerError = false;
45#define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46#define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
47
48int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49int yylex(); // declaration" of xxx warnings.
50int yyparse();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051using namespace llvm;
52
53static Module *ParserResult;
54
55// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56// relating to upreferences in the input stream.
57//
58//#define DEBUG_UPREFS 1
59#ifdef DEBUG_UPREFS
60#define UR_OUT(X) cerr << X
61#else
62#define UR_OUT(X)
63#endif
64
65#define YYERROR_VERBOSE 1
66
67static GlobalVariable *CurGV;
68
69
70// This contains info used when building the body of a function. It is
71// destroyed when the function is completed.
72//
73typedef std::vector<Value *> ValueList; // Numbered defs
74
75static void
76ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
77
78static struct PerModuleInfo {
79 Module *CurrentModule;
80 ValueList Values; // Module level numbered definitions
81 ValueList LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
84
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
89
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
94 //
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
98
99 void ModuleDone() {
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
103 //
104 ResolveDefinitions(LateResolveValues);
105 if (TriggerError)
106 return;
107
108 // Check to make sure that all global value forward references have been
109 // resolved!
110 //
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
113
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 I != E; ++I) {
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
118 }
119 GenerateError(UndefinedReferences);
120 return;
121 }
122
Chandler Carruth563d4a42007-08-04 01:56:21 +0000123 // Look for intrinsic functions and CallInst that need to be upgraded
124 for (Module::iterator FI = CurrentModule->begin(),
125 FE = CurrentModule->end(); FI != FE; )
126 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
127
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 Values.clear(); // Clear out function local definitions
129 Types.clear();
130 CurrentModule = 0;
131 }
132
133 // GetForwardRefForGlobal - Check to see if there is a forward reference
134 // for this global. If so, remove it from the GlobalRefs map and return it.
135 // If not, just return null.
136 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137 // Check to see if there is a forward reference to this global variable...
138 // if there is, eliminate it and patch the reference to use the new def'n.
139 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140 GlobalValue *Ret = 0;
141 if (I != GlobalRefs.end()) {
142 Ret = I->second;
143 GlobalRefs.erase(I);
144 }
145 return Ret;
146 }
147
148 bool TypeIsUnresolved(PATypeHolder* PATy) {
149 // If it isn't abstract, its resolved
150 const Type* Ty = PATy->get();
151 if (!Ty->isAbstract())
152 return false;
153 // Traverse the type looking for abstract types. If it isn't abstract then
154 // we don't need to traverse that leg of the type.
155 std::vector<const Type*> WorkList, SeenList;
156 WorkList.push_back(Ty);
157 while (!WorkList.empty()) {
158 const Type* Ty = WorkList.back();
159 SeenList.push_back(Ty);
160 WorkList.pop_back();
161 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162 // Check to see if this is an unresolved type
163 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165 for ( ; I != E; ++I) {
166 if (I->second.get() == OpTy)
167 return true;
168 }
169 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170 const Type* TheTy = SeqTy->getElementType();
171 if (TheTy->isAbstract() && TheTy != Ty) {
172 std::vector<const Type*>::iterator I = SeenList.begin(),
173 E = SeenList.end();
174 for ( ; I != E; ++I)
175 if (*I == TheTy)
176 break;
177 if (I == E)
178 WorkList.push_back(TheTy);
179 }
180 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182 const Type* TheTy = StrTy->getElementType(i);
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
185 E = SeenList.end();
186 for ( ; I != E; ++I)
187 if (*I == TheTy)
188 break;
189 if (I == E)
190 WorkList.push_back(TheTy);
191 }
192 }
193 }
194 }
195 return false;
196 }
197} CurModule;
198
199static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
201
202 ValueList Values; // Keep track of #'d definitions
203 unsigned NextValNum;
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
208
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
212
213 inline PerFunctionInfo() {
214 CurrentFunction = 0;
215 isDeclare = false;
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
218 }
219
220 inline void FunctionStart(Function *M) {
221 CurrentFunction = M;
222 NextValNum = 0;
223 }
224
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
230 return;
231 }
232
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
235
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
238 CurrentFunction = 0;
239 isDeclare = false;
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
242 }
243} CurFun; // Info for the current function...
244
245static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
246
247
248//===----------------------------------------------------------------------===//
249// Code to handle definitions of all the types
250//===----------------------------------------------------------------------===//
251
Chris Lattner906773a2008-08-29 17:20:18 +0000252/// InsertValue - Insert a value into the value table. If it is named, this
253/// returns -1, otherwise it returns the slot number for the value.
254static int InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 // Things that have names or are void typed don't get slot numbers
256 if (V->hasName() || (V->getType() == Type::VoidTy))
Chris Lattner906773a2008-08-29 17:20:18 +0000257 return -1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258
259 // In the case of function values, we have to allow for the forward reference
260 // of basic blocks, which are included in the numbering. Consequently, we keep
261 // track of the next insertion location with NextValNum. When a BB gets
262 // inserted, it could change the size of the CurFun.Values vector.
263 if (&ValueTab == &CurFun.Values) {
264 if (ValueTab.size() <= CurFun.NextValNum)
265 ValueTab.resize(CurFun.NextValNum+1);
266 ValueTab[CurFun.NextValNum++] = V;
Chris Lattner906773a2008-08-29 17:20:18 +0000267 return CurFun.NextValNum-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 }
269 // For all other lists, its okay to just tack it on the back of the vector.
270 ValueTab.push_back(V);
Chris Lattner906773a2008-08-29 17:20:18 +0000271 return ValueTab.size()-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272}
273
274static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
275 switch (D.Type) {
276 case ValID::LocalID: // Is it a numbered definition?
277 // Module constants occupy the lowest numbered slots...
278 if (D.Num < CurModule.Types.size())
279 return CurModule.Types[D.Num];
280 break;
281 case ValID::LocalName: // Is it a named definition?
282 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
283 D.destroy(); // Free old strdup'd memory...
284 return N;
285 }
286 break;
287 default:
288 GenerateError("Internal parser error: Invalid symbol type reference");
289 return 0;
290 }
291
292 // If we reached here, we referenced either a symbol that we don't know about
293 // or an id number that hasn't been read yet. We may be referencing something
294 // forward, so just create an entry to be resolved later and get to it...
295 //
296 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
297
298
299 if (inFunctionScope()) {
300 if (D.Type == ValID::LocalName) {
301 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
302 return 0;
303 } else {
304 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
305 return 0;
306 }
307 }
308
309 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
310 if (I != CurModule.LateResolveTypes.end())
311 return I->second;
312
313 Type *Typ = OpaqueType::get();
314 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
315 return Typ;
316 }
317
318// getExistingVal - Look up the value specified by the provided type and
319// the provided ValID. If the value exists and has already been defined, return
320// it. Otherwise return null.
321//
322static Value *getExistingVal(const Type *Ty, const ValID &D) {
323 if (isa<FunctionType>(Ty)) {
324 GenerateError("Functions are not values and "
325 "must be referenced as pointers");
326 return 0;
327 }
328
329 switch (D.Type) {
330 case ValID::LocalID: { // Is it a numbered definition?
331 // Check that the number is within bounds.
332 if (D.Num >= CurFun.Values.size())
333 return 0;
334 Value *Result = CurFun.Values[D.Num];
335 if (Ty != Result->getType()) {
336 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
337 Result->getType()->getDescription() + "' does not match "
338 "expected type, '" + Ty->getDescription() + "'");
339 return 0;
340 }
341 return Result;
342 }
343 case ValID::GlobalID: { // Is it a numbered definition?
344 if (D.Num >= CurModule.Values.size())
345 return 0;
346 Value *Result = CurModule.Values[D.Num];
347 if (Ty != Result->getType()) {
348 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
349 Result->getType()->getDescription() + "' does not match "
350 "expected type, '" + Ty->getDescription() + "'");
351 return 0;
352 }
353 return Result;
354 }
355
356 case ValID::LocalName: { // Is it a named definition?
357 if (!inFunctionScope())
358 return 0;
359 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
360 Value *N = SymTab.lookup(D.getName());
361 if (N == 0)
362 return 0;
363 if (N->getType() != Ty)
364 return 0;
365
366 D.destroy(); // Free old strdup'd memory...
367 return N;
368 }
369 case ValID::GlobalName: { // Is it a named definition?
370 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
371 Value *N = SymTab.lookup(D.getName());
372 if (N == 0)
373 return 0;
374 if (N->getType() != Ty)
375 return 0;
376
377 D.destroy(); // Free old strdup'd memory...
378 return N;
379 }
380
381 // Check to make sure that "Ty" is an integral type, and that our
382 // value will fit into the specified type...
383 case ValID::ConstSIntVal: // Is it a constant pool reference??
Chris Lattner59363a32008-02-19 04:36:25 +0000384 if (!isa<IntegerType>(Ty) ||
385 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 GenerateError("Signed integral constant '" +
387 itostr(D.ConstPool64) + "' is invalid for type '" +
388 Ty->getDescription() + "'");
389 return 0;
390 }
391 return ConstantInt::get(Ty, D.ConstPool64, true);
392
393 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000394 if (isa<IntegerType>(Ty) &&
395 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 return ConstantInt::get(Ty, D.UConstPool64);
Chris Lattner59363a32008-02-19 04:36:25 +0000397
398 if (!isa<IntegerType>(Ty) ||
399 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
400 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
401 "' is invalid or out of range for type '" +
402 Ty->getDescription() + "'");
403 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 }
Chris Lattner59363a32008-02-19 04:36:25 +0000405 // This is really a signed reference. Transmogrify.
406 return ConstantInt::get(Ty, D.ConstPool64, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407
Chris Lattnerf3d40022008-07-11 00:30:39 +0000408 case ValID::ConstAPInt: // Is it an unsigned const pool reference?
409 if (!isa<IntegerType>(Ty)) {
410 GenerateError("Integral constant '" + D.getName() +
411 "' is invalid or out of range for type '" +
412 Ty->getDescription() + "'");
413 return 0;
414 }
415
416 {
417 APSInt Tmp = *D.ConstPoolInt;
418 Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
419 return ConstantInt::get(Tmp);
420 }
421
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000423 if (!Ty->isFloatingPoint() ||
424 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 GenerateError("FP constant invalid for type");
426 return 0;
427 }
Chris Lattner05ba86e2008-04-20 00:41:19 +0000428 // Lexer has no type info, so builds all float and double FP constants
Dale Johannesen255b8fe2007-09-11 18:33:39 +0000429 // as double. Fix this here. Long double does not need this.
430 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
431 Ty==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000432 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner05ba86e2008-04-20 00:41:19 +0000433 return ConstantFP::get(*D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434
435 case ValID::ConstNullVal: // Is it a null value?
436 if (!isa<PointerType>(Ty)) {
437 GenerateError("Cannot create a a non pointer null");
438 return 0;
439 }
440 return ConstantPointerNull::get(cast<PointerType>(Ty));
441
442 case ValID::ConstUndefVal: // Is it an undef value?
443 return UndefValue::get(Ty);
444
445 case ValID::ConstZeroVal: // Is it a zero value?
446 return Constant::getNullValue(Ty);
447
448 case ValID::ConstantVal: // Fully resolved constant?
449 if (D.ConstantValue->getType() != Ty) {
450 GenerateError("Constant expression type different from required type");
451 return 0;
452 }
453 return D.ConstantValue;
454
455 case ValID::InlineAsmVal: { // Inline asm expression
456 const PointerType *PTy = dyn_cast<PointerType>(Ty);
457 const FunctionType *FTy =
458 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
459 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
460 GenerateError("Invalid type for asm constraint string");
461 return 0;
462 }
463 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
464 D.IAD->HasSideEffects);
465 D.destroy(); // Free InlineAsmDescriptor.
466 return IA;
467 }
468 default:
469 assert(0 && "Unhandled case!");
470 return 0;
471 } // End of switch
472
473 assert(0 && "Unhandled case!");
474 return 0;
475}
476
477// getVal - This function is identical to getExistingVal, except that if a
478// value is not already defined, it "improvises" by creating a placeholder var
479// that looks and acts just like the requested variable. When the value is
480// defined later, all uses of the placeholder variable are replaced with the
481// real thing.
482//
483static Value *getVal(const Type *Ty, const ValID &ID) {
484 if (Ty == Type::LabelTy) {
485 GenerateError("Cannot use a basic block here");
486 return 0;
487 }
488
489 // See if the value has already been defined.
490 Value *V = getExistingVal(Ty, ID);
491 if (V) return V;
492 if (TriggerError) return 0;
493
494 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
Dan Gohmane6b1ee62008-05-23 01:55:30 +0000495 GenerateError("Invalid use of a non-first-class type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 return 0;
497 }
498
499 // If we reached here, we referenced either a symbol that we don't know about
500 // or an id number that hasn't been read yet. We may be referencing something
501 // forward, so just create an entry to be resolved later and get to it...
502 //
503 switch (ID.Type) {
504 case ValID::GlobalName:
505 case ValID::GlobalID: {
506 const PointerType *PTy = dyn_cast<PointerType>(Ty);
507 if (!PTy) {
508 GenerateError("Invalid type for reference to global" );
509 return 0;
510 }
511 const Type* ElTy = PTy->getElementType();
512 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
Gabor Greif89f01162008-04-06 23:07:54 +0000513 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 else
Christopher Lamb0a243582007-12-11 09:02:08 +0000515 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
516 (Module*)0, false, PTy->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 break;
518 }
519 default:
520 V = new Argument(Ty);
521 }
522
523 // Remember where this forward reference came from. FIXME, shouldn't we try
524 // to recycle these things??
525 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000526 LLLgetLineNo())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527
528 if (inFunctionScope())
529 InsertValue(V, CurFun.LateResolveValues);
530 else
531 InsertValue(V, CurModule.LateResolveValues);
532 return V;
533}
534
535/// defineBBVal - This is a definition of a new basic block with the specified
536/// identifier which must be the same as CurFun.NextValNum, if its numeric.
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000537static BasicBlock *defineBBVal(const ValID &ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 assert(inFunctionScope() && "Can't get basic block at global scope!");
539
540 BasicBlock *BB = 0;
541
542 // First, see if this was forward referenced
543
544 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
545 if (BBI != CurFun.BBForwardRefs.end()) {
546 BB = BBI->second;
547 // The forward declaration could have been inserted anywhere in the
548 // function: insert it into the correct place now.
549 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
550 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
551
552 // We're about to erase the entry, save the key so we can clean it up.
553 ValID Tmp = BBI->first;
554
555 // Erase the forward ref from the map as its no longer "forward"
556 CurFun.BBForwardRefs.erase(ID);
557
558 // The key has been removed from the map but so we don't want to leave
559 // strdup'd memory around so destroy it too.
560 Tmp.destroy();
561
562 // If its a numbered definition, bump the number and set the BB value.
563 if (ID.Type == ValID::LocalID) {
564 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
565 InsertValue(BB);
566 }
Devang Patel890cc572008-03-03 18:58:47 +0000567 } else {
568 // We haven't seen this BB before and its first mention is a definition.
569 // Just create it and return it.
570 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
Gabor Greif89f01162008-04-06 23:07:54 +0000571 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Devang Patel890cc572008-03-03 18:58:47 +0000572 if (ID.Type == ValID::LocalID) {
573 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
574 InsertValue(BB);
575 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576 }
577
Devang Patel890cc572008-03-03 18:58:47 +0000578 ID.destroy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 return BB;
580}
581
582/// getBBVal - get an existing BB value or create a forward reference for it.
583///
584static BasicBlock *getBBVal(const ValID &ID) {
585 assert(inFunctionScope() && "Can't get basic block at global scope!");
586
587 BasicBlock *BB = 0;
588
589 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
590 if (BBI != CurFun.BBForwardRefs.end()) {
591 BB = BBI->second;
592 } if (ID.Type == ValID::LocalName) {
593 std::string Name = ID.getName();
594 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000595 if (N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 if (N->getType()->getTypeID() == Type::LabelTyID)
597 BB = cast<BasicBlock>(N);
598 else
599 GenerateError("Reference to label '" + Name + "' is actually of type '"+
600 N->getType()->getDescription() + "'");
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000601 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 } else if (ID.Type == ValID::LocalID) {
603 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
604 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
605 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
606 else
607 GenerateError("Reference to label '%" + utostr(ID.Num) +
608 "' is actually of type '"+
609 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
610 }
611 } else {
612 GenerateError("Illegal label reference " + ID.getName());
613 return 0;
614 }
615
616 // If its already been defined, return it now.
617 if (BB) {
618 ID.destroy(); // Free strdup'd memory.
619 return BB;
620 }
621
622 // Otherwise, this block has not been seen before, create it.
623 std::string Name;
624 if (ID.Type == ValID::LocalName)
625 Name = ID.getName();
Gabor Greif89f01162008-04-06 23:07:54 +0000626 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627
628 // Insert it in the forward refs map.
629 CurFun.BBForwardRefs[ID] = BB;
630
631 return BB;
632}
633
634
635//===----------------------------------------------------------------------===//
636// Code to handle forward references in instructions
637//===----------------------------------------------------------------------===//
638//
639// This code handles the late binding needed with statements that reference
640// values not defined yet... for example, a forward branch, or the PHI node for
641// a loop body.
642//
643// This keeps a table (CurFun.LateResolveValues) of all such forward references
644// and back patchs after we are done.
645//
646
647// ResolveDefinitions - If we could not resolve some defs at parsing
648// time (forward branches, phi functions for loops, etc...) resolve the
649// defs now...
650//
651static void
652ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
653 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
654 while (!LateResolvers.empty()) {
655 Value *V = LateResolvers.back();
656 LateResolvers.pop_back();
657
658 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
659 CurModule.PlaceHolderInfo.find(V);
660 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
661
662 ValID &DID = PHI->second.first;
663
664 Value *TheRealValue = getExistingVal(V->getType(), DID);
665 if (TriggerError)
666 return;
667 if (TheRealValue) {
668 V->replaceAllUsesWith(TheRealValue);
669 delete V;
670 CurModule.PlaceHolderInfo.erase(PHI);
671 } else if (FutureLateResolvers) {
672 // Functions have their unresolved items forwarded to the module late
673 // resolver table
674 InsertValue(V, *FutureLateResolvers);
675 } else {
676 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
677 GenerateError("Reference to an invalid definition: '" +DID.getName()+
678 "' of type '" + V->getType()->getDescription() + "'",
679 PHI->second.second);
680 return;
681 } else {
682 GenerateError("Reference to an invalid definition: #" +
683 itostr(DID.Num) + " of type '" +
684 V->getType()->getDescription() + "'",
685 PHI->second.second);
686 return;
687 }
688 }
689 }
690 LateResolvers.clear();
691}
692
693// ResolveTypeTo - A brand new type was just declared. This means that (if
694// name is not null) things referencing Name can be resolved. Otherwise, things
695// refering to the number can be resolved. Do this now.
696//
697static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
698 ValID D;
699 if (Name)
700 D = ValID::createLocalName(*Name);
701 else
702 D = ValID::createLocalID(CurModule.Types.size());
703
704 std::map<ValID, PATypeHolder>::iterator I =
705 CurModule.LateResolveTypes.find(D);
706 if (I != CurModule.LateResolveTypes.end()) {
707 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
708 CurModule.LateResolveTypes.erase(I);
709 }
710}
711
712// setValueName - Set the specified value to the name given. The name may be
713// null potentially, in which case this is a noop. The string passed in is
714// assumed to be a malloc'd string buffer, and is free'd by this function.
715//
716static void setValueName(Value *V, std::string *NameStr) {
717 if (!NameStr) return;
718 std::string Name(*NameStr); // Copy string
719 delete NameStr; // Free old string
720
721 if (V->getType() == Type::VoidTy) {
722 GenerateError("Can't assign name '" + Name+"' to value with void type");
723 return;
724 }
725
726 assert(inFunctionScope() && "Must be in function scope!");
727 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
728 if (ST.lookup(Name)) {
729 GenerateError("Redefinition of value '" + Name + "' of type '" +
730 V->getType()->getDescription() + "'");
731 return;
732 }
733
734 // Set the name.
735 V->setName(Name);
736}
737
738/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
739/// this is a declaration, otherwise it is a definition.
740static GlobalVariable *
741ParseGlobalVariable(std::string *NameStr,
742 GlobalValue::LinkageTypes Linkage,
743 GlobalValue::VisibilityTypes Visibility,
744 bool isConstantGlobal, const Type *Ty,
Christopher Lamb0a243582007-12-11 09:02:08 +0000745 Constant *Initializer, bool IsThreadLocal,
746 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 if (isa<FunctionType>(Ty)) {
748 GenerateError("Cannot declare global vars of function type");
749 return 0;
750 }
Dan Gohmane5febe42008-05-31 00:58:22 +0000751 if (Ty == Type::LabelTy) {
752 GenerateError("Cannot declare global vars of label type");
753 return 0;
754 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755
Christopher Lamb0a243582007-12-11 09:02:08 +0000756 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757
758 std::string Name;
759 if (NameStr) {
760 Name = *NameStr; // Copy string
761 delete NameStr; // Free old string
762 }
763
764 // See if this global value was forward referenced. If so, recycle the
765 // object.
766 ValID ID;
767 if (!Name.empty()) {
768 ID = ValID::createGlobalName(Name);
769 } else {
770 ID = ValID::createGlobalID(CurModule.Values.size());
771 }
772
773 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
774 // Move the global to the end of the list, from whereever it was
775 // previously inserted.
776 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
777 CurModule.CurrentModule->getGlobalList().remove(GV);
778 CurModule.CurrentModule->getGlobalList().push_back(GV);
779 GV->setInitializer(Initializer);
780 GV->setLinkage(Linkage);
781 GV->setVisibility(Visibility);
782 GV->setConstant(isConstantGlobal);
783 GV->setThreadLocal(IsThreadLocal);
784 InsertValue(GV, CurModule.Values);
785 return GV;
786 }
787
788 // If this global has a name
789 if (!Name.empty()) {
790 // if the global we're parsing has an initializer (is a definition) and
791 // has external linkage.
792 if (Initializer && Linkage != GlobalValue::InternalLinkage)
793 // If there is already a global with external linkage with this name
794 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
795 // If we allow this GVar to get created, it will be renamed in the
796 // symbol table because it conflicts with an existing GVar. We can't
797 // allow redefinition of GVars whose linking indicates that their name
798 // must stay the same. Issue the error.
799 GenerateError("Redefinition of global variable named '" + Name +
800 "' of type '" + Ty->getDescription() + "'");
801 return 0;
802 }
803 }
804
805 // Otherwise there is no existing GV to use, create one now.
806 GlobalVariable *GV =
807 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb0a243582007-12-11 09:02:08 +0000808 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 GV->setVisibility(Visibility);
810 InsertValue(GV, CurModule.Values);
811 return GV;
812}
813
814// setTypeName - Set the specified type to the name given. The name may be
815// null potentially, in which case this is a noop. The string passed in is
816// assumed to be a malloc'd string buffer, and is freed by this function.
817//
818// This function returns true if the type has already been defined, but is
819// allowed to be redefined in the specified context. If the name is a new name
820// for the type plane, it is inserted and false is returned.
821static bool setTypeName(const Type *T, std::string *NameStr) {
822 assert(!inFunctionScope() && "Can't give types function-local names!");
823 if (NameStr == 0) return false;
824
825 std::string Name(*NameStr); // Copy string
826 delete NameStr; // Free old string
827
828 // We don't allow assigning names to void type
829 if (T == Type::VoidTy) {
830 GenerateError("Can't assign name '" + Name + "' to the void type");
831 return false;
832 }
833
834 // Set the type name, checking for conflicts as we do so.
835 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
836
837 if (AlreadyExists) { // Inserting a name that is already defined???
838 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
839 assert(Existing && "Conflict but no matching type?!");
840
841 // There is only one case where this is allowed: when we are refining an
842 // opaque type. In this case, Existing will be an opaque type.
843 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
844 // We ARE replacing an opaque type!
845 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
846 return true;
847 }
848
849 // Otherwise, this is an attempt to redefine a type. That's okay if
850 // the redefinition is identical to the original. This will be so if
851 // Existing and T point to the same Type object. In this one case we
852 // allow the equivalent redefinition.
853 if (Existing == T) return true; // Yes, it's equal.
854
855 // Any other kind of (non-equivalent) redefinition is an error.
856 GenerateError("Redefinition of type named '" + Name + "' of type '" +
857 T->getDescription() + "'");
858 }
859
860 return false;
861}
862
863//===----------------------------------------------------------------------===//
864// Code for handling upreferences in type names...
865//
866
867// TypeContains - Returns true if Ty directly contains E in it.
868//
869static bool TypeContains(const Type *Ty, const Type *E) {
870 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
871 E) != Ty->subtype_end();
872}
873
874namespace {
875 struct UpRefRecord {
876 // NestingLevel - The number of nesting levels that need to be popped before
877 // this type is resolved.
878 unsigned NestingLevel;
879
880 // LastContainedTy - This is the type at the current binding level for the
881 // type. Every time we reduce the nesting level, this gets updated.
882 const Type *LastContainedTy;
883
884 // UpRefTy - This is the actual opaque type that the upreference is
885 // represented with.
886 OpaqueType *UpRefTy;
887
888 UpRefRecord(unsigned NL, OpaqueType *URTy)
889 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
890 };
891}
892
893// UpRefs - A list of the outstanding upreferences that need to be resolved.
894static std::vector<UpRefRecord> UpRefs;
895
896/// HandleUpRefs - Every time we finish a new layer of types, this function is
897/// called. It loops through the UpRefs vector, which is a list of the
898/// currently active types. For each type, if the up reference is contained in
899/// the newly completed type, we decrement the level count. When the level
900/// count reaches zero, the upreferenced type is the type that is passed in:
901/// thus we can complete the cycle.
902///
903static PATypeHolder HandleUpRefs(const Type *ty) {
904 // If Ty isn't abstract, or if there are no up-references in it, then there is
905 // nothing to resolve here.
906 if (!ty->isAbstract() || UpRefs.empty()) return ty;
907
908 PATypeHolder Ty(ty);
909 UR_OUT("Type '" << Ty->getDescription() <<
910 "' newly formed. Resolving upreferences.\n" <<
911 UpRefs.size() << " upreferences active!\n");
912
913 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
914 // to zero), we resolve them all together before we resolve them to Ty. At
915 // the end of the loop, if there is anything to resolve to Ty, it will be in
916 // this variable.
917 OpaqueType *TypeToResolve = 0;
918
919 for (unsigned i = 0; i != UpRefs.size(); ++i) {
920 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
921 << UpRefs[i].second->getDescription() << ") = "
922 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
923 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
924 // Decrement level of upreference
925 unsigned Level = --UpRefs[i].NestingLevel;
926 UpRefs[i].LastContainedTy = Ty;
927 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
928 if (Level == 0) { // Upreference should be resolved!
929 if (!TypeToResolve) {
930 TypeToResolve = UpRefs[i].UpRefTy;
931 } else {
932 UR_OUT(" * Resolving upreference for "
933 << UpRefs[i].second->getDescription() << "\n";
934 std::string OldName = UpRefs[i].UpRefTy->getDescription());
935 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
936 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
937 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
938 }
939 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
940 --i; // Do not skip the next element...
941 }
942 }
943 }
944
945 if (TypeToResolve) {
946 UR_OUT(" * Resolving upreference for "
947 << UpRefs[i].second->getDescription() << "\n";
948 std::string OldName = TypeToResolve->getDescription());
949 TypeToResolve->refineAbstractTypeTo(Ty);
950 }
951
952 return Ty;
953}
954
955//===----------------------------------------------------------------------===//
956// RunVMAsmParser - Define an interface to this parser
957//===----------------------------------------------------------------------===//
958//
959static Module* RunParser(Module * M);
960
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000961Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
962 InitLLLexer(MB);
963 Module *M = RunParser(new Module(LLLgetFilename()));
964 FreeLexer();
965 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966}
967
968%}
969
970%union {
971 llvm::Module *ModuleVal;
972 llvm::Function *FunctionVal;
973 llvm::BasicBlock *BasicBlockVal;
974 llvm::TerminatorInst *TermInstVal;
975 llvm::Instruction *InstVal;
976 llvm::Constant *ConstVal;
977
978 const llvm::Type *PrimType;
979 std::list<llvm::PATypeHolder> *TypeList;
980 llvm::PATypeHolder *TypeVal;
981 llvm::Value *ValueVal;
982 std::vector<llvm::Value*> *ValueList;
Dan Gohmane5febe42008-05-31 00:58:22 +0000983 std::vector<unsigned> *ConstantList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 llvm::ArgListType *ArgList;
985 llvm::TypeWithAttrs TypeWithAttrs;
986 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000987 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988
989 // Represent the RHS of PHI node
990 std::list<std::pair<llvm::Value*,
991 llvm::BasicBlock*> > *PHIList;
992 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
993 std::vector<llvm::Constant*> *ConstVector;
994
995 llvm::GlobalValue::LinkageTypes Linkage;
996 llvm::GlobalValue::VisibilityTypes Visibility;
Dale Johannesend915ee52008-02-19 21:40:51 +0000997 llvm::ParameterAttributes ParamAttrs;
Devang Patel5df692d2008-09-02 20:52:40 +0000998 llvm::FunctionNotes FunctionNotes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 llvm::APInt *APIntVal;
1000 int64_t SInt64Val;
1001 uint64_t UInt64Val;
1002 int SIntVal;
1003 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001004 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 bool BoolVal;
1006
1007 std::string *StrVal; // This memory must be deleted
1008 llvm::ValID ValIDVal;
1009
1010 llvm::Instruction::BinaryOps BinaryOpVal;
1011 llvm::Instruction::TermOps TermOpVal;
1012 llvm::Instruction::MemoryOps MemOpVal;
1013 llvm::Instruction::CastOps CastOpVal;
1014 llvm::Instruction::OtherOps OtherOpVal;
1015 llvm::ICmpInst::Predicate IPredicate;
1016 llvm::FCmpInst::Predicate FPredicate;
1017}
1018
1019%type <ModuleVal> Module
1020%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1021%type <BasicBlockVal> BasicBlock InstructionList
1022%type <TermInstVal> BBTerminatorInst
1023%type <InstVal> Inst InstVal MemoryInst
1024%type <ConstVal> ConstVal ConstExpr AliaseeRef
1025%type <ConstVector> ConstVector
1026%type <ArgList> ArgList ArgListH
1027%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001028%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029%type <ValueList> IndexList // For GEP indices
Dan Gohmane5febe42008-05-31 00:58:22 +00001030%type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031%type <TypeList> TypeListI
1032%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1033%type <TypeWithAttrs> ArgType
1034%type <JumpTable> JumpTable
1035%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1036%type <BoolVal> ThreadLocal // 'thread_local' or not
1037%type <BoolVal> OptVolatile // 'volatile' or not
1038%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1039%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1040%type <Linkage> GVInternalLinkage GVExternalLinkage
1041%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1042%type <Linkage> AliasLinkage
1043%type <Visibility> GVVisibilityStyle
1044
1045// ValueRef - Unresolved reference to a definition or BB
1046%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1047%type <ValueVal> ResolvedVal // <type> <valref> pair
Devang Patelbf507402008-02-20 22:40:23 +00001048%type <ValueList> ReturnedVal
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049// Tokens and types for handling constant integer values
1050//
1051// ESINT64VAL - A negative number within long long range
1052%token <SInt64Val> ESINT64VAL
1053
1054// EUINT64VAL - A positive number within uns. long long range
1055%token <UInt64Val> EUINT64VAL
1056
1057// ESAPINTVAL - A negative number with arbitrary precision
1058%token <APIntVal> ESAPINTVAL
1059
1060// EUAPINTVAL - A positive number with arbitrary precision
1061%token <APIntVal> EUAPINTVAL
1062
1063%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1064%token <FPVal> FPVAL // Float or Double constant
1065
1066// Built in types...
1067%type <TypeVal> Types ResultTypes
1068%type <PrimType> IntType FPType PrimType // Classifications
1069%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001070%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071%token TYPE
1072
1073
1074%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1075%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1076%type <StrVal> LocalName OptLocalName OptLocalAssign
1077%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001078%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079
Christopher Lamb668d9a02007-12-12 08:45:45 +00001080%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081
1082%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1083%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1084%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
Dale Johannesen280e7bc2008-05-14 20:13:36 +00001085%token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
Christopher Lamb0a243582007-12-11 09:02:08 +00001086%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1088%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
Dale Johannesen9cdf0652008-08-13 18:41:46 +00001089%token X86_SSECALLCC_TOK
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00001090%token DATALAYOUT
Chris Lattner906773a2008-08-29 17:20:18 +00001091%type <UIntVal> OptCallingConv LocalNumber
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092%type <ParamAttrs> OptParamAttrs ParamAttr
1093%type <ParamAttrs> OptFuncAttrs FuncAttr
Devang Patel5df692d2008-09-02 20:52:40 +00001094%type <FunctionNotes> OptFuncNotes FuncNote
1095%type <FunctionNotes> FuncNoteList
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096
1097// Basic Block Terminating Operators
1098%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1099
1100// Binary Operators
1101%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1102%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1103%token <BinaryOpVal> SHL LSHR ASHR
1104
Nate Begeman646fa482008-05-12 19:01:56 +00001105%token <OtherOpVal> ICMP FCMP VICMP VFCMP
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106%type <IPredicate> IPredicates
1107%type <FPredicate> FPredicates
1108%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1109%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1110
1111// Memory Instructions
1112%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1113
1114// Cast Operators
1115%type <CastOpVal> CastOps
1116%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1117%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1118
1119// Other Operators
1120%token <OtherOpVal> PHI_TOK SELECT VAARG
1121%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Devang Patel3b8849c2008-02-19 22:27:01 +00001122%token <OtherOpVal> GETRESULT
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001123%token <OtherOpVal> EXTRACTVALUE INSERTVALUE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124
1125// Function Attributes
Reid Spenceraa8ae282007-07-31 03:50:36 +00001126%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001127%token READNONE READONLY GC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128
Devang Patel5df692d2008-09-02 20:52:40 +00001129// Function Notes
1130%token FNNOTE INLINE ALWAYS NEVER OPTIMIZEFORSIZE
1131
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132// Visibility Styles
1133%token DEFAULT HIDDEN PROTECTED
1134
1135%start Module
1136%%
1137
1138
1139// Operations that are notably excluded from this list include:
1140// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1141//
1142ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1143LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1144CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1145 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1146
1147IPredicates
1148 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1149 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1150 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1151 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1152 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1153 ;
1154
1155FPredicates
1156 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1157 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1158 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1159 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1160 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1161 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1162 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1163 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1164 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1165 ;
1166
1167// These are some types that allow classification if we only want a particular
1168// thing... for example, only a signed, unsigned, or integral type.
1169IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001170FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171
1172LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1173OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1174
Christopher Lamb668d9a02007-12-12 08:45:45 +00001175OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1176 | /*empty*/ { $$=0; };
1177
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178/// OptLocalAssign - Value producing statements have an optional assignment
1179/// component.
1180OptLocalAssign : LocalName '=' {
1181 $$ = $1;
1182 CHECK_FOR_ERROR
1183 }
1184 | /*empty*/ {
1185 $$ = 0;
1186 CHECK_FOR_ERROR
1187 };
1188
Chris Lattner906773a2008-08-29 17:20:18 +00001189LocalNumber : LOCALVAL_ID '=' {
1190 $$ = $1;
1191 CHECK_FOR_ERROR
1192};
1193
1194
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1196
1197OptGlobalAssign : GlobalAssign
1198 | /*empty*/ {
1199 $$ = 0;
1200 CHECK_FOR_ERROR
1201 };
1202
1203GlobalAssign : GlobalName '=' {
1204 $$ = $1;
1205 CHECK_FOR_ERROR
1206 };
1207
1208GVInternalLinkage
1209 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1210 | WEAK { $$ = GlobalValue::WeakLinkage; }
1211 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1212 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1213 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
Dale Johannesen280e7bc2008-05-14 20:13:36 +00001214 | COMMON { $$ = GlobalValue::CommonLinkage; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 ;
1216
1217GVExternalLinkage
1218 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1219 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1220 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1221 ;
1222
1223GVVisibilityStyle
1224 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1225 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1226 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1227 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1228 ;
1229
1230FunctionDeclareLinkage
1231 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1232 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1233 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1234 ;
1235
1236FunctionDefineLinkage
1237 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1238 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1239 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1240 | WEAK { $$ = GlobalValue::WeakLinkage; }
1241 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1242 ;
1243
1244AliasLinkage
1245 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1246 | WEAK { $$ = GlobalValue::WeakLinkage; }
1247 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1248 ;
1249
1250OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1251 CCC_TOK { $$ = CallingConv::C; } |
1252 FASTCC_TOK { $$ = CallingConv::Fast; } |
1253 COLDCC_TOK { $$ = CallingConv::Cold; } |
1254 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1255 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
Dale Johannesen9cdf0652008-08-13 18:41:46 +00001256 X86_SSECALLCC_TOK { $$ = CallingConv::X86_SSECall; } |
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 CC_TOK EUINT64VAL {
1258 if ((unsigned)$2 != $2)
1259 GEN_ERROR("Calling conv too large");
1260 $$ = $2;
1261 CHECK_FOR_ERROR
1262 };
1263
Reid Spenceraa8ae282007-07-31 03:50:36 +00001264ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1265 | ZEXT { $$ = ParamAttr::ZExt; }
1266 | SIGNEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 | SEXT { $$ = ParamAttr::SExt; }
1268 | INREG { $$ = ParamAttr::InReg; }
1269 | SRET { $$ = ParamAttr::StructRet; }
1270 | NOALIAS { $$ = ParamAttr::NoAlias; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001271 | BYVAL { $$ = ParamAttr::ByVal; }
1272 | NEST { $$ = ParamAttr::Nest; }
Dale Johannesenf92f3162008-02-22 17:50:51 +00001273 | ALIGN EUINT64VAL { $$ =
1274 ParamAttr::constructAlignmentFromInt($2); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 ;
1276
1277OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1278 | OptParamAttrs ParamAttr {
1279 $$ = $1 | $2;
1280 }
1281 ;
1282
1283FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1284 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001285 | ZEROEXT { $$ = ParamAttr::ZExt; }
1286 | SIGNEXT { $$ = ParamAttr::SExt; }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001287 | READNONE { $$ = ParamAttr::ReadNone; }
1288 | READONLY { $$ = ParamAttr::ReadOnly; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 ;
1290
1291OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1292 | OptFuncAttrs FuncAttr {
1293 $$ = $1 | $2;
1294 }
1295 ;
1296
Devang Patel5df692d2008-09-02 20:52:40 +00001297FuncNoteList : FuncNote { $$ = $1; }
1298 | FuncNoteList ',' FuncNote {
1299 FunctionNotes tmp = $1 | $3;
1300 if ($3 == FP_NoInline && ($1 & FP_AlwaysInline))
1301 GEN_ERROR("Function Notes may include only one inline notes!")
1302 if ($3 == FP_AlwaysInline && ($1 & FP_NoInline))
1303 GEN_ERROR("Function Notes may include only one inline notes!")
1304 $$ = tmp;
1305 CHECK_FOR_ERROR
1306 }
1307 ;
1308
1309FuncNote : INLINE '=' NEVER { $$ = FP_NoInline; }
1310 | INLINE '=' ALWAYS { $$ = FP_AlwaysInline; }
1311 | OPTIMIZEFORSIZE { $$ = FP_OptimizeForSize; }
1312 ;
1313
1314OptFuncNotes : /* empty */ { $$ = FP_None; }
1315 | FNNOTE '(' FuncNoteList ')' {
1316 $$ = $3;
1317 }
1318 ;
1319
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001320OptGC : /* empty */ { $$ = 0; }
1321 | GC STRINGCONSTANT {
1322 $$ = $2;
1323 }
1324 ;
1325
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1327// a comma before it.
1328OptAlign : /*empty*/ { $$ = 0; } |
1329 ALIGN EUINT64VAL {
1330 $$ = $2;
1331 if ($$ != 0 && !isPowerOf2_32($$))
1332 GEN_ERROR("Alignment must be a power of two");
1333 CHECK_FOR_ERROR
1334};
1335OptCAlign : /*empty*/ { $$ = 0; } |
1336 ',' ALIGN EUINT64VAL {
1337 $$ = $3;
1338 if ($$ != 0 && !isPowerOf2_32($$))
1339 GEN_ERROR("Alignment must be a power of two");
1340 CHECK_FOR_ERROR
1341};
1342
1343
Christopher Lamb0a243582007-12-11 09:02:08 +00001344
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345SectionString : SECTION STRINGCONSTANT {
1346 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1347 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1348 GEN_ERROR("Invalid character in section name");
1349 $$ = $2;
1350 CHECK_FOR_ERROR
1351};
1352
1353OptSection : /*empty*/ { $$ = 0; } |
1354 SectionString { $$ = $1; };
1355
1356// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1357// is set to be the global we are processing.
1358//
1359GlobalVarAttributes : /* empty */ {} |
1360 ',' GlobalVarAttribute GlobalVarAttributes {};
1361GlobalVarAttribute : SectionString {
1362 CurGV->setSection(*$1);
1363 delete $1;
1364 CHECK_FOR_ERROR
1365 }
1366 | ALIGN EUINT64VAL {
1367 if ($2 != 0 && !isPowerOf2_32($2))
1368 GEN_ERROR("Alignment must be a power of two");
1369 CurGV->setAlignment($2);
1370 CHECK_FOR_ERROR
1371 };
1372
1373//===----------------------------------------------------------------------===//
1374// Types includes all predefined types... except void, because it can only be
1375// used in specific contexts (function returning void for example).
1376
1377// Derived types are added later...
1378//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001379PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380
1381Types
1382 : OPAQUE {
1383 $$ = new PATypeHolder(OpaqueType::get());
1384 CHECK_FOR_ERROR
1385 }
1386 | PrimType {
1387 $$ = new PATypeHolder($1);
1388 CHECK_FOR_ERROR
1389 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00001390 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 if (*$1 == Type::LabelTy)
1392 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb668d9a02007-12-12 08:45:45 +00001393 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb0a243582007-12-11 09:02:08 +00001394 delete $1;
1395 CHECK_FOR_ERROR
1396 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 | SymbolicValueRef { // Named types are also simple types...
1398 const Type* tmp = getTypeVal($1);
1399 CHECK_FOR_ERROR
1400 $$ = new PATypeHolder(tmp);
1401 }
1402 | '\\' EUINT64VAL { // Type UpReference
1403 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1404 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1405 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1406 $$ = new PATypeHolder(OT);
1407 UR_OUT("New Upreference!\n");
1408 CHECK_FOR_ERROR
1409 }
1410 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001411 // Allow but ignore attributes on function types; this permits auto-upgrade.
1412 // FIXME: remove in LLVM 3.0.
Chris Lattner73de3c02008-04-23 05:37:08 +00001413 const Type *RetTy = *$1;
1414 if (!FunctionType::isValidReturnType(RetTy))
1415 GEN_ERROR("Invalid result type for LLVM function");
1416
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001419 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 const Type *Ty = I->Ty->get();
1421 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1425 if (isVarArg) Params.pop_back();
1426
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001427 for (unsigned i = 0; i != Params.size(); ++i)
1428 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1429 GEN_ERROR("Function arguments must be value types!");
1430
1431 CHECK_FOR_ERROR
1432
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001433 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 delete $3; // Delete the argument list
1435 delete $1; // Delete the return type handle
1436 $$ = new PATypeHolder(HandleUpRefs(FT));
1437 CHECK_FOR_ERROR
1438 }
1439 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001440 // Allow but ignore attributes on function types; this permits auto-upgrade.
1441 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001444 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445 const Type* Ty = I->Ty->get();
1446 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001448
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1450 if (isVarArg) Params.pop_back();
1451
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001452 for (unsigned i = 0; i != Params.size(); ++i)
1453 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1454 GEN_ERROR("Function arguments must be value types!");
1455
1456 CHECK_FOR_ERROR
1457
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001458 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 delete $3; // Delete the argument list
1460 $$ = new PATypeHolder(HandleUpRefs(FT));
1461 CHECK_FOR_ERROR
1462 }
1463
1464 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
Dan Gohmane5febe42008-05-31 00:58:22 +00001465 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001466 delete $4;
1467 CHECK_FOR_ERROR
1468 }
1469 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1470 const llvm::Type* ElemTy = $4->get();
1471 if ((unsigned)$2 != $2)
1472 GEN_ERROR("Unsigned result not equal to signed result");
1473 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1474 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1476 delete $4;
1477 CHECK_FOR_ERROR
1478 }
1479 | '{' TypeListI '}' { // Structure type?
1480 std::vector<const Type*> Elements;
1481 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1482 E = $2->end(); I != E; ++I)
1483 Elements.push_back(*I);
1484
1485 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1486 delete $2;
1487 CHECK_FOR_ERROR
1488 }
1489 | '{' '}' { // Empty structure type?
1490 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1491 CHECK_FOR_ERROR
1492 }
1493 | '<' '{' TypeListI '}' '>' {
1494 std::vector<const Type*> Elements;
1495 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1496 E = $3->end(); I != E; ++I)
1497 Elements.push_back(*I);
1498
1499 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1500 delete $3;
1501 CHECK_FOR_ERROR
1502 }
1503 | '<' '{' '}' '>' { // Empty structure type?
1504 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1505 CHECK_FOR_ERROR
1506 }
1507 ;
1508
1509ArgType
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001510 : Types OptParamAttrs {
1511 // Allow but ignore attributes on function types; this permits auto-upgrade.
1512 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 $$.Ty = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001514 $$.Attrs = ParamAttr::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 }
1516 ;
1517
1518ResultTypes
1519 : Types {
1520 if (!UpRefs.empty())
1521 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Devang Patel3d5a1e862008-02-23 01:17:37 +00001522 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 GEN_ERROR("LLVM functions cannot return aggregate types");
1524 $$ = $1;
1525 }
1526 | VOID {
1527 $$ = new PATypeHolder(Type::VoidTy);
1528 }
1529 ;
1530
1531ArgTypeList : ArgType {
1532 $$ = new TypeWithAttrsList();
1533 $$->push_back($1);
1534 CHECK_FOR_ERROR
1535 }
1536 | ArgTypeList ',' ArgType {
1537 ($$=$1)->push_back($3);
1538 CHECK_FOR_ERROR
1539 }
1540 ;
1541
1542ArgTypeListI
1543 : ArgTypeList
1544 | ArgTypeList ',' DOTDOTDOT {
1545 $$=$1;
1546 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1547 TWA.Ty = new PATypeHolder(Type::VoidTy);
1548 $$->push_back(TWA);
1549 CHECK_FOR_ERROR
1550 }
1551 | DOTDOTDOT {
1552 $$ = new TypeWithAttrsList;
1553 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1554 TWA.Ty = new PATypeHolder(Type::VoidTy);
1555 $$->push_back(TWA);
1556 CHECK_FOR_ERROR
1557 }
1558 | /*empty*/ {
1559 $$ = new TypeWithAttrsList();
1560 CHECK_FOR_ERROR
1561 };
1562
1563// TypeList - Used for struct declarations and as a basis for function type
1564// declaration type lists
1565//
1566TypeListI : Types {
1567 $$ = new std::list<PATypeHolder>();
1568 $$->push_back(*$1);
1569 delete $1;
1570 CHECK_FOR_ERROR
1571 }
1572 | TypeListI ',' Types {
1573 ($$=$1)->push_back(*$3);
1574 delete $3;
1575 CHECK_FOR_ERROR
1576 };
1577
1578// ConstVal - The various declarations that go into the constant pool. This
1579// production is used ONLY to represent constants that show up AFTER a 'const',
1580// 'constant' or 'global' token at global scope. Constants that can be inlined
1581// into other expressions (such as integers and constexprs) are handled by the
1582// ResolvedVal, ValueRef and ConstValueRef productions.
1583//
1584ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1585 if (!UpRefs.empty())
1586 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1587 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1588 if (ATy == 0)
1589 GEN_ERROR("Cannot make array constant with type: '" +
1590 (*$1)->getDescription() + "'");
1591 const Type *ETy = ATy->getElementType();
Dan Gohman7185e4b2008-06-23 18:43:26 +00001592 uint64_t NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593
1594 // Verify that we have the correct size...
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001595 if (NumElements != uint64_t(-1) && NumElements != $3->size())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1597 utostr($3->size()) + " arguments, but has size of " +
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001598 utostr(NumElements) + "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599
1600 // Verify all elements are correct type!
1601 for (unsigned i = 0; i < $3->size(); i++) {
1602 if (ETy != (*$3)[i]->getType())
1603 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1604 ETy->getDescription() +"' as required!\nIt is of type '"+
1605 (*$3)[i]->getType()->getDescription() + "'.");
1606 }
1607
1608 $$ = ConstantArray::get(ATy, *$3);
1609 delete $1; delete $3;
1610 CHECK_FOR_ERROR
1611 }
1612 | Types '[' ']' {
1613 if (!UpRefs.empty())
1614 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1615 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1616 if (ATy == 0)
1617 GEN_ERROR("Cannot make array constant with type: '" +
1618 (*$1)->getDescription() + "'");
1619
Dan Gohman7185e4b2008-06-23 18:43:26 +00001620 uint64_t NumElements = ATy->getNumElements();
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001621 if (NumElements != uint64_t(-1) && NumElements != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001623 " arguments, but has size of " + utostr(NumElements) +"");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1625 delete $1;
1626 CHECK_FOR_ERROR
1627 }
1628 | Types 'c' STRINGCONSTANT {
1629 if (!UpRefs.empty())
1630 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1631 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1632 if (ATy == 0)
1633 GEN_ERROR("Cannot make array constant with type: '" +
1634 (*$1)->getDescription() + "'");
1635
Dan Gohman7185e4b2008-06-23 18:43:26 +00001636 uint64_t NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637 const Type *ETy = ATy->getElementType();
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001638 if (NumElements != uint64_t(-1) && NumElements != $3->length())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639 GEN_ERROR("Can't build string constant of size " +
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001640 utostr($3->length()) +
1641 " when array has size " + utostr(NumElements) + "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642 std::vector<Constant*> Vals;
1643 if (ETy == Type::Int8Ty) {
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001644 for (uint64_t i = 0; i < $3->length(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1646 } else {
1647 delete $3;
1648 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1649 }
1650 delete $3;
1651 $$ = ConstantArray::get(ATy, Vals);
1652 delete $1;
1653 CHECK_FOR_ERROR
1654 }
1655 | Types '<' ConstVector '>' { // Nonempty unsized arr
1656 if (!UpRefs.empty())
1657 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1658 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1659 if (PTy == 0)
1660 GEN_ERROR("Cannot make packed constant with type: '" +
1661 (*$1)->getDescription() + "'");
1662 const Type *ETy = PTy->getElementType();
Dan Gohman7185e4b2008-06-23 18:43:26 +00001663 unsigned NumElements = PTy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001664
1665 // Verify that we have the correct size...
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001666 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001667 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1668 utostr($3->size()) + " arguments, but has size of " +
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001669 utostr(NumElements) + "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670
1671 // Verify all elements are correct type!
1672 for (unsigned i = 0; i < $3->size(); i++) {
1673 if (ETy != (*$3)[i]->getType())
1674 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1675 ETy->getDescription() +"' as required!\nIt is of type '"+
1676 (*$3)[i]->getType()->getDescription() + "'.");
1677 }
1678
1679 $$ = ConstantVector::get(PTy, *$3);
1680 delete $1; delete $3;
1681 CHECK_FOR_ERROR
1682 }
1683 | Types '{' ConstVector '}' {
1684 const StructType *STy = dyn_cast<StructType>($1->get());
1685 if (STy == 0)
1686 GEN_ERROR("Cannot make struct constant with type: '" +
1687 (*$1)->getDescription() + "'");
1688
1689 if ($3->size() != STy->getNumContainedTypes())
1690 GEN_ERROR("Illegal number of initializers for structure type");
1691
1692 // Check to ensure that constants are compatible with the type initializer!
1693 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1694 if ((*$3)[i]->getType() != STy->getElementType(i))
1695 GEN_ERROR("Expected type '" +
1696 STy->getElementType(i)->getDescription() +
1697 "' for element #" + utostr(i) +
1698 " of structure initializer");
1699
1700 // Check to ensure that Type is not packed
1701 if (STy->isPacked())
1702 GEN_ERROR("Unpacked Initializer to vector type '" +
1703 STy->getDescription() + "'");
1704
1705 $$ = ConstantStruct::get(STy, *$3);
1706 delete $1; delete $3;
1707 CHECK_FOR_ERROR
1708 }
1709 | Types '{' '}' {
1710 if (!UpRefs.empty())
1711 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1712 const StructType *STy = dyn_cast<StructType>($1->get());
1713 if (STy == 0)
1714 GEN_ERROR("Cannot make struct constant with type: '" +
1715 (*$1)->getDescription() + "'");
1716
1717 if (STy->getNumContainedTypes() != 0)
1718 GEN_ERROR("Illegal number of initializers for structure type");
1719
1720 // Check to ensure that Type is not packed
1721 if (STy->isPacked())
1722 GEN_ERROR("Unpacked Initializer to vector type '" +
1723 STy->getDescription() + "'");
1724
1725 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1726 delete $1;
1727 CHECK_FOR_ERROR
1728 }
1729 | Types '<' '{' ConstVector '}' '>' {
1730 const StructType *STy = dyn_cast<StructType>($1->get());
1731 if (STy == 0)
1732 GEN_ERROR("Cannot make struct constant with type: '" +
1733 (*$1)->getDescription() + "'");
1734
1735 if ($4->size() != STy->getNumContainedTypes())
1736 GEN_ERROR("Illegal number of initializers for structure type");
1737
1738 // Check to ensure that constants are compatible with the type initializer!
1739 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1740 if ((*$4)[i]->getType() != STy->getElementType(i))
1741 GEN_ERROR("Expected type '" +
1742 STy->getElementType(i)->getDescription() +
1743 "' for element #" + utostr(i) +
1744 " of structure initializer");
1745
1746 // Check to ensure that Type is packed
1747 if (!STy->isPacked())
1748 GEN_ERROR("Vector initializer to non-vector type '" +
1749 STy->getDescription() + "'");
1750
1751 $$ = ConstantStruct::get(STy, *$4);
1752 delete $1; delete $4;
1753 CHECK_FOR_ERROR
1754 }
1755 | Types '<' '{' '}' '>' {
1756 if (!UpRefs.empty())
1757 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1758 const StructType *STy = dyn_cast<StructType>($1->get());
1759 if (STy == 0)
1760 GEN_ERROR("Cannot make struct constant with type: '" +
1761 (*$1)->getDescription() + "'");
1762
1763 if (STy->getNumContainedTypes() != 0)
1764 GEN_ERROR("Illegal number of initializers for structure type");
1765
1766 // Check to ensure that Type is packed
1767 if (!STy->isPacked())
1768 GEN_ERROR("Vector initializer to non-vector type '" +
1769 STy->getDescription() + "'");
1770
1771 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1772 delete $1;
1773 CHECK_FOR_ERROR
1774 }
1775 | Types NULL_TOK {
1776 if (!UpRefs.empty())
1777 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1778 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1779 if (PTy == 0)
1780 GEN_ERROR("Cannot make null pointer constant with type: '" +
1781 (*$1)->getDescription() + "'");
1782
1783 $$ = ConstantPointerNull::get(PTy);
1784 delete $1;
1785 CHECK_FOR_ERROR
1786 }
1787 | Types UNDEF {
1788 if (!UpRefs.empty())
1789 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1790 $$ = UndefValue::get($1->get());
1791 delete $1;
1792 CHECK_FOR_ERROR
1793 }
1794 | Types SymbolicValueRef {
1795 if (!UpRefs.empty())
1796 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1797 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1798 if (Ty == 0)
Devang Patel3b8849c2008-02-19 22:27:01 +00001799 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800
1801 // ConstExprs can exist in the body of a function, thus creating
1802 // GlobalValues whenever they refer to a variable. Because we are in
1803 // the context of a function, getExistingVal will search the functions
1804 // symbol table instead of the module symbol table for the global symbol,
1805 // which throws things all off. To get around this, we just tell
1806 // getExistingVal that we are at global scope here.
1807 //
1808 Function *SavedCurFn = CurFun.CurrentFunction;
1809 CurFun.CurrentFunction = 0;
1810
1811 Value *V = getExistingVal(Ty, $2);
1812 CHECK_FOR_ERROR
1813
1814 CurFun.CurrentFunction = SavedCurFn;
1815
1816 // If this is an initializer for a constant pointer, which is referencing a
1817 // (currently) undefined variable, create a stub now that shall be replaced
1818 // in the future with the right type of variable.
1819 //
1820 if (V == 0) {
1821 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1822 const PointerType *PT = cast<PointerType>(Ty);
1823
1824 // First check to see if the forward references value is already created!
1825 PerModuleInfo::GlobalRefsType::iterator I =
1826 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1827
1828 if (I != CurModule.GlobalRefs.end()) {
1829 V = I->second; // Placeholder already exists, use it...
1830 $2.destroy();
1831 } else {
1832 std::string Name;
1833 if ($2.Type == ValID::GlobalName)
1834 Name = $2.getName();
1835 else if ($2.Type != ValID::GlobalID)
1836 GEN_ERROR("Invalid reference to global");
1837
1838 // Create the forward referenced global.
1839 GlobalValue *GV;
1840 if (const FunctionType *FTy =
1841 dyn_cast<FunctionType>(PT->getElementType())) {
Gabor Greif89f01162008-04-06 23:07:54 +00001842 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1843 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001844 } else {
1845 GV = new GlobalVariable(PT->getElementType(), false,
1846 GlobalValue::ExternalWeakLinkage, 0,
1847 Name, CurModule.CurrentModule);
1848 }
1849
1850 // Keep track of the fact that we have a forward ref to recycle it
1851 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1852 V = GV;
1853 }
1854 }
1855
1856 $$ = cast<GlobalValue>(V);
1857 delete $1; // Free the type handle
1858 CHECK_FOR_ERROR
1859 }
1860 | Types ConstExpr {
1861 if (!UpRefs.empty())
1862 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1863 if ($1->get() != $2->getType())
1864 GEN_ERROR("Mismatched types for constant expression: " +
1865 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1866 $$ = $2;
1867 delete $1;
1868 CHECK_FOR_ERROR
1869 }
1870 | Types ZEROINITIALIZER {
1871 if (!UpRefs.empty())
1872 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1873 const Type *Ty = $1->get();
1874 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1875 GEN_ERROR("Cannot create a null initialized value of this type");
1876 $$ = Constant::getNullValue(Ty);
1877 delete $1;
1878 CHECK_FOR_ERROR
1879 }
1880 | IntType ESINT64VAL { // integral constants
1881 if (!ConstantInt::isValueValidForType($1, $2))
1882 GEN_ERROR("Constant value doesn't fit in type");
1883 $$ = ConstantInt::get($1, $2, true);
1884 CHECK_FOR_ERROR
1885 }
1886 | IntType ESAPINTVAL { // arbitrary precision integer constants
1887 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1888 if ($2->getBitWidth() > BitWidth) {
1889 GEN_ERROR("Constant value does not fit in type");
1890 }
1891 $2->sextOrTrunc(BitWidth);
1892 $$ = ConstantInt::get(*$2);
1893 delete $2;
1894 CHECK_FOR_ERROR
1895 }
1896 | IntType EUINT64VAL { // integral constants
1897 if (!ConstantInt::isValueValidForType($1, $2))
1898 GEN_ERROR("Constant value doesn't fit in type");
1899 $$ = ConstantInt::get($1, $2, false);
1900 CHECK_FOR_ERROR
1901 }
1902 | IntType EUAPINTVAL { // arbitrary precision integer constants
1903 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1904 if ($2->getBitWidth() > BitWidth) {
1905 GEN_ERROR("Constant value does not fit in type");
1906 }
1907 $2->zextOrTrunc(BitWidth);
1908 $$ = ConstantInt::get(*$2);
1909 delete $2;
1910 CHECK_FOR_ERROR
1911 }
1912 | INTTYPE TRUETOK { // Boolean constants
Dan Gohmane5febe42008-05-31 00:58:22 +00001913 if (cast<IntegerType>($1)->getBitWidth() != 1)
1914 GEN_ERROR("Constant true must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001915 $$ = ConstantInt::getTrue();
1916 CHECK_FOR_ERROR
1917 }
1918 | INTTYPE FALSETOK { // Boolean constants
Dan Gohmane5febe42008-05-31 00:58:22 +00001919 if (cast<IntegerType>($1)->getBitWidth() != 1)
1920 GEN_ERROR("Constant false must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001921 $$ = ConstantInt::getFalse();
1922 CHECK_FOR_ERROR
1923 }
Dale Johannesen043064d2007-09-12 03:31:28 +00001924 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001925 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001926 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen255b8fe2007-09-11 18:33:39 +00001927 // Lexer has no type info, so builds all float and double FP constants
1928 // as double. Fix this here. Long double is done right.
1929 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001930 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner05ba86e2008-04-20 00:41:19 +00001931 $$ = ConstantFP::get(*$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001932 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001933 CHECK_FOR_ERROR
1934 };
1935
1936
1937ConstExpr: CastOps '(' ConstVal TO Types ')' {
1938 if (!UpRefs.empty())
1939 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1940 Constant *Val = $3;
1941 const Type *DestTy = $5->get();
1942 if (!CastInst::castIsValid($1, $3, DestTy))
1943 GEN_ERROR("invalid cast opcode for cast from '" +
1944 Val->getType()->getDescription() + "' to '" +
1945 DestTy->getDescription() + "'");
1946 $$ = ConstantExpr::getCast($1, $3, DestTy);
1947 delete $5;
1948 }
1949 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1950 if (!isa<PointerType>($3->getType()))
1951 GEN_ERROR("GetElementPtr requires a pointer operand");
1952
1953 const Type *IdxTy =
Dan Gohman8055f772008-05-15 19:50:34 +00001954 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001955 if (!IdxTy)
1956 GEN_ERROR("Index list invalid for constant getelementptr");
1957
1958 SmallVector<Constant*, 8> IdxVec;
1959 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1960 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1961 IdxVec.push_back(C);
1962 else
1963 GEN_ERROR("Indices to constant getelementptr must be constants");
1964
1965 delete $4;
1966
1967 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1968 CHECK_FOR_ERROR
1969 }
1970 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1971 if ($3->getType() != Type::Int1Ty)
1972 GEN_ERROR("Select condition must be of boolean type");
1973 if ($5->getType() != $7->getType())
1974 GEN_ERROR("Select operand types must match");
1975 $$ = ConstantExpr::getSelect($3, $5, $7);
1976 CHECK_FOR_ERROR
1977 }
1978 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1979 if ($3->getType() != $5->getType())
1980 GEN_ERROR("Binary operator types must match");
1981 CHECK_FOR_ERROR;
1982 $$ = ConstantExpr::get($1, $3, $5);
1983 }
1984 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1985 if ($3->getType() != $5->getType())
1986 GEN_ERROR("Logical operator types must match");
1987 if (!$3->getType()->isInteger()) {
Nate Begemanbb1ce942008-07-29 15:49:41 +00001988 if (!isa<VectorType>($3->getType()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1990 GEN_ERROR("Logical operator requires integral operands");
1991 }
1992 $$ = ConstantExpr::get($1, $3, $5);
1993 CHECK_FOR_ERROR
1994 }
1995 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1996 if ($4->getType() != $6->getType())
1997 GEN_ERROR("icmp operand types must match");
1998 $$ = ConstantExpr::getICmp($2, $4, $6);
1999 }
2000 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2001 if ($4->getType() != $6->getType())
2002 GEN_ERROR("fcmp operand types must match");
2003 $$ = ConstantExpr::getFCmp($2, $4, $6);
2004 }
Nate Begeman646fa482008-05-12 19:01:56 +00002005 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2006 if ($4->getType() != $6->getType())
2007 GEN_ERROR("vicmp operand types must match");
2008 $$ = ConstantExpr::getVICmp($2, $4, $6);
2009 }
2010 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2011 if ($4->getType() != $6->getType())
2012 GEN_ERROR("vfcmp operand types must match");
2013 $$ = ConstantExpr::getVFCmp($2, $4, $6);
2014 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002015 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2016 if (!ExtractElementInst::isValidOperands($3, $5))
2017 GEN_ERROR("Invalid extractelement operands");
2018 $$ = ConstantExpr::getExtractElement($3, $5);
2019 CHECK_FOR_ERROR
2020 }
2021 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2022 if (!InsertElementInst::isValidOperands($3, $5, $7))
2023 GEN_ERROR("Invalid insertelement operands");
2024 $$ = ConstantExpr::getInsertElement($3, $5, $7);
2025 CHECK_FOR_ERROR
2026 }
2027 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2028 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2029 GEN_ERROR("Invalid shufflevector operands");
2030 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2031 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002032 }
Dan Gohmane5febe42008-05-31 00:58:22 +00002033 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002034 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2035 GEN_ERROR("ExtractValue requires an aggregate operand");
2036
Dan Gohmane5febe42008-05-31 00:58:22 +00002037 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002038 delete $4;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002039 CHECK_FOR_ERROR
2040 }
Dan Gohmane5febe42008-05-31 00:58:22 +00002041 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002042 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2043 GEN_ERROR("InsertValue requires an aggregate operand");
2044
Dan Gohmane5febe42008-05-31 00:58:22 +00002045 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002046 delete $6;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002047 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 };
2049
2050
2051// ConstVector - A list of comma separated constants.
2052ConstVector : ConstVector ',' ConstVal {
2053 ($$ = $1)->push_back($3);
2054 CHECK_FOR_ERROR
2055 }
2056 | ConstVal {
2057 $$ = new std::vector<Constant*>();
2058 $$->push_back($1);
2059 CHECK_FOR_ERROR
2060 };
2061
2062
2063// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2064GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2065
2066// ThreadLocal
2067ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2068
2069// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2070AliaseeRef : ResultTypes SymbolicValueRef {
2071 const Type* VTy = $1->get();
2072 Value *V = getVal(VTy, $2);
Chris Lattnerbb856a32007-08-06 21:00:46 +00002073 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002074 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2075 if (!Aliasee)
2076 GEN_ERROR("Aliases can be created only to global values");
2077
2078 $$ = Aliasee;
2079 CHECK_FOR_ERROR
2080 delete $1;
2081 }
2082 | BITCAST '(' AliaseeRef TO Types ')' {
2083 Constant *Val = $3;
2084 const Type *DestTy = $5->get();
2085 if (!CastInst::castIsValid($1, $3, DestTy))
2086 GEN_ERROR("invalid cast opcode for cast from '" +
2087 Val->getType()->getDescription() + "' to '" +
2088 DestTy->getDescription() + "'");
2089
2090 $$ = ConstantExpr::getCast($1, $3, DestTy);
2091 CHECK_FOR_ERROR
2092 delete $5;
2093 };
2094
2095//===----------------------------------------------------------------------===//
2096// Rules to match Modules
2097//===----------------------------------------------------------------------===//
2098
2099// Module rule: Capture the result of parsing the whole file into a result
2100// variable...
2101//
2102Module
2103 : DefinitionList {
2104 $$ = ParserResult = CurModule.CurrentModule;
2105 CurModule.ModuleDone();
2106 CHECK_FOR_ERROR;
2107 }
2108 | /*empty*/ {
2109 $$ = ParserResult = CurModule.CurrentModule;
2110 CurModule.ModuleDone();
2111 CHECK_FOR_ERROR;
2112 }
2113 ;
2114
2115DefinitionList
2116 : Definition
2117 | DefinitionList Definition
2118 ;
2119
2120Definition
2121 : DEFINE { CurFun.isDeclare = false; } Function {
2122 CurFun.FunctionDone();
2123 CHECK_FOR_ERROR
2124 }
2125 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2126 CHECK_FOR_ERROR
2127 }
2128 | MODULE ASM_TOK AsmBlock {
2129 CHECK_FOR_ERROR
2130 }
2131 | OptLocalAssign TYPE Types {
2132 if (!UpRefs.empty())
2133 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2134 // Eagerly resolve types. This is not an optimization, this is a
2135 // requirement that is due to the fact that we could have this:
2136 //
2137 // %list = type { %list * }
2138 // %list = type { %list * } ; repeated type decl
2139 //
2140 // If types are not resolved eagerly, then the two types will not be
2141 // determined to be the same type!
2142 //
2143 ResolveTypeTo($1, *$3);
2144
2145 if (!setTypeName(*$3, $1) && !$1) {
2146 CHECK_FOR_ERROR
2147 // If this is a named type that is not a redefinition, add it to the slot
2148 // table.
2149 CurModule.Types.push_back(*$3);
2150 }
2151
2152 delete $3;
2153 CHECK_FOR_ERROR
2154 }
2155 | OptLocalAssign TYPE VOID {
2156 ResolveTypeTo($1, $3);
2157
2158 if (!setTypeName($3, $1) && !$1) {
2159 CHECK_FOR_ERROR
2160 // If this is a named type that is not a redefinition, add it to the slot
2161 // table.
2162 CurModule.Types.push_back($3);
2163 }
2164 CHECK_FOR_ERROR
2165 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00002166 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2167 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168 /* "Externally Visible" Linkage */
2169 if ($5 == 0)
2170 GEN_ERROR("Global value initializer is not a constant");
2171 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb668d9a02007-12-12 08:45:45 +00002172 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb0a243582007-12-11 09:02:08 +00002173 CHECK_FOR_ERROR
2174 } GlobalVarAttributes {
2175 CurGV = 0;
2176 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002178 ConstVal OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002179 if ($6 == 0)
2180 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb668d9a02007-12-12 08:45:45 +00002181 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002182 CHECK_FOR_ERROR
2183 } GlobalVarAttributes {
2184 CurGV = 0;
2185 }
2186 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002187 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 if (!UpRefs.empty())
2189 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb668d9a02007-12-12 08:45:45 +00002190 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002191 CHECK_FOR_ERROR
2192 delete $6;
2193 } GlobalVarAttributes {
2194 CurGV = 0;
2195 CHECK_FOR_ERROR
2196 }
2197 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2198 std::string Name;
2199 if ($1) {
2200 Name = *$1;
2201 delete $1;
2202 }
2203 if (Name.empty())
2204 GEN_ERROR("Alias name cannot be empty");
2205
2206 Constant* Aliasee = $5;
2207 if (Aliasee == 0)
2208 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2209
2210 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2211 CurModule.CurrentModule);
2212 GA->setVisibility($2);
2213 InsertValue(GA, CurModule.Values);
Chris Lattner5eefce32007-09-10 23:24:14 +00002214
2215
2216 // If there was a forward reference of this alias, resolve it now.
2217
2218 ValID ID;
2219 if (!Name.empty())
2220 ID = ValID::createGlobalName(Name);
2221 else
2222 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2223
2224 if (GlobalValue *FWGV =
2225 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2226 // Replace uses of the fwdref with the actual alias.
2227 FWGV->replaceAllUsesWith(GA);
2228 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2229 GV->eraseFromParent();
2230 else
2231 cast<Function>(FWGV)->eraseFromParent();
2232 }
2233 ID.destroy();
2234
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 CHECK_FOR_ERROR
2236 }
2237 | TARGET TargetDefinition {
2238 CHECK_FOR_ERROR
2239 }
2240 | DEPLIBS '=' LibrariesDefinition {
2241 CHECK_FOR_ERROR
2242 }
2243 ;
2244
2245
2246AsmBlock : STRINGCONSTANT {
2247 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2248 if (AsmSoFar.empty())
2249 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2250 else
2251 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2252 delete $1;
2253 CHECK_FOR_ERROR
2254};
2255
2256TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2257 CurModule.CurrentModule->setTargetTriple(*$3);
2258 delete $3;
2259 }
2260 | DATALAYOUT '=' STRINGCONSTANT {
2261 CurModule.CurrentModule->setDataLayout(*$3);
2262 delete $3;
2263 };
2264
2265LibrariesDefinition : '[' LibList ']';
2266
2267LibList : LibList ',' STRINGCONSTANT {
2268 CurModule.CurrentModule->addLibrary(*$3);
2269 delete $3;
2270 CHECK_FOR_ERROR
2271 }
2272 | STRINGCONSTANT {
2273 CurModule.CurrentModule->addLibrary(*$1);
2274 delete $1;
2275 CHECK_FOR_ERROR
2276 }
2277 | /* empty: end of list */ {
2278 CHECK_FOR_ERROR
2279 }
2280 ;
2281
2282//===----------------------------------------------------------------------===//
2283// Rules to match Function Headers
2284//===----------------------------------------------------------------------===//
2285
2286ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2287 if (!UpRefs.empty())
2288 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00002289 if (!(*$3)->isFirstClassType())
2290 GEN_ERROR("Argument types must be first-class");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2292 $$ = $1;
2293 $1->push_back(E);
2294 CHECK_FOR_ERROR
2295 }
2296 | Types OptParamAttrs OptLocalName {
2297 if (!UpRefs.empty())
2298 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00002299 if (!(*$1)->isFirstClassType())
2300 GEN_ERROR("Argument types must be first-class");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002301 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2302 $$ = new ArgListType;
2303 $$->push_back(E);
2304 CHECK_FOR_ERROR
2305 };
2306
2307ArgList : ArgListH {
2308 $$ = $1;
2309 CHECK_FOR_ERROR
2310 }
2311 | ArgListH ',' DOTDOTDOT {
2312 $$ = $1;
2313 struct ArgListEntry E;
2314 E.Ty = new PATypeHolder(Type::VoidTy);
2315 E.Name = 0;
2316 E.Attrs = ParamAttr::None;
2317 $$->push_back(E);
2318 CHECK_FOR_ERROR
2319 }
2320 | DOTDOTDOT {
2321 $$ = new ArgListType;
2322 struct ArgListEntry E;
2323 E.Ty = new PATypeHolder(Type::VoidTy);
2324 E.Name = 0;
2325 E.Attrs = ParamAttr::None;
2326 $$->push_back(E);
2327 CHECK_FOR_ERROR
2328 }
2329 | /* empty */ {
2330 $$ = 0;
2331 CHECK_FOR_ERROR
2332 };
2333
2334FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Devang Patel5df692d2008-09-02 20:52:40 +00002335 OptFuncAttrs OptSection OptAlign OptGC OptFuncNotes {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002336 std::string FunctionName(*$3);
2337 delete $3; // Free strdup'd memory!
2338
2339 // Check the function result for abstractness if this is a define. We should
2340 // have no abstract types at this point
2341 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2342 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2343
Chris Lattner73de3c02008-04-23 05:37:08 +00002344 if (!FunctionType::isValidReturnType(*$2))
2345 GEN_ERROR("Invalid result type for LLVM function");
2346
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002347 std::vector<const Type*> ParamTypeList;
Chris Lattner1c8733e2008-03-12 17:45:29 +00002348 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2349 if ($7 != ParamAttr::None)
2350 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002351 if ($5) { // If there are arguments...
2352 unsigned index = 1;
2353 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2354 const Type* Ty = I->Ty->get();
2355 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2356 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2357 ParamTypeList.push_back(Ty);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002358 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2359 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002360 }
2361 }
2362
2363 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2364 if (isVarArg) ParamTypeList.pop_back();
2365
Chris Lattner1c8733e2008-03-12 17:45:29 +00002366 PAListPtr PAL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002367 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002368 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002369
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002370 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambfb623c62007-12-17 01:17:35 +00002371 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002372 delete $2;
2373
2374 ValID ID;
2375 if (!FunctionName.empty()) {
2376 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2377 } else {
2378 ID = ValID::createGlobalID(CurModule.Values.size());
2379 }
2380
2381 Function *Fn = 0;
2382 // See if this function was forward referenced. If so, recycle the object.
2383 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2384 // Move the function to the end of the list, from whereever it was
2385 // previously inserted.
2386 Fn = cast<Function>(FWRef);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002387 assert(Fn->getParamAttrs().isEmpty() &&
2388 "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002389 CurModule.CurrentModule->getFunctionList().remove(Fn);
2390 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2391 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2392 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002393 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002394 // The existing function doesn't have the same type. This is an overload
2395 // error.
2396 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002397 } else if (Fn->getParamAttrs() != PAL) {
2398 // The existing function doesn't have the same parameter attributes.
2399 // This is an overload error.
2400 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002401 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2402 // Neither the existing or the current function is a declaration and they
2403 // have the same name and same type. Clearly this is a redefinition.
2404 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002405 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002406 // Make sure to strip off any argument names so we can't get conflicts.
2407 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2408 AI != AE; ++AI)
2409 AI->setName("");
2410 }
2411 } else { // Not already defined?
Gabor Greif89f01162008-04-06 23:07:54 +00002412 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2413 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002414 InsertValue(Fn, CurModule.Values);
2415 }
2416
2417 CurFun.FunctionStart(Fn);
2418
2419 if (CurFun.isDeclare) {
2420 // If we have declaration, always overwrite linkage. This will allow us to
2421 // correctly handle cases, when pointer to function is passed as argument to
2422 // another function.
2423 Fn->setLinkage(CurFun.Linkage);
2424 Fn->setVisibility(CurFun.Visibility);
2425 }
2426 Fn->setCallingConv($1);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002427 Fn->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002428 Fn->setAlignment($9);
2429 if ($8) {
2430 Fn->setSection(*$8);
2431 delete $8;
2432 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002433 if ($10) {
Gordon Henriksen8bccc832008-08-17 18:48:50 +00002434 Fn->setGC($10->c_str());
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002435 delete $10;
2436 }
Devang Patel5df692d2008-09-02 20:52:40 +00002437 if ($11) {
2438 Fn->setNotes($11);
2439 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002440
2441 // Add all of the arguments we parsed to the function...
2442 if ($5) { // Is null if empty...
2443 if (isVarArg) { // Nuke the last entry
2444 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2445 "Not a varargs marker!");
2446 delete $5->back().Ty;
2447 $5->pop_back(); // Delete the last entry
2448 }
2449 Function::arg_iterator ArgIt = Fn->arg_begin();
2450 Function::arg_iterator ArgEnd = Fn->arg_end();
2451 unsigned Idx = 1;
2452 for (ArgListType::iterator I = $5->begin();
2453 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2454 delete I->Ty; // Delete the typeholder...
2455 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2456 CHECK_FOR_ERROR
2457 InsertValue(ArgIt);
2458 Idx++;
2459 }
2460
2461 delete $5; // We're now done with the argument list
2462 }
2463 CHECK_FOR_ERROR
2464};
2465
2466BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2467
2468FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2469 $$ = CurFun.CurrentFunction;
2470
2471 // Make sure that we keep track of the linkage type even if there was a
2472 // previous "declare".
2473 $$->setLinkage($1);
2474 $$->setVisibility($2);
2475};
2476
2477END : ENDTOK | '}'; // Allow end of '}' to end a function
2478
2479Function : BasicBlockList END {
2480 $$ = $1;
2481 CHECK_FOR_ERROR
2482};
2483
2484FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2485 CurFun.CurrentFunction->setLinkage($1);
2486 CurFun.CurrentFunction->setVisibility($2);
2487 $$ = CurFun.CurrentFunction;
2488 CurFun.FunctionDone();
2489 CHECK_FOR_ERROR
2490 };
2491
2492//===----------------------------------------------------------------------===//
2493// Rules to match Basic Blocks
2494//===----------------------------------------------------------------------===//
2495
2496OptSideEffect : /* empty */ {
2497 $$ = false;
2498 CHECK_FOR_ERROR
2499 }
2500 | SIDEEFFECT {
2501 $$ = true;
2502 CHECK_FOR_ERROR
2503 };
2504
2505ConstValueRef : ESINT64VAL { // A reference to a direct constant
2506 $$ = ValID::create($1);
2507 CHECK_FOR_ERROR
2508 }
2509 | EUINT64VAL {
2510 $$ = ValID::create($1);
2511 CHECK_FOR_ERROR
2512 }
Chris Lattnerf3d40022008-07-11 00:30:39 +00002513 | ESAPINTVAL { // arbitrary precision integer constants
2514 $$ = ValID::create(*$1, true);
2515 delete $1;
2516 CHECK_FOR_ERROR
2517 }
2518 | EUAPINTVAL { // arbitrary precision integer constants
2519 $$ = ValID::create(*$1, false);
2520 delete $1;
2521 CHECK_FOR_ERROR
2522 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002523 | FPVAL { // Perhaps it's an FP constant?
2524 $$ = ValID::create($1);
2525 CHECK_FOR_ERROR
2526 }
2527 | TRUETOK {
2528 $$ = ValID::create(ConstantInt::getTrue());
2529 CHECK_FOR_ERROR
2530 }
2531 | FALSETOK {
2532 $$ = ValID::create(ConstantInt::getFalse());
2533 CHECK_FOR_ERROR
2534 }
2535 | NULL_TOK {
2536 $$ = ValID::createNull();
2537 CHECK_FOR_ERROR
2538 }
2539 | UNDEF {
2540 $$ = ValID::createUndef();
2541 CHECK_FOR_ERROR
2542 }
2543 | ZEROINITIALIZER { // A vector zero constant.
2544 $$ = ValID::createZeroInit();
2545 CHECK_FOR_ERROR
2546 }
2547 | '<' ConstVector '>' { // Nonempty unsized packed vector
2548 const Type *ETy = (*$2)[0]->getType();
Dan Gohman7185e4b2008-06-23 18:43:26 +00002549 unsigned NumElements = $2->size();
Dan Gohmane5febe42008-05-31 00:58:22 +00002550
2551 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2552 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553
2554 VectorType* pt = VectorType::get(ETy, NumElements);
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002555 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556
2557 // Verify all elements are correct type!
2558 for (unsigned i = 0; i < $2->size(); i++) {
2559 if (ETy != (*$2)[i]->getType())
2560 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2561 ETy->getDescription() +"' as required!\nIt is of type '" +
2562 (*$2)[i]->getType()->getDescription() + "'.");
2563 }
2564
2565 $$ = ValID::create(ConstantVector::get(pt, *$2));
2566 delete PTy; delete $2;
2567 CHECK_FOR_ERROR
2568 }
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002569 | '[' ConstVector ']' { // Nonempty unsized arr
2570 const Type *ETy = (*$2)[0]->getType();
Dan Gohman7185e4b2008-06-23 18:43:26 +00002571 uint64_t NumElements = $2->size();
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002572
2573 if (!ETy->isFirstClassType())
2574 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2575
2576 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2577 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2578
2579 // Verify all elements are correct type!
2580 for (unsigned i = 0; i < $2->size(); i++) {
2581 if (ETy != (*$2)[i]->getType())
2582 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2583 ETy->getDescription() +"' as required!\nIt is of type '"+
2584 (*$2)[i]->getType()->getDescription() + "'.");
2585 }
2586
2587 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2588 delete PTy; delete $2;
2589 CHECK_FOR_ERROR
2590 }
2591 | '[' ']' {
Dan Gohman7185e4b2008-06-23 18:43:26 +00002592 // Use undef instead of an array because it's inconvenient to determine
2593 // the element type at this point, there being no elements to examine.
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002594 $$ = ValID::createUndef();
2595 CHECK_FOR_ERROR
2596 }
2597 | 'c' STRINGCONSTANT {
Dan Gohman7185e4b2008-06-23 18:43:26 +00002598 uint64_t NumElements = $2->length();
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002599 const Type *ETy = Type::Int8Ty;
2600
2601 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2602
2603 std::vector<Constant*> Vals;
2604 for (unsigned i = 0; i < $2->length(); ++i)
2605 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2606 delete $2;
2607 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2608 CHECK_FOR_ERROR
2609 }
2610 | '{' ConstVector '}' {
2611 std::vector<const Type*> Elements($2->size());
2612 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2613 Elements[i] = (*$2)[i]->getType();
2614
2615 const StructType *STy = StructType::get(Elements);
2616 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2617
2618 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2619 delete PTy; delete $2;
2620 CHECK_FOR_ERROR
2621 }
2622 | '{' '}' {
2623 const StructType *STy = StructType::get(std::vector<const Type*>());
2624 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2625 CHECK_FOR_ERROR
2626 }
2627 | '<' '{' ConstVector '}' '>' {
2628 std::vector<const Type*> Elements($3->size());
2629 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2630 Elements[i] = (*$3)[i]->getType();
2631
2632 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2633 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2634
2635 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2636 delete PTy; delete $3;
2637 CHECK_FOR_ERROR
2638 }
2639 | '<' '{' '}' '>' {
2640 const StructType *STy = StructType::get(std::vector<const Type*>(),
2641 /*isPacked=*/true);
2642 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2643 CHECK_FOR_ERROR
2644 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645 | ConstExpr {
2646 $$ = ValID::create($1);
2647 CHECK_FOR_ERROR
2648 }
2649 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2650 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2651 delete $3;
2652 delete $5;
2653 CHECK_FOR_ERROR
2654 };
2655
2656// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2657// another value.
2658//
2659SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2660 $$ = ValID::createLocalID($1);
2661 CHECK_FOR_ERROR
2662 }
2663 | GLOBALVAL_ID {
2664 $$ = ValID::createGlobalID($1);
2665 CHECK_FOR_ERROR
2666 }
2667 | LocalName { // Is it a named reference...?
2668 $$ = ValID::createLocalName(*$1);
2669 delete $1;
2670 CHECK_FOR_ERROR
2671 }
2672 | GlobalName { // Is it a named reference...?
2673 $$ = ValID::createGlobalName(*$1);
2674 delete $1;
2675 CHECK_FOR_ERROR
2676 };
2677
2678// ValueRef - A reference to a definition... either constant or symbolic
2679ValueRef : SymbolicValueRef | ConstValueRef;
2680
2681
2682// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2683// type immediately preceeds the value reference, and allows complex constant
2684// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2685ResolvedVal : Types ValueRef {
2686 if (!UpRefs.empty())
2687 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2688 $$ = getVal(*$1, $2);
2689 delete $1;
2690 CHECK_FOR_ERROR
2691 }
2692 ;
2693
Devang Patelbf507402008-02-20 22:40:23 +00002694ReturnedVal : ResolvedVal {
2695 $$ = new std::vector<Value *>();
2696 $$->push_back($1);
2697 CHECK_FOR_ERROR
2698 }
Devang Patel087fe2b2008-02-23 00:38:56 +00002699 | ReturnedVal ',' ResolvedVal {
Devang Patelbf507402008-02-20 22:40:23 +00002700 ($$=$1)->push_back($3);
2701 CHECK_FOR_ERROR
2702 };
2703
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002704BasicBlockList : BasicBlockList BasicBlock {
2705 $$ = $1;
2706 CHECK_FOR_ERROR
2707 }
2708 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2709 $$ = $1;
2710 CHECK_FOR_ERROR
2711 };
2712
2713
2714// Basic blocks are terminated by branching instructions:
2715// br, br/cc, switch, ret
2716//
Chris Lattner906773a2008-08-29 17:20:18 +00002717BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002718 setValueName($3, $2);
2719 CHECK_FOR_ERROR
2720 InsertValue($3);
2721 $1->getInstList().push_back($3);
2722 $$ = $1;
2723 CHECK_FOR_ERROR
2724 };
2725
Chris Lattner906773a2008-08-29 17:20:18 +00002726BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2727 CHECK_FOR_ERROR
2728 int ValNum = InsertValue($3);
2729 if (ValNum != (int)$2)
2730 GEN_ERROR("Result value number %" + utostr($2) +
2731 " is incorrect, expected %" + utostr((unsigned)ValNum));
2732
2733 $1->getInstList().push_back($3);
2734 $$ = $1;
2735 CHECK_FOR_ERROR
2736};
2737
2738
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739InstructionList : InstructionList Inst {
2740 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2741 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2742 if (CI2->getParent() == 0)
2743 $1->getInstList().push_back(CI2);
2744 $1->getInstList().push_back($2);
2745 $$ = $1;
2746 CHECK_FOR_ERROR
2747 }
2748 | /* empty */ { // Empty space between instruction lists
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002749 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002750 CHECK_FOR_ERROR
2751 }
2752 | LABELSTR { // Labelled (named) basic block
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002753 $$ = defineBBVal(ValID::createLocalName(*$1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754 delete $1;
2755 CHECK_FOR_ERROR
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002756
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002757 };
2758
Devang Patelbf507402008-02-20 22:40:23 +00002759BBTerminatorInst :
2760 RET ReturnedVal { // Return with a result...
Devang Patelda2c8d52008-02-26 22:17:48 +00002761 ValueList &VL = *$2;
Devang Patelb4851dc2008-02-26 23:19:08 +00002762 assert(!VL.empty() && "Invalid ret operands!");
Dan Gohmanb94a0ba2008-07-23 00:54:54 +00002763 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2764 if (VL.size() > 1 ||
2765 (isa<StructType>(ReturnType) &&
2766 (VL.empty() || VL[0]->getType() != ReturnType))) {
2767 Value *RV = UndefValue::get(ReturnType);
2768 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2769 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2770 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2771 RV = I;
2772 }
2773 $$ = ReturnInst::Create(RV);
2774 } else {
2775 $$ = ReturnInst::Create(VL[0]);
2776 }
Devang Patelbf507402008-02-20 22:40:23 +00002777 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778 CHECK_FOR_ERROR
2779 }
2780 | RET VOID { // Return with no result...
Gabor Greif89f01162008-04-06 23:07:54 +00002781 $$ = ReturnInst::Create();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 CHECK_FOR_ERROR
2783 }
2784 | BR LABEL ValueRef { // Unconditional Branch...
2785 BasicBlock* tmpBB = getBBVal($3);
2786 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002787 $$ = BranchInst::Create(tmpBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788 } // Conditional Branch...
2789 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
Dan Gohmane5febe42008-05-31 00:58:22 +00002790 if (cast<IntegerType>($2)->getBitWidth() != 1)
2791 GEN_ERROR("Branch condition must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002792 BasicBlock* tmpBBA = getBBVal($6);
2793 CHECK_FOR_ERROR
2794 BasicBlock* tmpBBB = getBBVal($9);
2795 CHECK_FOR_ERROR
2796 Value* tmpVal = getVal(Type::Int1Ty, $3);
2797 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002798 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799 }
2800 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2801 Value* tmpVal = getVal($2, $3);
2802 CHECK_FOR_ERROR
2803 BasicBlock* tmpBB = getBBVal($6);
2804 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002805 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002806 $$ = S;
2807
2808 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2809 E = $8->end();
2810 for (; I != E; ++I) {
2811 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2812 S->addCase(CI, I->second);
2813 else
2814 GEN_ERROR("Switch case is constant, but not a simple integer");
2815 }
2816 delete $8;
2817 CHECK_FOR_ERROR
2818 }
2819 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2820 Value* tmpVal = getVal($2, $3);
2821 CHECK_FOR_ERROR
2822 BasicBlock* tmpBB = getBBVal($6);
2823 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002824 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002825 $$ = S;
2826 CHECK_FOR_ERROR
2827 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002828 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002829 TO LABEL ValueRef UNWIND LABEL ValueRef {
2830
2831 // Handle the short syntax
2832 const PointerType *PFTy = 0;
2833 const FunctionType *Ty = 0;
2834 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2835 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2836 // Pull out the types of all of the arguments...
2837 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002838 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002839 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 const Type *Ty = I->Val->getType();
2841 if (Ty == Type::VoidTy)
2842 GEN_ERROR("Short call syntax cannot be used with varargs");
2843 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002844 }
Chris Lattner73de3c02008-04-23 05:37:08 +00002845
2846 if (!FunctionType::isValidReturnType(*$3))
2847 GEN_ERROR("Invalid result type for LLVM function");
2848
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002849 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00002850 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002851 }
2852
2853 delete $3;
2854
2855 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2856 CHECK_FOR_ERROR
2857 BasicBlock *Normal = getBBVal($11);
2858 CHECK_FOR_ERROR
2859 BasicBlock *Except = getBBVal($14);
2860 CHECK_FOR_ERROR
2861
Chris Lattner1c8733e2008-03-12 17:45:29 +00002862 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2863 if ($8 != ParamAttr::None)
2864 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002865
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 // Check the arguments
2867 ValueList Args;
2868 if ($6->empty()) { // Has no arguments?
2869 // Make sure no arguments is a good thing!
2870 if (Ty->getNumParams() != 0)
2871 GEN_ERROR("No arguments passed to a function that "
2872 "expects arguments");
2873 } else { // Has arguments?
2874 // Loop through FunctionType's arguments and ensure they are specified
2875 // correctly!
2876 FunctionType::param_iterator I = Ty->param_begin();
2877 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002878 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002879 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002880
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002881 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002882 if (ArgI->Val->getType() != *I)
2883 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2884 (*I)->getDescription() + "'");
2885 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002886 if (ArgI->Attrs != ParamAttr::None)
2887 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 }
2889
2890 if (Ty->isVarArg()) {
2891 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00002892 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002893 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00002894 if (ArgI->Attrs != ParamAttr::None)
2895 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Chris Lattner59363a32008-02-19 04:36:25 +00002896 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002897 } else if (I != E || ArgI != ArgE)
2898 GEN_ERROR("Invalid number of parameters detected");
2899 }
2900
Chris Lattner1c8733e2008-03-12 17:45:29 +00002901 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002902 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002903 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002904
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 // Create the InvokeInst
Dan Gohman8055f772008-05-15 19:50:34 +00002906 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2907 Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908 II->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002909 II->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 $$ = II;
2911 delete $6;
2912 CHECK_FOR_ERROR
2913 }
2914 | UNWIND {
2915 $$ = new UnwindInst();
2916 CHECK_FOR_ERROR
2917 }
2918 | UNREACHABLE {
2919 $$ = new UnreachableInst();
2920 CHECK_FOR_ERROR
2921 };
2922
2923
2924
2925JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2926 $$ = $1;
2927 Constant *V = cast<Constant>(getExistingVal($2, $3));
2928 CHECK_FOR_ERROR
2929 if (V == 0)
2930 GEN_ERROR("May only switch on a constant pool value");
2931
2932 BasicBlock* tmpBB = getBBVal($6);
2933 CHECK_FOR_ERROR
2934 $$->push_back(std::make_pair(V, tmpBB));
2935 }
2936 | IntType ConstValueRef ',' LABEL ValueRef {
2937 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2938 Constant *V = cast<Constant>(getExistingVal($1, $2));
2939 CHECK_FOR_ERROR
2940
2941 if (V == 0)
2942 GEN_ERROR("May only switch on a constant pool value");
2943
2944 BasicBlock* tmpBB = getBBVal($5);
2945 CHECK_FOR_ERROR
2946 $$->push_back(std::make_pair(V, tmpBB));
2947 };
2948
2949Inst : OptLocalAssign InstVal {
2950 // Is this definition named?? if so, assign the name...
2951 setValueName($2, $1);
2952 CHECK_FOR_ERROR
2953 InsertValue($2);
2954 $$ = $2;
2955 CHECK_FOR_ERROR
2956 };
2957
Chris Lattner906773a2008-08-29 17:20:18 +00002958Inst : LocalNumber InstVal {
2959 CHECK_FOR_ERROR
2960 int ValNum = InsertValue($2);
2961
2962 if (ValNum != (int)$1)
2963 GEN_ERROR("Result value number %" + utostr($1) +
2964 " is incorrect, expected %" + utostr((unsigned)ValNum));
2965
2966 $$ = $2;
2967 CHECK_FOR_ERROR
2968 };
2969
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002970
2971PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2972 if (!UpRefs.empty())
2973 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2974 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2975 Value* tmpVal = getVal(*$1, $3);
2976 CHECK_FOR_ERROR
2977 BasicBlock* tmpBB = getBBVal($5);
2978 CHECK_FOR_ERROR
2979 $$->push_back(std::make_pair(tmpVal, tmpBB));
2980 delete $1;
2981 }
2982 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2983 $$ = $1;
2984 Value* tmpVal = getVal($1->front().first->getType(), $4);
2985 CHECK_FOR_ERROR
2986 BasicBlock* tmpBB = getBBVal($6);
2987 CHECK_FOR_ERROR
2988 $1->push_back(std::make_pair(tmpVal, tmpBB));
2989 };
2990
2991
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002992ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2993 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002994 if (!UpRefs.empty())
2995 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2996 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00002997 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002998 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002999 $$->push_back(E);
3000 delete $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003001 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003002 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003003 | LABEL OptParamAttrs ValueRef OptParamAttrs {
3004 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00003005 // Labels are only valid in ASMs
3006 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003007 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
Dale Johannesencfb19e62007-11-05 21:20:28 +00003008 $$->push_back(E);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003009 CHECK_FOR_ERROR
Dale Johannesencfb19e62007-11-05 21:20:28 +00003010 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003011 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
3012 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 if (!UpRefs.empty())
3014 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3015 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003016 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 $$->push_back(E);
3018 delete $3;
3019 CHECK_FOR_ERROR
3020 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003021 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
3022 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00003023 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003024 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
Dale Johannesencfb19e62007-11-05 21:20:28 +00003025 $$->push_back(E);
3026 CHECK_FOR_ERROR
3027 }
3028 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029
3030IndexList // Used for gep instructions and constant expressions
3031 : /*empty*/ { $$ = new std::vector<Value*>(); }
3032 | IndexList ',' ResolvedVal {
3033 $$ = $1;
3034 $$->push_back($3);
3035 CHECK_FOR_ERROR
3036 }
3037 ;
3038
Dan Gohmane5febe42008-05-31 00:58:22 +00003039ConstantIndexList // Used for insertvalue and extractvalue instructions
3040 : ',' EUINT64VAL {
3041 $$ = new std::vector<unsigned>();
3042 if ((unsigned)$2 != $2)
3043 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3044 $$->push_back($2);
3045 }
3046 | ConstantIndexList ',' EUINT64VAL {
3047 $$ = $1;
3048 if ((unsigned)$3 != $3)
3049 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3050 $$->push_back($3);
3051 CHECK_FOR_ERROR
3052 }
3053 ;
3054
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003055OptTailCall : TAIL CALL {
3056 $$ = true;
3057 CHECK_FOR_ERROR
3058 }
3059 | CALL {
3060 $$ = false;
3061 CHECK_FOR_ERROR
3062 };
3063
3064InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3065 if (!UpRefs.empty())
3066 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3067 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3068 !isa<VectorType>((*$2).get()))
3069 GEN_ERROR(
3070 "Arithmetic operator requires integer, FP, or packed operands");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003071 Value* val1 = getVal(*$2, $3);
3072 CHECK_FOR_ERROR
3073 Value* val2 = getVal(*$2, $5);
3074 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003075 $$ = BinaryOperator::Create($1, val1, val2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003076 if ($$ == 0)
3077 GEN_ERROR("binary operator returned null");
3078 delete $2;
3079 }
3080 | LogicalOps Types ValueRef ',' ValueRef {
3081 if (!UpRefs.empty())
3082 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3083 if (!(*$2)->isInteger()) {
Nate Begemanbb1ce942008-07-29 15:49:41 +00003084 if (!isa<VectorType>($2->get()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085 !cast<VectorType>($2->get())->getElementType()->isInteger())
3086 GEN_ERROR("Logical operator requires integral operands");
3087 }
3088 Value* tmpVal1 = getVal(*$2, $3);
3089 CHECK_FOR_ERROR
3090 Value* tmpVal2 = getVal(*$2, $5);
3091 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003092 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003093 if ($$ == 0)
3094 GEN_ERROR("binary operator returned null");
3095 delete $2;
3096 }
3097 | ICMP IPredicates Types ValueRef ',' ValueRef {
3098 if (!UpRefs.empty())
3099 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3100 if (isa<VectorType>((*$3).get()))
3101 GEN_ERROR("Vector types not supported by icmp instruction");
3102 Value* tmpVal1 = getVal(*$3, $4);
3103 CHECK_FOR_ERROR
3104 Value* tmpVal2 = getVal(*$3, $6);
3105 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003106 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 if ($$ == 0)
3108 GEN_ERROR("icmp operator returned null");
3109 delete $3;
3110 }
3111 | FCMP FPredicates Types ValueRef ',' ValueRef {
3112 if (!UpRefs.empty())
3113 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3114 if (isa<VectorType>((*$3).get()))
3115 GEN_ERROR("Vector types not supported by fcmp instruction");
3116 Value* tmpVal1 = getVal(*$3, $4);
3117 CHECK_FOR_ERROR
3118 Value* tmpVal2 = getVal(*$3, $6);
3119 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003120 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 if ($$ == 0)
3122 GEN_ERROR("fcmp operator returned null");
3123 delete $3;
3124 }
Nate Begeman646fa482008-05-12 19:01:56 +00003125 | VICMP IPredicates Types ValueRef ',' ValueRef {
3126 if (!UpRefs.empty())
3127 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3128 if (!isa<VectorType>((*$3).get()))
3129 GEN_ERROR("Scalar types not supported by vicmp instruction");
3130 Value* tmpVal1 = getVal(*$3, $4);
3131 CHECK_FOR_ERROR
3132 Value* tmpVal2 = getVal(*$3, $6);
3133 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003134 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Nate Begeman646fa482008-05-12 19:01:56 +00003135 if ($$ == 0)
3136 GEN_ERROR("icmp operator returned null");
3137 delete $3;
3138 }
3139 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3140 if (!UpRefs.empty())
3141 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3142 if (!isa<VectorType>((*$3).get()))
3143 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3144 Value* tmpVal1 = getVal(*$3, $4);
3145 CHECK_FOR_ERROR
3146 Value* tmpVal2 = getVal(*$3, $6);
3147 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003148 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Nate Begeman646fa482008-05-12 19:01:56 +00003149 if ($$ == 0)
3150 GEN_ERROR("fcmp operator returned null");
3151 delete $3;
3152 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003153 | CastOps ResolvedVal TO Types {
3154 if (!UpRefs.empty())
3155 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3156 Value* Val = $2;
3157 const Type* DestTy = $4->get();
3158 if (!CastInst::castIsValid($1, Val, DestTy))
3159 GEN_ERROR("invalid cast opcode for cast from '" +
3160 Val->getType()->getDescription() + "' to '" +
3161 DestTy->getDescription() + "'");
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003162 $$ = CastInst::Create($1, Val, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003163 delete $4;
3164 }
3165 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3166 if ($2->getType() != Type::Int1Ty)
3167 GEN_ERROR("select condition must be boolean");
3168 if ($4->getType() != $6->getType())
3169 GEN_ERROR("select value types should match");
Gabor Greif89f01162008-04-06 23:07:54 +00003170 $$ = SelectInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171 CHECK_FOR_ERROR
3172 }
3173 | VAARG ResolvedVal ',' Types {
3174 if (!UpRefs.empty())
3175 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3176 $$ = new VAArgInst($2, *$4);
3177 delete $4;
3178 CHECK_FOR_ERROR
3179 }
3180 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3181 if (!ExtractElementInst::isValidOperands($2, $4))
3182 GEN_ERROR("Invalid extractelement operands");
3183 $$ = new ExtractElementInst($2, $4);
3184 CHECK_FOR_ERROR
3185 }
3186 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3187 if (!InsertElementInst::isValidOperands($2, $4, $6))
3188 GEN_ERROR("Invalid insertelement operands");
Gabor Greif89f01162008-04-06 23:07:54 +00003189 $$ = InsertElementInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190 CHECK_FOR_ERROR
3191 }
3192 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3193 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3194 GEN_ERROR("Invalid shufflevector operands");
3195 $$ = new ShuffleVectorInst($2, $4, $6);
3196 CHECK_FOR_ERROR
3197 }
3198 | PHI_TOK PHIList {
3199 const Type *Ty = $2->front().first->getType();
3200 if (!Ty->isFirstClassType())
3201 GEN_ERROR("PHI node operands must be of first class type");
Gabor Greif89f01162008-04-06 23:07:54 +00003202 $$ = PHINode::Create(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 ((PHINode*)$$)->reserveOperandSpace($2->size());
3204 while ($2->begin() != $2->end()) {
3205 if ($2->front().first->getType() != Ty)
3206 GEN_ERROR("All elements of a PHI node must be of the same type");
3207 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3208 $2->pop_front();
3209 }
3210 delete $2; // Free the list...
3211 CHECK_FOR_ERROR
3212 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00003213 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 OptFuncAttrs {
3215
3216 // Handle the short syntax
3217 const PointerType *PFTy = 0;
3218 const FunctionType *Ty = 0;
3219 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3220 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3221 // Pull out the types of all of the arguments...
3222 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00003223 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003224 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003225 const Type *Ty = I->Val->getType();
3226 if (Ty == Type::VoidTy)
3227 GEN_ERROR("Short call syntax cannot be used with varargs");
3228 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229 }
Chris Lattner73de3c02008-04-23 05:37:08 +00003230
3231 if (!FunctionType::isValidReturnType(*$3))
3232 GEN_ERROR("Invalid result type for LLVM function");
3233
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003234 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00003235 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003236 }
3237
3238 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3239 CHECK_FOR_ERROR
3240
3241 // Check for call to invalid intrinsic to avoid crashing later.
3242 if (Function *theF = dyn_cast<Function>(V)) {
3243 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3244 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3245 !theF->getIntrinsicID(true))
3246 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3247 theF->getName() + "'");
3248 }
3249
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003250 // Set up the ParamAttrs for the function
Chris Lattner1c8733e2008-03-12 17:45:29 +00003251 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3252 if ($8 != ParamAttr::None)
3253 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 // Check the arguments
3255 ValueList Args;
3256 if ($6->empty()) { // Has no arguments?
3257 // Make sure no arguments is a good thing!
3258 if (Ty->getNumParams() != 0)
3259 GEN_ERROR("No arguments passed to a function that "
3260 "expects arguments");
3261 } else { // Has arguments?
3262 // Loop through FunctionType's arguments and ensure they are specified
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003263 // correctly. Also, gather any parameter attributes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003264 FunctionType::param_iterator I = Ty->param_begin();
3265 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00003266 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003267 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003268
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003269 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270 if (ArgI->Val->getType() != *I)
3271 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3272 (*I)->getDescription() + "'");
3273 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00003274 if (ArgI->Attrs != ParamAttr::None)
3275 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003276 }
3277 if (Ty->isVarArg()) {
3278 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00003279 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003280 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00003281 if (ArgI->Attrs != ParamAttr::None)
3282 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Chris Lattner59363a32008-02-19 04:36:25 +00003283 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284 } else if (I != E || ArgI != ArgE)
3285 GEN_ERROR("Invalid number of parameters detected");
3286 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003287
3288 // Finish off the ParamAttrs and check them
Chris Lattner1c8733e2008-03-12 17:45:29 +00003289 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003290 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00003291 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003292
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003293 // Create the call node
Gabor Greif89f01162008-04-06 23:07:54 +00003294 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295 CI->setTailCall($1);
3296 CI->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003297 CI->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003298 $$ = CI;
3299 delete $6;
3300 delete $3;
3301 CHECK_FOR_ERROR
3302 }
3303 | MemoryInst {
3304 $$ = $1;
3305 CHECK_FOR_ERROR
3306 };
3307
3308OptVolatile : VOLATILE {
3309 $$ = true;
3310 CHECK_FOR_ERROR
3311 }
3312 | /* empty */ {
3313 $$ = false;
3314 CHECK_FOR_ERROR
3315 };
3316
3317
3318
3319MemoryInst : MALLOC Types OptCAlign {
3320 if (!UpRefs.empty())
3321 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3322 $$ = new MallocInst(*$2, 0, $3);
3323 delete $2;
3324 CHECK_FOR_ERROR
3325 }
3326 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3327 if (!UpRefs.empty())
3328 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00003329 if ($4 != Type::Int32Ty)
3330 GEN_ERROR("Malloc array size is not a 32-bit integer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003331 Value* tmpVal = getVal($4, $5);
3332 CHECK_FOR_ERROR
3333 $$ = new MallocInst(*$2, tmpVal, $6);
3334 delete $2;
3335 }
3336 | ALLOCA Types OptCAlign {
3337 if (!UpRefs.empty())
3338 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3339 $$ = new AllocaInst(*$2, 0, $3);
3340 delete $2;
3341 CHECK_FOR_ERROR
3342 }
3343 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3344 if (!UpRefs.empty())
3345 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00003346 if ($4 != Type::Int32Ty)
3347 GEN_ERROR("Alloca array size is not a 32-bit integer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003348 Value* tmpVal = getVal($4, $5);
3349 CHECK_FOR_ERROR
3350 $$ = new AllocaInst(*$2, tmpVal, $6);
3351 delete $2;
3352 }
3353 | FREE ResolvedVal {
3354 if (!isa<PointerType>($2->getType()))
3355 GEN_ERROR("Trying to free nonpointer type " +
3356 $2->getType()->getDescription() + "");
3357 $$ = new FreeInst($2);
3358 CHECK_FOR_ERROR
3359 }
3360
3361 | OptVolatile LOAD Types ValueRef OptCAlign {
3362 if (!UpRefs.empty())
3363 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3364 if (!isa<PointerType>($3->get()))
3365 GEN_ERROR("Can't load from nonpointer type: " +
3366 (*$3)->getDescription());
3367 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3368 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3369 (*$3)->getDescription());
3370 Value* tmpVal = getVal(*$3, $4);
3371 CHECK_FOR_ERROR
3372 $$ = new LoadInst(tmpVal, "", $1, $5);
3373 delete $3;
3374 }
3375 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3376 if (!UpRefs.empty())
3377 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3378 const PointerType *PT = dyn_cast<PointerType>($5->get());
3379 if (!PT)
3380 GEN_ERROR("Can't store to a nonpointer type: " +
3381 (*$5)->getDescription());
3382 const Type *ElTy = PT->getElementType();
3383 if (ElTy != $3->getType())
3384 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3385 "' into space of type '" + ElTy->getDescription() + "'");
3386
3387 Value* tmpVal = getVal(*$5, $6);
3388 CHECK_FOR_ERROR
3389 $$ = new StoreInst($3, tmpVal, $1, $7);
3390 delete $5;
3391 }
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003392 | GETRESULT Types ValueRef ',' EUINT64VAL {
Dan Gohmanb94a0ba2008-07-23 00:54:54 +00003393 if (!UpRefs.empty())
3394 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3395 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3396 GEN_ERROR("getresult insn requires an aggregate operand");
3397 if (!ExtractValueInst::getIndexedType(*$2, $5))
3398 GEN_ERROR("Invalid getresult index for type '" +
3399 (*$2)->getDescription()+ "'");
3400
3401 Value *tmpVal = getVal(*$2, $3);
Devang Patel3b8849c2008-02-19 22:27:01 +00003402 CHECK_FOR_ERROR
Dan Gohmanb94a0ba2008-07-23 00:54:54 +00003403 $$ = ExtractValueInst::Create(tmpVal, $5);
3404 delete $2;
Devang Patel3b8849c2008-02-19 22:27:01 +00003405 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 | GETELEMENTPTR Types ValueRef IndexList {
3407 if (!UpRefs.empty())
3408 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3409 if (!isa<PointerType>($2->get()))
3410 GEN_ERROR("getelementptr insn requires pointer operand");
3411
Dan Gohman8055f772008-05-15 19:50:34 +00003412 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413 GEN_ERROR("Invalid getelementptr indices for type '" +
3414 (*$2)->getDescription()+ "'");
3415 Value* tmpVal = getVal(*$2, $3);
3416 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00003417 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003418 delete $2;
3419 delete $4;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003420 }
Dan Gohmane5febe42008-05-31 00:58:22 +00003421 | EXTRACTVALUE Types ValueRef ConstantIndexList {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003422 if (!UpRefs.empty())
3423 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3424 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3425 GEN_ERROR("extractvalue insn requires an aggregate operand");
3426
3427 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3428 GEN_ERROR("Invalid extractvalue indices for type '" +
3429 (*$2)->getDescription()+ "'");
3430 Value* tmpVal = getVal(*$2, $3);
3431 CHECK_FOR_ERROR
3432 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3433 delete $2;
3434 delete $4;
3435 }
Dan Gohmane5febe42008-05-31 00:58:22 +00003436 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003437 if (!UpRefs.empty())
3438 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3439 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3440 GEN_ERROR("extractvalue insn requires an aggregate operand");
3441
3442 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3443 GEN_ERROR("Invalid insertvalue indices for type '" +
3444 (*$2)->getDescription()+ "'");
3445 Value* aggVal = getVal(*$2, $3);
3446 Value* tmpVal = getVal(*$5, $6);
3447 CHECK_FOR_ERROR
3448 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3449 delete $2;
3450 delete $5;
3451 delete $7;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003452 };
3453
3454
3455%%
3456
3457// common code from the two 'RunVMAsmParser' functions
3458static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003460 // Check to make sure the parser succeeded
3461 if (yyparse()) {
3462 if (ParserResult)
3463 delete ParserResult;
3464 return 0;
3465 }
3466
3467 // Emit an error if there are any unresolved types left.
3468 if (!CurModule.LateResolveTypes.empty()) {
3469 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3470 if (DID.Type == ValID::LocalName) {
3471 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3472 } else {
3473 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3474 }
3475 if (ParserResult)
3476 delete ParserResult;
3477 return 0;
3478 }
3479
3480 // Emit an error if there are any unresolved values left.
3481 if (!CurModule.LateResolveValues.empty()) {
3482 Value *V = CurModule.LateResolveValues.back();
3483 std::map<Value*, std::pair<ValID, int> >::iterator I =
3484 CurModule.PlaceHolderInfo.find(V);
3485
3486 if (I != CurModule.PlaceHolderInfo.end()) {
3487 ValID &DID = I->second.first;
3488 if (DID.Type == ValID::LocalName) {
3489 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3490 } else {
3491 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3492 }
3493 if (ParserResult)
3494 delete ParserResult;
3495 return 0;
3496 }
3497 }
3498
3499 // Check to make sure that parsing produced a result
3500 if (!ParserResult)
3501 return 0;
3502
3503 // Reset ParserResult variable while saving its value for the result.
3504 Module *Result = ParserResult;
3505 ParserResult = 0;
3506
3507 return Result;
3508}
3509
3510void llvm::GenerateError(const std::string &message, int LineNo) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003511 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 // TODO: column number in exception
3513 if (TheParseError)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003514 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003515 TriggerError = 1;
3516}
3517
3518int yyerror(const char *ErrorMsg) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003519 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003521 if (yychar != YYEMPTY && yychar != 0) {
3522 errMsg += " while reading token: '";
3523 errMsg += std::string(LLLgetTokenStart(),
3524 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3525 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003526 GenerateError(errMsg);
3527 return 0;
3528}