blob: ea3aef3a0bceb7c0ad132f1e505b65eed73d9ca8 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the bison parser for LLVM assembly languages files.
11//
12//===----------------------------------------------------------------------===//
13
14%{
15#include "ParserInternals.h"
16#include "llvm/CallingConv.h"
17#include "llvm/InlineAsm.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/ValueSymbolTable.h"
Chandler Carrutha228e392007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/Streams.h"
28#include <algorithm>
29#include <list>
30#include <map>
31#include <utility>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032
33// The following is a gross hack. In order to rid the libAsmParser library of
34// exceptions, we have to have a way of getting the yyparse function to go into
35// an error situation. So, whenever we want an error to occur, the GenerateError
36// function (see bottom of file) sets TriggerError. Then, at the end of each
37// production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38// (a goto) to put YACC in error state. Furthermore, several calls to
39// GenerateError are made from inside productions and they must simulate the
40// previous exception behavior by exiting the production immediately. We have
41// replaced these with the GEN_ERROR macro which calls GeneratError and then
42// immediately invokes YYERROR. This would be so much cleaner if it was a
43// recursive descent parser.
44static bool TriggerError = false;
45#define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46#define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
47
48int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49int yylex(); // declaration" of xxx warnings.
50int yyparse();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051using namespace llvm;
52
53static Module *ParserResult;
54
55// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56// relating to upreferences in the input stream.
57//
58//#define DEBUG_UPREFS 1
59#ifdef DEBUG_UPREFS
60#define UR_OUT(X) cerr << X
61#else
62#define UR_OUT(X)
63#endif
64
65#define YYERROR_VERBOSE 1
66
67static GlobalVariable *CurGV;
68
69
70// This contains info used when building the body of a function. It is
71// destroyed when the function is completed.
72//
73typedef std::vector<Value *> ValueList; // Numbered defs
74
75static void
76ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
77
78static struct PerModuleInfo {
79 Module *CurrentModule;
80 ValueList Values; // Module level numbered definitions
81 ValueList LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
84
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
89
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
94 //
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
98
99 void ModuleDone() {
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
103 //
104 ResolveDefinitions(LateResolveValues);
105 if (TriggerError)
106 return;
107
108 // Check to make sure that all global value forward references have been
109 // resolved!
110 //
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
113
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 I != E; ++I) {
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
118 }
119 GenerateError(UndefinedReferences);
120 return;
121 }
122
Chandler Carrutha228e392007-08-04 01:51:18 +0000123 // Look for intrinsic functions and CallInst that need to be upgraded
124 for (Module::iterator FI = CurrentModule->begin(),
125 FE = CurrentModule->end(); FI != FE; )
126 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
127
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 Values.clear(); // Clear out function local definitions
129 Types.clear();
130 CurrentModule = 0;
131 }
132
133 // GetForwardRefForGlobal - Check to see if there is a forward reference
134 // for this global. If so, remove it from the GlobalRefs map and return it.
135 // If not, just return null.
136 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137 // Check to see if there is a forward reference to this global variable...
138 // if there is, eliminate it and patch the reference to use the new def'n.
139 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140 GlobalValue *Ret = 0;
141 if (I != GlobalRefs.end()) {
142 Ret = I->second;
143 GlobalRefs.erase(I);
144 }
145 return Ret;
146 }
147
148 bool TypeIsUnresolved(PATypeHolder* PATy) {
149 // If it isn't abstract, its resolved
150 const Type* Ty = PATy->get();
151 if (!Ty->isAbstract())
152 return false;
153 // Traverse the type looking for abstract types. If it isn't abstract then
154 // we don't need to traverse that leg of the type.
155 std::vector<const Type*> WorkList, SeenList;
156 WorkList.push_back(Ty);
157 while (!WorkList.empty()) {
158 const Type* Ty = WorkList.back();
159 SeenList.push_back(Ty);
160 WorkList.pop_back();
161 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162 // Check to see if this is an unresolved type
163 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165 for ( ; I != E; ++I) {
166 if (I->second.get() == OpTy)
167 return true;
168 }
169 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170 const Type* TheTy = SeqTy->getElementType();
171 if (TheTy->isAbstract() && TheTy != Ty) {
172 std::vector<const Type*>::iterator I = SeenList.begin(),
173 E = SeenList.end();
174 for ( ; I != E; ++I)
175 if (*I == TheTy)
176 break;
177 if (I == E)
178 WorkList.push_back(TheTy);
179 }
180 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182 const Type* TheTy = StrTy->getElementType(i);
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
185 E = SeenList.end();
186 for ( ; I != E; ++I)
187 if (*I == TheTy)
188 break;
189 if (I == E)
190 WorkList.push_back(TheTy);
191 }
192 }
193 }
194 }
195 return false;
196 }
197} CurModule;
198
199static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
201
202 ValueList Values; // Keep track of #'d definitions
203 unsigned NextValNum;
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
208
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
212
213 inline PerFunctionInfo() {
214 CurrentFunction = 0;
215 isDeclare = false;
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
218 }
219
220 inline void FunctionStart(Function *M) {
221 CurrentFunction = M;
222 NextValNum = 0;
223 }
224
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
230 return;
231 }
232
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
235
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
238 CurrentFunction = 0;
239 isDeclare = false;
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
242 }
243} CurFun; // Info for the current function...
244
245static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
246
247
248//===----------------------------------------------------------------------===//
249// Code to handle definitions of all the types
250//===----------------------------------------------------------------------===//
251
252static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
253 // Things that have names or are void typed don't get slot numbers
254 if (V->hasName() || (V->getType() == Type::VoidTy))
255 return;
256
257 // In the case of function values, we have to allow for the forward reference
258 // of basic blocks, which are included in the numbering. Consequently, we keep
259 // track of the next insertion location with NextValNum. When a BB gets
260 // inserted, it could change the size of the CurFun.Values vector.
261 if (&ValueTab == &CurFun.Values) {
262 if (ValueTab.size() <= CurFun.NextValNum)
263 ValueTab.resize(CurFun.NextValNum+1);
264 ValueTab[CurFun.NextValNum++] = V;
265 return;
266 }
267 // For all other lists, its okay to just tack it on the back of the vector.
268 ValueTab.push_back(V);
269}
270
271static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
272 switch (D.Type) {
273 case ValID::LocalID: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if (D.Num < CurModule.Types.size())
276 return CurModule.Types[D.Num];
277 break;
278 case ValID::LocalName: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
280 D.destroy(); // Free old strdup'd memory...
281 return N;
282 }
283 break;
284 default:
285 GenerateError("Internal parser error: Invalid symbol type reference");
286 return 0;
287 }
288
289 // If we reached here, we referenced either a symbol that we don't know about
290 // or an id number that hasn't been read yet. We may be referencing something
291 // forward, so just create an entry to be resolved later and get to it...
292 //
293 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
294
295
296 if (inFunctionScope()) {
297 if (D.Type == ValID::LocalName) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
299 return 0;
300 } else {
301 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
302 return 0;
303 }
304 }
305
306 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307 if (I != CurModule.LateResolveTypes.end())
308 return I->second;
309
310 Type *Typ = OpaqueType::get();
311 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
312 return Typ;
313 }
314
315// getExistingVal - Look up the value specified by the provided type and
316// the provided ValID. If the value exists and has already been defined, return
317// it. Otherwise return null.
318//
319static Value *getExistingVal(const Type *Ty, const ValID &D) {
320 if (isa<FunctionType>(Ty)) {
321 GenerateError("Functions are not values and "
322 "must be referenced as pointers");
323 return 0;
324 }
325
326 switch (D.Type) {
327 case ValID::LocalID: { // Is it a numbered definition?
328 // Check that the number is within bounds.
329 if (D.Num >= CurFun.Values.size())
330 return 0;
331 Value *Result = CurFun.Values[D.Num];
332 if (Ty != Result->getType()) {
333 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
334 Result->getType()->getDescription() + "' does not match "
335 "expected type, '" + Ty->getDescription() + "'");
336 return 0;
337 }
338 return Result;
339 }
340 case ValID::GlobalID: { // Is it a numbered definition?
341 if (D.Num >= CurModule.Values.size())
342 return 0;
343 Value *Result = CurModule.Values[D.Num];
344 if (Ty != Result->getType()) {
345 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
346 Result->getType()->getDescription() + "' does not match "
347 "expected type, '" + Ty->getDescription() + "'");
348 return 0;
349 }
350 return Result;
351 }
352
353 case ValID::LocalName: { // Is it a named definition?
354 if (!inFunctionScope())
355 return 0;
356 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
357 Value *N = SymTab.lookup(D.getName());
358 if (N == 0)
359 return 0;
360 if (N->getType() != Ty)
361 return 0;
362
363 D.destroy(); // Free old strdup'd memory...
364 return N;
365 }
366 case ValID::GlobalName: { // Is it a named definition?
367 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
368 Value *N = SymTab.lookup(D.getName());
369 if (N == 0)
370 return 0;
371 if (N->getType() != Ty)
372 return 0;
373
374 D.destroy(); // Free old strdup'd memory...
375 return N;
376 }
377
378 // Check to make sure that "Ty" is an integral type, and that our
379 // value will fit into the specified type...
380 case ValID::ConstSIntVal: // Is it a constant pool reference??
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000381 if (!isa<IntegerType>(Ty) ||
382 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 GenerateError("Signed integral constant '" +
384 itostr(D.ConstPool64) + "' is invalid for type '" +
385 Ty->getDescription() + "'");
386 return 0;
387 }
388 return ConstantInt::get(Ty, D.ConstPool64, true);
389
390 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000391 if (isa<IntegerType>(Ty) &&
392 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 return ConstantInt::get(Ty, D.UConstPool64);
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000394
395 if (!isa<IntegerType>(Ty) ||
396 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range for type '" +
399 Ty->getDescription() + "'");
400 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 }
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000402 // This is really a signed reference. Transmogrify.
403 return ConstantInt::get(Ty, D.ConstPool64, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404
405 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Chris Lattner97d8e5f2008-02-19 04:36:07 +0000406 if (!Ty->isFloatingPoint() ||
407 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 GenerateError("FP constant invalid for type");
409 return 0;
410 }
Chris Lattner5e0610f2008-04-20 00:41:09 +0000411 // Lexer has no type info, so builds all float and double FP constants
Dale Johannesen1616e902007-09-11 18:32:33 +0000412 // as double. Fix this here. Long double does not need this.
413 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
414 Ty==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000415 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000416 return ConstantFP::get(*D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417
418 case ValID::ConstNullVal: // Is it a null value?
419 if (!isa<PointerType>(Ty)) {
420 GenerateError("Cannot create a a non pointer null");
421 return 0;
422 }
423 return ConstantPointerNull::get(cast<PointerType>(Ty));
424
425 case ValID::ConstUndefVal: // Is it an undef value?
426 return UndefValue::get(Ty);
427
428 case ValID::ConstZeroVal: // Is it a zero value?
429 return Constant::getNullValue(Ty);
430
431 case ValID::ConstantVal: // Fully resolved constant?
432 if (D.ConstantValue->getType() != Ty) {
433 GenerateError("Constant expression type different from required type");
434 return 0;
435 }
436 return D.ConstantValue;
437
438 case ValID::InlineAsmVal: { // Inline asm expression
439 const PointerType *PTy = dyn_cast<PointerType>(Ty);
440 const FunctionType *FTy =
441 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
442 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
443 GenerateError("Invalid type for asm constraint string");
444 return 0;
445 }
446 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
447 D.IAD->HasSideEffects);
448 D.destroy(); // Free InlineAsmDescriptor.
449 return IA;
450 }
451 default:
452 assert(0 && "Unhandled case!");
453 return 0;
454 } // End of switch
455
456 assert(0 && "Unhandled case!");
457 return 0;
458}
459
460// getVal - This function is identical to getExistingVal, except that if a
461// value is not already defined, it "improvises" by creating a placeholder var
462// that looks and acts just like the requested variable. When the value is
463// defined later, all uses of the placeholder variable are replaced with the
464// real thing.
465//
466static Value *getVal(const Type *Ty, const ValID &ID) {
467 if (Ty == Type::LabelTy) {
468 GenerateError("Cannot use a basic block here");
469 return 0;
470 }
471
472 // See if the value has already been defined.
473 Value *V = getExistingVal(Ty, ID);
474 if (V) return V;
475 if (TriggerError) return 0;
476
477 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
Dan Gohmane6b1ee62008-05-23 01:55:30 +0000478 GenerateError("Invalid use of a non-first-class type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479 return 0;
480 }
481
482 // If we reached here, we referenced either a symbol that we don't know about
483 // or an id number that hasn't been read yet. We may be referencing something
484 // forward, so just create an entry to be resolved later and get to it...
485 //
486 switch (ID.Type) {
487 case ValID::GlobalName:
488 case ValID::GlobalID: {
489 const PointerType *PTy = dyn_cast<PointerType>(Ty);
490 if (!PTy) {
491 GenerateError("Invalid type for reference to global" );
492 return 0;
493 }
494 const Type* ElTy = PTy->getElementType();
495 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
Gabor Greifd6da1d02008-04-06 20:25:17 +0000496 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 else
Christopher Lamb44d62f62007-12-11 08:59:05 +0000498 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
499 (Module*)0, false, PTy->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 break;
501 }
502 default:
503 V = new Argument(Ty);
504 }
505
506 // Remember where this forward reference came from. FIXME, shouldn't we try
507 // to recycle these things??
508 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
Chris Lattner17e73c22007-11-18 08:46:26 +0000509 LLLgetLineNo())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
511 if (inFunctionScope())
512 InsertValue(V, CurFun.LateResolveValues);
513 else
514 InsertValue(V, CurModule.LateResolveValues);
515 return V;
516}
517
518/// defineBBVal - This is a definition of a new basic block with the specified
519/// identifier which must be the same as CurFun.NextValNum, if its numeric.
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000520static BasicBlock *defineBBVal(const ValID &ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 assert(inFunctionScope() && "Can't get basic block at global scope!");
522
523 BasicBlock *BB = 0;
524
525 // First, see if this was forward referenced
526
527 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
528 if (BBI != CurFun.BBForwardRefs.end()) {
529 BB = BBI->second;
530 // The forward declaration could have been inserted anywhere in the
531 // function: insert it into the correct place now.
532 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
533 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
534
535 // We're about to erase the entry, save the key so we can clean it up.
536 ValID Tmp = BBI->first;
537
538 // Erase the forward ref from the map as its no longer "forward"
539 CurFun.BBForwardRefs.erase(ID);
540
541 // The key has been removed from the map but so we don't want to leave
542 // strdup'd memory around so destroy it too.
543 Tmp.destroy();
544
545 // If its a numbered definition, bump the number and set the BB value.
546 if (ID.Type == ValID::LocalID) {
547 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
548 InsertValue(BB);
549 }
Nick Lewycky31f5f242008-03-02 02:48:09 +0000550 } else {
551 // We haven't seen this BB before and its first mention is a definition.
552 // Just create it and return it.
553 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
Gabor Greifd6da1d02008-04-06 20:25:17 +0000554 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Nick Lewycky31f5f242008-03-02 02:48:09 +0000555 if (ID.Type == ValID::LocalID) {
556 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
557 InsertValue(BB);
558 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 }
560
Nick Lewycky31f5f242008-03-02 02:48:09 +0000561 ID.destroy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562 return BB;
563}
564
565/// getBBVal - get an existing BB value or create a forward reference for it.
566///
567static BasicBlock *getBBVal(const ValID &ID) {
568 assert(inFunctionScope() && "Can't get basic block at global scope!");
569
570 BasicBlock *BB = 0;
571
572 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
573 if (BBI != CurFun.BBForwardRefs.end()) {
574 BB = BBI->second;
575 } if (ID.Type == ValID::LocalName) {
576 std::string Name = ID.getName();
577 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000578 if (N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 if (N->getType()->getTypeID() == Type::LabelTyID)
580 BB = cast<BasicBlock>(N);
581 else
582 GenerateError("Reference to label '" + Name + "' is actually of type '"+
583 N->getType()->getDescription() + "'");
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000584 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 } else if (ID.Type == ValID::LocalID) {
586 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
587 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
588 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
589 else
590 GenerateError("Reference to label '%" + utostr(ID.Num) +
591 "' is actually of type '"+
592 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
593 }
594 } else {
595 GenerateError("Illegal label reference " + ID.getName());
596 return 0;
597 }
598
599 // If its already been defined, return it now.
600 if (BB) {
601 ID.destroy(); // Free strdup'd memory.
602 return BB;
603 }
604
605 // Otherwise, this block has not been seen before, create it.
606 std::string Name;
607 if (ID.Type == ValID::LocalName)
608 Name = ID.getName();
Gabor Greifd6da1d02008-04-06 20:25:17 +0000609 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610
611 // Insert it in the forward refs map.
612 CurFun.BBForwardRefs[ID] = BB;
613
614 return BB;
615}
616
617
618//===----------------------------------------------------------------------===//
619// Code to handle forward references in instructions
620//===----------------------------------------------------------------------===//
621//
622// This code handles the late binding needed with statements that reference
623// values not defined yet... for example, a forward branch, or the PHI node for
624// a loop body.
625//
626// This keeps a table (CurFun.LateResolveValues) of all such forward references
627// and back patchs after we are done.
628//
629
630// ResolveDefinitions - If we could not resolve some defs at parsing
631// time (forward branches, phi functions for loops, etc...) resolve the
632// defs now...
633//
634static void
635ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
636 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
637 while (!LateResolvers.empty()) {
638 Value *V = LateResolvers.back();
639 LateResolvers.pop_back();
640
641 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
642 CurModule.PlaceHolderInfo.find(V);
643 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
644
645 ValID &DID = PHI->second.first;
646
647 Value *TheRealValue = getExistingVal(V->getType(), DID);
648 if (TriggerError)
649 return;
650 if (TheRealValue) {
651 V->replaceAllUsesWith(TheRealValue);
652 delete V;
653 CurModule.PlaceHolderInfo.erase(PHI);
654 } else if (FutureLateResolvers) {
655 // Functions have their unresolved items forwarded to the module late
656 // resolver table
657 InsertValue(V, *FutureLateResolvers);
658 } else {
659 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
660 GenerateError("Reference to an invalid definition: '" +DID.getName()+
661 "' of type '" + V->getType()->getDescription() + "'",
662 PHI->second.second);
663 return;
664 } else {
665 GenerateError("Reference to an invalid definition: #" +
666 itostr(DID.Num) + " of type '" +
667 V->getType()->getDescription() + "'",
668 PHI->second.second);
669 return;
670 }
671 }
672 }
673 LateResolvers.clear();
674}
675
676// ResolveTypeTo - A brand new type was just declared. This means that (if
677// name is not null) things referencing Name can be resolved. Otherwise, things
678// refering to the number can be resolved. Do this now.
679//
680static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
681 ValID D;
682 if (Name)
683 D = ValID::createLocalName(*Name);
684 else
685 D = ValID::createLocalID(CurModule.Types.size());
686
687 std::map<ValID, PATypeHolder>::iterator I =
688 CurModule.LateResolveTypes.find(D);
689 if (I != CurModule.LateResolveTypes.end()) {
690 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
691 CurModule.LateResolveTypes.erase(I);
692 }
693}
694
695// setValueName - Set the specified value to the name given. The name may be
696// null potentially, in which case this is a noop. The string passed in is
697// assumed to be a malloc'd string buffer, and is free'd by this function.
698//
699static void setValueName(Value *V, std::string *NameStr) {
700 if (!NameStr) return;
701 std::string Name(*NameStr); // Copy string
702 delete NameStr; // Free old string
703
704 if (V->getType() == Type::VoidTy) {
705 GenerateError("Can't assign name '" + Name+"' to value with void type");
706 return;
707 }
708
709 assert(inFunctionScope() && "Must be in function scope!");
710 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
711 if (ST.lookup(Name)) {
712 GenerateError("Redefinition of value '" + Name + "' of type '" +
713 V->getType()->getDescription() + "'");
714 return;
715 }
716
717 // Set the name.
718 V->setName(Name);
719}
720
721/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
722/// this is a declaration, otherwise it is a definition.
723static GlobalVariable *
724ParseGlobalVariable(std::string *NameStr,
725 GlobalValue::LinkageTypes Linkage,
726 GlobalValue::VisibilityTypes Visibility,
727 bool isConstantGlobal, const Type *Ty,
Christopher Lamb44d62f62007-12-11 08:59:05 +0000728 Constant *Initializer, bool IsThreadLocal,
729 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 if (isa<FunctionType>(Ty)) {
731 GenerateError("Cannot declare global vars of function type");
732 return 0;
733 }
Dan Gohman36782aa2008-05-23 18:23:11 +0000734 if (Ty == Type::LabelTy) {
735 GenerateError("Cannot declare global vars of label type");
736 return 0;
737 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738
Christopher Lamb44d62f62007-12-11 08:59:05 +0000739 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740
741 std::string Name;
742 if (NameStr) {
743 Name = *NameStr; // Copy string
744 delete NameStr; // Free old string
745 }
746
747 // See if this global value was forward referenced. If so, recycle the
748 // object.
749 ValID ID;
750 if (!Name.empty()) {
751 ID = ValID::createGlobalName(Name);
752 } else {
753 ID = ValID::createGlobalID(CurModule.Values.size());
754 }
755
756 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
757 // Move the global to the end of the list, from whereever it was
758 // previously inserted.
759 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
760 CurModule.CurrentModule->getGlobalList().remove(GV);
761 CurModule.CurrentModule->getGlobalList().push_back(GV);
762 GV->setInitializer(Initializer);
763 GV->setLinkage(Linkage);
764 GV->setVisibility(Visibility);
765 GV->setConstant(isConstantGlobal);
766 GV->setThreadLocal(IsThreadLocal);
767 InsertValue(GV, CurModule.Values);
768 return GV;
769 }
770
771 // If this global has a name
772 if (!Name.empty()) {
773 // if the global we're parsing has an initializer (is a definition) and
774 // has external linkage.
775 if (Initializer && Linkage != GlobalValue::InternalLinkage)
776 // If there is already a global with external linkage with this name
777 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
778 // If we allow this GVar to get created, it will be renamed in the
779 // symbol table because it conflicts with an existing GVar. We can't
780 // allow redefinition of GVars whose linking indicates that their name
781 // must stay the same. Issue the error.
782 GenerateError("Redefinition of global variable named '" + Name +
783 "' of type '" + Ty->getDescription() + "'");
784 return 0;
785 }
786 }
787
788 // Otherwise there is no existing GV to use, create one now.
789 GlobalVariable *GV =
790 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb44d62f62007-12-11 08:59:05 +0000791 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 GV->setVisibility(Visibility);
793 InsertValue(GV, CurModule.Values);
794 return GV;
795}
796
797// setTypeName - Set the specified type to the name given. The name may be
798// null potentially, in which case this is a noop. The string passed in is
799// assumed to be a malloc'd string buffer, and is freed by this function.
800//
801// This function returns true if the type has already been defined, but is
802// allowed to be redefined in the specified context. If the name is a new name
803// for the type plane, it is inserted and false is returned.
804static bool setTypeName(const Type *T, std::string *NameStr) {
805 assert(!inFunctionScope() && "Can't give types function-local names!");
806 if (NameStr == 0) return false;
807
808 std::string Name(*NameStr); // Copy string
809 delete NameStr; // Free old string
810
811 // We don't allow assigning names to void type
812 if (T == Type::VoidTy) {
813 GenerateError("Can't assign name '" + Name + "' to the void type");
814 return false;
815 }
816
817 // Set the type name, checking for conflicts as we do so.
818 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
819
820 if (AlreadyExists) { // Inserting a name that is already defined???
821 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
822 assert(Existing && "Conflict but no matching type?!");
823
824 // There is only one case where this is allowed: when we are refining an
825 // opaque type. In this case, Existing will be an opaque type.
826 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
827 // We ARE replacing an opaque type!
828 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
829 return true;
830 }
831
832 // Otherwise, this is an attempt to redefine a type. That's okay if
833 // the redefinition is identical to the original. This will be so if
834 // Existing and T point to the same Type object. In this one case we
835 // allow the equivalent redefinition.
836 if (Existing == T) return true; // Yes, it's equal.
837
838 // Any other kind of (non-equivalent) redefinition is an error.
839 GenerateError("Redefinition of type named '" + Name + "' of type '" +
840 T->getDescription() + "'");
841 }
842
843 return false;
844}
845
846//===----------------------------------------------------------------------===//
847// Code for handling upreferences in type names...
848//
849
850// TypeContains - Returns true if Ty directly contains E in it.
851//
852static bool TypeContains(const Type *Ty, const Type *E) {
853 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
854 E) != Ty->subtype_end();
855}
856
857namespace {
858 struct UpRefRecord {
859 // NestingLevel - The number of nesting levels that need to be popped before
860 // this type is resolved.
861 unsigned NestingLevel;
862
863 // LastContainedTy - This is the type at the current binding level for the
864 // type. Every time we reduce the nesting level, this gets updated.
865 const Type *LastContainedTy;
866
867 // UpRefTy - This is the actual opaque type that the upreference is
868 // represented with.
869 OpaqueType *UpRefTy;
870
871 UpRefRecord(unsigned NL, OpaqueType *URTy)
872 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
873 };
874}
875
876// UpRefs - A list of the outstanding upreferences that need to be resolved.
877static std::vector<UpRefRecord> UpRefs;
878
879/// HandleUpRefs - Every time we finish a new layer of types, this function is
880/// called. It loops through the UpRefs vector, which is a list of the
881/// currently active types. For each type, if the up reference is contained in
882/// the newly completed type, we decrement the level count. When the level
883/// count reaches zero, the upreferenced type is the type that is passed in:
884/// thus we can complete the cycle.
885///
886static PATypeHolder HandleUpRefs(const Type *ty) {
887 // If Ty isn't abstract, or if there are no up-references in it, then there is
888 // nothing to resolve here.
889 if (!ty->isAbstract() || UpRefs.empty()) return ty;
890
891 PATypeHolder Ty(ty);
892 UR_OUT("Type '" << Ty->getDescription() <<
893 "' newly formed. Resolving upreferences.\n" <<
894 UpRefs.size() << " upreferences active!\n");
895
896 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
897 // to zero), we resolve them all together before we resolve them to Ty. At
898 // the end of the loop, if there is anything to resolve to Ty, it will be in
899 // this variable.
900 OpaqueType *TypeToResolve = 0;
901
902 for (unsigned i = 0; i != UpRefs.size(); ++i) {
903 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
904 << UpRefs[i].second->getDescription() << ") = "
905 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
906 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
907 // Decrement level of upreference
908 unsigned Level = --UpRefs[i].NestingLevel;
909 UpRefs[i].LastContainedTy = Ty;
910 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
911 if (Level == 0) { // Upreference should be resolved!
912 if (!TypeToResolve) {
913 TypeToResolve = UpRefs[i].UpRefTy;
914 } else {
915 UR_OUT(" * Resolving upreference for "
916 << UpRefs[i].second->getDescription() << "\n";
917 std::string OldName = UpRefs[i].UpRefTy->getDescription());
918 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
919 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
920 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
921 }
922 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
923 --i; // Do not skip the next element...
924 }
925 }
926 }
927
928 if (TypeToResolve) {
929 UR_OUT(" * Resolving upreference for "
930 << UpRefs[i].second->getDescription() << "\n";
931 std::string OldName = TypeToResolve->getDescription());
932 TypeToResolve->refineAbstractTypeTo(Ty);
933 }
934
935 return Ty;
936}
937
938//===----------------------------------------------------------------------===//
939// RunVMAsmParser - Define an interface to this parser
940//===----------------------------------------------------------------------===//
941//
942static Module* RunParser(Module * M);
943
Chris Lattner17e73c22007-11-18 08:46:26 +0000944Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
945 InitLLLexer(MB);
946 Module *M = RunParser(new Module(LLLgetFilename()));
947 FreeLexer();
948 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949}
950
951%}
952
953%union {
954 llvm::Module *ModuleVal;
955 llvm::Function *FunctionVal;
956 llvm::BasicBlock *BasicBlockVal;
957 llvm::TerminatorInst *TermInstVal;
958 llvm::Instruction *InstVal;
959 llvm::Constant *ConstVal;
960
961 const llvm::Type *PrimType;
962 std::list<llvm::PATypeHolder> *TypeList;
963 llvm::PATypeHolder *TypeVal;
964 llvm::Value *ValueVal;
965 std::vector<llvm::Value*> *ValueList;
Dan Gohmane5febe42008-05-31 00:58:22 +0000966 std::vector<unsigned> *ConstantList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 llvm::ArgListType *ArgList;
968 llvm::TypeWithAttrs TypeWithAttrs;
969 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000970 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971
972 // Represent the RHS of PHI node
973 std::list<std::pair<llvm::Value*,
974 llvm::BasicBlock*> > *PHIList;
975 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
976 std::vector<llvm::Constant*> *ConstVector;
977
978 llvm::GlobalValue::LinkageTypes Linkage;
979 llvm::GlobalValue::VisibilityTypes Visibility;
Dale Johannesenf4666f52008-02-19 21:38:47 +0000980 llvm::ParameterAttributes ParamAttrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 llvm::APInt *APIntVal;
982 int64_t SInt64Val;
983 uint64_t UInt64Val;
984 int SIntVal;
985 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000986 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 bool BoolVal;
988
989 std::string *StrVal; // This memory must be deleted
990 llvm::ValID ValIDVal;
991
992 llvm::Instruction::BinaryOps BinaryOpVal;
993 llvm::Instruction::TermOps TermOpVal;
994 llvm::Instruction::MemoryOps MemOpVal;
995 llvm::Instruction::CastOps CastOpVal;
996 llvm::Instruction::OtherOps OtherOpVal;
997 llvm::ICmpInst::Predicate IPredicate;
998 llvm::FCmpInst::Predicate FPredicate;
999}
1000
1001%type <ModuleVal> Module
1002%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1003%type <BasicBlockVal> BasicBlock InstructionList
1004%type <TermInstVal> BBTerminatorInst
1005%type <InstVal> Inst InstVal MemoryInst
1006%type <ConstVal> ConstVal ConstExpr AliaseeRef
1007%type <ConstVector> ConstVector
1008%type <ArgList> ArgList ArgListH
1009%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001010%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011%type <ValueList> IndexList // For GEP indices
Dan Gohmane5febe42008-05-31 00:58:22 +00001012%type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013%type <TypeList> TypeListI
1014%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1015%type <TypeWithAttrs> ArgType
1016%type <JumpTable> JumpTable
1017%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1018%type <BoolVal> ThreadLocal // 'thread_local' or not
1019%type <BoolVal> OptVolatile // 'volatile' or not
1020%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1021%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1022%type <Linkage> GVInternalLinkage GVExternalLinkage
1023%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1024%type <Linkage> AliasLinkage
1025%type <Visibility> GVVisibilityStyle
1026
1027// ValueRef - Unresolved reference to a definition or BB
1028%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1029%type <ValueVal> ResolvedVal // <type> <valref> pair
Devang Patel036f0382008-02-20 22:39:45 +00001030%type <ValueList> ReturnedVal
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031// Tokens and types for handling constant integer values
1032//
1033// ESINT64VAL - A negative number within long long range
1034%token <SInt64Val> ESINT64VAL
1035
1036// EUINT64VAL - A positive number within uns. long long range
1037%token <UInt64Val> EUINT64VAL
1038
1039// ESAPINTVAL - A negative number with arbitrary precision
1040%token <APIntVal> ESAPINTVAL
1041
1042// EUAPINTVAL - A positive number with arbitrary precision
1043%token <APIntVal> EUAPINTVAL
1044
1045%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1046%token <FPVal> FPVAL // Float or Double constant
1047
1048// Built in types...
1049%type <TypeVal> Types ResultTypes
1050%type <PrimType> IntType FPType PrimType // Classifications
1051%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001052%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053%token TYPE
1054
1055
1056%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1057%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1058%type <StrVal> LocalName OptLocalName OptLocalAssign
1059%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001060%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061
Christopher Lamb20a39e92007-12-12 08:44:39 +00001062%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063
1064%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1065%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1066%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
Dale Johannesen58562d32008-05-14 20:14:09 +00001067%token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
Christopher Lamb44d62f62007-12-11 08:59:05 +00001068%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1070%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00001071%token DATALAYOUT
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072%type <UIntVal> OptCallingConv
1073%type <ParamAttrs> OptParamAttrs ParamAttr
1074%type <ParamAttrs> OptFuncAttrs FuncAttr
1075
1076// Basic Block Terminating Operators
1077%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1078
1079// Binary Operators
1080%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1081%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1082%token <BinaryOpVal> SHL LSHR ASHR
1083
Nate Begeman646fa482008-05-12 19:01:56 +00001084%token <OtherOpVal> ICMP FCMP VICMP VFCMP
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085%type <IPredicate> IPredicates
1086%type <FPredicate> FPredicates
1087%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1088%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1089
1090// Memory Instructions
1091%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1092
1093// Cast Operators
1094%type <CastOpVal> CastOps
1095%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1096%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1097
1098// Other Operators
1099%token <OtherOpVal> PHI_TOK SELECT VAARG
1100%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Devang Patele5c806a2008-02-19 22:26:37 +00001101%token <OtherOpVal> GETRESULT
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001102%token <OtherOpVal> EXTRACTVALUE INSERTVALUE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103
1104// Function Attributes
Duncan Sands38947cd2007-07-27 12:58:54 +00001105%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001106%token READNONE READONLY GC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107
1108// Visibility Styles
1109%token DEFAULT HIDDEN PROTECTED
1110
1111%start Module
1112%%
1113
1114
1115// Operations that are notably excluded from this list include:
1116// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1117//
1118ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1119LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1120CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1121 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1122
1123IPredicates
1124 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1125 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1126 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1127 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1128 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1129 ;
1130
1131FPredicates
1132 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1133 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1134 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1135 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1136 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1137 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1138 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1139 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1140 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1141 ;
1142
1143// These are some types that allow classification if we only want a particular
1144// thing... for example, only a signed, unsigned, or integral type.
1145IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001146FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147
1148LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1149OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1150
Christopher Lamb20a39e92007-12-12 08:44:39 +00001151OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1152 | /*empty*/ { $$=0; };
1153
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154/// OptLocalAssign - Value producing statements have an optional assignment
1155/// component.
1156OptLocalAssign : LocalName '=' {
1157 $$ = $1;
1158 CHECK_FOR_ERROR
1159 }
1160 | /*empty*/ {
1161 $$ = 0;
1162 CHECK_FOR_ERROR
1163 };
1164
1165GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1166
1167OptGlobalAssign : GlobalAssign
1168 | /*empty*/ {
1169 $$ = 0;
1170 CHECK_FOR_ERROR
1171 };
1172
1173GlobalAssign : GlobalName '=' {
1174 $$ = $1;
1175 CHECK_FOR_ERROR
1176 };
1177
1178GVInternalLinkage
1179 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1180 | WEAK { $$ = GlobalValue::WeakLinkage; }
1181 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1182 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1183 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
Dale Johannesen58562d32008-05-14 20:14:09 +00001184 | COMMON { $$ = GlobalValue::CommonLinkage; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 ;
1186
1187GVExternalLinkage
1188 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1189 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1190 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1191 ;
1192
1193GVVisibilityStyle
1194 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1195 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1196 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1197 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1198 ;
1199
1200FunctionDeclareLinkage
1201 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1202 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1203 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1204 ;
1205
1206FunctionDefineLinkage
1207 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1208 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1209 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1210 | WEAK { $$ = GlobalValue::WeakLinkage; }
1211 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1212 ;
1213
1214AliasLinkage
1215 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1216 | WEAK { $$ = GlobalValue::WeakLinkage; }
1217 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1218 ;
1219
1220OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1221 CCC_TOK { $$ = CallingConv::C; } |
1222 FASTCC_TOK { $$ = CallingConv::Fast; } |
1223 COLDCC_TOK { $$ = CallingConv::Cold; } |
1224 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1225 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1226 CC_TOK EUINT64VAL {
1227 if ((unsigned)$2 != $2)
1228 GEN_ERROR("Calling conv too large");
1229 $$ = $2;
1230 CHECK_FOR_ERROR
1231 };
1232
Reid Spencerf234bed2007-07-19 23:13:04 +00001233ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001234 | ZEXT { $$ = ParamAttr::ZExt; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001235 | SIGNEXT { $$ = ParamAttr::SExt; }
Reid Spencer2abbad92007-07-31 02:57:37 +00001236 | SEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 | INREG { $$ = ParamAttr::InReg; }
1238 | SRET { $$ = ParamAttr::StructRet; }
1239 | NOALIAS { $$ = ParamAttr::NoAlias; }
Duncan Sands38947cd2007-07-27 12:58:54 +00001240 | BYVAL { $$ = ParamAttr::ByVal; }
1241 | NEST { $$ = ParamAttr::Nest; }
Dale Johannesen9b398782008-02-22 17:49:45 +00001242 | ALIGN EUINT64VAL { $$ =
1243 ParamAttr::constructAlignmentFromInt($2); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 ;
1245
1246OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1247 | OptParamAttrs ParamAttr {
1248 $$ = $1 | $2;
1249 }
1250 ;
1251
1252FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1253 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spencerf234bed2007-07-19 23:13:04 +00001254 | ZEROEXT { $$ = ParamAttr::ZExt; }
1255 | SIGNEXT { $$ = ParamAttr::SExt; }
Duncan Sands13e13f82007-11-22 20:23:04 +00001256 | READNONE { $$ = ParamAttr::ReadNone; }
1257 | READONLY { $$ = ParamAttr::ReadOnly; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 ;
1259
1260OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1261 | OptFuncAttrs FuncAttr {
1262 $$ = $1 | $2;
1263 }
1264 ;
1265
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001266OptGC : /* empty */ { $$ = 0; }
1267 | GC STRINGCONSTANT {
1268 $$ = $2;
1269 }
1270 ;
1271
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1273// a comma before it.
1274OptAlign : /*empty*/ { $$ = 0; } |
1275 ALIGN EUINT64VAL {
1276 $$ = $2;
1277 if ($$ != 0 && !isPowerOf2_32($$))
1278 GEN_ERROR("Alignment must be a power of two");
1279 CHECK_FOR_ERROR
1280};
1281OptCAlign : /*empty*/ { $$ = 0; } |
1282 ',' ALIGN EUINT64VAL {
1283 $$ = $3;
1284 if ($$ != 0 && !isPowerOf2_32($$))
1285 GEN_ERROR("Alignment must be a power of two");
1286 CHECK_FOR_ERROR
1287};
1288
1289
Christopher Lamb44d62f62007-12-11 08:59:05 +00001290
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291SectionString : SECTION STRINGCONSTANT {
1292 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1293 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1294 GEN_ERROR("Invalid character in section name");
1295 $$ = $2;
1296 CHECK_FOR_ERROR
1297};
1298
1299OptSection : /*empty*/ { $$ = 0; } |
1300 SectionString { $$ = $1; };
1301
1302// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1303// is set to be the global we are processing.
1304//
1305GlobalVarAttributes : /* empty */ {} |
1306 ',' GlobalVarAttribute GlobalVarAttributes {};
1307GlobalVarAttribute : SectionString {
1308 CurGV->setSection(*$1);
1309 delete $1;
1310 CHECK_FOR_ERROR
1311 }
1312 | ALIGN EUINT64VAL {
1313 if ($2 != 0 && !isPowerOf2_32($2))
1314 GEN_ERROR("Alignment must be a power of two");
1315 CurGV->setAlignment($2);
1316 CHECK_FOR_ERROR
1317 };
1318
1319//===----------------------------------------------------------------------===//
1320// Types includes all predefined types... except void, because it can only be
1321// used in specific contexts (function returning void for example).
1322
1323// Derived types are added later...
1324//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001325PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326
1327Types
1328 : OPAQUE {
1329 $$ = new PATypeHolder(OpaqueType::get());
1330 CHECK_FOR_ERROR
1331 }
1332 | PrimType {
1333 $$ = new PATypeHolder($1);
1334 CHECK_FOR_ERROR
1335 }
Christopher Lamb20a39e92007-12-12 08:44:39 +00001336 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 if (*$1 == Type::LabelTy)
1338 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb20a39e92007-12-12 08:44:39 +00001339 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb44d62f62007-12-11 08:59:05 +00001340 delete $1;
1341 CHECK_FOR_ERROR
1342 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 | SymbolicValueRef { // Named types are also simple types...
1344 const Type* tmp = getTypeVal($1);
1345 CHECK_FOR_ERROR
1346 $$ = new PATypeHolder(tmp);
1347 }
1348 | '\\' EUINT64VAL { // Type UpReference
1349 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1350 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1351 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1352 $$ = new PATypeHolder(OT);
1353 UR_OUT("New Upreference!\n");
1354 CHECK_FOR_ERROR
1355 }
1356 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001357 // Allow but ignore attributes on function types; this permits auto-upgrade.
1358 // FIXME: remove in LLVM 3.0.
Chris Lattner62de9332008-04-23 05:36:58 +00001359 const Type *RetTy = *$1;
1360 if (!FunctionType::isValidReturnType(RetTy))
1361 GEN_ERROR("Invalid result type for LLVM function");
1362
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001365 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001366 const Type *Ty = I->Ty->get();
1367 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001369
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1371 if (isVarArg) Params.pop_back();
1372
Anton Korobeynikov9ab58082007-12-03 21:00:45 +00001373 for (unsigned i = 0; i != Params.size(); ++i)
1374 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1375 GEN_ERROR("Function arguments must be value types!");
1376
1377 CHECK_FOR_ERROR
1378
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001379 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 delete $3; // Delete the argument list
1381 delete $1; // Delete the return type handle
1382 $$ = new PATypeHolder(HandleUpRefs(FT));
1383 CHECK_FOR_ERROR
1384 }
1385 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001386 // Allow but ignore attributes on function types; this permits auto-upgrade.
1387 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001390 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 const Type* Ty = I->Ty->get();
1392 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1396 if (isVarArg) Params.pop_back();
1397
Anton Korobeynikov9ab58082007-12-03 21:00:45 +00001398 for (unsigned i = 0; i != Params.size(); ++i)
1399 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1400 GEN_ERROR("Function arguments must be value types!");
1401
1402 CHECK_FOR_ERROR
1403
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001404 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 delete $3; // Delete the argument list
1406 $$ = new PATypeHolder(HandleUpRefs(FT));
1407 CHECK_FOR_ERROR
1408 }
1409
1410 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
Dan Gohmance5734e2008-05-23 21:40:55 +00001411 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 delete $4;
1413 CHECK_FOR_ERROR
1414 }
1415 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1416 const llvm::Type* ElemTy = $4->get();
1417 if ((unsigned)$2 != $2)
1418 GEN_ERROR("Unsigned result not equal to signed result");
1419 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1420 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1422 delete $4;
1423 CHECK_FOR_ERROR
1424 }
1425 | '{' TypeListI '}' { // Structure type?
1426 std::vector<const Type*> Elements;
1427 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1428 E = $2->end(); I != E; ++I)
1429 Elements.push_back(*I);
1430
1431 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1432 delete $2;
1433 CHECK_FOR_ERROR
1434 }
1435 | '{' '}' { // Empty structure type?
1436 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1437 CHECK_FOR_ERROR
1438 }
1439 | '<' '{' TypeListI '}' '>' {
1440 std::vector<const Type*> Elements;
1441 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1442 E = $3->end(); I != E; ++I)
1443 Elements.push_back(*I);
1444
1445 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1446 delete $3;
1447 CHECK_FOR_ERROR
1448 }
1449 | '<' '{' '}' '>' { // Empty structure type?
1450 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1451 CHECK_FOR_ERROR
1452 }
1453 ;
1454
1455ArgType
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001456 : Types OptParamAttrs {
1457 // Allow but ignore attributes on function types; this permits auto-upgrade.
1458 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 $$.Ty = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001460 $$.Attrs = ParamAttr::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001461 }
1462 ;
1463
1464ResultTypes
1465 : Types {
1466 if (!UpRefs.empty())
1467 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Devang Patel62417142008-02-23 01:17:17 +00001468 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 GEN_ERROR("LLVM functions cannot return aggregate types");
1470 $$ = $1;
1471 }
1472 | VOID {
1473 $$ = new PATypeHolder(Type::VoidTy);
1474 }
1475 ;
1476
1477ArgTypeList : ArgType {
1478 $$ = new TypeWithAttrsList();
1479 $$->push_back($1);
1480 CHECK_FOR_ERROR
1481 }
1482 | ArgTypeList ',' ArgType {
1483 ($$=$1)->push_back($3);
1484 CHECK_FOR_ERROR
1485 }
1486 ;
1487
1488ArgTypeListI
1489 : ArgTypeList
1490 | ArgTypeList ',' DOTDOTDOT {
1491 $$=$1;
1492 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1493 TWA.Ty = new PATypeHolder(Type::VoidTy);
1494 $$->push_back(TWA);
1495 CHECK_FOR_ERROR
1496 }
1497 | DOTDOTDOT {
1498 $$ = new TypeWithAttrsList;
1499 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1500 TWA.Ty = new PATypeHolder(Type::VoidTy);
1501 $$->push_back(TWA);
1502 CHECK_FOR_ERROR
1503 }
1504 | /*empty*/ {
1505 $$ = new TypeWithAttrsList();
1506 CHECK_FOR_ERROR
1507 };
1508
1509// TypeList - Used for struct declarations and as a basis for function type
1510// declaration type lists
1511//
1512TypeListI : Types {
1513 $$ = new std::list<PATypeHolder>();
1514 $$->push_back(*$1);
1515 delete $1;
1516 CHECK_FOR_ERROR
1517 }
1518 | TypeListI ',' Types {
1519 ($$=$1)->push_back(*$3);
1520 delete $3;
1521 CHECK_FOR_ERROR
1522 };
1523
1524// ConstVal - The various declarations that go into the constant pool. This
1525// production is used ONLY to represent constants that show up AFTER a 'const',
1526// 'constant' or 'global' token at global scope. Constants that can be inlined
1527// into other expressions (such as integers and constexprs) are handled by the
1528// ResolvedVal, ValueRef and ConstValueRef productions.
1529//
1530ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1531 if (!UpRefs.empty())
1532 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1533 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1534 if (ATy == 0)
1535 GEN_ERROR("Cannot make array constant with type: '" +
1536 (*$1)->getDescription() + "'");
1537 const Type *ETy = ATy->getElementType();
1538 int NumElements = ATy->getNumElements();
1539
1540 // Verify that we have the correct size...
1541 if (NumElements != -1 && NumElements != (int)$3->size())
1542 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1543 utostr($3->size()) + " arguments, but has size of " +
1544 itostr(NumElements) + "");
1545
1546 // Verify all elements are correct type!
1547 for (unsigned i = 0; i < $3->size(); i++) {
1548 if (ETy != (*$3)[i]->getType())
1549 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1550 ETy->getDescription() +"' as required!\nIt is of type '"+
1551 (*$3)[i]->getType()->getDescription() + "'.");
1552 }
1553
1554 $$ = ConstantArray::get(ATy, *$3);
1555 delete $1; delete $3;
1556 CHECK_FOR_ERROR
1557 }
1558 | Types '[' ']' {
1559 if (!UpRefs.empty())
1560 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1561 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1562 if (ATy == 0)
1563 GEN_ERROR("Cannot make array constant with type: '" +
1564 (*$1)->getDescription() + "'");
1565
1566 int NumElements = ATy->getNumElements();
1567 if (NumElements != -1 && NumElements != 0)
1568 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1569 " arguments, but has size of " + itostr(NumElements) +"");
1570 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1571 delete $1;
1572 CHECK_FOR_ERROR
1573 }
1574 | Types 'c' STRINGCONSTANT {
1575 if (!UpRefs.empty())
1576 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1577 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1578 if (ATy == 0)
1579 GEN_ERROR("Cannot make array constant with type: '" +
1580 (*$1)->getDescription() + "'");
1581
1582 int NumElements = ATy->getNumElements();
1583 const Type *ETy = ATy->getElementType();
1584 if (NumElements != -1 && NumElements != int($3->length()))
1585 GEN_ERROR("Can't build string constant of size " +
1586 itostr((int)($3->length())) +
1587 " when array has size " + itostr(NumElements) + "");
1588 std::vector<Constant*> Vals;
1589 if (ETy == Type::Int8Ty) {
1590 for (unsigned i = 0; i < $3->length(); ++i)
1591 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1592 } else {
1593 delete $3;
1594 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1595 }
1596 delete $3;
1597 $$ = ConstantArray::get(ATy, Vals);
1598 delete $1;
1599 CHECK_FOR_ERROR
1600 }
1601 | Types '<' ConstVector '>' { // Nonempty unsized arr
1602 if (!UpRefs.empty())
1603 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1604 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1605 if (PTy == 0)
1606 GEN_ERROR("Cannot make packed constant with type: '" +
1607 (*$1)->getDescription() + "'");
1608 const Type *ETy = PTy->getElementType();
1609 int NumElements = PTy->getNumElements();
1610
1611 // Verify that we have the correct size...
1612 if (NumElements != -1 && NumElements != (int)$3->size())
1613 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1614 utostr($3->size()) + " arguments, but has size of " +
1615 itostr(NumElements) + "");
1616
1617 // Verify all elements are correct type!
1618 for (unsigned i = 0; i < $3->size(); i++) {
1619 if (ETy != (*$3)[i]->getType())
1620 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1621 ETy->getDescription() +"' as required!\nIt is of type '"+
1622 (*$3)[i]->getType()->getDescription() + "'.");
1623 }
1624
1625 $$ = ConstantVector::get(PTy, *$3);
1626 delete $1; delete $3;
1627 CHECK_FOR_ERROR
1628 }
1629 | Types '{' ConstVector '}' {
1630 const StructType *STy = dyn_cast<StructType>($1->get());
1631 if (STy == 0)
1632 GEN_ERROR("Cannot make struct constant with type: '" +
1633 (*$1)->getDescription() + "'");
1634
1635 if ($3->size() != STy->getNumContainedTypes())
1636 GEN_ERROR("Illegal number of initializers for structure type");
1637
1638 // Check to ensure that constants are compatible with the type initializer!
1639 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1640 if ((*$3)[i]->getType() != STy->getElementType(i))
1641 GEN_ERROR("Expected type '" +
1642 STy->getElementType(i)->getDescription() +
1643 "' for element #" + utostr(i) +
1644 " of structure initializer");
1645
1646 // Check to ensure that Type is not packed
1647 if (STy->isPacked())
1648 GEN_ERROR("Unpacked Initializer to vector type '" +
1649 STy->getDescription() + "'");
1650
1651 $$ = ConstantStruct::get(STy, *$3);
1652 delete $1; delete $3;
1653 CHECK_FOR_ERROR
1654 }
1655 | Types '{' '}' {
1656 if (!UpRefs.empty())
1657 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1658 const StructType *STy = dyn_cast<StructType>($1->get());
1659 if (STy == 0)
1660 GEN_ERROR("Cannot make struct constant with type: '" +
1661 (*$1)->getDescription() + "'");
1662
1663 if (STy->getNumContainedTypes() != 0)
1664 GEN_ERROR("Illegal number of initializers for structure type");
1665
1666 // Check to ensure that Type is not packed
1667 if (STy->isPacked())
1668 GEN_ERROR("Unpacked Initializer to vector type '" +
1669 STy->getDescription() + "'");
1670
1671 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1672 delete $1;
1673 CHECK_FOR_ERROR
1674 }
1675 | Types '<' '{' ConstVector '}' '>' {
1676 const StructType *STy = dyn_cast<StructType>($1->get());
1677 if (STy == 0)
1678 GEN_ERROR("Cannot make struct constant with type: '" +
1679 (*$1)->getDescription() + "'");
1680
1681 if ($4->size() != STy->getNumContainedTypes())
1682 GEN_ERROR("Illegal number of initializers for structure type");
1683
1684 // Check to ensure that constants are compatible with the type initializer!
1685 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1686 if ((*$4)[i]->getType() != STy->getElementType(i))
1687 GEN_ERROR("Expected type '" +
1688 STy->getElementType(i)->getDescription() +
1689 "' for element #" + utostr(i) +
1690 " of structure initializer");
1691
1692 // Check to ensure that Type is packed
1693 if (!STy->isPacked())
1694 GEN_ERROR("Vector initializer to non-vector type '" +
1695 STy->getDescription() + "'");
1696
1697 $$ = ConstantStruct::get(STy, *$4);
1698 delete $1; delete $4;
1699 CHECK_FOR_ERROR
1700 }
1701 | Types '<' '{' '}' '>' {
1702 if (!UpRefs.empty())
1703 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1704 const StructType *STy = dyn_cast<StructType>($1->get());
1705 if (STy == 0)
1706 GEN_ERROR("Cannot make struct constant with type: '" +
1707 (*$1)->getDescription() + "'");
1708
1709 if (STy->getNumContainedTypes() != 0)
1710 GEN_ERROR("Illegal number of initializers for structure type");
1711
1712 // Check to ensure that Type is packed
1713 if (!STy->isPacked())
1714 GEN_ERROR("Vector initializer to non-vector type '" +
1715 STy->getDescription() + "'");
1716
1717 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1718 delete $1;
1719 CHECK_FOR_ERROR
1720 }
1721 | Types NULL_TOK {
1722 if (!UpRefs.empty())
1723 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1724 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1725 if (PTy == 0)
1726 GEN_ERROR("Cannot make null pointer constant with type: '" +
1727 (*$1)->getDescription() + "'");
1728
1729 $$ = ConstantPointerNull::get(PTy);
1730 delete $1;
1731 CHECK_FOR_ERROR
1732 }
1733 | Types UNDEF {
1734 if (!UpRefs.empty())
1735 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1736 $$ = UndefValue::get($1->get());
1737 delete $1;
1738 CHECK_FOR_ERROR
1739 }
1740 | Types SymbolicValueRef {
1741 if (!UpRefs.empty())
1742 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1743 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1744 if (Ty == 0)
Devang Patele5c806a2008-02-19 22:26:37 +00001745 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001746
1747 // ConstExprs can exist in the body of a function, thus creating
1748 // GlobalValues whenever they refer to a variable. Because we are in
1749 // the context of a function, getExistingVal will search the functions
1750 // symbol table instead of the module symbol table for the global symbol,
1751 // which throws things all off. To get around this, we just tell
1752 // getExistingVal that we are at global scope here.
1753 //
1754 Function *SavedCurFn = CurFun.CurrentFunction;
1755 CurFun.CurrentFunction = 0;
1756
1757 Value *V = getExistingVal(Ty, $2);
1758 CHECK_FOR_ERROR
1759
1760 CurFun.CurrentFunction = SavedCurFn;
1761
1762 // If this is an initializer for a constant pointer, which is referencing a
1763 // (currently) undefined variable, create a stub now that shall be replaced
1764 // in the future with the right type of variable.
1765 //
1766 if (V == 0) {
1767 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1768 const PointerType *PT = cast<PointerType>(Ty);
1769
1770 // First check to see if the forward references value is already created!
1771 PerModuleInfo::GlobalRefsType::iterator I =
1772 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1773
1774 if (I != CurModule.GlobalRefs.end()) {
1775 V = I->second; // Placeholder already exists, use it...
1776 $2.destroy();
1777 } else {
1778 std::string Name;
1779 if ($2.Type == ValID::GlobalName)
1780 Name = $2.getName();
1781 else if ($2.Type != ValID::GlobalID)
1782 GEN_ERROR("Invalid reference to global");
1783
1784 // Create the forward referenced global.
1785 GlobalValue *GV;
1786 if (const FunctionType *FTy =
1787 dyn_cast<FunctionType>(PT->getElementType())) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00001788 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1789 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001790 } else {
1791 GV = new GlobalVariable(PT->getElementType(), false,
1792 GlobalValue::ExternalWeakLinkage, 0,
1793 Name, CurModule.CurrentModule);
1794 }
1795
1796 // Keep track of the fact that we have a forward ref to recycle it
1797 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1798 V = GV;
1799 }
1800 }
1801
1802 $$ = cast<GlobalValue>(V);
1803 delete $1; // Free the type handle
1804 CHECK_FOR_ERROR
1805 }
1806 | Types ConstExpr {
1807 if (!UpRefs.empty())
1808 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1809 if ($1->get() != $2->getType())
1810 GEN_ERROR("Mismatched types for constant expression: " +
1811 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1812 $$ = $2;
1813 delete $1;
1814 CHECK_FOR_ERROR
1815 }
1816 | Types ZEROINITIALIZER {
1817 if (!UpRefs.empty())
1818 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1819 const Type *Ty = $1->get();
1820 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1821 GEN_ERROR("Cannot create a null initialized value of this type");
1822 $$ = Constant::getNullValue(Ty);
1823 delete $1;
1824 CHECK_FOR_ERROR
1825 }
1826 | IntType ESINT64VAL { // integral constants
1827 if (!ConstantInt::isValueValidForType($1, $2))
1828 GEN_ERROR("Constant value doesn't fit in type");
1829 $$ = ConstantInt::get($1, $2, true);
1830 CHECK_FOR_ERROR
1831 }
1832 | IntType ESAPINTVAL { // arbitrary precision integer constants
1833 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1834 if ($2->getBitWidth() > BitWidth) {
1835 GEN_ERROR("Constant value does not fit in type");
1836 }
1837 $2->sextOrTrunc(BitWidth);
1838 $$ = ConstantInt::get(*$2);
1839 delete $2;
1840 CHECK_FOR_ERROR
1841 }
1842 | IntType EUINT64VAL { // integral constants
1843 if (!ConstantInt::isValueValidForType($1, $2))
1844 GEN_ERROR("Constant value doesn't fit in type");
1845 $$ = ConstantInt::get($1, $2, false);
1846 CHECK_FOR_ERROR
1847 }
1848 | IntType EUAPINTVAL { // arbitrary precision integer constants
1849 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1850 if ($2->getBitWidth() > BitWidth) {
1851 GEN_ERROR("Constant value does not fit in type");
1852 }
1853 $2->zextOrTrunc(BitWidth);
1854 $$ = ConstantInt::get(*$2);
1855 delete $2;
1856 CHECK_FOR_ERROR
1857 }
1858 | INTTYPE TRUETOK { // Boolean constants
Dan Gohman36782aa2008-05-23 18:23:11 +00001859 if (cast<IntegerType>($1)->getBitWidth() != 1)
1860 GEN_ERROR("Constant true must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861 $$ = ConstantInt::getTrue();
1862 CHECK_FOR_ERROR
1863 }
1864 | INTTYPE FALSETOK { // Boolean constants
Dan Gohman36782aa2008-05-23 18:23:11 +00001865 if (cast<IntegerType>($1)->getBitWidth() != 1)
1866 GEN_ERROR("Constant false must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 $$ = ConstantInt::getFalse();
1868 CHECK_FOR_ERROR
1869 }
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00001870 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001871 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen1616e902007-09-11 18:32:33 +00001873 // Lexer has no type info, so builds all float and double FP constants
1874 // as double. Fix this here. Long double is done right.
1875 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001876 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner5e0610f2008-04-20 00:41:09 +00001877 $$ = ConstantFP::get(*$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001878 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879 CHECK_FOR_ERROR
1880 };
1881
1882
1883ConstExpr: CastOps '(' ConstVal TO Types ')' {
1884 if (!UpRefs.empty())
1885 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1886 Constant *Val = $3;
1887 const Type *DestTy = $5->get();
1888 if (!CastInst::castIsValid($1, $3, DestTy))
1889 GEN_ERROR("invalid cast opcode for cast from '" +
1890 Val->getType()->getDescription() + "' to '" +
1891 DestTy->getDescription() + "'");
1892 $$ = ConstantExpr::getCast($1, $3, DestTy);
1893 delete $5;
1894 }
1895 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1896 if (!isa<PointerType>($3->getType()))
1897 GEN_ERROR("GetElementPtr requires a pointer operand");
1898
1899 const Type *IdxTy =
Dan Gohman8055f772008-05-15 19:50:34 +00001900 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901 if (!IdxTy)
1902 GEN_ERROR("Index list invalid for constant getelementptr");
1903
1904 SmallVector<Constant*, 8> IdxVec;
1905 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1906 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1907 IdxVec.push_back(C);
1908 else
1909 GEN_ERROR("Indices to constant getelementptr must be constants");
1910
1911 delete $4;
1912
1913 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1914 CHECK_FOR_ERROR
1915 }
1916 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1917 if ($3->getType() != Type::Int1Ty)
1918 GEN_ERROR("Select condition must be of boolean type");
1919 if ($5->getType() != $7->getType())
1920 GEN_ERROR("Select operand types must match");
1921 $$ = ConstantExpr::getSelect($3, $5, $7);
1922 CHECK_FOR_ERROR
1923 }
1924 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1925 if ($3->getType() != $5->getType())
1926 GEN_ERROR("Binary operator types must match");
1927 CHECK_FOR_ERROR;
1928 $$ = ConstantExpr::get($1, $3, $5);
1929 }
1930 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1931 if ($3->getType() != $5->getType())
1932 GEN_ERROR("Logical operator types must match");
1933 if (!$3->getType()->isInteger()) {
1934 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1935 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1936 GEN_ERROR("Logical operator requires integral operands");
1937 }
1938 $$ = ConstantExpr::get($1, $3, $5);
1939 CHECK_FOR_ERROR
1940 }
1941 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1942 if ($4->getType() != $6->getType())
1943 GEN_ERROR("icmp operand types must match");
1944 $$ = ConstantExpr::getICmp($2, $4, $6);
1945 }
1946 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1947 if ($4->getType() != $6->getType())
1948 GEN_ERROR("fcmp operand types must match");
1949 $$ = ConstantExpr::getFCmp($2, $4, $6);
1950 }
Nate Begeman646fa482008-05-12 19:01:56 +00001951 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1952 if ($4->getType() != $6->getType())
1953 GEN_ERROR("vicmp operand types must match");
1954 $$ = ConstantExpr::getVICmp($2, $4, $6);
1955 }
1956 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1957 if ($4->getType() != $6->getType())
1958 GEN_ERROR("vfcmp operand types must match");
1959 $$ = ConstantExpr::getVFCmp($2, $4, $6);
1960 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001961 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1962 if (!ExtractElementInst::isValidOperands($3, $5))
1963 GEN_ERROR("Invalid extractelement operands");
1964 $$ = ConstantExpr::getExtractElement($3, $5);
1965 CHECK_FOR_ERROR
1966 }
1967 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1968 if (!InsertElementInst::isValidOperands($3, $5, $7))
1969 GEN_ERROR("Invalid insertelement operands");
1970 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1971 CHECK_FOR_ERROR
1972 }
1973 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1974 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1975 GEN_ERROR("Invalid shufflevector operands");
1976 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1977 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001978 }
Dan Gohmane5febe42008-05-31 00:58:22 +00001979 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001980 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1981 GEN_ERROR("ExtractValue requires an aggregate operand");
1982
Dan Gohmane5febe42008-05-31 00:58:22 +00001983 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001984 delete $4;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001985 CHECK_FOR_ERROR
1986 }
Dan Gohmane5febe42008-05-31 00:58:22 +00001987 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001988 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1989 GEN_ERROR("InsertValue requires an aggregate operand");
1990
Dan Gohmane5febe42008-05-31 00:58:22 +00001991 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001992 delete $6;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001993 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001994 };
1995
1996
1997// ConstVector - A list of comma separated constants.
1998ConstVector : ConstVector ',' ConstVal {
1999 ($$ = $1)->push_back($3);
2000 CHECK_FOR_ERROR
2001 }
2002 | ConstVal {
2003 $$ = new std::vector<Constant*>();
2004 $$->push_back($1);
2005 CHECK_FOR_ERROR
2006 };
2007
2008
2009// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2010GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2011
2012// ThreadLocal
2013ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2014
2015// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2016AliaseeRef : ResultTypes SymbolicValueRef {
2017 const Type* VTy = $1->get();
2018 Value *V = getVal(VTy, $2);
Chris Lattner0f800522007-08-06 21:00:37 +00002019 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2021 if (!Aliasee)
2022 GEN_ERROR("Aliases can be created only to global values");
2023
2024 $$ = Aliasee;
2025 CHECK_FOR_ERROR
2026 delete $1;
2027 }
2028 | BITCAST '(' AliaseeRef TO Types ')' {
2029 Constant *Val = $3;
2030 const Type *DestTy = $5->get();
2031 if (!CastInst::castIsValid($1, $3, DestTy))
2032 GEN_ERROR("invalid cast opcode for cast from '" +
2033 Val->getType()->getDescription() + "' to '" +
2034 DestTy->getDescription() + "'");
2035
2036 $$ = ConstantExpr::getCast($1, $3, DestTy);
2037 CHECK_FOR_ERROR
2038 delete $5;
2039 };
2040
2041//===----------------------------------------------------------------------===//
2042// Rules to match Modules
2043//===----------------------------------------------------------------------===//
2044
2045// Module rule: Capture the result of parsing the whole file into a result
2046// variable...
2047//
2048Module
2049 : DefinitionList {
2050 $$ = ParserResult = CurModule.CurrentModule;
2051 CurModule.ModuleDone();
2052 CHECK_FOR_ERROR;
2053 }
2054 | /*empty*/ {
2055 $$ = ParserResult = CurModule.CurrentModule;
2056 CurModule.ModuleDone();
2057 CHECK_FOR_ERROR;
2058 }
2059 ;
2060
2061DefinitionList
2062 : Definition
2063 | DefinitionList Definition
2064 ;
2065
2066Definition
2067 : DEFINE { CurFun.isDeclare = false; } Function {
2068 CurFun.FunctionDone();
2069 CHECK_FOR_ERROR
2070 }
2071 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2072 CHECK_FOR_ERROR
2073 }
2074 | MODULE ASM_TOK AsmBlock {
2075 CHECK_FOR_ERROR
2076 }
2077 | OptLocalAssign TYPE Types {
2078 if (!UpRefs.empty())
2079 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2080 // Eagerly resolve types. This is not an optimization, this is a
2081 // requirement that is due to the fact that we could have this:
2082 //
2083 // %list = type { %list * }
2084 // %list = type { %list * } ; repeated type decl
2085 //
2086 // If types are not resolved eagerly, then the two types will not be
2087 // determined to be the same type!
2088 //
2089 ResolveTypeTo($1, *$3);
2090
2091 if (!setTypeName(*$3, $1) && !$1) {
2092 CHECK_FOR_ERROR
2093 // If this is a named type that is not a redefinition, add it to the slot
2094 // table.
2095 CurModule.Types.push_back(*$3);
2096 }
2097
2098 delete $3;
2099 CHECK_FOR_ERROR
2100 }
2101 | OptLocalAssign TYPE VOID {
2102 ResolveTypeTo($1, $3);
2103
2104 if (!setTypeName($3, $1) && !$1) {
2105 CHECK_FOR_ERROR
2106 // If this is a named type that is not a redefinition, add it to the slot
2107 // table.
2108 CurModule.Types.push_back($3);
2109 }
2110 CHECK_FOR_ERROR
2111 }
Christopher Lamb20a39e92007-12-12 08:44:39 +00002112 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2113 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002114 /* "Externally Visible" Linkage */
2115 if ($5 == 0)
2116 GEN_ERROR("Global value initializer is not a constant");
2117 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb20a39e92007-12-12 08:44:39 +00002118 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb44d62f62007-12-11 08:59:05 +00002119 CHECK_FOR_ERROR
2120 } GlobalVarAttributes {
2121 CurGV = 0;
2122 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002123 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb20a39e92007-12-12 08:44:39 +00002124 ConstVal OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125 if ($6 == 0)
2126 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb20a39e92007-12-12 08:44:39 +00002127 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002128 CHECK_FOR_ERROR
2129 } GlobalVarAttributes {
2130 CurGV = 0;
2131 }
2132 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb20a39e92007-12-12 08:44:39 +00002133 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002134 if (!UpRefs.empty())
2135 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb20a39e92007-12-12 08:44:39 +00002136 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 CHECK_FOR_ERROR
2138 delete $6;
2139 } GlobalVarAttributes {
2140 CurGV = 0;
2141 CHECK_FOR_ERROR
2142 }
2143 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2144 std::string Name;
2145 if ($1) {
2146 Name = *$1;
2147 delete $1;
2148 }
2149 if (Name.empty())
2150 GEN_ERROR("Alias name cannot be empty");
2151
2152 Constant* Aliasee = $5;
2153 if (Aliasee == 0)
2154 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2155
2156 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2157 CurModule.CurrentModule);
2158 GA->setVisibility($2);
2159 InsertValue(GA, CurModule.Values);
Chris Lattner9d99b312007-09-10 23:23:53 +00002160
2161
2162 // If there was a forward reference of this alias, resolve it now.
2163
2164 ValID ID;
2165 if (!Name.empty())
2166 ID = ValID::createGlobalName(Name);
2167 else
2168 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2169
2170 if (GlobalValue *FWGV =
2171 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2172 // Replace uses of the fwdref with the actual alias.
2173 FWGV->replaceAllUsesWith(GA);
2174 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2175 GV->eraseFromParent();
2176 else
2177 cast<Function>(FWGV)->eraseFromParent();
2178 }
2179 ID.destroy();
2180
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181 CHECK_FOR_ERROR
2182 }
2183 | TARGET TargetDefinition {
2184 CHECK_FOR_ERROR
2185 }
2186 | DEPLIBS '=' LibrariesDefinition {
2187 CHECK_FOR_ERROR
2188 }
2189 ;
2190
2191
2192AsmBlock : STRINGCONSTANT {
2193 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2194 if (AsmSoFar.empty())
2195 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2196 else
2197 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2198 delete $1;
2199 CHECK_FOR_ERROR
2200};
2201
2202TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2203 CurModule.CurrentModule->setTargetTriple(*$3);
2204 delete $3;
2205 }
2206 | DATALAYOUT '=' STRINGCONSTANT {
2207 CurModule.CurrentModule->setDataLayout(*$3);
2208 delete $3;
2209 };
2210
2211LibrariesDefinition : '[' LibList ']';
2212
2213LibList : LibList ',' STRINGCONSTANT {
2214 CurModule.CurrentModule->addLibrary(*$3);
2215 delete $3;
2216 CHECK_FOR_ERROR
2217 }
2218 | STRINGCONSTANT {
2219 CurModule.CurrentModule->addLibrary(*$1);
2220 delete $1;
2221 CHECK_FOR_ERROR
2222 }
2223 | /* empty: end of list */ {
2224 CHECK_FOR_ERROR
2225 }
2226 ;
2227
2228//===----------------------------------------------------------------------===//
2229// Rules to match Function Headers
2230//===----------------------------------------------------------------------===//
2231
2232ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2233 if (!UpRefs.empty())
2234 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
Dan Gohman36782aa2008-05-23 18:23:11 +00002235 if (!(*$3)->isFirstClassType())
2236 GEN_ERROR("Argument types must be first-class");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2238 $$ = $1;
2239 $1->push_back(E);
2240 CHECK_FOR_ERROR
2241 }
2242 | Types OptParamAttrs OptLocalName {
2243 if (!UpRefs.empty())
2244 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Dan Gohman36782aa2008-05-23 18:23:11 +00002245 if (!(*$1)->isFirstClassType())
2246 GEN_ERROR("Argument types must be first-class");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2248 $$ = new ArgListType;
2249 $$->push_back(E);
2250 CHECK_FOR_ERROR
2251 };
2252
2253ArgList : ArgListH {
2254 $$ = $1;
2255 CHECK_FOR_ERROR
2256 }
2257 | ArgListH ',' DOTDOTDOT {
2258 $$ = $1;
2259 struct ArgListEntry E;
2260 E.Ty = new PATypeHolder(Type::VoidTy);
2261 E.Name = 0;
2262 E.Attrs = ParamAttr::None;
2263 $$->push_back(E);
2264 CHECK_FOR_ERROR
2265 }
2266 | DOTDOTDOT {
2267 $$ = new ArgListType;
2268 struct ArgListEntry E;
2269 E.Ty = new PATypeHolder(Type::VoidTy);
2270 E.Name = 0;
2271 E.Attrs = ParamAttr::None;
2272 $$->push_back(E);
2273 CHECK_FOR_ERROR
2274 }
2275 | /* empty */ {
2276 $$ = 0;
2277 CHECK_FOR_ERROR
2278 };
2279
2280FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002281 OptFuncAttrs OptSection OptAlign OptGC {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002282 std::string FunctionName(*$3);
2283 delete $3; // Free strdup'd memory!
2284
2285 // Check the function result for abstractness if this is a define. We should
2286 // have no abstract types at this point
2287 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2288 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2289
Chris Lattner62de9332008-04-23 05:36:58 +00002290 if (!FunctionType::isValidReturnType(*$2))
2291 GEN_ERROR("Invalid result type for LLVM function");
2292
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002293 std::vector<const Type*> ParamTypeList;
Chris Lattner1c8733e2008-03-12 17:45:29 +00002294 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2295 if ($7 != ParamAttr::None)
2296 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002297 if ($5) { // If there are arguments...
2298 unsigned index = 1;
2299 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2300 const Type* Ty = I->Ty->get();
2301 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2302 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2303 ParamTypeList.push_back(Ty);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002304 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2305 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002306 }
2307 }
2308
2309 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2310 if (isVarArg) ParamTypeList.pop_back();
2311
Chris Lattner1c8733e2008-03-12 17:45:29 +00002312 PAListPtr PAL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002314 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002315
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002316 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambbb2f2222007-12-17 01:12:55 +00002317 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002318 delete $2;
2319
2320 ValID ID;
2321 if (!FunctionName.empty()) {
2322 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2323 } else {
2324 ID = ValID::createGlobalID(CurModule.Values.size());
2325 }
2326
2327 Function *Fn = 0;
2328 // See if this function was forward referenced. If so, recycle the object.
2329 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2330 // Move the function to the end of the list, from whereever it was
2331 // previously inserted.
2332 Fn = cast<Function>(FWRef);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002333 assert(Fn->getParamAttrs().isEmpty() &&
2334 "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335 CurModule.CurrentModule->getFunctionList().remove(Fn);
2336 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2337 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2338 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002339 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002340 // The existing function doesn't have the same type. This is an overload
2341 // error.
2342 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002343 } else if (Fn->getParamAttrs() != PAL) {
2344 // The existing function doesn't have the same parameter attributes.
2345 // This is an overload error.
2346 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002347 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2348 // Neither the existing or the current function is a declaration and they
2349 // have the same name and same type. Clearly this is a redefinition.
2350 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002351 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002352 // Make sure to strip off any argument names so we can't get conflicts.
2353 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2354 AI != AE; ++AI)
2355 AI->setName("");
2356 }
2357 } else { // Not already defined?
Gabor Greifd6da1d02008-04-06 20:25:17 +00002358 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2359 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002360 InsertValue(Fn, CurModule.Values);
2361 }
2362
2363 CurFun.FunctionStart(Fn);
2364
2365 if (CurFun.isDeclare) {
2366 // If we have declaration, always overwrite linkage. This will allow us to
2367 // correctly handle cases, when pointer to function is passed as argument to
2368 // another function.
2369 Fn->setLinkage(CurFun.Linkage);
2370 Fn->setVisibility(CurFun.Visibility);
2371 }
2372 Fn->setCallingConv($1);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002373 Fn->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002374 Fn->setAlignment($9);
2375 if ($8) {
2376 Fn->setSection(*$8);
2377 delete $8;
2378 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002379 if ($10) {
2380 Fn->setCollector($10->c_str());
2381 delete $10;
2382 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002383
2384 // Add all of the arguments we parsed to the function...
2385 if ($5) { // Is null if empty...
2386 if (isVarArg) { // Nuke the last entry
2387 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2388 "Not a varargs marker!");
2389 delete $5->back().Ty;
2390 $5->pop_back(); // Delete the last entry
2391 }
2392 Function::arg_iterator ArgIt = Fn->arg_begin();
2393 Function::arg_iterator ArgEnd = Fn->arg_end();
2394 unsigned Idx = 1;
2395 for (ArgListType::iterator I = $5->begin();
2396 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2397 delete I->Ty; // Delete the typeholder...
2398 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2399 CHECK_FOR_ERROR
2400 InsertValue(ArgIt);
2401 Idx++;
2402 }
2403
2404 delete $5; // We're now done with the argument list
2405 }
2406 CHECK_FOR_ERROR
2407};
2408
2409BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2410
2411FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2412 $$ = CurFun.CurrentFunction;
2413
2414 // Make sure that we keep track of the linkage type even if there was a
2415 // previous "declare".
2416 $$->setLinkage($1);
2417 $$->setVisibility($2);
2418};
2419
2420END : ENDTOK | '}'; // Allow end of '}' to end a function
2421
2422Function : BasicBlockList END {
2423 $$ = $1;
2424 CHECK_FOR_ERROR
2425};
2426
2427FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2428 CurFun.CurrentFunction->setLinkage($1);
2429 CurFun.CurrentFunction->setVisibility($2);
2430 $$ = CurFun.CurrentFunction;
2431 CurFun.FunctionDone();
2432 CHECK_FOR_ERROR
2433 };
2434
2435//===----------------------------------------------------------------------===//
2436// Rules to match Basic Blocks
2437//===----------------------------------------------------------------------===//
2438
2439OptSideEffect : /* empty */ {
2440 $$ = false;
2441 CHECK_FOR_ERROR
2442 }
2443 | SIDEEFFECT {
2444 $$ = true;
2445 CHECK_FOR_ERROR
2446 };
2447
2448ConstValueRef : ESINT64VAL { // A reference to a direct constant
2449 $$ = ValID::create($1);
2450 CHECK_FOR_ERROR
2451 }
2452 | EUINT64VAL {
2453 $$ = ValID::create($1);
2454 CHECK_FOR_ERROR
2455 }
2456 | FPVAL { // Perhaps it's an FP constant?
2457 $$ = ValID::create($1);
2458 CHECK_FOR_ERROR
2459 }
2460 | TRUETOK {
2461 $$ = ValID::create(ConstantInt::getTrue());
2462 CHECK_FOR_ERROR
2463 }
2464 | FALSETOK {
2465 $$ = ValID::create(ConstantInt::getFalse());
2466 CHECK_FOR_ERROR
2467 }
2468 | NULL_TOK {
2469 $$ = ValID::createNull();
2470 CHECK_FOR_ERROR
2471 }
2472 | UNDEF {
2473 $$ = ValID::createUndef();
2474 CHECK_FOR_ERROR
2475 }
2476 | ZEROINITIALIZER { // A vector zero constant.
2477 $$ = ValID::createZeroInit();
2478 CHECK_FOR_ERROR
2479 }
2480 | '<' ConstVector '>' { // Nonempty unsized packed vector
2481 const Type *ETy = (*$2)[0]->getType();
2482 int NumElements = $2->size();
Dan Gohman36782aa2008-05-23 18:23:11 +00002483
2484 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2485 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486
2487 VectorType* pt = VectorType::get(ETy, NumElements);
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002488 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489
2490 // Verify all elements are correct type!
2491 for (unsigned i = 0; i < $2->size(); i++) {
2492 if (ETy != (*$2)[i]->getType())
2493 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2494 ETy->getDescription() +"' as required!\nIt is of type '" +
2495 (*$2)[i]->getType()->getDescription() + "'.");
2496 }
2497
2498 $$ = ValID::create(ConstantVector::get(pt, *$2));
2499 delete PTy; delete $2;
2500 CHECK_FOR_ERROR
2501 }
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002502 | '[' ConstVector ']' { // Nonempty unsized arr
2503 const Type *ETy = (*$2)[0]->getType();
2504 int NumElements = $2->size();
2505
2506 if (!ETy->isFirstClassType())
2507 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2508
2509 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2510 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2511
2512 // Verify all elements are correct type!
2513 for (unsigned i = 0; i < $2->size(); i++) {
2514 if (ETy != (*$2)[i]->getType())
2515 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2516 ETy->getDescription() +"' as required!\nIt is of type '"+
2517 (*$2)[i]->getType()->getDescription() + "'.");
2518 }
2519
2520 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2521 delete PTy; delete $2;
2522 CHECK_FOR_ERROR
2523 }
2524 | '[' ']' {
2525 $$ = ValID::createUndef();
2526 CHECK_FOR_ERROR
2527 }
2528 | 'c' STRINGCONSTANT {
2529 int NumElements = $2->length();
2530 const Type *ETy = Type::Int8Ty;
2531
2532 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2533
2534 std::vector<Constant*> Vals;
2535 for (unsigned i = 0; i < $2->length(); ++i)
2536 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2537 delete $2;
2538 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2539 CHECK_FOR_ERROR
2540 }
2541 | '{' ConstVector '}' {
2542 std::vector<const Type*> Elements($2->size());
2543 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2544 Elements[i] = (*$2)[i]->getType();
2545
2546 const StructType *STy = StructType::get(Elements);
2547 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2548
2549 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2550 delete PTy; delete $2;
2551 CHECK_FOR_ERROR
2552 }
2553 | '{' '}' {
2554 const StructType *STy = StructType::get(std::vector<const Type*>());
2555 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2556 CHECK_FOR_ERROR
2557 }
2558 | '<' '{' ConstVector '}' '>' {
2559 std::vector<const Type*> Elements($3->size());
2560 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2561 Elements[i] = (*$3)[i]->getType();
2562
2563 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2564 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2565
2566 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2567 delete PTy; delete $3;
2568 CHECK_FOR_ERROR
2569 }
2570 | '<' '{' '}' '>' {
2571 const StructType *STy = StructType::get(std::vector<const Type*>(),
2572 /*isPacked=*/true);
2573 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2574 CHECK_FOR_ERROR
2575 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002576 | ConstExpr {
2577 $$ = ValID::create($1);
2578 CHECK_FOR_ERROR
2579 }
2580 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2581 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2582 delete $3;
2583 delete $5;
2584 CHECK_FOR_ERROR
2585 };
2586
2587// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2588// another value.
2589//
2590SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2591 $$ = ValID::createLocalID($1);
2592 CHECK_FOR_ERROR
2593 }
2594 | GLOBALVAL_ID {
2595 $$ = ValID::createGlobalID($1);
2596 CHECK_FOR_ERROR
2597 }
2598 | LocalName { // Is it a named reference...?
2599 $$ = ValID::createLocalName(*$1);
2600 delete $1;
2601 CHECK_FOR_ERROR
2602 }
2603 | GlobalName { // Is it a named reference...?
2604 $$ = ValID::createGlobalName(*$1);
2605 delete $1;
2606 CHECK_FOR_ERROR
2607 };
2608
2609// ValueRef - A reference to a definition... either constant or symbolic
2610ValueRef : SymbolicValueRef | ConstValueRef;
2611
2612
2613// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2614// type immediately preceeds the value reference, and allows complex constant
2615// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2616ResolvedVal : Types ValueRef {
2617 if (!UpRefs.empty())
2618 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2619 $$ = getVal(*$1, $2);
2620 delete $1;
2621 CHECK_FOR_ERROR
2622 }
2623 ;
2624
Devang Patel036f0382008-02-20 22:39:45 +00002625ReturnedVal : ResolvedVal {
2626 $$ = new std::vector<Value *>();
2627 $$->push_back($1);
2628 CHECK_FOR_ERROR
2629 }
Devang Patel1a932fc2008-02-23 00:35:18 +00002630 | ReturnedVal ',' ResolvedVal {
Devang Patel036f0382008-02-20 22:39:45 +00002631 ($$=$1)->push_back($3);
2632 CHECK_FOR_ERROR
2633 };
2634
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002635BasicBlockList : BasicBlockList BasicBlock {
2636 $$ = $1;
2637 CHECK_FOR_ERROR
2638 }
2639 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2640 $$ = $1;
2641 CHECK_FOR_ERROR
2642 };
2643
2644
2645// Basic blocks are terminated by branching instructions:
2646// br, br/cc, switch, ret
2647//
2648BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2649 setValueName($3, $2);
2650 CHECK_FOR_ERROR
2651 InsertValue($3);
2652 $1->getInstList().push_back($3);
2653 $$ = $1;
2654 CHECK_FOR_ERROR
2655 };
2656
2657InstructionList : InstructionList Inst {
2658 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2659 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2660 if (CI2->getParent() == 0)
2661 $1->getInstList().push_back(CI2);
2662 $1->getInstList().push_back($2);
2663 $$ = $1;
2664 CHECK_FOR_ERROR
2665 }
2666 | /* empty */ { // Empty space between instruction lists
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002667 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002668 CHECK_FOR_ERROR
2669 }
2670 | LABELSTR { // Labelled (named) basic block
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002671 $$ = defineBBVal(ValID::createLocalName(*$1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672 delete $1;
2673 CHECK_FOR_ERROR
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002674
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002675 };
2676
Devang Patel036f0382008-02-20 22:39:45 +00002677BBTerminatorInst :
2678 RET ReturnedVal { // Return with a result...
Devang Patelbbbb8202008-02-26 22:12:58 +00002679 ValueList &VL = *$2;
Devang Patel202ec472008-02-26 23:17:50 +00002680 assert(!VL.empty() && "Invalid ret operands!");
Gabor Greifd6da1d02008-04-06 20:25:17 +00002681 $$ = ReturnInst::Create(&VL[0], VL.size());
Devang Patel036f0382008-02-20 22:39:45 +00002682 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002683 CHECK_FOR_ERROR
2684 }
2685 | RET VOID { // Return with no result...
Gabor Greifd6da1d02008-04-06 20:25:17 +00002686 $$ = ReturnInst::Create();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002687 CHECK_FOR_ERROR
2688 }
2689 | BR LABEL ValueRef { // Unconditional Branch...
2690 BasicBlock* tmpBB = getBBVal($3);
2691 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002692 $$ = BranchInst::Create(tmpBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693 } // Conditional Branch...
2694 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
Dan Gohman36782aa2008-05-23 18:23:11 +00002695 if (cast<IntegerType>($2)->getBitWidth() != 1)
2696 GEN_ERROR("Branch condition must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 BasicBlock* tmpBBA = getBBVal($6);
2698 CHECK_FOR_ERROR
2699 BasicBlock* tmpBBB = getBBVal($9);
2700 CHECK_FOR_ERROR
2701 Value* tmpVal = getVal(Type::Int1Ty, $3);
2702 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002703 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002704 }
2705 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2706 Value* tmpVal = getVal($2, $3);
2707 CHECK_FOR_ERROR
2708 BasicBlock* tmpBB = getBBVal($6);
2709 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002710 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002711 $$ = S;
2712
2713 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2714 E = $8->end();
2715 for (; I != E; ++I) {
2716 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2717 S->addCase(CI, I->second);
2718 else
2719 GEN_ERROR("Switch case is constant, but not a simple integer");
2720 }
2721 delete $8;
2722 CHECK_FOR_ERROR
2723 }
2724 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2725 Value* tmpVal = getVal($2, $3);
2726 CHECK_FOR_ERROR
2727 BasicBlock* tmpBB = getBBVal($6);
2728 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00002729 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002730 $$ = S;
2731 CHECK_FOR_ERROR
2732 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002733 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734 TO LABEL ValueRef UNWIND LABEL ValueRef {
2735
2736 // Handle the short syntax
2737 const PointerType *PFTy = 0;
2738 const FunctionType *Ty = 0;
2739 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2740 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2741 // Pull out the types of all of the arguments...
2742 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002743 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002744 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 const Type *Ty = I->Val->getType();
2746 if (Ty == Type::VoidTy)
2747 GEN_ERROR("Short call syntax cannot be used with varargs");
2748 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749 }
Chris Lattner62de9332008-04-23 05:36:58 +00002750
2751 if (!FunctionType::isValidReturnType(*$3))
2752 GEN_ERROR("Invalid result type for LLVM function");
2753
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002754 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambbb2f2222007-12-17 01:12:55 +00002755 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002756 }
2757
2758 delete $3;
2759
2760 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2761 CHECK_FOR_ERROR
2762 BasicBlock *Normal = getBBVal($11);
2763 CHECK_FOR_ERROR
2764 BasicBlock *Except = getBBVal($14);
2765 CHECK_FOR_ERROR
2766
Chris Lattner1c8733e2008-03-12 17:45:29 +00002767 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2768 if ($8 != ParamAttr::None)
2769 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002770
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 // Check the arguments
2772 ValueList Args;
2773 if ($6->empty()) { // Has no arguments?
2774 // Make sure no arguments is a good thing!
2775 if (Ty->getNumParams() != 0)
2776 GEN_ERROR("No arguments passed to a function that "
2777 "expects arguments");
2778 } else { // Has arguments?
2779 // Loop through FunctionType's arguments and ensure they are specified
2780 // correctly!
2781 FunctionType::param_iterator I = Ty->param_begin();
2782 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002783 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002784 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002785
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002786 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002787 if (ArgI->Val->getType() != *I)
2788 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2789 (*I)->getDescription() + "'");
2790 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002791 if (ArgI->Attrs != ParamAttr::None)
2792 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002793 }
2794
2795 if (Ty->isVarArg()) {
2796 if (I == E)
Duncan Sands6c3314b2008-01-11 21:23:39 +00002797 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00002799 if (ArgI->Attrs != ParamAttr::None)
2800 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Duncan Sands6c3314b2008-01-11 21:23:39 +00002801 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 } else if (I != E || ArgI != ArgE)
2803 GEN_ERROR("Invalid number of parameters detected");
2804 }
2805
Chris Lattner1c8733e2008-03-12 17:45:29 +00002806 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002807 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002808 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002809
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002810 // Create the InvokeInst
Gabor Greifb91ea9d2008-05-15 10:04:30 +00002811 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2812 Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813 II->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002814 II->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002815 $$ = II;
2816 delete $6;
2817 CHECK_FOR_ERROR
2818 }
2819 | UNWIND {
2820 $$ = new UnwindInst();
2821 CHECK_FOR_ERROR
2822 }
2823 | UNREACHABLE {
2824 $$ = new UnreachableInst();
2825 CHECK_FOR_ERROR
2826 };
2827
2828
2829
2830JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2831 $$ = $1;
2832 Constant *V = cast<Constant>(getExistingVal($2, $3));
2833 CHECK_FOR_ERROR
2834 if (V == 0)
2835 GEN_ERROR("May only switch on a constant pool value");
2836
2837 BasicBlock* tmpBB = getBBVal($6);
2838 CHECK_FOR_ERROR
2839 $$->push_back(std::make_pair(V, tmpBB));
2840 }
2841 | IntType ConstValueRef ',' LABEL ValueRef {
2842 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2843 Constant *V = cast<Constant>(getExistingVal($1, $2));
2844 CHECK_FOR_ERROR
2845
2846 if (V == 0)
2847 GEN_ERROR("May only switch on a constant pool value");
2848
2849 BasicBlock* tmpBB = getBBVal($5);
2850 CHECK_FOR_ERROR
2851 $$->push_back(std::make_pair(V, tmpBB));
2852 };
2853
2854Inst : OptLocalAssign InstVal {
2855 // Is this definition named?? if so, assign the name...
2856 setValueName($2, $1);
2857 CHECK_FOR_ERROR
2858 InsertValue($2);
2859 $$ = $2;
2860 CHECK_FOR_ERROR
2861 };
2862
2863
2864PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2865 if (!UpRefs.empty())
2866 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2867 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2868 Value* tmpVal = getVal(*$1, $3);
2869 CHECK_FOR_ERROR
2870 BasicBlock* tmpBB = getBBVal($5);
2871 CHECK_FOR_ERROR
2872 $$->push_back(std::make_pair(tmpVal, tmpBB));
2873 delete $1;
2874 }
2875 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2876 $$ = $1;
2877 Value* tmpVal = getVal($1->front().first->getType(), $4);
2878 CHECK_FOR_ERROR
2879 BasicBlock* tmpBB = getBBVal($6);
2880 CHECK_FOR_ERROR
2881 $1->push_back(std::make_pair(tmpVal, tmpBB));
2882 };
2883
2884
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002885ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2886 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002887 if (!UpRefs.empty())
2888 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2889 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00002890 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002891 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002892 $$->push_back(E);
2893 delete $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002894 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002896 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2897 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002898 // Labels are only valid in ASMs
2899 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002900 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002901 $$->push_back(E);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002902 CHECK_FOR_ERROR
Dale Johannesencfb19e62007-11-05 21:20:28 +00002903 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002904 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2905 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002906 if (!UpRefs.empty())
2907 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2908 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002909 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 $$->push_back(E);
2911 delete $3;
2912 CHECK_FOR_ERROR
2913 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002914 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2915 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002916 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002917 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002918 $$->push_back(E);
2919 CHECK_FOR_ERROR
2920 }
2921 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002922
2923IndexList // Used for gep instructions and constant expressions
2924 : /*empty*/ { $$ = new std::vector<Value*>(); }
2925 | IndexList ',' ResolvedVal {
2926 $$ = $1;
2927 $$->push_back($3);
2928 CHECK_FOR_ERROR
2929 }
2930 ;
2931
Dan Gohmane5febe42008-05-31 00:58:22 +00002932ConstantIndexList // Used for insertvalue and extractvalue instructions
2933 : ',' EUINT64VAL {
2934 $$ = new std::vector<unsigned>();
2935 if ((unsigned)$2 != $2)
2936 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
2937 $$->push_back($2);
2938 }
2939 | ConstantIndexList ',' EUINT64VAL {
2940 $$ = $1;
2941 if ((unsigned)$3 != $3)
2942 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
2943 $$->push_back($3);
2944 CHECK_FOR_ERROR
2945 }
2946 ;
2947
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002948OptTailCall : TAIL CALL {
2949 $$ = true;
2950 CHECK_FOR_ERROR
2951 }
2952 | CALL {
2953 $$ = false;
2954 CHECK_FOR_ERROR
2955 };
2956
2957InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2958 if (!UpRefs.empty())
2959 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2960 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2961 !isa<VectorType>((*$2).get()))
2962 GEN_ERROR(
2963 "Arithmetic operator requires integer, FP, or packed operands");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002964 Value* val1 = getVal(*$2, $3);
2965 CHECK_FOR_ERROR
2966 Value* val2 = getVal(*$2, $5);
2967 CHECK_FOR_ERROR
Gabor Greifa645dd32008-05-16 19:29:10 +00002968 $$ = BinaryOperator::Create($1, val1, val2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 if ($$ == 0)
2970 GEN_ERROR("binary operator returned null");
2971 delete $2;
2972 }
2973 | LogicalOps Types ValueRef ',' ValueRef {
2974 if (!UpRefs.empty())
2975 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2976 if (!(*$2)->isInteger()) {
2977 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2978 !cast<VectorType>($2->get())->getElementType()->isInteger())
2979 GEN_ERROR("Logical operator requires integral operands");
2980 }
2981 Value* tmpVal1 = getVal(*$2, $3);
2982 CHECK_FOR_ERROR
2983 Value* tmpVal2 = getVal(*$2, $5);
2984 CHECK_FOR_ERROR
Gabor Greifa645dd32008-05-16 19:29:10 +00002985 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 if ($$ == 0)
2987 GEN_ERROR("binary operator returned null");
2988 delete $2;
2989 }
2990 | ICMP IPredicates Types ValueRef ',' ValueRef {
2991 if (!UpRefs.empty())
2992 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2993 if (isa<VectorType>((*$3).get()))
2994 GEN_ERROR("Vector types not supported by icmp instruction");
2995 Value* tmpVal1 = getVal(*$3, $4);
2996 CHECK_FOR_ERROR
2997 Value* tmpVal2 = getVal(*$3, $6);
2998 CHECK_FOR_ERROR
Gabor Greifa645dd32008-05-16 19:29:10 +00002999 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 if ($$ == 0)
3001 GEN_ERROR("icmp operator returned null");
3002 delete $3;
3003 }
3004 | FCMP FPredicates Types ValueRef ',' ValueRef {
3005 if (!UpRefs.empty())
3006 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3007 if (isa<VectorType>((*$3).get()))
3008 GEN_ERROR("Vector types not supported by fcmp instruction");
3009 Value* tmpVal1 = getVal(*$3, $4);
3010 CHECK_FOR_ERROR
3011 Value* tmpVal2 = getVal(*$3, $6);
3012 CHECK_FOR_ERROR
Gabor Greifa645dd32008-05-16 19:29:10 +00003013 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003014 if ($$ == 0)
3015 GEN_ERROR("fcmp operator returned null");
3016 delete $3;
3017 }
Nate Begeman646fa482008-05-12 19:01:56 +00003018 | VICMP IPredicates Types ValueRef ',' ValueRef {
3019 if (!UpRefs.empty())
3020 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3021 if (!isa<VectorType>((*$3).get()))
3022 GEN_ERROR("Scalar types not supported by vicmp instruction");
3023 Value* tmpVal1 = getVal(*$3, $4);
3024 CHECK_FOR_ERROR
3025 Value* tmpVal2 = getVal(*$3, $6);
3026 CHECK_FOR_ERROR
Gabor Greifa645dd32008-05-16 19:29:10 +00003027 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Nate Begeman646fa482008-05-12 19:01:56 +00003028 if ($$ == 0)
3029 GEN_ERROR("icmp operator returned null");
3030 delete $3;
3031 }
3032 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3033 if (!UpRefs.empty())
3034 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3035 if (!isa<VectorType>((*$3).get()))
3036 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3037 Value* tmpVal1 = getVal(*$3, $4);
3038 CHECK_FOR_ERROR
3039 Value* tmpVal2 = getVal(*$3, $6);
3040 CHECK_FOR_ERROR
Gabor Greifa645dd32008-05-16 19:29:10 +00003041 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Nate Begeman646fa482008-05-12 19:01:56 +00003042 if ($$ == 0)
3043 GEN_ERROR("fcmp operator returned null");
3044 delete $3;
3045 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046 | CastOps ResolvedVal TO Types {
3047 if (!UpRefs.empty())
3048 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3049 Value* Val = $2;
3050 const Type* DestTy = $4->get();
3051 if (!CastInst::castIsValid($1, Val, DestTy))
3052 GEN_ERROR("invalid cast opcode for cast from '" +
3053 Val->getType()->getDescription() + "' to '" +
3054 DestTy->getDescription() + "'");
Gabor Greifa645dd32008-05-16 19:29:10 +00003055 $$ = CastInst::Create($1, Val, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003056 delete $4;
3057 }
3058 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3059 if ($2->getType() != Type::Int1Ty)
3060 GEN_ERROR("select condition must be boolean");
3061 if ($4->getType() != $6->getType())
3062 GEN_ERROR("select value types should match");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003063 $$ = SelectInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003064 CHECK_FOR_ERROR
3065 }
3066 | VAARG ResolvedVal ',' Types {
3067 if (!UpRefs.empty())
3068 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3069 $$ = new VAArgInst($2, *$4);
3070 delete $4;
3071 CHECK_FOR_ERROR
3072 }
3073 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3074 if (!ExtractElementInst::isValidOperands($2, $4))
3075 GEN_ERROR("Invalid extractelement operands");
3076 $$ = new ExtractElementInst($2, $4);
3077 CHECK_FOR_ERROR
3078 }
3079 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3080 if (!InsertElementInst::isValidOperands($2, $4, $6))
3081 GEN_ERROR("Invalid insertelement operands");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003082 $$ = InsertElementInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003083 CHECK_FOR_ERROR
3084 }
3085 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3086 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3087 GEN_ERROR("Invalid shufflevector operands");
3088 $$ = new ShuffleVectorInst($2, $4, $6);
3089 CHECK_FOR_ERROR
3090 }
3091 | PHI_TOK PHIList {
3092 const Type *Ty = $2->front().first->getType();
3093 if (!Ty->isFirstClassType())
3094 GEN_ERROR("PHI node operands must be of first class type");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003095 $$ = PHINode::Create(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003096 ((PHINode*)$$)->reserveOperandSpace($2->size());
3097 while ($2->begin() != $2->end()) {
3098 if ($2->front().first->getType() != Ty)
3099 GEN_ERROR("All elements of a PHI node must be of the same type");
3100 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3101 $2->pop_front();
3102 }
3103 delete $2; // Free the list...
3104 CHECK_FOR_ERROR
3105 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00003106 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 OptFuncAttrs {
3108
3109 // Handle the short syntax
3110 const PointerType *PFTy = 0;
3111 const FunctionType *Ty = 0;
3112 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3113 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3114 // Pull out the types of all of the arguments...
3115 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00003116 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003117 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118 const Type *Ty = I->Val->getType();
3119 if (Ty == Type::VoidTy)
3120 GEN_ERROR("Short call syntax cannot be used with varargs");
3121 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003122 }
Chris Lattner62de9332008-04-23 05:36:58 +00003123
3124 if (!FunctionType::isValidReturnType(*$3))
3125 GEN_ERROR("Invalid result type for LLVM function");
3126
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003127 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambbb2f2222007-12-17 01:12:55 +00003128 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003129 }
3130
3131 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3132 CHECK_FOR_ERROR
3133
3134 // Check for call to invalid intrinsic to avoid crashing later.
3135 if (Function *theF = dyn_cast<Function>(V)) {
3136 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3137 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3138 !theF->getIntrinsicID(true))
3139 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3140 theF->getName() + "'");
3141 }
3142
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003143 // Set up the ParamAttrs for the function
Chris Lattner1c8733e2008-03-12 17:45:29 +00003144 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3145 if ($8 != ParamAttr::None)
3146 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 // Check the arguments
3148 ValueList Args;
3149 if ($6->empty()) { // Has no arguments?
3150 // Make sure no arguments is a good thing!
3151 if (Ty->getNumParams() != 0)
3152 GEN_ERROR("No arguments passed to a function that "
3153 "expects arguments");
3154 } else { // Has arguments?
3155 // Loop through FunctionType's arguments and ensure they are specified
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003156 // correctly. Also, gather any parameter attributes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003157 FunctionType::param_iterator I = Ty->param_begin();
3158 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00003159 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003160 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003162 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003163 if (ArgI->Val->getType() != *I)
3164 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3165 (*I)->getDescription() + "'");
3166 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00003167 if (ArgI->Attrs != ParamAttr::None)
3168 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003169 }
3170 if (Ty->isVarArg()) {
3171 if (I == E)
Duncan Sands6c3314b2008-01-11 21:23:39 +00003172 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00003174 if (ArgI->Attrs != ParamAttr::None)
3175 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Duncan Sands6c3314b2008-01-11 21:23:39 +00003176 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 } else if (I != E || ArgI != ArgE)
3178 GEN_ERROR("Invalid number of parameters detected");
3179 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003180
3181 // Finish off the ParamAttrs and check them
Chris Lattner1c8733e2008-03-12 17:45:29 +00003182 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003183 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00003184 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003185
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003186 // Create the call node
Gabor Greifd6da1d02008-04-06 20:25:17 +00003187 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 CI->setTailCall($1);
3189 CI->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003190 CI->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003191 $$ = CI;
3192 delete $6;
3193 delete $3;
3194 CHECK_FOR_ERROR
3195 }
3196 | MemoryInst {
3197 $$ = $1;
3198 CHECK_FOR_ERROR
3199 };
3200
3201OptVolatile : VOLATILE {
3202 $$ = true;
3203 CHECK_FOR_ERROR
3204 }
3205 | /* empty */ {
3206 $$ = false;
3207 CHECK_FOR_ERROR
3208 };
3209
3210
3211
3212MemoryInst : MALLOC Types OptCAlign {
3213 if (!UpRefs.empty())
3214 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3215 $$ = new MallocInst(*$2, 0, $3);
3216 delete $2;
3217 CHECK_FOR_ERROR
3218 }
3219 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3220 if (!UpRefs.empty())
3221 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
Dan Gohman36782aa2008-05-23 18:23:11 +00003222 if ($4 != Type::Int32Ty)
3223 GEN_ERROR("Malloc array size is not a 32-bit integer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 Value* tmpVal = getVal($4, $5);
3225 CHECK_FOR_ERROR
3226 $$ = new MallocInst(*$2, tmpVal, $6);
3227 delete $2;
3228 }
3229 | ALLOCA Types OptCAlign {
3230 if (!UpRefs.empty())
3231 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3232 $$ = new AllocaInst(*$2, 0, $3);
3233 delete $2;
3234 CHECK_FOR_ERROR
3235 }
3236 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3237 if (!UpRefs.empty())
3238 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
Dan Gohman36782aa2008-05-23 18:23:11 +00003239 if ($4 != Type::Int32Ty)
3240 GEN_ERROR("Alloca array size is not a 32-bit integer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003241 Value* tmpVal = getVal($4, $5);
3242 CHECK_FOR_ERROR
3243 $$ = new AllocaInst(*$2, tmpVal, $6);
3244 delete $2;
3245 }
3246 | FREE ResolvedVal {
3247 if (!isa<PointerType>($2->getType()))
3248 GEN_ERROR("Trying to free nonpointer type " +
3249 $2->getType()->getDescription() + "");
3250 $$ = new FreeInst($2);
3251 CHECK_FOR_ERROR
3252 }
3253
3254 | OptVolatile LOAD Types ValueRef OptCAlign {
3255 if (!UpRefs.empty())
3256 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3257 if (!isa<PointerType>($3->get()))
3258 GEN_ERROR("Can't load from nonpointer type: " +
3259 (*$3)->getDescription());
3260 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3261 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3262 (*$3)->getDescription());
3263 Value* tmpVal = getVal(*$3, $4);
3264 CHECK_FOR_ERROR
3265 $$ = new LoadInst(tmpVal, "", $1, $5);
3266 delete $3;
3267 }
3268 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3269 if (!UpRefs.empty())
3270 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3271 const PointerType *PT = dyn_cast<PointerType>($5->get());
3272 if (!PT)
3273 GEN_ERROR("Can't store to a nonpointer type: " +
3274 (*$5)->getDescription());
3275 const Type *ElTy = PT->getElementType();
3276 if (ElTy != $3->getType())
3277 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3278 "' into space of type '" + ElTy->getDescription() + "'");
3279
3280 Value* tmpVal = getVal(*$5, $6);
3281 CHECK_FOR_ERROR
3282 $$ = new StoreInst($3, tmpVal, $1, $7);
3283 delete $5;
3284 }
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003285 | GETRESULT Types ValueRef ',' EUINT64VAL {
Devang Patel89c3d672008-02-22 19:31:15 +00003286 Value *TmpVal = getVal($2->get(), $3);
Devang Patele5c806a2008-02-19 22:26:37 +00003287 if (!GetResultInst::isValidOperands(TmpVal, $5))
3288 GEN_ERROR("Invalid getresult operands");
3289 $$ = new GetResultInst(TmpVal, $5);
Devang Patel1a932fc2008-02-23 00:35:18 +00003290 delete $2;
Devang Patele5c806a2008-02-19 22:26:37 +00003291 CHECK_FOR_ERROR
3292 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003293 | GETELEMENTPTR Types ValueRef IndexList {
3294 if (!UpRefs.empty())
3295 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3296 if (!isa<PointerType>($2->get()))
3297 GEN_ERROR("getelementptr insn requires pointer operand");
3298
Dan Gohman8055f772008-05-15 19:50:34 +00003299 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003300 GEN_ERROR("Invalid getelementptr indices for type '" +
3301 (*$2)->getDescription()+ "'");
3302 Value* tmpVal = getVal(*$2, $3);
3303 CHECK_FOR_ERROR
Gabor Greifd6da1d02008-04-06 20:25:17 +00003304 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305 delete $2;
3306 delete $4;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003307 }
Dan Gohmane5febe42008-05-31 00:58:22 +00003308 | EXTRACTVALUE Types ValueRef ConstantIndexList {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003309 if (!UpRefs.empty())
3310 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3311 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3312 GEN_ERROR("extractvalue insn requires an aggregate operand");
3313
3314 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3315 GEN_ERROR("Invalid extractvalue indices for type '" +
3316 (*$2)->getDescription()+ "'");
3317 Value* tmpVal = getVal(*$2, $3);
3318 CHECK_FOR_ERROR
3319 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3320 delete $2;
3321 delete $4;
3322 }
Dan Gohmane5febe42008-05-31 00:58:22 +00003323 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003324 if (!UpRefs.empty())
3325 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3326 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3327 GEN_ERROR("extractvalue insn requires an aggregate operand");
3328
3329 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3330 GEN_ERROR("Invalid insertvalue indices for type '" +
3331 (*$2)->getDescription()+ "'");
3332 Value* aggVal = getVal(*$2, $3);
3333 Value* tmpVal = getVal(*$5, $6);
3334 CHECK_FOR_ERROR
3335 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3336 delete $2;
3337 delete $5;
3338 delete $7;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003339 };
3340
3341
3342%%
3343
3344// common code from the two 'RunVMAsmParser' functions
3345static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003347 // Check to make sure the parser succeeded
3348 if (yyparse()) {
3349 if (ParserResult)
3350 delete ParserResult;
3351 return 0;
3352 }
3353
3354 // Emit an error if there are any unresolved types left.
3355 if (!CurModule.LateResolveTypes.empty()) {
3356 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3357 if (DID.Type == ValID::LocalName) {
3358 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3359 } else {
3360 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3361 }
3362 if (ParserResult)
3363 delete ParserResult;
3364 return 0;
3365 }
3366
3367 // Emit an error if there are any unresolved values left.
3368 if (!CurModule.LateResolveValues.empty()) {
3369 Value *V = CurModule.LateResolveValues.back();
3370 std::map<Value*, std::pair<ValID, int> >::iterator I =
3371 CurModule.PlaceHolderInfo.find(V);
3372
3373 if (I != CurModule.PlaceHolderInfo.end()) {
3374 ValID &DID = I->second.first;
3375 if (DID.Type == ValID::LocalName) {
3376 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3377 } else {
3378 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3379 }
3380 if (ParserResult)
3381 delete ParserResult;
3382 return 0;
3383 }
3384 }
3385
3386 // Check to make sure that parsing produced a result
3387 if (!ParserResult)
3388 return 0;
3389
3390 // Reset ParserResult variable while saving its value for the result.
3391 Module *Result = ParserResult;
3392 ParserResult = 0;
3393
3394 return Result;
3395}
3396
3397void llvm::GenerateError(const std::string &message, int LineNo) {
Chris Lattner17e73c22007-11-18 08:46:26 +00003398 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 // TODO: column number in exception
3400 if (TheParseError)
Chris Lattner17e73c22007-11-18 08:46:26 +00003401 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 TriggerError = 1;
3403}
3404
3405int yyerror(const char *ErrorMsg) {
Chris Lattner17e73c22007-11-18 08:46:26 +00003406 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003407 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Chris Lattner17e73c22007-11-18 08:46:26 +00003408 if (yychar != YYEMPTY && yychar != 0) {
3409 errMsg += " while reading token: '";
3410 errMsg += std::string(LLLgetTokenStart(),
3411 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3412 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413 GenerateError(errMsg);
3414 return 0;
3415}