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