blob: f3a59ee0a6e8112703ddb8c7430a8e9355f4d0a4 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the bison parser for LLVM assembly languages files.
11//
12//===----------------------------------------------------------------------===//
13
14%{
15#include "ParserInternals.h"
16#include "llvm/CallingConv.h"
17#include "llvm/InlineAsm.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/ValueSymbolTable.h"
Chandler Carruth563d4a42007-08-04 01:56:21 +000021#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/Streams.h"
28#include <algorithm>
29#include <list>
30#include <map>
31#include <utility>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032
33// The following is a gross hack. In order to rid the libAsmParser library of
34// exceptions, we have to have a way of getting the yyparse function to go into
35// an error situation. So, whenever we want an error to occur, the GenerateError
36// function (see bottom of file) sets TriggerError. Then, at the end of each
37// production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38// (a goto) to put YACC in error state. Furthermore, several calls to
39// GenerateError are made from inside productions and they must simulate the
40// previous exception behavior by exiting the production immediately. We have
41// replaced these with the GEN_ERROR macro which calls GeneratError and then
42// immediately invokes YYERROR. This would be so much cleaner if it was a
43// recursive descent parser.
44static bool TriggerError = false;
45#define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46#define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
47
48int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49int yylex(); // declaration" of xxx warnings.
50int yyparse();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051using namespace llvm;
52
53static Module *ParserResult;
54
55// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56// relating to upreferences in the input stream.
57//
58//#define DEBUG_UPREFS 1
59#ifdef DEBUG_UPREFS
60#define UR_OUT(X) cerr << X
61#else
62#define UR_OUT(X)
63#endif
64
65#define YYERROR_VERBOSE 1
66
67static GlobalVariable *CurGV;
68
69
70// This contains info used when building the body of a function. It is
71// destroyed when the function is completed.
72//
73typedef std::vector<Value *> ValueList; // Numbered defs
74
75static void
76ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
77
78static struct PerModuleInfo {
79 Module *CurrentModule;
80 ValueList Values; // Module level numbered definitions
81 ValueList LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
84
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
89
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
94 //
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
98
99 void ModuleDone() {
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
103 //
104 ResolveDefinitions(LateResolveValues);
105 if (TriggerError)
106 return;
107
108 // Check to make sure that all global value forward references have been
109 // resolved!
110 //
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
113
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 I != E; ++I) {
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
118 }
119 GenerateError(UndefinedReferences);
120 return;
121 }
122
Chandler Carruth563d4a42007-08-04 01:56:21 +0000123 // Look for intrinsic functions and CallInst that need to be upgraded
124 for (Module::iterator FI = CurrentModule->begin(),
125 FE = CurrentModule->end(); FI != FE; )
126 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
127
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 Values.clear(); // Clear out function local definitions
129 Types.clear();
130 CurrentModule = 0;
131 }
132
133 // GetForwardRefForGlobal - Check to see if there is a forward reference
134 // for this global. If so, remove it from the GlobalRefs map and return it.
135 // If not, just return null.
136 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137 // Check to see if there is a forward reference to this global variable...
138 // if there is, eliminate it and patch the reference to use the new def'n.
139 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140 GlobalValue *Ret = 0;
141 if (I != GlobalRefs.end()) {
142 Ret = I->second;
143 GlobalRefs.erase(I);
144 }
145 return Ret;
146 }
147
148 bool TypeIsUnresolved(PATypeHolder* PATy) {
149 // If it isn't abstract, its resolved
150 const Type* Ty = PATy->get();
151 if (!Ty->isAbstract())
152 return false;
153 // Traverse the type looking for abstract types. If it isn't abstract then
154 // we don't need to traverse that leg of the type.
155 std::vector<const Type*> WorkList, SeenList;
156 WorkList.push_back(Ty);
157 while (!WorkList.empty()) {
158 const Type* Ty = WorkList.back();
159 SeenList.push_back(Ty);
160 WorkList.pop_back();
161 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162 // Check to see if this is an unresolved type
163 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165 for ( ; I != E; ++I) {
166 if (I->second.get() == OpTy)
167 return true;
168 }
169 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170 const Type* TheTy = SeqTy->getElementType();
171 if (TheTy->isAbstract() && TheTy != Ty) {
172 std::vector<const Type*>::iterator I = SeenList.begin(),
173 E = SeenList.end();
174 for ( ; I != E; ++I)
175 if (*I == TheTy)
176 break;
177 if (I == E)
178 WorkList.push_back(TheTy);
179 }
180 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182 const Type* TheTy = StrTy->getElementType(i);
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
185 E = SeenList.end();
186 for ( ; I != E; ++I)
187 if (*I == TheTy)
188 break;
189 if (I == E)
190 WorkList.push_back(TheTy);
191 }
192 }
193 }
194 }
195 return false;
196 }
197} CurModule;
198
199static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
201
202 ValueList Values; // Keep track of #'d definitions
203 unsigned NextValNum;
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
208
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
212
213 inline PerFunctionInfo() {
214 CurrentFunction = 0;
215 isDeclare = false;
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
218 }
219
220 inline void FunctionStart(Function *M) {
221 CurrentFunction = M;
222 NextValNum = 0;
223 }
224
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
230 return;
231 }
232
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
235
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
238 CurrentFunction = 0;
239 isDeclare = false;
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
242 }
243} CurFun; // Info for the current function...
244
245static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
246
247
248//===----------------------------------------------------------------------===//
249// Code to handle definitions of all the types
250//===----------------------------------------------------------------------===//
251
252static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
253 // Things that have names or are void typed don't get slot numbers
254 if (V->hasName() || (V->getType() == Type::VoidTy))
255 return;
256
257 // In the case of function values, we have to allow for the forward reference
258 // of basic blocks, which are included in the numbering. Consequently, we keep
259 // track of the next insertion location with NextValNum. When a BB gets
260 // inserted, it could change the size of the CurFun.Values vector.
261 if (&ValueTab == &CurFun.Values) {
262 if (ValueTab.size() <= CurFun.NextValNum)
263 ValueTab.resize(CurFun.NextValNum+1);
264 ValueTab[CurFun.NextValNum++] = V;
265 return;
266 }
267 // For all other lists, its okay to just tack it on the back of the vector.
268 ValueTab.push_back(V);
269}
270
271static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
272 switch (D.Type) {
273 case ValID::LocalID: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if (D.Num < CurModule.Types.size())
276 return CurModule.Types[D.Num];
277 break;
278 case ValID::LocalName: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
280 D.destroy(); // Free old strdup'd memory...
281 return N;
282 }
283 break;
284 default:
285 GenerateError("Internal parser error: Invalid symbol type reference");
286 return 0;
287 }
288
289 // If we reached here, we referenced either a symbol that we don't know about
290 // or an id number that hasn't been read yet. We may be referencing something
291 // forward, so just create an entry to be resolved later and get to it...
292 //
293 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
294
295
296 if (inFunctionScope()) {
297 if (D.Type == ValID::LocalName) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
299 return 0;
300 } else {
301 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
302 return 0;
303 }
304 }
305
306 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307 if (I != CurModule.LateResolveTypes.end())
308 return I->second;
309
310 Type *Typ = OpaqueType::get();
311 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
312 return Typ;
313 }
314
315// getExistingVal - Look up the value specified by the provided type and
316// the provided ValID. If the value exists and has already been defined, return
317// it. Otherwise return null.
318//
319static Value *getExistingVal(const Type *Ty, const ValID &D) {
320 if (isa<FunctionType>(Ty)) {
321 GenerateError("Functions are not values and "
322 "must be referenced as pointers");
323 return 0;
324 }
325
326 switch (D.Type) {
327 case ValID::LocalID: { // Is it a numbered definition?
328 // Check that the number is within bounds.
329 if (D.Num >= CurFun.Values.size())
330 return 0;
331 Value *Result = CurFun.Values[D.Num];
332 if (Ty != Result->getType()) {
333 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
334 Result->getType()->getDescription() + "' does not match "
335 "expected type, '" + Ty->getDescription() + "'");
336 return 0;
337 }
338 return Result;
339 }
340 case ValID::GlobalID: { // Is it a numbered definition?
341 if (D.Num >= CurModule.Values.size())
342 return 0;
343 Value *Result = CurModule.Values[D.Num];
344 if (Ty != Result->getType()) {
345 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
346 Result->getType()->getDescription() + "' does not match "
347 "expected type, '" + Ty->getDescription() + "'");
348 return 0;
349 }
350 return Result;
351 }
352
353 case ValID::LocalName: { // Is it a named definition?
354 if (!inFunctionScope())
355 return 0;
356 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
357 Value *N = SymTab.lookup(D.getName());
358 if (N == 0)
359 return 0;
360 if (N->getType() != Ty)
361 return 0;
362
363 D.destroy(); // Free old strdup'd memory...
364 return N;
365 }
366 case ValID::GlobalName: { // Is it a named definition?
367 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
368 Value *N = SymTab.lookup(D.getName());
369 if (N == 0)
370 return 0;
371 if (N->getType() != Ty)
372 return 0;
373
374 D.destroy(); // Free old strdup'd memory...
375 return N;
376 }
377
378 // Check to make sure that "Ty" is an integral type, and that our
379 // value will fit into the specified type...
380 case ValID::ConstSIntVal: // Is it a constant pool reference??
Chris Lattner59363a32008-02-19 04:36:25 +0000381 if (!isa<IntegerType>(Ty) ||
382 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 GenerateError("Signed integral constant '" +
384 itostr(D.ConstPool64) + "' is invalid for type '" +
385 Ty->getDescription() + "'");
386 return 0;
387 }
388 return ConstantInt::get(Ty, D.ConstPool64, true);
389
390 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000391 if (isa<IntegerType>(Ty) &&
392 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 return ConstantInt::get(Ty, D.UConstPool64);
Chris Lattner59363a32008-02-19 04:36:25 +0000394
395 if (!isa<IntegerType>(Ty) ||
396 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range for type '" +
399 Ty->getDescription() + "'");
400 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 }
Chris Lattner59363a32008-02-19 04:36:25 +0000402 // This is really a signed reference. Transmogrify.
403 return ConstantInt::get(Ty, D.ConstPool64, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404
405 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000406 if (!Ty->isFloatingPoint() ||
407 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 GenerateError("FP constant invalid for type");
409 return 0;
410 }
Chris Lattner05ba86e2008-04-20 00:41:19 +0000411 // Lexer has no type info, so builds all float and double FP constants
Dale Johannesen255b8fe2007-09-11 18:33:39 +0000412 // as double. Fix this here. Long double does not need this.
413 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
414 Ty==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000415 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner05ba86e2008-04-20 00:41:19 +0000416 return ConstantFP::get(*D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417
418 case ValID::ConstNullVal: // Is it a null value?
419 if (!isa<PointerType>(Ty)) {
420 GenerateError("Cannot create a a non pointer null");
421 return 0;
422 }
423 return ConstantPointerNull::get(cast<PointerType>(Ty));
424
425 case ValID::ConstUndefVal: // Is it an undef value?
426 return UndefValue::get(Ty);
427
428 case ValID::ConstZeroVal: // Is it a zero value?
429 return Constant::getNullValue(Ty);
430
431 case ValID::ConstantVal: // Fully resolved constant?
432 if (D.ConstantValue->getType() != Ty) {
433 GenerateError("Constant expression type different from required type");
434 return 0;
435 }
436 return D.ConstantValue;
437
438 case ValID::InlineAsmVal: { // Inline asm expression
439 const PointerType *PTy = dyn_cast<PointerType>(Ty);
440 const FunctionType *FTy =
441 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
442 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
443 GenerateError("Invalid type for asm constraint string");
444 return 0;
445 }
446 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
447 D.IAD->HasSideEffects);
448 D.destroy(); // Free InlineAsmDescriptor.
449 return IA;
450 }
451 default:
452 assert(0 && "Unhandled case!");
453 return 0;
454 } // End of switch
455
456 assert(0 && "Unhandled case!");
457 return 0;
458}
459
460// getVal - This function is identical to getExistingVal, except that if a
461// value is not already defined, it "improvises" by creating a placeholder var
462// that looks and acts just like the requested variable. When the value is
463// defined later, all uses of the placeholder variable are replaced with the
464// real thing.
465//
466static Value *getVal(const Type *Ty, const ValID &ID) {
467 if (Ty == Type::LabelTy) {
468 GenerateError("Cannot use a basic block here");
469 return 0;
470 }
471
472 // See if the value has already been defined.
473 Value *V = getExistingVal(Ty, ID);
474 if (V) return V;
475 if (TriggerError) return 0;
476
477 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
478 GenerateError("Invalid use of a composite type");
479 return 0;
480 }
481
482 // If we reached here, we referenced either a symbol that we don't know about
483 // or an id number that hasn't been read yet. We may be referencing something
484 // forward, so just create an entry to be resolved later and get to it...
485 //
486 switch (ID.Type) {
487 case ValID::GlobalName:
488 case ValID::GlobalID: {
489 const PointerType *PTy = dyn_cast<PointerType>(Ty);
490 if (!PTy) {
491 GenerateError("Invalid type for reference to global" );
492 return 0;
493 }
494 const Type* ElTy = PTy->getElementType();
495 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
Gabor Greif89f01162008-04-06 23:07:54 +0000496 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 else
Christopher Lamb0a243582007-12-11 09:02:08 +0000498 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
499 (Module*)0, false, PTy->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 break;
501 }
502 default:
503 V = new Argument(Ty);
504 }
505
506 // Remember where this forward reference came from. FIXME, shouldn't we try
507 // to recycle these things??
508 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000509 LLLgetLineNo())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
511 if (inFunctionScope())
512 InsertValue(V, CurFun.LateResolveValues);
513 else
514 InsertValue(V, CurModule.LateResolveValues);
515 return V;
516}
517
518/// defineBBVal - This is a definition of a new basic block with the specified
519/// identifier which must be the same as CurFun.NextValNum, if its numeric.
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000520static BasicBlock *defineBBVal(const ValID &ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 assert(inFunctionScope() && "Can't get basic block at global scope!");
522
523 BasicBlock *BB = 0;
524
525 // First, see if this was forward referenced
526
527 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
528 if (BBI != CurFun.BBForwardRefs.end()) {
529 BB = BBI->second;
530 // The forward declaration could have been inserted anywhere in the
531 // function: insert it into the correct place now.
532 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
533 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
534
535 // We're about to erase the entry, save the key so we can clean it up.
536 ValID Tmp = BBI->first;
537
538 // Erase the forward ref from the map as its no longer "forward"
539 CurFun.BBForwardRefs.erase(ID);
540
541 // The key has been removed from the map but so we don't want to leave
542 // strdup'd memory around so destroy it too.
543 Tmp.destroy();
544
545 // If its a numbered definition, bump the number and set the BB value.
546 if (ID.Type == ValID::LocalID) {
547 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
548 InsertValue(BB);
549 }
Devang Patel890cc572008-03-03 18:58:47 +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 Greif89f01162008-04-06 23:07:54 +0000554 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Devang Patel890cc572008-03-03 18:58:47 +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
Devang Patel890cc572008-03-03 18:58:47 +0000561 ID.destroy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562 return BB;
563}
564
565/// getBBVal - get an existing BB value or create a forward reference for it.
566///
567static BasicBlock *getBBVal(const ValID &ID) {
568 assert(inFunctionScope() && "Can't get basic block at global scope!");
569
570 BasicBlock *BB = 0;
571
572 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
573 if (BBI != CurFun.BBForwardRefs.end()) {
574 BB = BBI->second;
575 } if (ID.Type == ValID::LocalName) {
576 std::string Name = ID.getName();
577 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000578 if (N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 if (N->getType()->getTypeID() == Type::LabelTyID)
580 BB = cast<BasicBlock>(N);
581 else
582 GenerateError("Reference to label '" + Name + "' is actually of type '"+
583 N->getType()->getDescription() + "'");
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000584 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 } else if (ID.Type == ValID::LocalID) {
586 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
587 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
588 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
589 else
590 GenerateError("Reference to label '%" + utostr(ID.Num) +
591 "' is actually of type '"+
592 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
593 }
594 } else {
595 GenerateError("Illegal label reference " + ID.getName());
596 return 0;
597 }
598
599 // If its already been defined, return it now.
600 if (BB) {
601 ID.destroy(); // Free strdup'd memory.
602 return BB;
603 }
604
605 // Otherwise, this block has not been seen before, create it.
606 std::string Name;
607 if (ID.Type == ValID::LocalName)
608 Name = ID.getName();
Gabor Greif89f01162008-04-06 23:07:54 +0000609 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610
611 // Insert it in the forward refs map.
612 CurFun.BBForwardRefs[ID] = BB;
613
614 return BB;
615}
616
617
618//===----------------------------------------------------------------------===//
619// Code to handle forward references in instructions
620//===----------------------------------------------------------------------===//
621//
622// This code handles the late binding needed with statements that reference
623// values not defined yet... for example, a forward branch, or the PHI node for
624// a loop body.
625//
626// This keeps a table (CurFun.LateResolveValues) of all such forward references
627// and back patchs after we are done.
628//
629
630// ResolveDefinitions - If we could not resolve some defs at parsing
631// time (forward branches, phi functions for loops, etc...) resolve the
632// defs now...
633//
634static void
635ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
636 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
637 while (!LateResolvers.empty()) {
638 Value *V = LateResolvers.back();
639 LateResolvers.pop_back();
640
641 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
642 CurModule.PlaceHolderInfo.find(V);
643 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
644
645 ValID &DID = PHI->second.first;
646
647 Value *TheRealValue = getExistingVal(V->getType(), DID);
648 if (TriggerError)
649 return;
650 if (TheRealValue) {
651 V->replaceAllUsesWith(TheRealValue);
652 delete V;
653 CurModule.PlaceHolderInfo.erase(PHI);
654 } else if (FutureLateResolvers) {
655 // Functions have their unresolved items forwarded to the module late
656 // resolver table
657 InsertValue(V, *FutureLateResolvers);
658 } else {
659 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
660 GenerateError("Reference to an invalid definition: '" +DID.getName()+
661 "' of type '" + V->getType()->getDescription() + "'",
662 PHI->second.second);
663 return;
664 } else {
665 GenerateError("Reference to an invalid definition: #" +
666 itostr(DID.Num) + " of type '" +
667 V->getType()->getDescription() + "'",
668 PHI->second.second);
669 return;
670 }
671 }
672 }
673 LateResolvers.clear();
674}
675
676// ResolveTypeTo - A brand new type was just declared. This means that (if
677// name is not null) things referencing Name can be resolved. Otherwise, things
678// refering to the number can be resolved. Do this now.
679//
680static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
681 ValID D;
682 if (Name)
683 D = ValID::createLocalName(*Name);
684 else
685 D = ValID::createLocalID(CurModule.Types.size());
686
687 std::map<ValID, PATypeHolder>::iterator I =
688 CurModule.LateResolveTypes.find(D);
689 if (I != CurModule.LateResolveTypes.end()) {
690 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
691 CurModule.LateResolveTypes.erase(I);
692 }
693}
694
695// setValueName - Set the specified value to the name given. The name may be
696// null potentially, in which case this is a noop. The string passed in is
697// assumed to be a malloc'd string buffer, and is free'd by this function.
698//
699static void setValueName(Value *V, std::string *NameStr) {
700 if (!NameStr) return;
701 std::string Name(*NameStr); // Copy string
702 delete NameStr; // Free old string
703
704 if (V->getType() == Type::VoidTy) {
705 GenerateError("Can't assign name '" + Name+"' to value with void type");
706 return;
707 }
708
709 assert(inFunctionScope() && "Must be in function scope!");
710 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
711 if (ST.lookup(Name)) {
712 GenerateError("Redefinition of value '" + Name + "' of type '" +
713 V->getType()->getDescription() + "'");
714 return;
715 }
716
717 // Set the name.
718 V->setName(Name);
719}
720
721/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
722/// this is a declaration, otherwise it is a definition.
723static GlobalVariable *
724ParseGlobalVariable(std::string *NameStr,
725 GlobalValue::LinkageTypes Linkage,
726 GlobalValue::VisibilityTypes Visibility,
727 bool isConstantGlobal, const Type *Ty,
Christopher Lamb0a243582007-12-11 09:02:08 +0000728 Constant *Initializer, bool IsThreadLocal,
729 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 if (isa<FunctionType>(Ty)) {
731 GenerateError("Cannot declare global vars of function type");
732 return 0;
733 }
734
Christopher Lamb0a243582007-12-11 09:02:08 +0000735 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736
737 std::string Name;
738 if (NameStr) {
739 Name = *NameStr; // Copy string
740 delete NameStr; // Free old string
741 }
742
743 // See if this global value was forward referenced. If so, recycle the
744 // object.
745 ValID ID;
746 if (!Name.empty()) {
747 ID = ValID::createGlobalName(Name);
748 } else {
749 ID = ValID::createGlobalID(CurModule.Values.size());
750 }
751
752 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
753 // Move the global to the end of the list, from whereever it was
754 // previously inserted.
755 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
756 CurModule.CurrentModule->getGlobalList().remove(GV);
757 CurModule.CurrentModule->getGlobalList().push_back(GV);
758 GV->setInitializer(Initializer);
759 GV->setLinkage(Linkage);
760 GV->setVisibility(Visibility);
761 GV->setConstant(isConstantGlobal);
762 GV->setThreadLocal(IsThreadLocal);
763 InsertValue(GV, CurModule.Values);
764 return GV;
765 }
766
767 // If this global has a name
768 if (!Name.empty()) {
769 // if the global we're parsing has an initializer (is a definition) and
770 // has external linkage.
771 if (Initializer && Linkage != GlobalValue::InternalLinkage)
772 // If there is already a global with external linkage with this name
773 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
774 // If we allow this GVar to get created, it will be renamed in the
775 // symbol table because it conflicts with an existing GVar. We can't
776 // allow redefinition of GVars whose linking indicates that their name
777 // must stay the same. Issue the error.
778 GenerateError("Redefinition of global variable named '" + Name +
779 "' of type '" + Ty->getDescription() + "'");
780 return 0;
781 }
782 }
783
784 // Otherwise there is no existing GV to use, create one now.
785 GlobalVariable *GV =
786 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb0a243582007-12-11 09:02:08 +0000787 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 GV->setVisibility(Visibility);
789 InsertValue(GV, CurModule.Values);
790 return GV;
791}
792
793// setTypeName - Set the specified type to the name given. The name may be
794// null potentially, in which case this is a noop. The string passed in is
795// assumed to be a malloc'd string buffer, and is freed by this function.
796//
797// This function returns true if the type has already been defined, but is
798// allowed to be redefined in the specified context. If the name is a new name
799// for the type plane, it is inserted and false is returned.
800static bool setTypeName(const Type *T, std::string *NameStr) {
801 assert(!inFunctionScope() && "Can't give types function-local names!");
802 if (NameStr == 0) return false;
803
804 std::string Name(*NameStr); // Copy string
805 delete NameStr; // Free old string
806
807 // We don't allow assigning names to void type
808 if (T == Type::VoidTy) {
809 GenerateError("Can't assign name '" + Name + "' to the void type");
810 return false;
811 }
812
813 // Set the type name, checking for conflicts as we do so.
814 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
815
816 if (AlreadyExists) { // Inserting a name that is already defined???
817 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
818 assert(Existing && "Conflict but no matching type?!");
819
820 // There is only one case where this is allowed: when we are refining an
821 // opaque type. In this case, Existing will be an opaque type.
822 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
823 // We ARE replacing an opaque type!
824 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
825 return true;
826 }
827
828 // Otherwise, this is an attempt to redefine a type. That's okay if
829 // the redefinition is identical to the original. This will be so if
830 // Existing and T point to the same Type object. In this one case we
831 // allow the equivalent redefinition.
832 if (Existing == T) return true; // Yes, it's equal.
833
834 // Any other kind of (non-equivalent) redefinition is an error.
835 GenerateError("Redefinition of type named '" + Name + "' of type '" +
836 T->getDescription() + "'");
837 }
838
839 return false;
840}
841
842//===----------------------------------------------------------------------===//
843// Code for handling upreferences in type names...
844//
845
846// TypeContains - Returns true if Ty directly contains E in it.
847//
848static bool TypeContains(const Type *Ty, const Type *E) {
849 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
850 E) != Ty->subtype_end();
851}
852
853namespace {
854 struct UpRefRecord {
855 // NestingLevel - The number of nesting levels that need to be popped before
856 // this type is resolved.
857 unsigned NestingLevel;
858
859 // LastContainedTy - This is the type at the current binding level for the
860 // type. Every time we reduce the nesting level, this gets updated.
861 const Type *LastContainedTy;
862
863 // UpRefTy - This is the actual opaque type that the upreference is
864 // represented with.
865 OpaqueType *UpRefTy;
866
867 UpRefRecord(unsigned NL, OpaqueType *URTy)
868 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
869 };
870}
871
872// UpRefs - A list of the outstanding upreferences that need to be resolved.
873static std::vector<UpRefRecord> UpRefs;
874
875/// HandleUpRefs - Every time we finish a new layer of types, this function is
876/// called. It loops through the UpRefs vector, which is a list of the
877/// currently active types. For each type, if the up reference is contained in
878/// the newly completed type, we decrement the level count. When the level
879/// count reaches zero, the upreferenced type is the type that is passed in:
880/// thus we can complete the cycle.
881///
882static PATypeHolder HandleUpRefs(const Type *ty) {
883 // If Ty isn't abstract, or if there are no up-references in it, then there is
884 // nothing to resolve here.
885 if (!ty->isAbstract() || UpRefs.empty()) return ty;
886
887 PATypeHolder Ty(ty);
888 UR_OUT("Type '" << Ty->getDescription() <<
889 "' newly formed. Resolving upreferences.\n" <<
890 UpRefs.size() << " upreferences active!\n");
891
892 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
893 // to zero), we resolve them all together before we resolve them to Ty. At
894 // the end of the loop, if there is anything to resolve to Ty, it will be in
895 // this variable.
896 OpaqueType *TypeToResolve = 0;
897
898 for (unsigned i = 0; i != UpRefs.size(); ++i) {
899 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
900 << UpRefs[i].second->getDescription() << ") = "
901 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
902 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
903 // Decrement level of upreference
904 unsigned Level = --UpRefs[i].NestingLevel;
905 UpRefs[i].LastContainedTy = Ty;
906 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
907 if (Level == 0) { // Upreference should be resolved!
908 if (!TypeToResolve) {
909 TypeToResolve = UpRefs[i].UpRefTy;
910 } else {
911 UR_OUT(" * Resolving upreference for "
912 << UpRefs[i].second->getDescription() << "\n";
913 std::string OldName = UpRefs[i].UpRefTy->getDescription());
914 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
915 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
916 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
917 }
918 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
919 --i; // Do not skip the next element...
920 }
921 }
922 }
923
924 if (TypeToResolve) {
925 UR_OUT(" * Resolving upreference for "
926 << UpRefs[i].second->getDescription() << "\n";
927 std::string OldName = TypeToResolve->getDescription());
928 TypeToResolve->refineAbstractTypeTo(Ty);
929 }
930
931 return Ty;
932}
933
934//===----------------------------------------------------------------------===//
935// RunVMAsmParser - Define an interface to this parser
936//===----------------------------------------------------------------------===//
937//
938static Module* RunParser(Module * M);
939
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000940Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
941 InitLLLexer(MB);
942 Module *M = RunParser(new Module(LLLgetFilename()));
943 FreeLexer();
944 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945}
946
947%}
948
949%union {
950 llvm::Module *ModuleVal;
951 llvm::Function *FunctionVal;
952 llvm::BasicBlock *BasicBlockVal;
953 llvm::TerminatorInst *TermInstVal;
954 llvm::Instruction *InstVal;
955 llvm::Constant *ConstVal;
956
957 const llvm::Type *PrimType;
958 std::list<llvm::PATypeHolder> *TypeList;
959 llvm::PATypeHolder *TypeVal;
960 llvm::Value *ValueVal;
961 std::vector<llvm::Value*> *ValueList;
962 llvm::ArgListType *ArgList;
963 llvm::TypeWithAttrs TypeWithAttrs;
964 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000965 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
967 // Represent the RHS of PHI node
968 std::list<std::pair<llvm::Value*,
969 llvm::BasicBlock*> > *PHIList;
970 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
971 std::vector<llvm::Constant*> *ConstVector;
972
973 llvm::GlobalValue::LinkageTypes Linkage;
974 llvm::GlobalValue::VisibilityTypes Visibility;
Dale Johannesend915ee52008-02-19 21:40:51 +0000975 llvm::ParameterAttributes ParamAttrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 llvm::APInt *APIntVal;
977 int64_t SInt64Val;
978 uint64_t UInt64Val;
979 int SIntVal;
980 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000981 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 bool BoolVal;
983
984 std::string *StrVal; // This memory must be deleted
985 llvm::ValID ValIDVal;
986
987 llvm::Instruction::BinaryOps BinaryOpVal;
988 llvm::Instruction::TermOps TermOpVal;
989 llvm::Instruction::MemoryOps MemOpVal;
990 llvm::Instruction::CastOps CastOpVal;
991 llvm::Instruction::OtherOps OtherOpVal;
992 llvm::ICmpInst::Predicate IPredicate;
993 llvm::FCmpInst::Predicate FPredicate;
994}
995
996%type <ModuleVal> Module
997%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
998%type <BasicBlockVal> BasicBlock InstructionList
999%type <TermInstVal> BBTerminatorInst
1000%type <InstVal> Inst InstVal MemoryInst
1001%type <ConstVal> ConstVal ConstExpr AliaseeRef
1002%type <ConstVector> ConstVector
1003%type <ArgList> ArgList ArgListH
1004%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001005%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006%type <ValueList> IndexList // For GEP indices
1007%type <TypeList> TypeListI
1008%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1009%type <TypeWithAttrs> ArgType
1010%type <JumpTable> JumpTable
1011%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1012%type <BoolVal> ThreadLocal // 'thread_local' or not
1013%type <BoolVal> OptVolatile // 'volatile' or not
1014%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1015%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1016%type <Linkage> GVInternalLinkage GVExternalLinkage
1017%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1018%type <Linkage> AliasLinkage
1019%type <Visibility> GVVisibilityStyle
1020
1021// ValueRef - Unresolved reference to a definition or BB
1022%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1023%type <ValueVal> ResolvedVal // <type> <valref> pair
Devang Patelbf507402008-02-20 22:40:23 +00001024%type <ValueList> ReturnedVal
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025// Tokens and types for handling constant integer values
1026//
1027// ESINT64VAL - A negative number within long long range
1028%token <SInt64Val> ESINT64VAL
1029
1030// EUINT64VAL - A positive number within uns. long long range
1031%token <UInt64Val> EUINT64VAL
1032
1033// ESAPINTVAL - A negative number with arbitrary precision
1034%token <APIntVal> ESAPINTVAL
1035
1036// EUAPINTVAL - A positive number with arbitrary precision
1037%token <APIntVal> EUAPINTVAL
1038
1039%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1040%token <FPVal> FPVAL // Float or Double constant
1041
1042// Built in types...
1043%type <TypeVal> Types ResultTypes
1044%type <PrimType> IntType FPType PrimType // Classifications
1045%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001046%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047%token TYPE
1048
1049
1050%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1051%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1052%type <StrVal> LocalName OptLocalName OptLocalAssign
1053%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001054%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055
Christopher Lamb668d9a02007-12-12 08:45:45 +00001056%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057
1058%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1059%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1060%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1061%token DLLIMPORT DLLEXPORT EXTERN_WEAK
Christopher Lamb0a243582007-12-11 09:02:08 +00001062%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1064%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00001065%token DATALAYOUT
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066%type <UIntVal> OptCallingConv
1067%type <ParamAttrs> OptParamAttrs ParamAttr
1068%type <ParamAttrs> OptFuncAttrs FuncAttr
1069
1070// Basic Block Terminating Operators
1071%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1072
1073// Binary Operators
1074%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1075%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1076%token <BinaryOpVal> SHL LSHR ASHR
1077
1078%token <OtherOpVal> ICMP FCMP
1079%type <IPredicate> IPredicates
1080%type <FPredicate> FPredicates
1081%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1082%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1083
1084// Memory Instructions
1085%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1086
1087// Cast Operators
1088%type <CastOpVal> CastOps
1089%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1090%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1091
1092// Other Operators
1093%token <OtherOpVal> PHI_TOK SELECT VAARG
1094%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Devang Patel3b8849c2008-02-19 22:27:01 +00001095%token <OtherOpVal> GETRESULT
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096
1097// Function Attributes
Reid Spenceraa8ae282007-07-31 03:50:36 +00001098%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001099%token READNONE READONLY GC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100
1101// Visibility Styles
1102%token DEFAULT HIDDEN PROTECTED
1103
1104%start Module
1105%%
1106
1107
1108// Operations that are notably excluded from this list include:
1109// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1110//
1111ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1112LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1113CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1114 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1115
1116IPredicates
1117 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1118 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1119 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1120 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1121 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1122 ;
1123
1124FPredicates
1125 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1126 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1127 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1128 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1129 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1130 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1131 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1132 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1133 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1134 ;
1135
1136// These are some types that allow classification if we only want a particular
1137// thing... for example, only a signed, unsigned, or integral type.
1138IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001139FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140
1141LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1142OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1143
Christopher Lamb668d9a02007-12-12 08:45:45 +00001144OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1145 | /*empty*/ { $$=0; };
1146
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147/// OptLocalAssign - Value producing statements have an optional assignment
1148/// component.
1149OptLocalAssign : LocalName '=' {
1150 $$ = $1;
1151 CHECK_FOR_ERROR
1152 }
1153 | /*empty*/ {
1154 $$ = 0;
1155 CHECK_FOR_ERROR
1156 };
1157
1158GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1159
1160OptGlobalAssign : GlobalAssign
1161 | /*empty*/ {
1162 $$ = 0;
1163 CHECK_FOR_ERROR
1164 };
1165
1166GlobalAssign : GlobalName '=' {
1167 $$ = $1;
1168 CHECK_FOR_ERROR
1169 };
1170
1171GVInternalLinkage
1172 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1173 | WEAK { $$ = GlobalValue::WeakLinkage; }
1174 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1175 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1176 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1177 ;
1178
1179GVExternalLinkage
1180 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1181 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1182 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1183 ;
1184
1185GVVisibilityStyle
1186 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1187 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1188 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1189 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1190 ;
1191
1192FunctionDeclareLinkage
1193 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1194 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1195 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1196 ;
1197
1198FunctionDefineLinkage
1199 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1200 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1201 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1202 | WEAK { $$ = GlobalValue::WeakLinkage; }
1203 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1204 ;
1205
1206AliasLinkage
1207 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1208 | WEAK { $$ = GlobalValue::WeakLinkage; }
1209 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1210 ;
1211
1212OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1213 CCC_TOK { $$ = CallingConv::C; } |
1214 FASTCC_TOK { $$ = CallingConv::Fast; } |
1215 COLDCC_TOK { $$ = CallingConv::Cold; } |
1216 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1217 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1218 CC_TOK EUINT64VAL {
1219 if ((unsigned)$2 != $2)
1220 GEN_ERROR("Calling conv too large");
1221 $$ = $2;
1222 CHECK_FOR_ERROR
1223 };
1224
Reid Spenceraa8ae282007-07-31 03:50:36 +00001225ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1226 | ZEXT { $$ = ParamAttr::ZExt; }
1227 | SIGNEXT { $$ = ParamAttr::SExt; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 | SEXT { $$ = ParamAttr::SExt; }
1229 | INREG { $$ = ParamAttr::InReg; }
1230 | SRET { $$ = ParamAttr::StructRet; }
1231 | NOALIAS { $$ = ParamAttr::NoAlias; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001232 | BYVAL { $$ = ParamAttr::ByVal; }
1233 | NEST { $$ = ParamAttr::Nest; }
Dale Johannesenf92f3162008-02-22 17:50:51 +00001234 | ALIGN EUINT64VAL { $$ =
1235 ParamAttr::constructAlignmentFromInt($2); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 ;
1237
1238OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1239 | OptParamAttrs ParamAttr {
1240 $$ = $1 | $2;
1241 }
1242 ;
1243
1244FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1245 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
Reid Spenceraa8ae282007-07-31 03:50:36 +00001246 | ZEROEXT { $$ = ParamAttr::ZExt; }
1247 | SIGNEXT { $$ = ParamAttr::SExt; }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001248 | READNONE { $$ = ParamAttr::ReadNone; }
1249 | READONLY { $$ = ParamAttr::ReadOnly; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 ;
1251
1252OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1253 | OptFuncAttrs FuncAttr {
1254 $$ = $1 | $2;
1255 }
1256 ;
1257
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001258OptGC : /* empty */ { $$ = 0; }
1259 | GC STRINGCONSTANT {
1260 $$ = $2;
1261 }
1262 ;
1263
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1265// a comma before it.
1266OptAlign : /*empty*/ { $$ = 0; } |
1267 ALIGN EUINT64VAL {
1268 $$ = $2;
1269 if ($$ != 0 && !isPowerOf2_32($$))
1270 GEN_ERROR("Alignment must be a power of two");
1271 CHECK_FOR_ERROR
1272};
1273OptCAlign : /*empty*/ { $$ = 0; } |
1274 ',' ALIGN EUINT64VAL {
1275 $$ = $3;
1276 if ($$ != 0 && !isPowerOf2_32($$))
1277 GEN_ERROR("Alignment must be a power of two");
1278 CHECK_FOR_ERROR
1279};
1280
1281
Christopher Lamb0a243582007-12-11 09:02:08 +00001282
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283SectionString : SECTION STRINGCONSTANT {
1284 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1285 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1286 GEN_ERROR("Invalid character in section name");
1287 $$ = $2;
1288 CHECK_FOR_ERROR
1289};
1290
1291OptSection : /*empty*/ { $$ = 0; } |
1292 SectionString { $$ = $1; };
1293
1294// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1295// is set to be the global we are processing.
1296//
1297GlobalVarAttributes : /* empty */ {} |
1298 ',' GlobalVarAttribute GlobalVarAttributes {};
1299GlobalVarAttribute : SectionString {
1300 CurGV->setSection(*$1);
1301 delete $1;
1302 CHECK_FOR_ERROR
1303 }
1304 | ALIGN EUINT64VAL {
1305 if ($2 != 0 && !isPowerOf2_32($2))
1306 GEN_ERROR("Alignment must be a power of two");
1307 CurGV->setAlignment($2);
1308 CHECK_FOR_ERROR
1309 };
1310
1311//===----------------------------------------------------------------------===//
1312// Types includes all predefined types... except void, because it can only be
1313// used in specific contexts (function returning void for example).
1314
1315// Derived types are added later...
1316//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001317PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318
1319Types
1320 : OPAQUE {
1321 $$ = new PATypeHolder(OpaqueType::get());
1322 CHECK_FOR_ERROR
1323 }
1324 | PrimType {
1325 $$ = new PATypeHolder($1);
1326 CHECK_FOR_ERROR
1327 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00001328 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 if (*$1 == Type::LabelTy)
1330 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb668d9a02007-12-12 08:45:45 +00001331 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb0a243582007-12-11 09:02:08 +00001332 delete $1;
1333 CHECK_FOR_ERROR
1334 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 | SymbolicValueRef { // Named types are also simple types...
1336 const Type* tmp = getTypeVal($1);
1337 CHECK_FOR_ERROR
1338 $$ = new PATypeHolder(tmp);
1339 }
1340 | '\\' EUINT64VAL { // Type UpReference
1341 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1342 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1343 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1344 $$ = new PATypeHolder(OT);
1345 UR_OUT("New Upreference!\n");
1346 CHECK_FOR_ERROR
1347 }
1348 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001349 // Allow but ignore attributes on function types; this permits auto-upgrade.
1350 // FIXME: remove in LLVM 3.0.
Chris Lattner73de3c02008-04-23 05:37:08 +00001351 const Type *RetTy = *$1;
1352 if (!FunctionType::isValidReturnType(RetTy))
1353 GEN_ERROR("Invalid result type for LLVM function");
1354
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001357 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 const Type *Ty = I->Ty->get();
1359 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001361
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1363 if (isVarArg) Params.pop_back();
1364
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001365 for (unsigned i = 0; i != Params.size(); ++i)
1366 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1367 GEN_ERROR("Function arguments must be value types!");
1368
1369 CHECK_FOR_ERROR
1370
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001371 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372 delete $3; // Delete the argument list
1373 delete $1; // Delete the return type handle
1374 $$ = new PATypeHolder(HandleUpRefs(FT));
1375 CHECK_FOR_ERROR
1376 }
1377 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001378 // Allow but ignore attributes on function types; this permits auto-upgrade.
1379 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001382 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 const Type* Ty = I->Ty->get();
1384 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001386
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1388 if (isVarArg) Params.pop_back();
1389
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001390 for (unsigned i = 0; i != Params.size(); ++i)
1391 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1392 GEN_ERROR("Function arguments must be value types!");
1393
1394 CHECK_FOR_ERROR
1395
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001396 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 delete $3; // Delete the argument list
1398 $$ = new PATypeHolder(HandleUpRefs(FT));
1399 CHECK_FOR_ERROR
1400 }
1401
1402 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1403 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1404 delete $4;
1405 CHECK_FOR_ERROR
1406 }
1407 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1408 const llvm::Type* ElemTy = $4->get();
1409 if ((unsigned)$2 != $2)
1410 GEN_ERROR("Unsigned result not equal to signed result");
1411 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1412 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1414 delete $4;
1415 CHECK_FOR_ERROR
1416 }
1417 | '{' TypeListI '}' { // Structure type?
1418 std::vector<const Type*> Elements;
1419 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1420 E = $2->end(); I != E; ++I)
1421 Elements.push_back(*I);
1422
1423 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1424 delete $2;
1425 CHECK_FOR_ERROR
1426 }
1427 | '{' '}' { // Empty structure type?
1428 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1429 CHECK_FOR_ERROR
1430 }
1431 | '<' '{' TypeListI '}' '>' {
1432 std::vector<const Type*> Elements;
1433 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1434 E = $3->end(); I != E; ++I)
1435 Elements.push_back(*I);
1436
1437 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1438 delete $3;
1439 CHECK_FOR_ERROR
1440 }
1441 | '<' '{' '}' '>' { // Empty structure type?
1442 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1443 CHECK_FOR_ERROR
1444 }
1445 ;
1446
1447ArgType
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001448 : Types OptParamAttrs {
1449 // Allow but ignore attributes on function types; this permits auto-upgrade.
1450 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 $$.Ty = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001452 $$.Attrs = ParamAttr::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 }
1454 ;
1455
1456ResultTypes
1457 : Types {
1458 if (!UpRefs.empty())
1459 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Devang Patel3d5a1e862008-02-23 01:17:37 +00001460 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001461 GEN_ERROR("LLVM functions cannot return aggregate types");
1462 $$ = $1;
1463 }
1464 | VOID {
1465 $$ = new PATypeHolder(Type::VoidTy);
1466 }
1467 ;
1468
1469ArgTypeList : ArgType {
1470 $$ = new TypeWithAttrsList();
1471 $$->push_back($1);
1472 CHECK_FOR_ERROR
1473 }
1474 | ArgTypeList ',' ArgType {
1475 ($$=$1)->push_back($3);
1476 CHECK_FOR_ERROR
1477 }
1478 ;
1479
1480ArgTypeListI
1481 : ArgTypeList
1482 | ArgTypeList ',' DOTDOTDOT {
1483 $$=$1;
1484 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1485 TWA.Ty = new PATypeHolder(Type::VoidTy);
1486 $$->push_back(TWA);
1487 CHECK_FOR_ERROR
1488 }
1489 | DOTDOTDOT {
1490 $$ = new TypeWithAttrsList;
1491 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1492 TWA.Ty = new PATypeHolder(Type::VoidTy);
1493 $$->push_back(TWA);
1494 CHECK_FOR_ERROR
1495 }
1496 | /*empty*/ {
1497 $$ = new TypeWithAttrsList();
1498 CHECK_FOR_ERROR
1499 };
1500
1501// TypeList - Used for struct declarations and as a basis for function type
1502// declaration type lists
1503//
1504TypeListI : Types {
1505 $$ = new std::list<PATypeHolder>();
1506 $$->push_back(*$1);
1507 delete $1;
1508 CHECK_FOR_ERROR
1509 }
1510 | TypeListI ',' Types {
1511 ($$=$1)->push_back(*$3);
1512 delete $3;
1513 CHECK_FOR_ERROR
1514 };
1515
1516// ConstVal - The various declarations that go into the constant pool. This
1517// production is used ONLY to represent constants that show up AFTER a 'const',
1518// 'constant' or 'global' token at global scope. Constants that can be inlined
1519// into other expressions (such as integers and constexprs) are handled by the
1520// ResolvedVal, ValueRef and ConstValueRef productions.
1521//
1522ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1523 if (!UpRefs.empty())
1524 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1525 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1526 if (ATy == 0)
1527 GEN_ERROR("Cannot make array constant with type: '" +
1528 (*$1)->getDescription() + "'");
1529 const Type *ETy = ATy->getElementType();
1530 int NumElements = ATy->getNumElements();
1531
1532 // Verify that we have the correct size...
1533 if (NumElements != -1 && NumElements != (int)$3->size())
1534 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1535 utostr($3->size()) + " arguments, but has size of " +
1536 itostr(NumElements) + "");
1537
1538 // Verify all elements are correct type!
1539 for (unsigned i = 0; i < $3->size(); i++) {
1540 if (ETy != (*$3)[i]->getType())
1541 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1542 ETy->getDescription() +"' as required!\nIt is of type '"+
1543 (*$3)[i]->getType()->getDescription() + "'.");
1544 }
1545
1546 $$ = ConstantArray::get(ATy, *$3);
1547 delete $1; delete $3;
1548 CHECK_FOR_ERROR
1549 }
1550 | Types '[' ']' {
1551 if (!UpRefs.empty())
1552 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1553 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1554 if (ATy == 0)
1555 GEN_ERROR("Cannot make array constant with type: '" +
1556 (*$1)->getDescription() + "'");
1557
1558 int NumElements = ATy->getNumElements();
1559 if (NumElements != -1 && NumElements != 0)
1560 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1561 " arguments, but has size of " + itostr(NumElements) +"");
1562 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1563 delete $1;
1564 CHECK_FOR_ERROR
1565 }
1566 | Types 'c' STRINGCONSTANT {
1567 if (!UpRefs.empty())
1568 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1569 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1570 if (ATy == 0)
1571 GEN_ERROR("Cannot make array constant with type: '" +
1572 (*$1)->getDescription() + "'");
1573
1574 int NumElements = ATy->getNumElements();
1575 const Type *ETy = ATy->getElementType();
1576 if (NumElements != -1 && NumElements != int($3->length()))
1577 GEN_ERROR("Can't build string constant of size " +
1578 itostr((int)($3->length())) +
1579 " when array has size " + itostr(NumElements) + "");
1580 std::vector<Constant*> Vals;
1581 if (ETy == Type::Int8Ty) {
1582 for (unsigned i = 0; i < $3->length(); ++i)
1583 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1584 } else {
1585 delete $3;
1586 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1587 }
1588 delete $3;
1589 $$ = ConstantArray::get(ATy, Vals);
1590 delete $1;
1591 CHECK_FOR_ERROR
1592 }
1593 | Types '<' ConstVector '>' { // Nonempty unsized arr
1594 if (!UpRefs.empty())
1595 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1596 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1597 if (PTy == 0)
1598 GEN_ERROR("Cannot make packed constant with type: '" +
1599 (*$1)->getDescription() + "'");
1600 const Type *ETy = PTy->getElementType();
1601 int NumElements = PTy->getNumElements();
1602
1603 // Verify that we have the correct size...
1604 if (NumElements != -1 && NumElements != (int)$3->size())
1605 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1606 utostr($3->size()) + " arguments, but has size of " +
1607 itostr(NumElements) + "");
1608
1609 // Verify all elements are correct type!
1610 for (unsigned i = 0; i < $3->size(); i++) {
1611 if (ETy != (*$3)[i]->getType())
1612 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1613 ETy->getDescription() +"' as required!\nIt is of type '"+
1614 (*$3)[i]->getType()->getDescription() + "'.");
1615 }
1616
1617 $$ = ConstantVector::get(PTy, *$3);
1618 delete $1; delete $3;
1619 CHECK_FOR_ERROR
1620 }
1621 | Types '{' ConstVector '}' {
1622 const StructType *STy = dyn_cast<StructType>($1->get());
1623 if (STy == 0)
1624 GEN_ERROR("Cannot make struct constant with type: '" +
1625 (*$1)->getDescription() + "'");
1626
1627 if ($3->size() != STy->getNumContainedTypes())
1628 GEN_ERROR("Illegal number of initializers for structure type");
1629
1630 // Check to ensure that constants are compatible with the type initializer!
1631 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1632 if ((*$3)[i]->getType() != STy->getElementType(i))
1633 GEN_ERROR("Expected type '" +
1634 STy->getElementType(i)->getDescription() +
1635 "' for element #" + utostr(i) +
1636 " of structure initializer");
1637
1638 // Check to ensure that Type is not packed
1639 if (STy->isPacked())
1640 GEN_ERROR("Unpacked Initializer to vector type '" +
1641 STy->getDescription() + "'");
1642
1643 $$ = ConstantStruct::get(STy, *$3);
1644 delete $1; delete $3;
1645 CHECK_FOR_ERROR
1646 }
1647 | Types '{' '}' {
1648 if (!UpRefs.empty())
1649 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1650 const StructType *STy = dyn_cast<StructType>($1->get());
1651 if (STy == 0)
1652 GEN_ERROR("Cannot make struct constant with type: '" +
1653 (*$1)->getDescription() + "'");
1654
1655 if (STy->getNumContainedTypes() != 0)
1656 GEN_ERROR("Illegal number of initializers for structure type");
1657
1658 // Check to ensure that Type is not packed
1659 if (STy->isPacked())
1660 GEN_ERROR("Unpacked Initializer to vector type '" +
1661 STy->getDescription() + "'");
1662
1663 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1664 delete $1;
1665 CHECK_FOR_ERROR
1666 }
1667 | Types '<' '{' ConstVector '}' '>' {
1668 const StructType *STy = dyn_cast<StructType>($1->get());
1669 if (STy == 0)
1670 GEN_ERROR("Cannot make struct constant with type: '" +
1671 (*$1)->getDescription() + "'");
1672
1673 if ($4->size() != STy->getNumContainedTypes())
1674 GEN_ERROR("Illegal number of initializers for structure type");
1675
1676 // Check to ensure that constants are compatible with the type initializer!
1677 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1678 if ((*$4)[i]->getType() != STy->getElementType(i))
1679 GEN_ERROR("Expected type '" +
1680 STy->getElementType(i)->getDescription() +
1681 "' for element #" + utostr(i) +
1682 " of structure initializer");
1683
1684 // Check to ensure that Type is packed
1685 if (!STy->isPacked())
1686 GEN_ERROR("Vector initializer to non-vector type '" +
1687 STy->getDescription() + "'");
1688
1689 $$ = ConstantStruct::get(STy, *$4);
1690 delete $1; delete $4;
1691 CHECK_FOR_ERROR
1692 }
1693 | Types '<' '{' '}' '>' {
1694 if (!UpRefs.empty())
1695 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1696 const StructType *STy = dyn_cast<StructType>($1->get());
1697 if (STy == 0)
1698 GEN_ERROR("Cannot make struct constant with type: '" +
1699 (*$1)->getDescription() + "'");
1700
1701 if (STy->getNumContainedTypes() != 0)
1702 GEN_ERROR("Illegal number of initializers for structure type");
1703
1704 // Check to ensure that Type is packed
1705 if (!STy->isPacked())
1706 GEN_ERROR("Vector initializer to non-vector type '" +
1707 STy->getDescription() + "'");
1708
1709 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1710 delete $1;
1711 CHECK_FOR_ERROR
1712 }
1713 | Types NULL_TOK {
1714 if (!UpRefs.empty())
1715 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1716 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1717 if (PTy == 0)
1718 GEN_ERROR("Cannot make null pointer constant with type: '" +
1719 (*$1)->getDescription() + "'");
1720
1721 $$ = ConstantPointerNull::get(PTy);
1722 delete $1;
1723 CHECK_FOR_ERROR
1724 }
1725 | Types UNDEF {
1726 if (!UpRefs.empty())
1727 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1728 $$ = UndefValue::get($1->get());
1729 delete $1;
1730 CHECK_FOR_ERROR
1731 }
1732 | Types SymbolicValueRef {
1733 if (!UpRefs.empty())
1734 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1735 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1736 if (Ty == 0)
Devang Patel3b8849c2008-02-19 22:27:01 +00001737 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738
1739 // ConstExprs can exist in the body of a function, thus creating
1740 // GlobalValues whenever they refer to a variable. Because we are in
1741 // the context of a function, getExistingVal will search the functions
1742 // symbol table instead of the module symbol table for the global symbol,
1743 // which throws things all off. To get around this, we just tell
1744 // getExistingVal that we are at global scope here.
1745 //
1746 Function *SavedCurFn = CurFun.CurrentFunction;
1747 CurFun.CurrentFunction = 0;
1748
1749 Value *V = getExistingVal(Ty, $2);
1750 CHECK_FOR_ERROR
1751
1752 CurFun.CurrentFunction = SavedCurFn;
1753
1754 // If this is an initializer for a constant pointer, which is referencing a
1755 // (currently) undefined variable, create a stub now that shall be replaced
1756 // in the future with the right type of variable.
1757 //
1758 if (V == 0) {
1759 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1760 const PointerType *PT = cast<PointerType>(Ty);
1761
1762 // First check to see if the forward references value is already created!
1763 PerModuleInfo::GlobalRefsType::iterator I =
1764 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1765
1766 if (I != CurModule.GlobalRefs.end()) {
1767 V = I->second; // Placeholder already exists, use it...
1768 $2.destroy();
1769 } else {
1770 std::string Name;
1771 if ($2.Type == ValID::GlobalName)
1772 Name = $2.getName();
1773 else if ($2.Type != ValID::GlobalID)
1774 GEN_ERROR("Invalid reference to global");
1775
1776 // Create the forward referenced global.
1777 GlobalValue *GV;
1778 if (const FunctionType *FTy =
1779 dyn_cast<FunctionType>(PT->getElementType())) {
Gabor Greif89f01162008-04-06 23:07:54 +00001780 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1781 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001782 } else {
1783 GV = new GlobalVariable(PT->getElementType(), false,
1784 GlobalValue::ExternalWeakLinkage, 0,
1785 Name, CurModule.CurrentModule);
1786 }
1787
1788 // Keep track of the fact that we have a forward ref to recycle it
1789 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1790 V = GV;
1791 }
1792 }
1793
1794 $$ = cast<GlobalValue>(V);
1795 delete $1; // Free the type handle
1796 CHECK_FOR_ERROR
1797 }
1798 | Types ConstExpr {
1799 if (!UpRefs.empty())
1800 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1801 if ($1->get() != $2->getType())
1802 GEN_ERROR("Mismatched types for constant expression: " +
1803 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1804 $$ = $2;
1805 delete $1;
1806 CHECK_FOR_ERROR
1807 }
1808 | Types ZEROINITIALIZER {
1809 if (!UpRefs.empty())
1810 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1811 const Type *Ty = $1->get();
1812 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1813 GEN_ERROR("Cannot create a null initialized value of this type");
1814 $$ = Constant::getNullValue(Ty);
1815 delete $1;
1816 CHECK_FOR_ERROR
1817 }
1818 | IntType ESINT64VAL { // integral constants
1819 if (!ConstantInt::isValueValidForType($1, $2))
1820 GEN_ERROR("Constant value doesn't fit in type");
1821 $$ = ConstantInt::get($1, $2, true);
1822 CHECK_FOR_ERROR
1823 }
1824 | IntType ESAPINTVAL { // arbitrary precision integer constants
1825 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1826 if ($2->getBitWidth() > BitWidth) {
1827 GEN_ERROR("Constant value does not fit in type");
1828 }
1829 $2->sextOrTrunc(BitWidth);
1830 $$ = ConstantInt::get(*$2);
1831 delete $2;
1832 CHECK_FOR_ERROR
1833 }
1834 | IntType EUINT64VAL { // integral constants
1835 if (!ConstantInt::isValueValidForType($1, $2))
1836 GEN_ERROR("Constant value doesn't fit in type");
1837 $$ = ConstantInt::get($1, $2, false);
1838 CHECK_FOR_ERROR
1839 }
1840 | IntType EUAPINTVAL { // arbitrary precision integer constants
1841 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1842 if ($2->getBitWidth() > BitWidth) {
1843 GEN_ERROR("Constant value does not fit in type");
1844 }
1845 $2->zextOrTrunc(BitWidth);
1846 $$ = ConstantInt::get(*$2);
1847 delete $2;
1848 CHECK_FOR_ERROR
1849 }
1850 | INTTYPE TRUETOK { // Boolean constants
1851 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1852 $$ = ConstantInt::getTrue();
1853 CHECK_FOR_ERROR
1854 }
1855 | INTTYPE FALSETOK { // Boolean constants
1856 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1857 $$ = ConstantInt::getFalse();
1858 CHECK_FOR_ERROR
1859 }
Dale Johannesen043064d2007-09-12 03:31:28 +00001860 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001861 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001862 GEN_ERROR("Floating point constant invalid for type");
Dale Johannesen255b8fe2007-09-11 18:33:39 +00001863 // Lexer has no type info, so builds all float and double FP constants
1864 // as double. Fix this here. Long double is done right.
1865 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001866 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner05ba86e2008-04-20 00:41:19 +00001867 $$ = ConstantFP::get(*$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001868 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001869 CHECK_FOR_ERROR
1870 };
1871
1872
1873ConstExpr: CastOps '(' ConstVal TO Types ')' {
1874 if (!UpRefs.empty())
1875 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1876 Constant *Val = $3;
1877 const Type *DestTy = $5->get();
1878 if (!CastInst::castIsValid($1, $3, DestTy))
1879 GEN_ERROR("invalid cast opcode for cast from '" +
1880 Val->getType()->getDescription() + "' to '" +
1881 DestTy->getDescription() + "'");
1882 $$ = ConstantExpr::getCast($1, $3, DestTy);
1883 delete $5;
1884 }
1885 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1886 if (!isa<PointerType>($3->getType()))
1887 GEN_ERROR("GetElementPtr requires a pointer operand");
1888
1889 const Type *IdxTy =
David Greene48556392007-09-04 18:46:50 +00001890 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891 true);
1892 if (!IdxTy)
1893 GEN_ERROR("Index list invalid for constant getelementptr");
1894
1895 SmallVector<Constant*, 8> IdxVec;
1896 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1897 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1898 IdxVec.push_back(C);
1899 else
1900 GEN_ERROR("Indices to constant getelementptr must be constants");
1901
1902 delete $4;
1903
1904 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1905 CHECK_FOR_ERROR
1906 }
1907 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1908 if ($3->getType() != Type::Int1Ty)
1909 GEN_ERROR("Select condition must be of boolean type");
1910 if ($5->getType() != $7->getType())
1911 GEN_ERROR("Select operand types must match");
1912 $$ = ConstantExpr::getSelect($3, $5, $7);
1913 CHECK_FOR_ERROR
1914 }
1915 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1916 if ($3->getType() != $5->getType())
1917 GEN_ERROR("Binary operator types must match");
1918 CHECK_FOR_ERROR;
1919 $$ = ConstantExpr::get($1, $3, $5);
1920 }
1921 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1922 if ($3->getType() != $5->getType())
1923 GEN_ERROR("Logical operator types must match");
1924 if (!$3->getType()->isInteger()) {
1925 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1926 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1927 GEN_ERROR("Logical operator requires integral operands");
1928 }
1929 $$ = ConstantExpr::get($1, $3, $5);
1930 CHECK_FOR_ERROR
1931 }
1932 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1933 if ($4->getType() != $6->getType())
1934 GEN_ERROR("icmp operand types must match");
1935 $$ = ConstantExpr::getICmp($2, $4, $6);
1936 }
1937 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1938 if ($4->getType() != $6->getType())
1939 GEN_ERROR("fcmp operand types must match");
1940 $$ = ConstantExpr::getFCmp($2, $4, $6);
1941 }
1942 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1943 if (!ExtractElementInst::isValidOperands($3, $5))
1944 GEN_ERROR("Invalid extractelement operands");
1945 $$ = ConstantExpr::getExtractElement($3, $5);
1946 CHECK_FOR_ERROR
1947 }
1948 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1949 if (!InsertElementInst::isValidOperands($3, $5, $7))
1950 GEN_ERROR("Invalid insertelement operands");
1951 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1952 CHECK_FOR_ERROR
1953 }
1954 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1955 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1956 GEN_ERROR("Invalid shufflevector operands");
1957 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1958 CHECK_FOR_ERROR
1959 };
1960
1961
1962// ConstVector - A list of comma separated constants.
1963ConstVector : ConstVector ',' ConstVal {
1964 ($$ = $1)->push_back($3);
1965 CHECK_FOR_ERROR
1966 }
1967 | ConstVal {
1968 $$ = new std::vector<Constant*>();
1969 $$->push_back($1);
1970 CHECK_FOR_ERROR
1971 };
1972
1973
1974// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1975GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1976
1977// ThreadLocal
1978ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1979
1980// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1981AliaseeRef : ResultTypes SymbolicValueRef {
1982 const Type* VTy = $1->get();
1983 Value *V = getVal(VTy, $2);
Chris Lattnerbb856a32007-08-06 21:00:46 +00001984 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001985 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1986 if (!Aliasee)
1987 GEN_ERROR("Aliases can be created only to global values");
1988
1989 $$ = Aliasee;
1990 CHECK_FOR_ERROR
1991 delete $1;
1992 }
1993 | BITCAST '(' AliaseeRef TO Types ')' {
1994 Constant *Val = $3;
1995 const Type *DestTy = $5->get();
1996 if (!CastInst::castIsValid($1, $3, DestTy))
1997 GEN_ERROR("invalid cast opcode for cast from '" +
1998 Val->getType()->getDescription() + "' to '" +
1999 DestTy->getDescription() + "'");
2000
2001 $$ = ConstantExpr::getCast($1, $3, DestTy);
2002 CHECK_FOR_ERROR
2003 delete $5;
2004 };
2005
2006//===----------------------------------------------------------------------===//
2007// Rules to match Modules
2008//===----------------------------------------------------------------------===//
2009
2010// Module rule: Capture the result of parsing the whole file into a result
2011// variable...
2012//
2013Module
2014 : DefinitionList {
2015 $$ = ParserResult = CurModule.CurrentModule;
2016 CurModule.ModuleDone();
2017 CHECK_FOR_ERROR;
2018 }
2019 | /*empty*/ {
2020 $$ = ParserResult = CurModule.CurrentModule;
2021 CurModule.ModuleDone();
2022 CHECK_FOR_ERROR;
2023 }
2024 ;
2025
2026DefinitionList
2027 : Definition
2028 | DefinitionList Definition
2029 ;
2030
2031Definition
2032 : DEFINE { CurFun.isDeclare = false; } Function {
2033 CurFun.FunctionDone();
2034 CHECK_FOR_ERROR
2035 }
2036 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2037 CHECK_FOR_ERROR
2038 }
2039 | MODULE ASM_TOK AsmBlock {
2040 CHECK_FOR_ERROR
2041 }
2042 | OptLocalAssign TYPE Types {
2043 if (!UpRefs.empty())
2044 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2045 // Eagerly resolve types. This is not an optimization, this is a
2046 // requirement that is due to the fact that we could have this:
2047 //
2048 // %list = type { %list * }
2049 // %list = type { %list * } ; repeated type decl
2050 //
2051 // If types are not resolved eagerly, then the two types will not be
2052 // determined to be the same type!
2053 //
2054 ResolveTypeTo($1, *$3);
2055
2056 if (!setTypeName(*$3, $1) && !$1) {
2057 CHECK_FOR_ERROR
2058 // If this is a named type that is not a redefinition, add it to the slot
2059 // table.
2060 CurModule.Types.push_back(*$3);
2061 }
2062
2063 delete $3;
2064 CHECK_FOR_ERROR
2065 }
2066 | OptLocalAssign TYPE VOID {
2067 ResolveTypeTo($1, $3);
2068
2069 if (!setTypeName($3, $1) && !$1) {
2070 CHECK_FOR_ERROR
2071 // If this is a named type that is not a redefinition, add it to the slot
2072 // table.
2073 CurModule.Types.push_back($3);
2074 }
2075 CHECK_FOR_ERROR
2076 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00002077 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2078 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002079 /* "Externally Visible" Linkage */
2080 if ($5 == 0)
2081 GEN_ERROR("Global value initializer is not a constant");
2082 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb668d9a02007-12-12 08:45:45 +00002083 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb0a243582007-12-11 09:02:08 +00002084 CHECK_FOR_ERROR
2085 } GlobalVarAttributes {
2086 CurGV = 0;
2087 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002089 ConstVal OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002090 if ($6 == 0)
2091 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb668d9a02007-12-12 08:45:45 +00002092 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002093 CHECK_FOR_ERROR
2094 } GlobalVarAttributes {
2095 CurGV = 0;
2096 }
2097 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002098 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 if (!UpRefs.empty())
2100 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb668d9a02007-12-12 08:45:45 +00002101 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002102 CHECK_FOR_ERROR
2103 delete $6;
2104 } GlobalVarAttributes {
2105 CurGV = 0;
2106 CHECK_FOR_ERROR
2107 }
2108 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2109 std::string Name;
2110 if ($1) {
2111 Name = *$1;
2112 delete $1;
2113 }
2114 if (Name.empty())
2115 GEN_ERROR("Alias name cannot be empty");
2116
2117 Constant* Aliasee = $5;
2118 if (Aliasee == 0)
2119 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2120
2121 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2122 CurModule.CurrentModule);
2123 GA->setVisibility($2);
2124 InsertValue(GA, CurModule.Values);
Chris Lattner5eefce32007-09-10 23:24:14 +00002125
2126
2127 // If there was a forward reference of this alias, resolve it now.
2128
2129 ValID ID;
2130 if (!Name.empty())
2131 ID = ValID::createGlobalName(Name);
2132 else
2133 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2134
2135 if (GlobalValue *FWGV =
2136 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2137 // Replace uses of the fwdref with the actual alias.
2138 FWGV->replaceAllUsesWith(GA);
2139 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2140 GV->eraseFromParent();
2141 else
2142 cast<Function>(FWGV)->eraseFromParent();
2143 }
2144 ID.destroy();
2145
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002146 CHECK_FOR_ERROR
2147 }
2148 | TARGET TargetDefinition {
2149 CHECK_FOR_ERROR
2150 }
2151 | DEPLIBS '=' LibrariesDefinition {
2152 CHECK_FOR_ERROR
2153 }
2154 ;
2155
2156
2157AsmBlock : STRINGCONSTANT {
2158 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2159 if (AsmSoFar.empty())
2160 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2161 else
2162 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2163 delete $1;
2164 CHECK_FOR_ERROR
2165};
2166
2167TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2168 CurModule.CurrentModule->setTargetTriple(*$3);
2169 delete $3;
2170 }
2171 | DATALAYOUT '=' STRINGCONSTANT {
2172 CurModule.CurrentModule->setDataLayout(*$3);
2173 delete $3;
2174 };
2175
2176LibrariesDefinition : '[' LibList ']';
2177
2178LibList : LibList ',' STRINGCONSTANT {
2179 CurModule.CurrentModule->addLibrary(*$3);
2180 delete $3;
2181 CHECK_FOR_ERROR
2182 }
2183 | STRINGCONSTANT {
2184 CurModule.CurrentModule->addLibrary(*$1);
2185 delete $1;
2186 CHECK_FOR_ERROR
2187 }
2188 | /* empty: end of list */ {
2189 CHECK_FOR_ERROR
2190 }
2191 ;
2192
2193//===----------------------------------------------------------------------===//
2194// Rules to match Function Headers
2195//===----------------------------------------------------------------------===//
2196
2197ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2198 if (!UpRefs.empty())
2199 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2200 if (*$3 == Type::VoidTy)
2201 GEN_ERROR("void typed arguments are invalid");
2202 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2203 $$ = $1;
2204 $1->push_back(E);
2205 CHECK_FOR_ERROR
2206 }
2207 | Types OptParamAttrs OptLocalName {
2208 if (!UpRefs.empty())
2209 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2210 if (*$1 == Type::VoidTy)
2211 GEN_ERROR("void typed arguments are invalid");
2212 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2213 $$ = new ArgListType;
2214 $$->push_back(E);
2215 CHECK_FOR_ERROR
2216 };
2217
2218ArgList : ArgListH {
2219 $$ = $1;
2220 CHECK_FOR_ERROR
2221 }
2222 | ArgListH ',' DOTDOTDOT {
2223 $$ = $1;
2224 struct ArgListEntry E;
2225 E.Ty = new PATypeHolder(Type::VoidTy);
2226 E.Name = 0;
2227 E.Attrs = ParamAttr::None;
2228 $$->push_back(E);
2229 CHECK_FOR_ERROR
2230 }
2231 | DOTDOTDOT {
2232 $$ = new ArgListType;
2233 struct ArgListEntry E;
2234 E.Ty = new PATypeHolder(Type::VoidTy);
2235 E.Name = 0;
2236 E.Attrs = ParamAttr::None;
2237 $$->push_back(E);
2238 CHECK_FOR_ERROR
2239 }
2240 | /* empty */ {
2241 $$ = 0;
2242 CHECK_FOR_ERROR
2243 };
2244
2245FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002246 OptFuncAttrs OptSection OptAlign OptGC {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247 std::string FunctionName(*$3);
2248 delete $3; // Free strdup'd memory!
2249
2250 // Check the function result for abstractness if this is a define. We should
2251 // have no abstract types at this point
2252 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2253 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2254
Chris Lattner73de3c02008-04-23 05:37:08 +00002255 if (!FunctionType::isValidReturnType(*$2))
2256 GEN_ERROR("Invalid result type for LLVM function");
2257
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 std::vector<const Type*> ParamTypeList;
Chris Lattner1c8733e2008-03-12 17:45:29 +00002259 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2260 if ($7 != ParamAttr::None)
2261 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002262 if ($5) { // If there are arguments...
2263 unsigned index = 1;
2264 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2265 const Type* Ty = I->Ty->get();
2266 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2267 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2268 ParamTypeList.push_back(Ty);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002269 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2270 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271 }
2272 }
2273
2274 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2275 if (isVarArg) ParamTypeList.pop_back();
2276
Chris Lattner1c8733e2008-03-12 17:45:29 +00002277 PAListPtr PAL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002278 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002279 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002281 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambfb623c62007-12-17 01:17:35 +00002282 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283 delete $2;
2284
2285 ValID ID;
2286 if (!FunctionName.empty()) {
2287 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2288 } else {
2289 ID = ValID::createGlobalID(CurModule.Values.size());
2290 }
2291
2292 Function *Fn = 0;
2293 // See if this function was forward referenced. If so, recycle the object.
2294 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2295 // Move the function to the end of the list, from whereever it was
2296 // previously inserted.
2297 Fn = cast<Function>(FWRef);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002298 assert(Fn->getParamAttrs().isEmpty() &&
2299 "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002300 CurModule.CurrentModule->getFunctionList().remove(Fn);
2301 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2302 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2303 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002304 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 // The existing function doesn't have the same type. This is an overload
2306 // error.
2307 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002308 } else if (Fn->getParamAttrs() != PAL) {
2309 // The existing function doesn't have the same parameter attributes.
2310 // This is an overload error.
2311 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002312 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2313 // Neither the existing or the current function is a declaration and they
2314 // have the same name and same type. Clearly this is a redefinition.
2315 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002316 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002317 // Make sure to strip off any argument names so we can't get conflicts.
2318 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2319 AI != AE; ++AI)
2320 AI->setName("");
2321 }
2322 } else { // Not already defined?
Gabor Greif89f01162008-04-06 23:07:54 +00002323 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2324 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002325 InsertValue(Fn, CurModule.Values);
2326 }
2327
2328 CurFun.FunctionStart(Fn);
2329
2330 if (CurFun.isDeclare) {
2331 // If we have declaration, always overwrite linkage. This will allow us to
2332 // correctly handle cases, when pointer to function is passed as argument to
2333 // another function.
2334 Fn->setLinkage(CurFun.Linkage);
2335 Fn->setVisibility(CurFun.Visibility);
2336 }
2337 Fn->setCallingConv($1);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002338 Fn->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002339 Fn->setAlignment($9);
2340 if ($8) {
2341 Fn->setSection(*$8);
2342 delete $8;
2343 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002344 if ($10) {
2345 Fn->setCollector($10->c_str());
2346 delete $10;
2347 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002348
2349 // Add all of the arguments we parsed to the function...
2350 if ($5) { // Is null if empty...
2351 if (isVarArg) { // Nuke the last entry
2352 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2353 "Not a varargs marker!");
2354 delete $5->back().Ty;
2355 $5->pop_back(); // Delete the last entry
2356 }
2357 Function::arg_iterator ArgIt = Fn->arg_begin();
2358 Function::arg_iterator ArgEnd = Fn->arg_end();
2359 unsigned Idx = 1;
2360 for (ArgListType::iterator I = $5->begin();
2361 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2362 delete I->Ty; // Delete the typeholder...
2363 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2364 CHECK_FOR_ERROR
2365 InsertValue(ArgIt);
2366 Idx++;
2367 }
2368
2369 delete $5; // We're now done with the argument list
2370 }
2371 CHECK_FOR_ERROR
2372};
2373
2374BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2375
2376FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2377 $$ = CurFun.CurrentFunction;
2378
2379 // Make sure that we keep track of the linkage type even if there was a
2380 // previous "declare".
2381 $$->setLinkage($1);
2382 $$->setVisibility($2);
2383};
2384
2385END : ENDTOK | '}'; // Allow end of '}' to end a function
2386
2387Function : BasicBlockList END {
2388 $$ = $1;
2389 CHECK_FOR_ERROR
2390};
2391
2392FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2393 CurFun.CurrentFunction->setLinkage($1);
2394 CurFun.CurrentFunction->setVisibility($2);
2395 $$ = CurFun.CurrentFunction;
2396 CurFun.FunctionDone();
2397 CHECK_FOR_ERROR
2398 };
2399
2400//===----------------------------------------------------------------------===//
2401// Rules to match Basic Blocks
2402//===----------------------------------------------------------------------===//
2403
2404OptSideEffect : /* empty */ {
2405 $$ = false;
2406 CHECK_FOR_ERROR
2407 }
2408 | SIDEEFFECT {
2409 $$ = true;
2410 CHECK_FOR_ERROR
2411 };
2412
2413ConstValueRef : ESINT64VAL { // A reference to a direct constant
2414 $$ = ValID::create($1);
2415 CHECK_FOR_ERROR
2416 }
2417 | EUINT64VAL {
2418 $$ = ValID::create($1);
2419 CHECK_FOR_ERROR
2420 }
2421 | FPVAL { // Perhaps it's an FP constant?
2422 $$ = ValID::create($1);
2423 CHECK_FOR_ERROR
2424 }
2425 | TRUETOK {
2426 $$ = ValID::create(ConstantInt::getTrue());
2427 CHECK_FOR_ERROR
2428 }
2429 | FALSETOK {
2430 $$ = ValID::create(ConstantInt::getFalse());
2431 CHECK_FOR_ERROR
2432 }
2433 | NULL_TOK {
2434 $$ = ValID::createNull();
2435 CHECK_FOR_ERROR
2436 }
2437 | UNDEF {
2438 $$ = ValID::createUndef();
2439 CHECK_FOR_ERROR
2440 }
2441 | ZEROINITIALIZER { // A vector zero constant.
2442 $$ = ValID::createZeroInit();
2443 CHECK_FOR_ERROR
2444 }
2445 | '<' ConstVector '>' { // Nonempty unsized packed vector
2446 const Type *ETy = (*$2)[0]->getType();
2447 int NumElements = $2->size();
2448
2449 VectorType* pt = VectorType::get(ETy, NumElements);
2450 PATypeHolder* PTy = new PATypeHolder(
2451 HandleUpRefs(
2452 VectorType::get(
2453 ETy,
2454 NumElements)
2455 )
2456 );
2457
2458 // Verify all elements are correct type!
2459 for (unsigned i = 0; i < $2->size(); i++) {
2460 if (ETy != (*$2)[i]->getType())
2461 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2462 ETy->getDescription() +"' as required!\nIt is of type '" +
2463 (*$2)[i]->getType()->getDescription() + "'.");
2464 }
2465
2466 $$ = ValID::create(ConstantVector::get(pt, *$2));
2467 delete PTy; delete $2;
2468 CHECK_FOR_ERROR
2469 }
2470 | ConstExpr {
2471 $$ = ValID::create($1);
2472 CHECK_FOR_ERROR
2473 }
2474 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2475 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2476 delete $3;
2477 delete $5;
2478 CHECK_FOR_ERROR
2479 };
2480
2481// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2482// another value.
2483//
2484SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2485 $$ = ValID::createLocalID($1);
2486 CHECK_FOR_ERROR
2487 }
2488 | GLOBALVAL_ID {
2489 $$ = ValID::createGlobalID($1);
2490 CHECK_FOR_ERROR
2491 }
2492 | LocalName { // Is it a named reference...?
2493 $$ = ValID::createLocalName(*$1);
2494 delete $1;
2495 CHECK_FOR_ERROR
2496 }
2497 | GlobalName { // Is it a named reference...?
2498 $$ = ValID::createGlobalName(*$1);
2499 delete $1;
2500 CHECK_FOR_ERROR
2501 };
2502
2503// ValueRef - A reference to a definition... either constant or symbolic
2504ValueRef : SymbolicValueRef | ConstValueRef;
2505
2506
2507// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2508// type immediately preceeds the value reference, and allows complex constant
2509// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2510ResolvedVal : Types ValueRef {
2511 if (!UpRefs.empty())
2512 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2513 $$ = getVal(*$1, $2);
2514 delete $1;
2515 CHECK_FOR_ERROR
2516 }
2517 ;
2518
Devang Patelbf507402008-02-20 22:40:23 +00002519ReturnedVal : ResolvedVal {
2520 $$ = new std::vector<Value *>();
2521 $$->push_back($1);
2522 CHECK_FOR_ERROR
2523 }
Devang Patel087fe2b2008-02-23 00:38:56 +00002524 | ReturnedVal ',' ResolvedVal {
Devang Patelbf507402008-02-20 22:40:23 +00002525 ($$=$1)->push_back($3);
2526 CHECK_FOR_ERROR
2527 };
2528
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529BasicBlockList : BasicBlockList BasicBlock {
2530 $$ = $1;
2531 CHECK_FOR_ERROR
2532 }
2533 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2534 $$ = $1;
2535 CHECK_FOR_ERROR
2536 };
2537
2538
2539// Basic blocks are terminated by branching instructions:
2540// br, br/cc, switch, ret
2541//
2542BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2543 setValueName($3, $2);
2544 CHECK_FOR_ERROR
2545 InsertValue($3);
2546 $1->getInstList().push_back($3);
2547 $$ = $1;
2548 CHECK_FOR_ERROR
2549 };
2550
2551InstructionList : InstructionList Inst {
2552 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2553 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2554 if (CI2->getParent() == 0)
2555 $1->getInstList().push_back(CI2);
2556 $1->getInstList().push_back($2);
2557 $$ = $1;
2558 CHECK_FOR_ERROR
2559 }
2560 | /* empty */ { // Empty space between instruction lists
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002561 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 CHECK_FOR_ERROR
2563 }
2564 | LABELSTR { // Labelled (named) basic block
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002565 $$ = defineBBVal(ValID::createLocalName(*$1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566 delete $1;
2567 CHECK_FOR_ERROR
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002568
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569 };
2570
Devang Patelbf507402008-02-20 22:40:23 +00002571BBTerminatorInst :
2572 RET ReturnedVal { // Return with a result...
Devang Patelda2c8d52008-02-26 22:17:48 +00002573 ValueList &VL = *$2;
Devang Patelb4851dc2008-02-26 23:19:08 +00002574 assert(!VL.empty() && "Invalid ret operands!");
Gabor Greif89f01162008-04-06 23:07:54 +00002575 $$ = ReturnInst::Create(&VL[0], VL.size());
Devang Patelbf507402008-02-20 22:40:23 +00002576 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577 CHECK_FOR_ERROR
2578 }
2579 | RET VOID { // Return with no result...
Gabor Greif89f01162008-04-06 23:07:54 +00002580 $$ = ReturnInst::Create();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002581 CHECK_FOR_ERROR
2582 }
2583 | BR LABEL ValueRef { // Unconditional Branch...
2584 BasicBlock* tmpBB = getBBVal($3);
2585 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002586 $$ = BranchInst::Create(tmpBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587 } // Conditional Branch...
2588 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2589 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2590 BasicBlock* tmpBBA = getBBVal($6);
2591 CHECK_FOR_ERROR
2592 BasicBlock* tmpBBB = getBBVal($9);
2593 CHECK_FOR_ERROR
2594 Value* tmpVal = getVal(Type::Int1Ty, $3);
2595 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002596 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002597 }
2598 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2599 Value* tmpVal = getVal($2, $3);
2600 CHECK_FOR_ERROR
2601 BasicBlock* tmpBB = getBBVal($6);
2602 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002603 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002604 $$ = S;
2605
2606 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2607 E = $8->end();
2608 for (; I != E; ++I) {
2609 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2610 S->addCase(CI, I->second);
2611 else
2612 GEN_ERROR("Switch case is constant, but not a simple integer");
2613 }
2614 delete $8;
2615 CHECK_FOR_ERROR
2616 }
2617 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2618 Value* tmpVal = getVal($2, $3);
2619 CHECK_FOR_ERROR
2620 BasicBlock* tmpBB = getBBVal($6);
2621 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002622 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623 $$ = S;
2624 CHECK_FOR_ERROR
2625 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002626 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002627 TO LABEL ValueRef UNWIND LABEL ValueRef {
2628
2629 // Handle the short syntax
2630 const PointerType *PFTy = 0;
2631 const FunctionType *Ty = 0;
2632 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2633 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2634 // Pull out the types of all of the arguments...
2635 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002636 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002637 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 const Type *Ty = I->Val->getType();
2639 if (Ty == Type::VoidTy)
2640 GEN_ERROR("Short call syntax cannot be used with varargs");
2641 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002642 }
Chris Lattner73de3c02008-04-23 05:37:08 +00002643
2644 if (!FunctionType::isValidReturnType(*$3))
2645 GEN_ERROR("Invalid result type for LLVM function");
2646
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002647 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00002648 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002649 }
2650
2651 delete $3;
2652
2653 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2654 CHECK_FOR_ERROR
2655 BasicBlock *Normal = getBBVal($11);
2656 CHECK_FOR_ERROR
2657 BasicBlock *Except = getBBVal($14);
2658 CHECK_FOR_ERROR
2659
Chris Lattner1c8733e2008-03-12 17:45:29 +00002660 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2661 if ($8 != ParamAttr::None)
2662 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002663
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 // Check the arguments
2665 ValueList Args;
2666 if ($6->empty()) { // Has no arguments?
2667 // Make sure no arguments is a good thing!
2668 if (Ty->getNumParams() != 0)
2669 GEN_ERROR("No arguments passed to a function that "
2670 "expects arguments");
2671 } else { // Has arguments?
2672 // Loop through FunctionType's arguments and ensure they are specified
2673 // correctly!
2674 FunctionType::param_iterator I = Ty->param_begin();
2675 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002676 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002677 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002679 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680 if (ArgI->Val->getType() != *I)
2681 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2682 (*I)->getDescription() + "'");
2683 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00002684 if (ArgI->Attrs != ParamAttr::None)
2685 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 }
2687
2688 if (Ty->isVarArg()) {
2689 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00002690 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002691 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00002692 if (ArgI->Attrs != ParamAttr::None)
2693 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Chris Lattner59363a32008-02-19 04:36:25 +00002694 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002695 } else if (I != E || ArgI != ArgE)
2696 GEN_ERROR("Invalid number of parameters detected");
2697 }
2698
Chris Lattner1c8733e2008-03-12 17:45:29 +00002699 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002700 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00002701 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002702
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 // Create the InvokeInst
Gabor Greif89f01162008-04-06 23:07:54 +00002704 InvokeInst *II = InvokeInst::Create(V, Normal, Except, Args.begin(),Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002705 II->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002706 II->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002707 $$ = II;
2708 delete $6;
2709 CHECK_FOR_ERROR
2710 }
2711 | UNWIND {
2712 $$ = new UnwindInst();
2713 CHECK_FOR_ERROR
2714 }
2715 | UNREACHABLE {
2716 $$ = new UnreachableInst();
2717 CHECK_FOR_ERROR
2718 };
2719
2720
2721
2722JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2723 $$ = $1;
2724 Constant *V = cast<Constant>(getExistingVal($2, $3));
2725 CHECK_FOR_ERROR
2726 if (V == 0)
2727 GEN_ERROR("May only switch on a constant pool value");
2728
2729 BasicBlock* tmpBB = getBBVal($6);
2730 CHECK_FOR_ERROR
2731 $$->push_back(std::make_pair(V, tmpBB));
2732 }
2733 | IntType ConstValueRef ',' LABEL ValueRef {
2734 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2735 Constant *V = cast<Constant>(getExistingVal($1, $2));
2736 CHECK_FOR_ERROR
2737
2738 if (V == 0)
2739 GEN_ERROR("May only switch on a constant pool value");
2740
2741 BasicBlock* tmpBB = getBBVal($5);
2742 CHECK_FOR_ERROR
2743 $$->push_back(std::make_pair(V, tmpBB));
2744 };
2745
2746Inst : OptLocalAssign InstVal {
2747 // Is this definition named?? if so, assign the name...
2748 setValueName($2, $1);
2749 CHECK_FOR_ERROR
2750 InsertValue($2);
2751 $$ = $2;
2752 CHECK_FOR_ERROR
2753 };
2754
2755
2756PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2757 if (!UpRefs.empty())
2758 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2759 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2760 Value* tmpVal = getVal(*$1, $3);
2761 CHECK_FOR_ERROR
2762 BasicBlock* tmpBB = getBBVal($5);
2763 CHECK_FOR_ERROR
2764 $$->push_back(std::make_pair(tmpVal, tmpBB));
2765 delete $1;
2766 }
2767 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2768 $$ = $1;
2769 Value* tmpVal = getVal($1->front().first->getType(), $4);
2770 CHECK_FOR_ERROR
2771 BasicBlock* tmpBB = getBBVal($6);
2772 CHECK_FOR_ERROR
2773 $1->push_back(std::make_pair(tmpVal, tmpBB));
2774 };
2775
2776
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002777ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2778 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779 if (!UpRefs.empty())
2780 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2781 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00002782 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002783 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002784 $$->push_back(E);
2785 delete $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002786 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002787 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002788 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2789 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002790 // Labels are only valid in ASMs
2791 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002792 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002793 $$->push_back(E);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002794 CHECK_FOR_ERROR
Dale Johannesencfb19e62007-11-05 21:20:28 +00002795 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002796 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2797 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 if (!UpRefs.empty())
2799 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2800 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002801 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 $$->push_back(E);
2803 delete $3;
2804 CHECK_FOR_ERROR
2805 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002806 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2807 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00002808 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002809 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
Dale Johannesencfb19e62007-11-05 21:20:28 +00002810 $$->push_back(E);
2811 CHECK_FOR_ERROR
2812 }
2813 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002814
2815IndexList // Used for gep instructions and constant expressions
2816 : /*empty*/ { $$ = new std::vector<Value*>(); }
2817 | IndexList ',' ResolvedVal {
2818 $$ = $1;
2819 $$->push_back($3);
2820 CHECK_FOR_ERROR
2821 }
2822 ;
2823
2824OptTailCall : TAIL CALL {
2825 $$ = true;
2826 CHECK_FOR_ERROR
2827 }
2828 | CALL {
2829 $$ = false;
2830 CHECK_FOR_ERROR
2831 };
2832
2833InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2834 if (!UpRefs.empty())
2835 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2836 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2837 !isa<VectorType>((*$2).get()))
2838 GEN_ERROR(
2839 "Arithmetic operator requires integer, FP, or packed operands");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 Value* val1 = getVal(*$2, $3);
2841 CHECK_FOR_ERROR
2842 Value* val2 = getVal(*$2, $5);
2843 CHECK_FOR_ERROR
2844 $$ = BinaryOperator::create($1, val1, val2);
2845 if ($$ == 0)
2846 GEN_ERROR("binary operator returned null");
2847 delete $2;
2848 }
2849 | LogicalOps Types ValueRef ',' ValueRef {
2850 if (!UpRefs.empty())
2851 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2852 if (!(*$2)->isInteger()) {
2853 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2854 !cast<VectorType>($2->get())->getElementType()->isInteger())
2855 GEN_ERROR("Logical operator requires integral operands");
2856 }
2857 Value* tmpVal1 = getVal(*$2, $3);
2858 CHECK_FOR_ERROR
2859 Value* tmpVal2 = getVal(*$2, $5);
2860 CHECK_FOR_ERROR
2861 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2862 if ($$ == 0)
2863 GEN_ERROR("binary operator returned null");
2864 delete $2;
2865 }
2866 | ICMP IPredicates Types ValueRef ',' ValueRef {
2867 if (!UpRefs.empty())
2868 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2869 if (isa<VectorType>((*$3).get()))
2870 GEN_ERROR("Vector types not supported by icmp instruction");
2871 Value* tmpVal1 = getVal(*$3, $4);
2872 CHECK_FOR_ERROR
2873 Value* tmpVal2 = getVal(*$3, $6);
2874 CHECK_FOR_ERROR
2875 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2876 if ($$ == 0)
2877 GEN_ERROR("icmp operator returned null");
2878 delete $3;
2879 }
2880 | FCMP FPredicates Types ValueRef ',' ValueRef {
2881 if (!UpRefs.empty())
2882 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2883 if (isa<VectorType>((*$3).get()))
2884 GEN_ERROR("Vector types not supported by fcmp instruction");
2885 Value* tmpVal1 = getVal(*$3, $4);
2886 CHECK_FOR_ERROR
2887 Value* tmpVal2 = getVal(*$3, $6);
2888 CHECK_FOR_ERROR
2889 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2890 if ($$ == 0)
2891 GEN_ERROR("fcmp operator returned null");
2892 delete $3;
2893 }
2894 | CastOps ResolvedVal TO Types {
2895 if (!UpRefs.empty())
2896 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2897 Value* Val = $2;
2898 const Type* DestTy = $4->get();
2899 if (!CastInst::castIsValid($1, Val, DestTy))
2900 GEN_ERROR("invalid cast opcode for cast from '" +
2901 Val->getType()->getDescription() + "' to '" +
2902 DestTy->getDescription() + "'");
2903 $$ = CastInst::create($1, Val, DestTy);
2904 delete $4;
2905 }
2906 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2907 if ($2->getType() != Type::Int1Ty)
2908 GEN_ERROR("select condition must be boolean");
2909 if ($4->getType() != $6->getType())
2910 GEN_ERROR("select value types should match");
Gabor Greif89f01162008-04-06 23:07:54 +00002911 $$ = SelectInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002912 CHECK_FOR_ERROR
2913 }
2914 | VAARG ResolvedVal ',' Types {
2915 if (!UpRefs.empty())
2916 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2917 $$ = new VAArgInst($2, *$4);
2918 delete $4;
2919 CHECK_FOR_ERROR
2920 }
2921 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2922 if (!ExtractElementInst::isValidOperands($2, $4))
2923 GEN_ERROR("Invalid extractelement operands");
2924 $$ = new ExtractElementInst($2, $4);
2925 CHECK_FOR_ERROR
2926 }
2927 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2928 if (!InsertElementInst::isValidOperands($2, $4, $6))
2929 GEN_ERROR("Invalid insertelement operands");
Gabor Greif89f01162008-04-06 23:07:54 +00002930 $$ = InsertElementInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931 CHECK_FOR_ERROR
2932 }
2933 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2934 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2935 GEN_ERROR("Invalid shufflevector operands");
2936 $$ = new ShuffleVectorInst($2, $4, $6);
2937 CHECK_FOR_ERROR
2938 }
2939 | PHI_TOK PHIList {
2940 const Type *Ty = $2->front().first->getType();
2941 if (!Ty->isFirstClassType())
2942 GEN_ERROR("PHI node operands must be of first class type");
Gabor Greif89f01162008-04-06 23:07:54 +00002943 $$ = PHINode::Create(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944 ((PHINode*)$$)->reserveOperandSpace($2->size());
2945 while ($2->begin() != $2->end()) {
2946 if ($2->front().first->getType() != Ty)
2947 GEN_ERROR("All elements of a PHI node must be of the same type");
2948 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2949 $2->pop_front();
2950 }
2951 delete $2; // Free the list...
2952 CHECK_FOR_ERROR
2953 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002954 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002955 OptFuncAttrs {
2956
2957 // Handle the short syntax
2958 const PointerType *PFTy = 0;
2959 const FunctionType *Ty = 0;
2960 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2961 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2962 // Pull out the types of all of the arguments...
2963 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002964 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002965 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 const Type *Ty = I->Val->getType();
2967 if (Ty == Type::VoidTy)
2968 GEN_ERROR("Short call syntax cannot be used with varargs");
2969 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002970 }
Chris Lattner73de3c02008-04-23 05:37:08 +00002971
2972 if (!FunctionType::isValidReturnType(*$3))
2973 GEN_ERROR("Invalid result type for LLVM function");
2974
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002975 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00002976 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977 }
2978
2979 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2980 CHECK_FOR_ERROR
2981
2982 // Check for call to invalid intrinsic to avoid crashing later.
2983 if (Function *theF = dyn_cast<Function>(V)) {
2984 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2985 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2986 !theF->getIntrinsicID(true))
2987 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2988 theF->getName() + "'");
2989 }
2990
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002991 // Set up the ParamAttrs for the function
Chris Lattner1c8733e2008-03-12 17:45:29 +00002992 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2993 if ($8 != ParamAttr::None)
2994 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 // Check the arguments
2996 ValueList Args;
2997 if ($6->empty()) { // Has no arguments?
2998 // Make sure no arguments is a good thing!
2999 if (Ty->getNumParams() != 0)
3000 GEN_ERROR("No arguments passed to a function that "
3001 "expects arguments");
3002 } else { // Has arguments?
3003 // Loop through FunctionType's arguments and ensure they are specified
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003004 // correctly. Also, gather any parameter attributes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005 FunctionType::param_iterator I = Ty->param_begin();
3006 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00003007 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003008 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003010 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011 if (ArgI->Val->getType() != *I)
3012 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3013 (*I)->getDescription() + "'");
3014 Args.push_back(ArgI->Val);
Chris Lattner1c8733e2008-03-12 17:45:29 +00003015 if (ArgI->Attrs != ParamAttr::None)
3016 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 }
3018 if (Ty->isVarArg()) {
3019 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00003020 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 Args.push_back(ArgI->Val); // push the remaining varargs
Chris Lattner1c8733e2008-03-12 17:45:29 +00003022 if (ArgI->Attrs != ParamAttr::None)
3023 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
Chris Lattner59363a32008-02-19 04:36:25 +00003024 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003025 } else if (I != E || ArgI != ArgE)
3026 GEN_ERROR("Invalid number of parameters detected");
3027 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003028
3029 // Finish off the ParamAttrs and check them
Chris Lattner1c8733e2008-03-12 17:45:29 +00003030 PAListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003031 if (!Attrs.empty())
Chris Lattner1c8733e2008-03-12 17:45:29 +00003032 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003033
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003034 // Create the call node
Gabor Greif89f01162008-04-06 23:07:54 +00003035 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036 CI->setTailCall($1);
3037 CI->setCallingConv($2);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003038 CI->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003039 $$ = CI;
3040 delete $6;
3041 delete $3;
3042 CHECK_FOR_ERROR
3043 }
3044 | MemoryInst {
3045 $$ = $1;
3046 CHECK_FOR_ERROR
3047 };
3048
3049OptVolatile : VOLATILE {
3050 $$ = true;
3051 CHECK_FOR_ERROR
3052 }
3053 | /* empty */ {
3054 $$ = false;
3055 CHECK_FOR_ERROR
3056 };
3057
3058
3059
3060MemoryInst : MALLOC Types OptCAlign {
3061 if (!UpRefs.empty())
3062 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3063 $$ = new MallocInst(*$2, 0, $3);
3064 delete $2;
3065 CHECK_FOR_ERROR
3066 }
3067 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3068 if (!UpRefs.empty())
3069 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3070 Value* tmpVal = getVal($4, $5);
3071 CHECK_FOR_ERROR
3072 $$ = new MallocInst(*$2, tmpVal, $6);
3073 delete $2;
3074 }
3075 | ALLOCA Types OptCAlign {
3076 if (!UpRefs.empty())
3077 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3078 $$ = new AllocaInst(*$2, 0, $3);
3079 delete $2;
3080 CHECK_FOR_ERROR
3081 }
3082 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3083 if (!UpRefs.empty())
3084 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3085 Value* tmpVal = getVal($4, $5);
3086 CHECK_FOR_ERROR
3087 $$ = new AllocaInst(*$2, tmpVal, $6);
3088 delete $2;
3089 }
3090 | FREE ResolvedVal {
3091 if (!isa<PointerType>($2->getType()))
3092 GEN_ERROR("Trying to free nonpointer type " +
3093 $2->getType()->getDescription() + "");
3094 $$ = new FreeInst($2);
3095 CHECK_FOR_ERROR
3096 }
3097
3098 | OptVolatile LOAD Types ValueRef OptCAlign {
3099 if (!UpRefs.empty())
3100 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3101 if (!isa<PointerType>($3->get()))
3102 GEN_ERROR("Can't load from nonpointer type: " +
3103 (*$3)->getDescription());
3104 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3105 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3106 (*$3)->getDescription());
3107 Value* tmpVal = getVal(*$3, $4);
3108 CHECK_FOR_ERROR
3109 $$ = new LoadInst(tmpVal, "", $1, $5);
3110 delete $3;
3111 }
3112 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3113 if (!UpRefs.empty())
3114 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3115 const PointerType *PT = dyn_cast<PointerType>($5->get());
3116 if (!PT)
3117 GEN_ERROR("Can't store to a nonpointer type: " +
3118 (*$5)->getDescription());
3119 const Type *ElTy = PT->getElementType();
3120 if (ElTy != $3->getType())
3121 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3122 "' into space of type '" + ElTy->getDescription() + "'");
3123
3124 Value* tmpVal = getVal(*$5, $6);
3125 CHECK_FOR_ERROR
3126 $$ = new StoreInst($3, tmpVal, $1, $7);
3127 delete $5;
3128 }
Dan Gohmandecb8c02008-04-23 20:11:27 +00003129| GETRESULT Types ValueRef ',' EUINT64VAL {
Devang Patelb52f9e72008-02-22 19:31:30 +00003130 Value *TmpVal = getVal($2->get(), $3);
Devang Patel3b8849c2008-02-19 22:27:01 +00003131 if (!GetResultInst::isValidOperands(TmpVal, $5))
3132 GEN_ERROR("Invalid getresult operands");
3133 $$ = new GetResultInst(TmpVal, $5);
Devang Patel087fe2b2008-02-23 00:38:56 +00003134 delete $2;
Devang Patel3b8849c2008-02-19 22:27:01 +00003135 CHECK_FOR_ERROR
3136 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137 | GETELEMENTPTR Types ValueRef IndexList {
3138 if (!UpRefs.empty())
3139 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3140 if (!isa<PointerType>($2->get()))
3141 GEN_ERROR("getelementptr insn requires pointer operand");
3142
David Greene48556392007-09-04 18:46:50 +00003143 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003144 GEN_ERROR("Invalid getelementptr indices for type '" +
3145 (*$2)->getDescription()+ "'");
3146 Value* tmpVal = getVal(*$2, $3);
3147 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00003148 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149 delete $2;
3150 delete $4;
3151 };
3152
3153
3154%%
3155
3156// common code from the two 'RunVMAsmParser' functions
3157static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159 // Check to make sure the parser succeeded
3160 if (yyparse()) {
3161 if (ParserResult)
3162 delete ParserResult;
3163 return 0;
3164 }
3165
3166 // Emit an error if there are any unresolved types left.
3167 if (!CurModule.LateResolveTypes.empty()) {
3168 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3169 if (DID.Type == ValID::LocalName) {
3170 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3171 } else {
3172 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3173 }
3174 if (ParserResult)
3175 delete ParserResult;
3176 return 0;
3177 }
3178
3179 // Emit an error if there are any unresolved values left.
3180 if (!CurModule.LateResolveValues.empty()) {
3181 Value *V = CurModule.LateResolveValues.back();
3182 std::map<Value*, std::pair<ValID, int> >::iterator I =
3183 CurModule.PlaceHolderInfo.find(V);
3184
3185 if (I != CurModule.PlaceHolderInfo.end()) {
3186 ValID &DID = I->second.first;
3187 if (DID.Type == ValID::LocalName) {
3188 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3189 } else {
3190 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3191 }
3192 if (ParserResult)
3193 delete ParserResult;
3194 return 0;
3195 }
3196 }
3197
3198 // Check to make sure that parsing produced a result
3199 if (!ParserResult)
3200 return 0;
3201
3202 // Reset ParserResult variable while saving its value for the result.
3203 Module *Result = ParserResult;
3204 ParserResult = 0;
3205
3206 return Result;
3207}
3208
3209void llvm::GenerateError(const std::string &message, int LineNo) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003210 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211 // TODO: column number in exception
3212 if (TheParseError)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003213 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 TriggerError = 1;
3215}
3216
3217int yyerror(const char *ErrorMsg) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003218 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003220 if (yychar != YYEMPTY && yychar != 0) {
3221 errMsg += " while reading token: '";
3222 errMsg += std::string(LLLgetTokenStart(),
3223 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3224 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003225 GenerateError(errMsg);
3226 return 0;
3227}