blob: fa86c1887e961a273557c74e6520dbfefe5da7dc [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
Eric Christopher329d2672008-09-24 04:55:49 +000036// 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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039// 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
Eric Christopher329d2672008-09-24 04:55:49 +000042// immediately invokes YYERROR. This would be so much cleaner if it was a
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043// 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
Eric Christopher329d2672008-09-24 04:55:49 +000075static void
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076ResolveDefinitions(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
Eric Christopher329d2672008-09-24 04:55:49 +0000154 // we don't need to traverse that leg of the type.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 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) {
Eric Christopher329d2672008-09-24 04:55:49 +0000172 std::vector<const Type*>::iterator I = SeenList.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 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) {
Eric Christopher329d2672008-09-24 04:55:49 +0000184 std::vector<const Type*>::iterator I = SeenList.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 E = SeenList.end();
186 for ( ; I != E; ++I)
187 if (*I == TheTy)
188 break;
189 if (I == E)
190 WorkList.push_back(TheTy);
191 }
192 }
193 }
194 }
195 return false;
196 }
197} CurModule;
198
199static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
201
202 ValueList Values; // Keep track of #'d definitions
203 unsigned NextValNum;
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
208
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
212
213 inline PerFunctionInfo() {
214 CurrentFunction = 0;
215 isDeclare = false;
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
218 }
219
220 inline void FunctionStart(Function *M) {
221 CurrentFunction = M;
222 NextValNum = 0;
223 }
224
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
230 return;
231 }
232
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
235
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
238 CurrentFunction = 0;
239 isDeclare = false;
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
242 }
243} CurFun; // Info for the current function...
244
245static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
246
247
248//===----------------------------------------------------------------------===//
249// Code to handle definitions of all the types
250//===----------------------------------------------------------------------===//
251
Chris Lattner906773a2008-08-29 17:20:18 +0000252/// InsertValue - Insert a value into the value table. If it is named, this
253/// returns -1, otherwise it returns the slot number for the value.
254static int InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 // Things that have names or are void typed don't get slot numbers
256 if (V->hasName() || (V->getType() == Type::VoidTy))
Chris Lattner906773a2008-08-29 17:20:18 +0000257 return -1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258
259 // In the case of function values, we have to allow for the forward reference
260 // of basic blocks, which are included in the numbering. Consequently, we keep
Eric Christopher329d2672008-09-24 04:55:49 +0000261 // track of the next insertion location with NextValNum. When a BB gets
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 // inserted, it could change the size of the CurFun.Values vector.
263 if (&ValueTab == &CurFun.Values) {
264 if (ValueTab.size() <= CurFun.NextValNum)
265 ValueTab.resize(CurFun.NextValNum+1);
266 ValueTab[CurFun.NextValNum++] = V;
Chris Lattner906773a2008-08-29 17:20:18 +0000267 return CurFun.NextValNum-1;
Eric Christopher329d2672008-09-24 04:55:49 +0000268 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 // For all other lists, its okay to just tack it on the back of the vector.
270 ValueTab.push_back(V);
Chris Lattner906773a2008-08-29 17:20:18 +0000271 return ValueTab.size()-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272}
273
274static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
275 switch (D.Type) {
276 case ValID::LocalID: // Is it a numbered definition?
277 // Module constants occupy the lowest numbered slots...
278 if (D.Num < CurModule.Types.size())
279 return CurModule.Types[D.Num];
280 break;
281 case ValID::LocalName: // Is it a named definition?
282 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
283 D.destroy(); // Free old strdup'd memory...
284 return N;
285 }
286 break;
287 default:
288 GenerateError("Internal parser error: Invalid symbol type reference");
289 return 0;
290 }
291
292 // If we reached here, we referenced either a symbol that we don't know about
293 // or an id number that hasn't been read yet. We may be referencing something
294 // forward, so just create an entry to be resolved later and get to it...
295 //
296 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
297
298
299 if (inFunctionScope()) {
300 if (D.Type == ValID::LocalName) {
301 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
302 return 0;
303 } else {
304 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
305 return 0;
306 }
307 }
308
309 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
310 if (I != CurModule.LateResolveTypes.end())
311 return I->second;
312
313 Type *Typ = OpaqueType::get();
314 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
315 return Typ;
316 }
317
318// getExistingVal - Look up the value specified by the provided type and
319// the provided ValID. If the value exists and has already been defined, return
320// it. Otherwise return null.
321//
322static Value *getExistingVal(const Type *Ty, const ValID &D) {
323 if (isa<FunctionType>(Ty)) {
324 GenerateError("Functions are not values and "
325 "must be referenced as pointers");
326 return 0;
327 }
328
329 switch (D.Type) {
330 case ValID::LocalID: { // Is it a numbered definition?
331 // Check that the number is within bounds.
Eric Christopher329d2672008-09-24 04:55:49 +0000332 if (D.Num >= CurFun.Values.size())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 return 0;
334 Value *Result = CurFun.Values[D.Num];
335 if (Ty != Result->getType()) {
336 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
Eric Christopher329d2672008-09-24 04:55:49 +0000337 Result->getType()->getDescription() + "' does not match "
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 "expected type, '" + Ty->getDescription() + "'");
339 return 0;
340 }
341 return Result;
342 }
343 case ValID::GlobalID: { // Is it a numbered definition?
Eric Christopher329d2672008-09-24 04:55:49 +0000344 if (D.Num >= CurModule.Values.size())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 return 0;
346 Value *Result = CurModule.Values[D.Num];
347 if (Ty != Result->getType()) {
348 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
Eric Christopher329d2672008-09-24 04:55:49 +0000349 Result->getType()->getDescription() + "' does not match "
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 "expected type, '" + Ty->getDescription() + "'");
351 return 0;
352 }
353 return Result;
354 }
Eric Christopher329d2672008-09-24 04:55:49 +0000355
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 case ValID::LocalName: { // Is it a named definition?
Eric Christopher329d2672008-09-24 04:55:49 +0000357 if (!inFunctionScope())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 return 0;
359 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
360 Value *N = SymTab.lookup(D.getName());
Eric Christopher329d2672008-09-24 04:55:49 +0000361 if (N == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362 return 0;
363 if (N->getType() != Ty)
364 return 0;
Eric Christopher329d2672008-09-24 04:55:49 +0000365
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 D.destroy(); // Free old strdup'd memory...
367 return N;
368 }
369 case ValID::GlobalName: { // Is it a named definition?
370 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
371 Value *N = SymTab.lookup(D.getName());
Eric Christopher329d2672008-09-24 04:55:49 +0000372 if (N == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373 return 0;
374 if (N->getType() != Ty)
375 return 0;
376
377 D.destroy(); // Free old strdup'd memory...
378 return N;
379 }
380
381 // Check to make sure that "Ty" is an integral type, and that our
382 // value will fit into the specified type...
383 case ValID::ConstSIntVal: // Is it a constant pool reference??
Chris Lattner59363a32008-02-19 04:36:25 +0000384 if (!isa<IntegerType>(Ty) ||
385 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 GenerateError("Signed integral constant '" +
387 itostr(D.ConstPool64) + "' is invalid for type '" +
388 Ty->getDescription() + "'");
389 return 0;
390 }
391 return ConstantInt::get(Ty, D.ConstPool64, true);
392
393 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000394 if (isa<IntegerType>(Ty) &&
395 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 return ConstantInt::get(Ty, D.UConstPool64);
Chris Lattner59363a32008-02-19 04:36:25 +0000397
398 if (!isa<IntegerType>(Ty) ||
399 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
400 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
401 "' is invalid or out of range for type '" +
402 Ty->getDescription() + "'");
403 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 }
Chris Lattner59363a32008-02-19 04:36:25 +0000405 // This is really a signed reference. Transmogrify.
406 return ConstantInt::get(Ty, D.ConstPool64, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407
Chris Lattnerf3d40022008-07-11 00:30:39 +0000408 case ValID::ConstAPInt: // Is it an unsigned const pool reference?
409 if (!isa<IntegerType>(Ty)) {
410 GenerateError("Integral constant '" + D.getName() +
411 "' is invalid or out of range for type '" +
412 Ty->getDescription() + "'");
413 return 0;
414 }
Eric Christopher329d2672008-09-24 04:55:49 +0000415
Chris Lattnerf3d40022008-07-11 00:30:39 +0000416 {
417 APSInt Tmp = *D.ConstPoolInt;
418 Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
419 return ConstantInt::get(Tmp);
420 }
Eric Christopher329d2672008-09-24 04:55:49 +0000421
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Chris Lattner59363a32008-02-19 04:36:25 +0000423 if (!Ty->isFloatingPoint() ||
424 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 GenerateError("FP constant invalid for type");
426 return 0;
427 }
Eric Christopher329d2672008-09-24 04:55:49 +0000428 // Lexer has no type info, so builds all float and double FP constants
Dale Johannesen255b8fe2007-09-11 18:33:39 +0000429 // as double. Fix this here. Long double does not need this.
430 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
431 Ty==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000432 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner05ba86e2008-04-20 00:41:19 +0000433 return ConstantFP::get(*D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434
435 case ValID::ConstNullVal: // Is it a null value?
436 if (!isa<PointerType>(Ty)) {
437 GenerateError("Cannot create a a non pointer null");
438 return 0;
439 }
440 return ConstantPointerNull::get(cast<PointerType>(Ty));
441
442 case ValID::ConstUndefVal: // Is it an undef value?
443 return UndefValue::get(Ty);
444
445 case ValID::ConstZeroVal: // Is it a zero value?
446 return Constant::getNullValue(Ty);
Eric Christopher329d2672008-09-24 04:55:49 +0000447
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 case ValID::ConstantVal: // Fully resolved constant?
449 if (D.ConstantValue->getType() != Ty) {
450 GenerateError("Constant expression type different from required type");
451 return 0;
452 }
453 return D.ConstantValue;
454
455 case ValID::InlineAsmVal: { // Inline asm expression
456 const PointerType *PTy = dyn_cast<PointerType>(Ty);
457 const FunctionType *FTy =
458 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
459 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
460 GenerateError("Invalid type for asm constraint string");
461 return 0;
462 }
463 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
464 D.IAD->HasSideEffects);
465 D.destroy(); // Free InlineAsmDescriptor.
466 return IA;
467 }
468 default:
469 assert(0 && "Unhandled case!");
470 return 0;
471 } // End of switch
472
473 assert(0 && "Unhandled case!");
474 return 0;
475}
476
477// getVal - This function is identical to getExistingVal, except that if a
478// value is not already defined, it "improvises" by creating a placeholder var
479// that looks and acts just like the requested variable. When the value is
480// defined later, all uses of the placeholder variable are replaced with the
481// real thing.
482//
483static Value *getVal(const Type *Ty, const ValID &ID) {
484 if (Ty == Type::LabelTy) {
485 GenerateError("Cannot use a basic block here");
486 return 0;
487 }
488
489 // See if the value has already been defined.
490 Value *V = getExistingVal(Ty, ID);
491 if (V) return V;
492 if (TriggerError) return 0;
493
494 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
Dan Gohmane6b1ee62008-05-23 01:55:30 +0000495 GenerateError("Invalid use of a non-first-class type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 return 0;
497 }
498
499 // If we reached here, we referenced either a symbol that we don't know about
500 // or an id number that hasn't been read yet. We may be referencing something
501 // forward, so just create an entry to be resolved later and get to it...
502 //
503 switch (ID.Type) {
504 case ValID::GlobalName:
505 case ValID::GlobalID: {
506 const PointerType *PTy = dyn_cast<PointerType>(Ty);
507 if (!PTy) {
508 GenerateError("Invalid type for reference to global" );
509 return 0;
510 }
511 const Type* ElTy = PTy->getElementType();
512 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
Gabor Greif89f01162008-04-06 23:07:54 +0000513 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 else
Christopher Lamb0a243582007-12-11 09:02:08 +0000515 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
516 (Module*)0, false, PTy->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 break;
518 }
519 default:
520 V = new Argument(Ty);
521 }
Eric Christopher329d2672008-09-24 04:55:49 +0000522
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 // Remember where this forward reference came from. FIXME, shouldn't we try
524 // to recycle these things??
525 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000526 LLLgetLineNo())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527
528 if (inFunctionScope())
529 InsertValue(V, CurFun.LateResolveValues);
530 else
531 InsertValue(V, CurModule.LateResolveValues);
532 return V;
533}
534
535/// defineBBVal - This is a definition of a new basic block with the specified
536/// identifier which must be the same as CurFun.NextValNum, if its numeric.
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000537static BasicBlock *defineBBVal(const ValID &ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 assert(inFunctionScope() && "Can't get basic block at global scope!");
539
540 BasicBlock *BB = 0;
541
542 // First, see if this was forward referenced
543
544 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
545 if (BBI != CurFun.BBForwardRefs.end()) {
546 BB = BBI->second;
547 // The forward declaration could have been inserted anywhere in the
548 // function: insert it into the correct place now.
549 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
550 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
551
552 // We're about to erase the entry, save the key so we can clean it up.
553 ValID Tmp = BBI->first;
554
555 // Erase the forward ref from the map as its no longer "forward"
556 CurFun.BBForwardRefs.erase(ID);
557
Eric Christopher329d2672008-09-24 04:55:49 +0000558 // The key has been removed from the map but so we don't want to leave
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 // strdup'd memory around so destroy it too.
560 Tmp.destroy();
561
562 // If its a numbered definition, bump the number and set the BB value.
563 if (ID.Type == ValID::LocalID) {
564 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
565 InsertValue(BB);
566 }
Eric Christopher329d2672008-09-24 04:55:49 +0000567 } else {
568 // We haven't seen this BB before and its first mention is a definition.
Devang Patel890cc572008-03-03 18:58:47 +0000569 // Just create it and return it.
570 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
Gabor Greif89f01162008-04-06 23:07:54 +0000571 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Devang Patel890cc572008-03-03 18:58:47 +0000572 if (ID.Type == ValID::LocalID) {
573 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
574 InsertValue(BB);
575 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576 }
577
Devang Patel890cc572008-03-03 18:58:47 +0000578 ID.destroy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 return BB;
580}
581
582/// getBBVal - get an existing BB value or create a forward reference for it.
Eric Christopher329d2672008-09-24 04:55:49 +0000583///
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584static BasicBlock *getBBVal(const ValID &ID) {
585 assert(inFunctionScope() && "Can't get basic block at global scope!");
586
587 BasicBlock *BB = 0;
588
589 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
590 if (BBI != CurFun.BBForwardRefs.end()) {
591 BB = BBI->second;
592 } if (ID.Type == ValID::LocalName) {
593 std::string Name = ID.getName();
594 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000595 if (N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 if (N->getType()->getTypeID() == Type::LabelTyID)
597 BB = cast<BasicBlock>(N);
598 else
599 GenerateError("Reference to label '" + Name + "' is actually of type '"+
600 N->getType()->getDescription() + "'");
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +0000601 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 } else if (ID.Type == ValID::LocalID) {
603 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
604 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
605 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
606 else
Eric Christopher329d2672008-09-24 04:55:49 +0000607 GenerateError("Reference to label '%" + utostr(ID.Num) +
608 "' is actually of type '"+
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
610 }
611 } else {
612 GenerateError("Illegal label reference " + ID.getName());
613 return 0;
614 }
615
616 // If its already been defined, return it now.
617 if (BB) {
618 ID.destroy(); // Free strdup'd memory.
619 return BB;
620 }
621
622 // Otherwise, this block has not been seen before, create it.
623 std::string Name;
624 if (ID.Type == ValID::LocalName)
625 Name = ID.getName();
Gabor Greif89f01162008-04-06 23:07:54 +0000626 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627
628 // Insert it in the forward refs map.
629 CurFun.BBForwardRefs[ID] = BB;
630
631 return BB;
632}
633
634
635//===----------------------------------------------------------------------===//
636// Code to handle forward references in instructions
637//===----------------------------------------------------------------------===//
638//
639// This code handles the late binding needed with statements that reference
640// values not defined yet... for example, a forward branch, or the PHI node for
641// a loop body.
642//
643// This keeps a table (CurFun.LateResolveValues) of all such forward references
644// and back patchs after we are done.
645//
646
647// ResolveDefinitions - If we could not resolve some defs at parsing
648// time (forward branches, phi functions for loops, etc...) resolve the
649// defs now...
650//
Eric Christopher329d2672008-09-24 04:55:49 +0000651static void
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
653 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
654 while (!LateResolvers.empty()) {
655 Value *V = LateResolvers.back();
656 LateResolvers.pop_back();
657
658 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
659 CurModule.PlaceHolderInfo.find(V);
660 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
661
662 ValID &DID = PHI->second.first;
663
664 Value *TheRealValue = getExistingVal(V->getType(), DID);
665 if (TriggerError)
666 return;
667 if (TheRealValue) {
668 V->replaceAllUsesWith(TheRealValue);
669 delete V;
670 CurModule.PlaceHolderInfo.erase(PHI);
671 } else if (FutureLateResolvers) {
672 // Functions have their unresolved items forwarded to the module late
673 // resolver table
674 InsertValue(V, *FutureLateResolvers);
675 } else {
676 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
677 GenerateError("Reference to an invalid definition: '" +DID.getName()+
678 "' of type '" + V->getType()->getDescription() + "'",
679 PHI->second.second);
680 return;
681 } else {
682 GenerateError("Reference to an invalid definition: #" +
683 itostr(DID.Num) + " of type '" +
684 V->getType()->getDescription() + "'",
685 PHI->second.second);
686 return;
687 }
688 }
689 }
690 LateResolvers.clear();
691}
692
693// ResolveTypeTo - A brand new type was just declared. This means that (if
694// name is not null) things referencing Name can be resolved. Otherwise, things
695// refering to the number can be resolved. Do this now.
696//
697static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
698 ValID D;
699 if (Name)
700 D = ValID::createLocalName(*Name);
Eric Christopher329d2672008-09-24 04:55:49 +0000701 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 D = ValID::createLocalID(CurModule.Types.size());
703
704 std::map<ValID, PATypeHolder>::iterator I =
705 CurModule.LateResolveTypes.find(D);
706 if (I != CurModule.LateResolveTypes.end()) {
707 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
708 CurModule.LateResolveTypes.erase(I);
709 }
710}
711
712// setValueName - Set the specified value to the name given. The name may be
713// null potentially, in which case this is a noop. The string passed in is
714// assumed to be a malloc'd string buffer, and is free'd by this function.
715//
716static void setValueName(Value *V, std::string *NameStr) {
717 if (!NameStr) return;
718 std::string Name(*NameStr); // Copy string
719 delete NameStr; // Free old string
720
721 if (V->getType() == Type::VoidTy) {
722 GenerateError("Can't assign name '" + Name+"' to value with void type");
723 return;
724 }
725
726 assert(inFunctionScope() && "Must be in function scope!");
727 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
728 if (ST.lookup(Name)) {
729 GenerateError("Redefinition of value '" + Name + "' of type '" +
730 V->getType()->getDescription() + "'");
731 return;
732 }
733
734 // Set the name.
735 V->setName(Name);
736}
737
738/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
739/// this is a declaration, otherwise it is a definition.
740static GlobalVariable *
741ParseGlobalVariable(std::string *NameStr,
742 GlobalValue::LinkageTypes Linkage,
743 GlobalValue::VisibilityTypes Visibility,
744 bool isConstantGlobal, const Type *Ty,
Christopher Lamb0a243582007-12-11 09:02:08 +0000745 Constant *Initializer, bool IsThreadLocal,
746 unsigned AddressSpace = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 if (isa<FunctionType>(Ty)) {
748 GenerateError("Cannot declare global vars of function type");
749 return 0;
750 }
Dan Gohmane5febe42008-05-31 00:58:22 +0000751 if (Ty == Type::LabelTy) {
752 GenerateError("Cannot declare global vars of label type");
753 return 0;
754 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755
Christopher Lamb0a243582007-12-11 09:02:08 +0000756 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757
758 std::string Name;
759 if (NameStr) {
760 Name = *NameStr; // Copy string
761 delete NameStr; // Free old string
762 }
763
764 // See if this global value was forward referenced. If so, recycle the
765 // object.
766 ValID ID;
767 if (!Name.empty()) {
768 ID = ValID::createGlobalName(Name);
769 } else {
770 ID = ValID::createGlobalID(CurModule.Values.size());
771 }
772
773 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
774 // Move the global to the end of the list, from whereever it was
775 // previously inserted.
776 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
777 CurModule.CurrentModule->getGlobalList().remove(GV);
778 CurModule.CurrentModule->getGlobalList().push_back(GV);
779 GV->setInitializer(Initializer);
780 GV->setLinkage(Linkage);
781 GV->setVisibility(Visibility);
782 GV->setConstant(isConstantGlobal);
783 GV->setThreadLocal(IsThreadLocal);
784 InsertValue(GV, CurModule.Values);
785 return GV;
786 }
787
788 // If this global has a name
789 if (!Name.empty()) {
790 // if the global we're parsing has an initializer (is a definition) and
791 // has external linkage.
792 if (Initializer && Linkage != GlobalValue::InternalLinkage)
793 // If there is already a global with external linkage with this name
794 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
795 // If we allow this GVar to get created, it will be renamed in the
796 // symbol table because it conflicts with an existing GVar. We can't
797 // allow redefinition of GVars whose linking indicates that their name
798 // must stay the same. Issue the error.
799 GenerateError("Redefinition of global variable named '" + Name +
800 "' of type '" + Ty->getDescription() + "'");
801 return 0;
802 }
803 }
804
805 // Otherwise there is no existing GV to use, create one now.
806 GlobalVariable *GV =
807 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
Christopher Lamb0a243582007-12-11 09:02:08 +0000808 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 GV->setVisibility(Visibility);
810 InsertValue(GV, CurModule.Values);
811 return GV;
812}
813
814// setTypeName - Set the specified type to the name given. The name may be
815// null potentially, in which case this is a noop. The string passed in is
816// assumed to be a malloc'd string buffer, and is freed by this function.
817//
818// This function returns true if the type has already been defined, but is
819// allowed to be redefined in the specified context. If the name is a new name
820// for the type plane, it is inserted and false is returned.
821static bool setTypeName(const Type *T, std::string *NameStr) {
822 assert(!inFunctionScope() && "Can't give types function-local names!");
823 if (NameStr == 0) return false;
Eric Christopher329d2672008-09-24 04:55:49 +0000824
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 std::string Name(*NameStr); // Copy string
826 delete NameStr; // Free old string
827
828 // We don't allow assigning names to void type
829 if (T == Type::VoidTy) {
830 GenerateError("Can't assign name '" + Name + "' to the void type");
831 return false;
832 }
833
834 // Set the type name, checking for conflicts as we do so.
835 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
836
837 if (AlreadyExists) { // Inserting a name that is already defined???
838 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
839 assert(Existing && "Conflict but no matching type?!");
840
841 // There is only one case where this is allowed: when we are refining an
842 // opaque type. In this case, Existing will be an opaque type.
843 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
844 // We ARE replacing an opaque type!
845 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
846 return true;
847 }
848
849 // Otherwise, this is an attempt to redefine a type. That's okay if
850 // the redefinition is identical to the original. This will be so if
851 // Existing and T point to the same Type object. In this one case we
852 // allow the equivalent redefinition.
853 if (Existing == T) return true; // Yes, it's equal.
854
855 // Any other kind of (non-equivalent) redefinition is an error.
856 GenerateError("Redefinition of type named '" + Name + "' of type '" +
857 T->getDescription() + "'");
858 }
859
860 return false;
861}
862
863//===----------------------------------------------------------------------===//
864// Code for handling upreferences in type names...
865//
866
867// TypeContains - Returns true if Ty directly contains E in it.
868//
869static bool TypeContains(const Type *Ty, const Type *E) {
870 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
871 E) != Ty->subtype_end();
872}
873
874namespace {
875 struct UpRefRecord {
876 // NestingLevel - The number of nesting levels that need to be popped before
877 // this type is resolved.
878 unsigned NestingLevel;
879
880 // LastContainedTy - This is the type at the current binding level for the
881 // type. Every time we reduce the nesting level, this gets updated.
882 const Type *LastContainedTy;
883
884 // UpRefTy - This is the actual opaque type that the upreference is
885 // represented with.
886 OpaqueType *UpRefTy;
887
888 UpRefRecord(unsigned NL, OpaqueType *URTy)
889 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
890 };
891}
892
893// UpRefs - A list of the outstanding upreferences that need to be resolved.
894static std::vector<UpRefRecord> UpRefs;
895
896/// HandleUpRefs - Every time we finish a new layer of types, this function is
897/// called. It loops through the UpRefs vector, which is a list of the
898/// currently active types. For each type, if the up reference is contained in
899/// the newly completed type, we decrement the level count. When the level
900/// count reaches zero, the upreferenced type is the type that is passed in:
901/// thus we can complete the cycle.
902///
903static PATypeHolder HandleUpRefs(const Type *ty) {
904 // If Ty isn't abstract, or if there are no up-references in it, then there is
905 // nothing to resolve here.
906 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Eric Christopher329d2672008-09-24 04:55:49 +0000907
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 PATypeHolder Ty(ty);
909 UR_OUT("Type '" << Ty->getDescription() <<
910 "' newly formed. Resolving upreferences.\n" <<
911 UpRefs.size() << " upreferences active!\n");
912
913 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
914 // to zero), we resolve them all together before we resolve them to Ty. At
915 // the end of the loop, if there is anything to resolve to Ty, it will be in
916 // this variable.
917 OpaqueType *TypeToResolve = 0;
918
919 for (unsigned i = 0; i != UpRefs.size(); ++i) {
920 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
921 << UpRefs[i].second->getDescription() << ") = "
922 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
923 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
924 // Decrement level of upreference
925 unsigned Level = --UpRefs[i].NestingLevel;
926 UpRefs[i].LastContainedTy = Ty;
927 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
928 if (Level == 0) { // Upreference should be resolved!
929 if (!TypeToResolve) {
930 TypeToResolve = UpRefs[i].UpRefTy;
931 } else {
932 UR_OUT(" * Resolving upreference for "
933 << UpRefs[i].second->getDescription() << "\n";
934 std::string OldName = UpRefs[i].UpRefTy->getDescription());
935 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
936 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
937 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
938 }
939 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
940 --i; // Do not skip the next element...
941 }
942 }
943 }
944
945 if (TypeToResolve) {
946 UR_OUT(" * Resolving upreference for "
947 << UpRefs[i].second->getDescription() << "\n";
948 std::string OldName = TypeToResolve->getDescription());
949 TypeToResolve->refineAbstractTypeTo(Ty);
950 }
951
952 return Ty;
953}
954
955//===----------------------------------------------------------------------===//
956// RunVMAsmParser - Define an interface to this parser
957//===----------------------------------------------------------------------===//
958//
959static Module* RunParser(Module * M);
960
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000961Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
962 InitLLLexer(MB);
963 Module *M = RunParser(new Module(LLLgetFilename()));
964 FreeLexer();
965 return M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966}
967
968%}
969
970%union {
971 llvm::Module *ModuleVal;
972 llvm::Function *FunctionVal;
973 llvm::BasicBlock *BasicBlockVal;
974 llvm::TerminatorInst *TermInstVal;
975 llvm::Instruction *InstVal;
976 llvm::Constant *ConstVal;
977
978 const llvm::Type *PrimType;
979 std::list<llvm::PATypeHolder> *TypeList;
980 llvm::PATypeHolder *TypeVal;
981 llvm::Value *ValueVal;
982 std::vector<llvm::Value*> *ValueList;
Dan Gohmane5febe42008-05-31 00:58:22 +0000983 std::vector<unsigned> *ConstantList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 llvm::ArgListType *ArgList;
985 llvm::TypeWithAttrs TypeWithAttrs;
986 llvm::TypeWithAttrsList *TypeWithAttrsList;
Dale Johannesencfb19e62007-11-05 21:20:28 +0000987 llvm::ParamList *ParamList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988
989 // Represent the RHS of PHI node
990 std::list<std::pair<llvm::Value*,
991 llvm::BasicBlock*> > *PHIList;
992 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
993 std::vector<llvm::Constant*> *ConstVector;
994
995 llvm::GlobalValue::LinkageTypes Linkage;
996 llvm::GlobalValue::VisibilityTypes Visibility;
Devang Pateld222f862008-09-25 21:00:45 +0000997 llvm::Attributes Attributes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 llvm::APInt *APIntVal;
999 int64_t SInt64Val;
1000 uint64_t UInt64Val;
1001 int SIntVal;
1002 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001003 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004 bool BoolVal;
1005
1006 std::string *StrVal; // This memory must be deleted
1007 llvm::ValID ValIDVal;
1008
1009 llvm::Instruction::BinaryOps BinaryOpVal;
1010 llvm::Instruction::TermOps TermOpVal;
1011 llvm::Instruction::MemoryOps MemOpVal;
1012 llvm::Instruction::CastOps CastOpVal;
1013 llvm::Instruction::OtherOps OtherOpVal;
1014 llvm::ICmpInst::Predicate IPredicate;
1015 llvm::FCmpInst::Predicate FPredicate;
1016}
1017
Eric Christopher329d2672008-09-24 04:55:49 +00001018%type <ModuleVal> Module
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1020%type <BasicBlockVal> BasicBlock InstructionList
1021%type <TermInstVal> BBTerminatorInst
1022%type <InstVal> Inst InstVal MemoryInst
1023%type <ConstVal> ConstVal ConstExpr AliaseeRef
1024%type <ConstVector> ConstVector
1025%type <ArgList> ArgList ArgListH
1026%type <PHIList> PHIList
Dale Johannesencfb19e62007-11-05 21:20:28 +00001027%type <ParamList> ParamList // For call param lists & GEP indices
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028%type <ValueList> IndexList // For GEP indices
Dan Gohmane5febe42008-05-31 00:58:22 +00001029%type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
Eric Christopher329d2672008-09-24 04:55:49 +00001030%type <TypeList> TypeListI
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031%type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1032%type <TypeWithAttrs> ArgType
1033%type <JumpTable> JumpTable
1034%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1035%type <BoolVal> ThreadLocal // 'thread_local' or not
1036%type <BoolVal> OptVolatile // 'volatile' or not
1037%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1038%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1039%type <Linkage> GVInternalLinkage GVExternalLinkage
1040%type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1041%type <Linkage> AliasLinkage
1042%type <Visibility> GVVisibilityStyle
1043
1044// ValueRef - Unresolved reference to a definition or BB
1045%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1046%type <ValueVal> ResolvedVal // <type> <valref> pair
Devang Patelbf507402008-02-20 22:40:23 +00001047%type <ValueList> ReturnedVal
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048// Tokens and types for handling constant integer values
1049//
1050// ESINT64VAL - A negative number within long long range
1051%token <SInt64Val> ESINT64VAL
1052
1053// EUINT64VAL - A positive number within uns. long long range
1054%token <UInt64Val> EUINT64VAL
1055
Eric Christopher329d2672008-09-24 04:55:49 +00001056// ESAPINTVAL - A negative number with arbitrary precision
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057%token <APIntVal> ESAPINTVAL
1058
Eric Christopher329d2672008-09-24 04:55:49 +00001059// EUAPINTVAL - A positive number with arbitrary precision
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060%token <APIntVal> EUAPINTVAL
1061
1062%token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1063%token <FPVal> FPVAL // Float or Double constant
1064
1065// Built in types...
1066%type <TypeVal> Types ResultTypes
1067%type <PrimType> IntType FPType PrimType // Classifications
Eric Christopher329d2672008-09-24 04:55:49 +00001068%token <PrimType> VOID INTTYPE
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001069%token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070%token TYPE
1071
1072
Eric Christopher329d2672008-09-24 04:55:49 +00001073%token<StrVal> LOCALVAR GLOBALVAR LABELSTR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074%token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1075%type <StrVal> LocalName OptLocalName OptLocalAssign
1076%type <StrVal> GlobalName OptGlobalAssign GlobalAssign
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001077%type <StrVal> OptSection SectionString OptGC
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078
Christopher Lamb668d9a02007-12-12 08:45:45 +00001079%type <UIntVal> OptAlign OptCAlign OptAddrSpace
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080
1081%token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1082%token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1083%token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
Dale Johannesen280e7bc2008-05-14 20:13:36 +00001084%token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
Christopher Lamb0a243582007-12-11 09:02:08 +00001085%token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1087%token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00001088%token DATALAYOUT
Chris Lattner906773a2008-08-29 17:20:18 +00001089%type <UIntVal> OptCallingConv LocalNumber
Devang Pateld222f862008-09-25 21:00:45 +00001090%type <Attributes> OptAttributes Attribute
1091%type <Attributes> OptFuncAttrs FuncAttr
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092
1093// Basic Block Terminating Operators
1094%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1095
1096// Binary Operators
1097%type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1098%token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1099%token <BinaryOpVal> SHL LSHR ASHR
1100
Eric Christopher329d2672008-09-24 04:55:49 +00001101%token <OtherOpVal> ICMP FCMP VICMP VFCMP
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102%type <IPredicate> IPredicates
1103%type <FPredicate> FPredicates
Eric Christopher329d2672008-09-24 04:55:49 +00001104%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1106
1107// Memory Instructions
1108%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1109
1110// Cast Operators
1111%type <CastOpVal> CastOps
1112%token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1113%token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1114
1115// Other Operators
1116%token <OtherOpVal> PHI_TOK SELECT VAARG
1117%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Devang Patel3b8849c2008-02-19 22:27:01 +00001118%token <OtherOpVal> GETRESULT
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001119%token <OtherOpVal> EXTRACTVALUE INSERTVALUE
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120
1121// Function Attributes
Reid Spenceraa8ae282007-07-31 03:50:36 +00001122%token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
Devang Patel008cd3e2008-09-26 23:51:19 +00001123%token READNONE READONLY GC OPTSIZE NOINLINE ALWAYSINLINE
Devang Patel5df692d2008-09-02 20:52:40 +00001124
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125// Visibility Styles
1126%token DEFAULT HIDDEN PROTECTED
1127
1128%start Module
1129%%
1130
1131
1132// Operations that are notably excluded from this list include:
1133// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1134//
1135ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1136LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
Eric Christopher329d2672008-09-24 04:55:49 +00001137CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1139
Eric Christopher329d2672008-09-24 04:55:49 +00001140IPredicates
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1142 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1143 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1144 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
Eric Christopher329d2672008-09-24 04:55:49 +00001145 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 ;
1147
Eric Christopher329d2672008-09-24 04:55:49 +00001148FPredicates
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1150 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1151 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1152 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1153 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1154 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1155 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1156 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1157 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1158 ;
1159
Eric Christopher329d2672008-09-24 04:55:49 +00001160// These are some types that allow classification if we only want a particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161// thing... for example, only a signed, unsigned, or integral type.
1162IntType : INTTYPE;
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001163FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164
1165LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1166OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1167
Christopher Lamb668d9a02007-12-12 08:45:45 +00001168OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1169 | /*empty*/ { $$=0; };
1170
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171/// OptLocalAssign - Value producing statements have an optional assignment
1172/// component.
1173OptLocalAssign : LocalName '=' {
1174 $$ = $1;
1175 CHECK_FOR_ERROR
1176 }
1177 | /*empty*/ {
1178 $$ = 0;
1179 CHECK_FOR_ERROR
1180 };
1181
Chris Lattner906773a2008-08-29 17:20:18 +00001182LocalNumber : LOCALVAL_ID '=' {
1183 $$ = $1;
1184 CHECK_FOR_ERROR
1185};
1186
1187
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1189
1190OptGlobalAssign : GlobalAssign
1191 | /*empty*/ {
1192 $$ = 0;
1193 CHECK_FOR_ERROR
1194 };
1195
1196GlobalAssign : GlobalName '=' {
1197 $$ = $1;
1198 CHECK_FOR_ERROR
1199 };
1200
Eric Christopher329d2672008-09-24 04:55:49 +00001201GVInternalLinkage
1202 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1203 | WEAK { $$ = GlobalValue::WeakLinkage; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1205 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
Eric Christopher329d2672008-09-24 04:55:49 +00001206 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
Dale Johannesen280e7bc2008-05-14 20:13:36 +00001207 | COMMON { $$ = GlobalValue::CommonLinkage; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 ;
1209
1210GVExternalLinkage
1211 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1212 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1213 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1214 ;
1215
1216GVVisibilityStyle
1217 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1218 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1219 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1220 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1221 ;
1222
1223FunctionDeclareLinkage
1224 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
Eric Christopher329d2672008-09-24 04:55:49 +00001225 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1227 ;
Eric Christopher329d2672008-09-24 04:55:49 +00001228
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229FunctionDefineLinkage
1230 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1231 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1232 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1233 | WEAK { $$ = GlobalValue::WeakLinkage; }
Eric Christopher329d2672008-09-24 04:55:49 +00001234 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1235 ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236
1237AliasLinkage
1238 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1239 | WEAK { $$ = GlobalValue::WeakLinkage; }
1240 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1241 ;
1242
1243OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1244 CCC_TOK { $$ = CallingConv::C; } |
1245 FASTCC_TOK { $$ = CallingConv::Fast; } |
1246 COLDCC_TOK { $$ = CallingConv::Cold; } |
1247 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1248 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1249 CC_TOK EUINT64VAL {
1250 if ((unsigned)$2 != $2)
1251 GEN_ERROR("Calling conv too large");
1252 $$ = $2;
1253 CHECK_FOR_ERROR
1254 };
1255
Devang Pateld222f862008-09-25 21:00:45 +00001256Attribute : ZEROEXT { $$ = Attribute::ZExt; }
1257 | ZEXT { $$ = Attribute::ZExt; }
1258 | SIGNEXT { $$ = Attribute::SExt; }
1259 | SEXT { $$ = Attribute::SExt; }
1260 | INREG { $$ = Attribute::InReg; }
1261 | SRET { $$ = Attribute::StructRet; }
1262 | NOALIAS { $$ = Attribute::NoAlias; }
1263 | BYVAL { $$ = Attribute::ByVal; }
1264 | NEST { $$ = Attribute::Nest; }
Eric Christopher329d2672008-09-24 04:55:49 +00001265 | ALIGN EUINT64VAL { $$ =
Devang Pateld222f862008-09-25 21:00:45 +00001266 Attribute::constructAlignmentFromInt($2); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 ;
1268
Devang Pateld222f862008-09-25 21:00:45 +00001269OptAttributes : /* empty */ { $$ = Attribute::None; }
1270 | OptAttributes Attribute {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 $$ = $1 | $2;
1272 }
1273 ;
1274
Devang Pateld222f862008-09-25 21:00:45 +00001275FuncAttr : NORETURN { $$ = Attribute::NoReturn; }
1276 | NOUNWIND { $$ = Attribute::NoUnwind; }
1277 | INREG { $$ = Attribute::InReg; }
1278 | ZEROEXT { $$ = Attribute::ZExt; }
1279 | SIGNEXT { $$ = Attribute::SExt; }
1280 | READNONE { $$ = Attribute::ReadNone; }
1281 | READONLY { $$ = Attribute::ReadOnly; }
Devang Patel008cd3e2008-09-26 23:51:19 +00001282 | NOINLINE { $$ = Attribute::NoInline }
1283 | ALWAYSINLINE { $$ = Attribute::AlwaysInline }
1284 | OPTSIZE { $$ = Attribute::OptimizeForSize }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 ;
1286
Devang Pateld222f862008-09-25 21:00:45 +00001287OptFuncAttrs : /* empty */ { $$ = Attribute::None; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 | OptFuncAttrs FuncAttr {
1289 $$ = $1 | $2;
1290 }
1291 ;
1292
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001293OptGC : /* empty */ { $$ = 0; }
1294 | GC STRINGCONSTANT {
1295 $$ = $2;
1296 }
1297 ;
1298
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1300// a comma before it.
1301OptAlign : /*empty*/ { $$ = 0; } |
1302 ALIGN EUINT64VAL {
1303 $$ = $2;
1304 if ($$ != 0 && !isPowerOf2_32($$))
1305 GEN_ERROR("Alignment must be a power of two");
1306 CHECK_FOR_ERROR
1307};
1308OptCAlign : /*empty*/ { $$ = 0; } |
1309 ',' ALIGN EUINT64VAL {
1310 $$ = $3;
1311 if ($$ != 0 && !isPowerOf2_32($$))
1312 GEN_ERROR("Alignment must be a power of two");
1313 CHECK_FOR_ERROR
1314};
1315
1316
Christopher Lamb0a243582007-12-11 09:02:08 +00001317
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318SectionString : SECTION STRINGCONSTANT {
1319 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1320 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1321 GEN_ERROR("Invalid character in section name");
1322 $$ = $2;
1323 CHECK_FOR_ERROR
1324};
1325
1326OptSection : /*empty*/ { $$ = 0; } |
1327 SectionString { $$ = $1; };
1328
1329// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1330// is set to be the global we are processing.
1331//
1332GlobalVarAttributes : /* empty */ {} |
1333 ',' GlobalVarAttribute GlobalVarAttributes {};
1334GlobalVarAttribute : SectionString {
1335 CurGV->setSection(*$1);
1336 delete $1;
1337 CHECK_FOR_ERROR
Eric Christopher329d2672008-09-24 04:55:49 +00001338 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 | ALIGN EUINT64VAL {
1340 if ($2 != 0 && !isPowerOf2_32($2))
1341 GEN_ERROR("Alignment must be a power of two");
1342 CurGV->setAlignment($2);
1343 CHECK_FOR_ERROR
1344 };
1345
1346//===----------------------------------------------------------------------===//
1347// Types includes all predefined types... except void, because it can only be
Eric Christopher329d2672008-09-24 04:55:49 +00001348// used in specific contexts (function returning void for example).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
1350// Derived types are added later...
1351//
Dale Johannesenf325d9f2007-08-03 01:03:46 +00001352PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353
Eric Christopher329d2672008-09-24 04:55:49 +00001354Types
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 : OPAQUE {
1356 $$ = new PATypeHolder(OpaqueType::get());
1357 CHECK_FOR_ERROR
1358 }
1359 | PrimType {
1360 $$ = new PATypeHolder($1);
1361 CHECK_FOR_ERROR
1362 }
Christopher Lamb668d9a02007-12-12 08:45:45 +00001363 | Types OptAddrSpace '*' { // Pointer type?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364 if (*$1 == Type::LabelTy)
1365 GEN_ERROR("Cannot form a pointer to a basic block");
Christopher Lamb668d9a02007-12-12 08:45:45 +00001366 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
Christopher Lamb0a243582007-12-11 09:02:08 +00001367 delete $1;
1368 CHECK_FOR_ERROR
1369 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 | SymbolicValueRef { // Named types are also simple types...
1371 const Type* tmp = getTypeVal($1);
1372 CHECK_FOR_ERROR
1373 $$ = new PATypeHolder(tmp);
1374 }
1375 | '\\' EUINT64VAL { // Type UpReference
1376 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1377 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1378 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1379 $$ = new PATypeHolder(OT);
1380 UR_OUT("New Upreference!\n");
1381 CHECK_FOR_ERROR
1382 }
1383 | Types '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001384 // Allow but ignore attributes on function types; this permits auto-upgrade.
1385 // FIXME: remove in LLVM 3.0.
Chris Lattner73de3c02008-04-23 05:37:08 +00001386 const Type *RetTy = *$1;
1387 if (!FunctionType::isValidReturnType(RetTy))
1388 GEN_ERROR("Invalid result type for LLVM function");
Eric Christopher329d2672008-09-24 04:55:49 +00001389
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001392 for (; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 const Type *Ty = I->Ty->get();
1394 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001396
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1398 if (isVarArg) Params.pop_back();
1399
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001400 for (unsigned i = 0; i != Params.size(); ++i)
1401 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1402 GEN_ERROR("Function arguments must be value types!");
1403
1404 CHECK_FOR_ERROR
1405
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001406 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001407 delete $3; // Delete the argument list
1408 delete $1; // Delete the return type handle
Eric Christopher329d2672008-09-24 04:55:49 +00001409 $$ = new PATypeHolder(HandleUpRefs(FT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 CHECK_FOR_ERROR
1411 }
1412 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001413 // Allow but ignore attributes on function types; this permits auto-upgrade.
1414 // FIXME: remove in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 std::vector<const Type*> Params;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001417 for ( ; I != E; ++I ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418 const Type* Ty = I->Ty->get();
1419 Params.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 }
Anton Korobeynikova2c02272007-12-03 19:16:54 +00001421
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1423 if (isVarArg) Params.pop_back();
1424
Anton Korobeynikove286f6d2007-12-03 21:01:29 +00001425 for (unsigned i = 0; i != Params.size(); ++i)
1426 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1427 GEN_ERROR("Function arguments must be value types!");
1428
1429 CHECK_FOR_ERROR
1430
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001431 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 delete $3; // Delete the argument list
Eric Christopher329d2672008-09-24 04:55:49 +00001433 $$ = new PATypeHolder(HandleUpRefs(FT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 CHECK_FOR_ERROR
1435 }
1436
1437 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
Dan Gohmane5febe42008-05-31 00:58:22 +00001438 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 delete $4;
1440 CHECK_FOR_ERROR
1441 }
1442 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1443 const llvm::Type* ElemTy = $4->get();
1444 if ((unsigned)$2 != $2)
1445 GEN_ERROR("Unsigned result not equal to signed result");
1446 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1447 GEN_ERROR("Element type of a VectorType must be primitive");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1449 delete $4;
1450 CHECK_FOR_ERROR
1451 }
1452 | '{' TypeListI '}' { // Structure type?
1453 std::vector<const Type*> Elements;
1454 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1455 E = $2->end(); I != E; ++I)
1456 Elements.push_back(*I);
1457
1458 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1459 delete $2;
1460 CHECK_FOR_ERROR
1461 }
1462 | '{' '}' { // Empty structure type?
1463 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1464 CHECK_FOR_ERROR
1465 }
1466 | '<' '{' TypeListI '}' '>' {
1467 std::vector<const Type*> Elements;
1468 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1469 E = $3->end(); I != E; ++I)
1470 Elements.push_back(*I);
1471
1472 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1473 delete $3;
1474 CHECK_FOR_ERROR
1475 }
1476 | '<' '{' '}' '>' { // Empty structure type?
1477 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1478 CHECK_FOR_ERROR
1479 }
1480 ;
1481
Eric Christopher329d2672008-09-24 04:55:49 +00001482ArgType
Devang Pateld222f862008-09-25 21:00:45 +00001483 : Types OptAttributes {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001484 // Allow but ignore attributes on function types; this permits auto-upgrade.
1485 // FIXME: remove in LLVM 3.0.
Eric Christopher329d2672008-09-24 04:55:49 +00001486 $$.Ty = $1;
Devang Pateld222f862008-09-25 21:00:45 +00001487 $$.Attrs = Attribute::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 }
1489 ;
1490
1491ResultTypes
1492 : Types {
1493 if (!UpRefs.empty())
1494 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Devang Patel3d5a1e862008-02-23 01:17:37 +00001495 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496 GEN_ERROR("LLVM functions cannot return aggregate types");
1497 $$ = $1;
1498 }
1499 | VOID {
1500 $$ = new PATypeHolder(Type::VoidTy);
1501 }
1502 ;
1503
1504ArgTypeList : ArgType {
1505 $$ = new TypeWithAttrsList();
1506 $$->push_back($1);
1507 CHECK_FOR_ERROR
1508 }
1509 | ArgTypeList ',' ArgType {
1510 ($$=$1)->push_back($3);
1511 CHECK_FOR_ERROR
1512 }
1513 ;
1514
Eric Christopher329d2672008-09-24 04:55:49 +00001515ArgTypeListI
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 : ArgTypeList
1517 | ArgTypeList ',' DOTDOTDOT {
1518 $$=$1;
Devang Pateld222f862008-09-25 21:00:45 +00001519 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520 TWA.Ty = new PATypeHolder(Type::VoidTy);
1521 $$->push_back(TWA);
1522 CHECK_FOR_ERROR
1523 }
1524 | DOTDOTDOT {
1525 $$ = new TypeWithAttrsList;
Devang Pateld222f862008-09-25 21:00:45 +00001526 TypeWithAttrs TWA; TWA.Attrs = Attribute::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001527 TWA.Ty = new PATypeHolder(Type::VoidTy);
1528 $$->push_back(TWA);
1529 CHECK_FOR_ERROR
1530 }
1531 | /*empty*/ {
1532 $$ = new TypeWithAttrsList();
1533 CHECK_FOR_ERROR
1534 };
1535
Eric Christopher329d2672008-09-24 04:55:49 +00001536// TypeList - Used for struct declarations and as a basis for function type
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537// declaration type lists
1538//
1539TypeListI : Types {
1540 $$ = new std::list<PATypeHolder>();
Eric Christopher329d2672008-09-24 04:55:49 +00001541 $$->push_back(*$1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 delete $1;
1543 CHECK_FOR_ERROR
1544 }
1545 | TypeListI ',' Types {
Eric Christopher329d2672008-09-24 04:55:49 +00001546 ($$=$1)->push_back(*$3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547 delete $3;
1548 CHECK_FOR_ERROR
1549 };
1550
1551// ConstVal - The various declarations that go into the constant pool. This
1552// production is used ONLY to represent constants that show up AFTER a 'const',
1553// 'constant' or 'global' token at global scope. Constants that can be inlined
1554// into other expressions (such as integers and constexprs) are handled by the
1555// ResolvedVal, ValueRef and ConstValueRef productions.
1556//
1557ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1558 if (!UpRefs.empty())
1559 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1560 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1561 if (ATy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001562 GEN_ERROR("Cannot make array constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563 (*$1)->getDescription() + "'");
1564 const Type *ETy = ATy->getElementType();
Dan Gohman7185e4b2008-06-23 18:43:26 +00001565 uint64_t NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566
1567 // Verify that we have the correct size...
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001568 if (NumElements != uint64_t(-1) && NumElements != $3->size())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001569 GEN_ERROR("Type mismatch: constant sized array initialized with " +
Eric Christopher329d2672008-09-24 04:55:49 +00001570 utostr($3->size()) + " arguments, but has size of " +
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001571 utostr(NumElements) + "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001572
1573 // Verify all elements are correct type!
1574 for (unsigned i = 0; i < $3->size(); i++) {
1575 if (ETy != (*$3)[i]->getType())
Eric Christopher329d2672008-09-24 04:55:49 +00001576 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577 ETy->getDescription() +"' as required!\nIt is of type '"+
1578 (*$3)[i]->getType()->getDescription() + "'.");
1579 }
1580
1581 $$ = ConstantArray::get(ATy, *$3);
1582 delete $1; delete $3;
1583 CHECK_FOR_ERROR
1584 }
1585 | Types '[' ']' {
1586 if (!UpRefs.empty())
1587 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1588 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1589 if (ATy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001590 GEN_ERROR("Cannot make array constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 (*$1)->getDescription() + "'");
1592
Dan Gohman7185e4b2008-06-23 18:43:26 +00001593 uint64_t NumElements = ATy->getNumElements();
Eric Christopher329d2672008-09-24 04:55:49 +00001594 if (NumElements != uint64_t(-1) && NumElements != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001595 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001596 " arguments, but has size of " + utostr(NumElements) +"");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001597 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1598 delete $1;
1599 CHECK_FOR_ERROR
1600 }
1601 | Types 'c' STRINGCONSTANT {
1602 if (!UpRefs.empty())
1603 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1604 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1605 if (ATy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001606 GEN_ERROR("Cannot make array constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 (*$1)->getDescription() + "'");
1608
Dan Gohman7185e4b2008-06-23 18:43:26 +00001609 uint64_t NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610 const Type *ETy = ATy->getElementType();
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001611 if (NumElements != uint64_t(-1) && NumElements != $3->length())
Eric Christopher329d2672008-09-24 04:55:49 +00001612 GEN_ERROR("Can't build string constant of size " +
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001613 utostr($3->length()) +
1614 " when array has size " + utostr(NumElements) + "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001615 std::vector<Constant*> Vals;
1616 if (ETy == Type::Int8Ty) {
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001617 for (uint64_t i = 0; i < $3->length(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1619 } else {
1620 delete $3;
1621 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1622 }
1623 delete $3;
1624 $$ = ConstantArray::get(ATy, Vals);
1625 delete $1;
1626 CHECK_FOR_ERROR
1627 }
1628 | Types '<' ConstVector '>' { // Nonempty unsized arr
1629 if (!UpRefs.empty())
1630 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1631 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1632 if (PTy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001633 GEN_ERROR("Cannot make packed constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634 (*$1)->getDescription() + "'");
1635 const Type *ETy = PTy->getElementType();
Dan Gohman7185e4b2008-06-23 18:43:26 +00001636 unsigned NumElements = PTy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637
1638 // Verify that we have the correct size...
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001639 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
Eric Christopher329d2672008-09-24 04:55:49 +00001641 utostr($3->size()) + " arguments, but has size of " +
Mon P Wang6bde9ec2008-06-25 08:15:39 +00001642 utostr(NumElements) + "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643
1644 // Verify all elements are correct type!
1645 for (unsigned i = 0; i < $3->size(); i++) {
1646 if (ETy != (*$3)[i]->getType())
Eric Christopher329d2672008-09-24 04:55:49 +00001647 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 ETy->getDescription() +"' as required!\nIt is of type '"+
1649 (*$3)[i]->getType()->getDescription() + "'.");
1650 }
1651
1652 $$ = ConstantVector::get(PTy, *$3);
1653 delete $1; delete $3;
1654 CHECK_FOR_ERROR
1655 }
1656 | Types '{' ConstVector '}' {
1657 const StructType *STy = dyn_cast<StructType>($1->get());
1658 if (STy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001659 GEN_ERROR("Cannot make struct constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 (*$1)->getDescription() + "'");
1661
1662 if ($3->size() != STy->getNumContainedTypes())
1663 GEN_ERROR("Illegal number of initializers for structure type");
1664
1665 // Check to ensure that constants are compatible with the type initializer!
1666 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1667 if ((*$3)[i]->getType() != STy->getElementType(i))
1668 GEN_ERROR("Expected type '" +
1669 STy->getElementType(i)->getDescription() +
1670 "' for element #" + utostr(i) +
1671 " of structure initializer");
1672
1673 // Check to ensure that Type is not packed
1674 if (STy->isPacked())
1675 GEN_ERROR("Unpacked Initializer to vector type '" +
1676 STy->getDescription() + "'");
1677
1678 $$ = ConstantStruct::get(STy, *$3);
1679 delete $1; delete $3;
1680 CHECK_FOR_ERROR
1681 }
1682 | Types '{' '}' {
1683 if (!UpRefs.empty())
1684 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1685 const StructType *STy = dyn_cast<StructType>($1->get());
1686 if (STy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001687 GEN_ERROR("Cannot make struct constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 (*$1)->getDescription() + "'");
1689
1690 if (STy->getNumContainedTypes() != 0)
1691 GEN_ERROR("Illegal number of initializers for structure type");
1692
1693 // Check to ensure that Type is not packed
1694 if (STy->isPacked())
1695 GEN_ERROR("Unpacked Initializer to vector type '" +
1696 STy->getDescription() + "'");
1697
1698 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1699 delete $1;
1700 CHECK_FOR_ERROR
1701 }
1702 | Types '<' '{' ConstVector '}' '>' {
1703 const StructType *STy = dyn_cast<StructType>($1->get());
1704 if (STy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001705 GEN_ERROR("Cannot make struct constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706 (*$1)->getDescription() + "'");
1707
1708 if ($4->size() != STy->getNumContainedTypes())
1709 GEN_ERROR("Illegal number of initializers for structure type");
1710
1711 // Check to ensure that constants are compatible with the type initializer!
1712 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1713 if ((*$4)[i]->getType() != STy->getElementType(i))
1714 GEN_ERROR("Expected type '" +
1715 STy->getElementType(i)->getDescription() +
1716 "' for element #" + utostr(i) +
1717 " of structure initializer");
1718
1719 // Check to ensure that Type is packed
1720 if (!STy->isPacked())
Eric Christopher329d2672008-09-24 04:55:49 +00001721 GEN_ERROR("Vector initializer to non-vector type '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722 STy->getDescription() + "'");
1723
1724 $$ = ConstantStruct::get(STy, *$4);
1725 delete $1; delete $4;
1726 CHECK_FOR_ERROR
1727 }
1728 | Types '<' '{' '}' '>' {
1729 if (!UpRefs.empty())
1730 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1731 const StructType *STy = dyn_cast<StructType>($1->get());
1732 if (STy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001733 GEN_ERROR("Cannot make struct constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734 (*$1)->getDescription() + "'");
1735
1736 if (STy->getNumContainedTypes() != 0)
1737 GEN_ERROR("Illegal number of initializers for structure type");
1738
1739 // Check to ensure that Type is packed
1740 if (!STy->isPacked())
Eric Christopher329d2672008-09-24 04:55:49 +00001741 GEN_ERROR("Vector initializer to non-vector type '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742 STy->getDescription() + "'");
1743
1744 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1745 delete $1;
1746 CHECK_FOR_ERROR
1747 }
1748 | Types NULL_TOK {
1749 if (!UpRefs.empty())
1750 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1751 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1752 if (PTy == 0)
Eric Christopher329d2672008-09-24 04:55:49 +00001753 GEN_ERROR("Cannot make null pointer constant with type: '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 (*$1)->getDescription() + "'");
1755
1756 $$ = ConstantPointerNull::get(PTy);
1757 delete $1;
1758 CHECK_FOR_ERROR
1759 }
1760 | Types UNDEF {
1761 if (!UpRefs.empty())
1762 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1763 $$ = UndefValue::get($1->get());
1764 delete $1;
1765 CHECK_FOR_ERROR
1766 }
1767 | Types SymbolicValueRef {
1768 if (!UpRefs.empty())
1769 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1770 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1771 if (Ty == 0)
Devang Patel3b8849c2008-02-19 22:27:01 +00001772 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773
1774 // ConstExprs can exist in the body of a function, thus creating
1775 // GlobalValues whenever they refer to a variable. Because we are in
1776 // the context of a function, getExistingVal will search the functions
1777 // symbol table instead of the module symbol table for the global symbol,
1778 // which throws things all off. To get around this, we just tell
1779 // getExistingVal that we are at global scope here.
1780 //
1781 Function *SavedCurFn = CurFun.CurrentFunction;
1782 CurFun.CurrentFunction = 0;
1783
1784 Value *V = getExistingVal(Ty, $2);
1785 CHECK_FOR_ERROR
1786
1787 CurFun.CurrentFunction = SavedCurFn;
1788
1789 // If this is an initializer for a constant pointer, which is referencing a
1790 // (currently) undefined variable, create a stub now that shall be replaced
1791 // in the future with the right type of variable.
1792 //
1793 if (V == 0) {
1794 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1795 const PointerType *PT = cast<PointerType>(Ty);
1796
1797 // First check to see if the forward references value is already created!
1798 PerModuleInfo::GlobalRefsType::iterator I =
1799 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
Eric Christopher329d2672008-09-24 04:55:49 +00001800
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001801 if (I != CurModule.GlobalRefs.end()) {
1802 V = I->second; // Placeholder already exists, use it...
1803 $2.destroy();
1804 } else {
1805 std::string Name;
1806 if ($2.Type == ValID::GlobalName)
1807 Name = $2.getName();
1808 else if ($2.Type != ValID::GlobalID)
1809 GEN_ERROR("Invalid reference to global");
1810
1811 // Create the forward referenced global.
1812 GlobalValue *GV;
Eric Christopher329d2672008-09-24 04:55:49 +00001813 if (const FunctionType *FTy =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001814 dyn_cast<FunctionType>(PT->getElementType())) {
Gabor Greif89f01162008-04-06 23:07:54 +00001815 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1816 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001817 } else {
1818 GV = new GlobalVariable(PT->getElementType(), false,
1819 GlobalValue::ExternalWeakLinkage, 0,
1820 Name, CurModule.CurrentModule);
1821 }
1822
1823 // Keep track of the fact that we have a forward ref to recycle it
1824 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1825 V = GV;
1826 }
1827 }
1828
1829 $$ = cast<GlobalValue>(V);
1830 delete $1; // Free the type handle
1831 CHECK_FOR_ERROR
1832 }
1833 | Types ConstExpr {
1834 if (!UpRefs.empty())
1835 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1836 if ($1->get() != $2->getType())
Eric Christopher329d2672008-09-24 04:55:49 +00001837 GEN_ERROR("Mismatched types for constant expression: " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001838 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1839 $$ = $2;
1840 delete $1;
1841 CHECK_FOR_ERROR
1842 }
1843 | Types ZEROINITIALIZER {
1844 if (!UpRefs.empty())
1845 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1846 const Type *Ty = $1->get();
1847 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1848 GEN_ERROR("Cannot create a null initialized value of this type");
1849 $$ = Constant::getNullValue(Ty);
1850 delete $1;
1851 CHECK_FOR_ERROR
1852 }
1853 | IntType ESINT64VAL { // integral constants
1854 if (!ConstantInt::isValueValidForType($1, $2))
1855 GEN_ERROR("Constant value doesn't fit in type");
1856 $$ = ConstantInt::get($1, $2, true);
1857 CHECK_FOR_ERROR
1858 }
1859 | IntType ESAPINTVAL { // arbitrary precision integer constants
1860 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1861 if ($2->getBitWidth() > BitWidth) {
1862 GEN_ERROR("Constant value does not fit in type");
1863 }
1864 $2->sextOrTrunc(BitWidth);
1865 $$ = ConstantInt::get(*$2);
1866 delete $2;
1867 CHECK_FOR_ERROR
1868 }
1869 | IntType EUINT64VAL { // integral constants
1870 if (!ConstantInt::isValueValidForType($1, $2))
1871 GEN_ERROR("Constant value doesn't fit in type");
1872 $$ = ConstantInt::get($1, $2, false);
1873 CHECK_FOR_ERROR
1874 }
1875 | IntType EUAPINTVAL { // arbitrary precision integer constants
1876 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1877 if ($2->getBitWidth() > BitWidth) {
1878 GEN_ERROR("Constant value does not fit in type");
Eric Christopher329d2672008-09-24 04:55:49 +00001879 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880 $2->zextOrTrunc(BitWidth);
1881 $$ = ConstantInt::get(*$2);
1882 delete $2;
1883 CHECK_FOR_ERROR
1884 }
1885 | INTTYPE TRUETOK { // Boolean constants
Dan Gohmane5febe42008-05-31 00:58:22 +00001886 if (cast<IntegerType>($1)->getBitWidth() != 1)
1887 GEN_ERROR("Constant true must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888 $$ = ConstantInt::getTrue();
1889 CHECK_FOR_ERROR
1890 }
1891 | INTTYPE FALSETOK { // Boolean constants
Dan Gohmane5febe42008-05-31 00:58:22 +00001892 if (cast<IntegerType>($1)->getBitWidth() != 1)
1893 GEN_ERROR("Constant false must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001894 $$ = ConstantInt::getFalse();
1895 CHECK_FOR_ERROR
1896 }
Dale Johannesen043064d2007-09-12 03:31:28 +00001897 | FPType FPVAL { // Floating point constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001898 if (!ConstantFP::isValueValidForType($1, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001899 GEN_ERROR("Floating point constant invalid for type");
Eric Christopher329d2672008-09-24 04:55:49 +00001900 // Lexer has no type info, so builds all float and double FP constants
Dale Johannesen255b8fe2007-09-11 18:33:39 +00001901 // as double. Fix this here. Long double is done right.
1902 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001903 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
Chris Lattner05ba86e2008-04-20 00:41:19 +00001904 $$ = ConstantFP::get(*$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00001905 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906 CHECK_FOR_ERROR
1907 };
1908
1909
1910ConstExpr: CastOps '(' ConstVal TO Types ')' {
1911 if (!UpRefs.empty())
1912 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1913 Constant *Val = $3;
1914 const Type *DestTy = $5->get();
1915 if (!CastInst::castIsValid($1, $3, DestTy))
1916 GEN_ERROR("invalid cast opcode for cast from '" +
1917 Val->getType()->getDescription() + "' to '" +
Eric Christopher329d2672008-09-24 04:55:49 +00001918 DestTy->getDescription() + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919 $$ = ConstantExpr::getCast($1, $3, DestTy);
1920 delete $5;
1921 }
1922 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1923 if (!isa<PointerType>($3->getType()))
1924 GEN_ERROR("GetElementPtr requires a pointer operand");
1925
1926 const Type *IdxTy =
Dan Gohman8055f772008-05-15 19:50:34 +00001927 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928 if (!IdxTy)
1929 GEN_ERROR("Index list invalid for constant getelementptr");
1930
1931 SmallVector<Constant*, 8> IdxVec;
1932 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1933 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1934 IdxVec.push_back(C);
1935 else
1936 GEN_ERROR("Indices to constant getelementptr must be constants");
1937
1938 delete $4;
1939
1940 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1941 CHECK_FOR_ERROR
1942 }
1943 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1944 if ($3->getType() != Type::Int1Ty)
1945 GEN_ERROR("Select condition must be of boolean type");
1946 if ($5->getType() != $7->getType())
1947 GEN_ERROR("Select operand types must match");
1948 $$ = ConstantExpr::getSelect($3, $5, $7);
1949 CHECK_FOR_ERROR
1950 }
1951 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1952 if ($3->getType() != $5->getType())
1953 GEN_ERROR("Binary operator types must match");
1954 CHECK_FOR_ERROR;
1955 $$ = ConstantExpr::get($1, $3, $5);
1956 }
1957 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1958 if ($3->getType() != $5->getType())
1959 GEN_ERROR("Logical operator types must match");
1960 if (!$3->getType()->isInteger()) {
Eric Christopher329d2672008-09-24 04:55:49 +00001961 if (!isa<VectorType>($3->getType()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001962 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1963 GEN_ERROR("Logical operator requires integral operands");
1964 }
1965 $$ = ConstantExpr::get($1, $3, $5);
1966 CHECK_FOR_ERROR
1967 }
1968 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1969 if ($4->getType() != $6->getType())
1970 GEN_ERROR("icmp operand types must match");
1971 $$ = ConstantExpr::getICmp($2, $4, $6);
1972 }
1973 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1974 if ($4->getType() != $6->getType())
1975 GEN_ERROR("fcmp operand types must match");
1976 $$ = ConstantExpr::getFCmp($2, $4, $6);
1977 }
Nate Begeman646fa482008-05-12 19:01:56 +00001978 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1979 if ($4->getType() != $6->getType())
1980 GEN_ERROR("vicmp operand types must match");
1981 $$ = ConstantExpr::getVICmp($2, $4, $6);
1982 }
1983 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1984 if ($4->getType() != $6->getType())
1985 GEN_ERROR("vfcmp operand types must match");
1986 $$ = ConstantExpr::getVFCmp($2, $4, $6);
1987 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1989 if (!ExtractElementInst::isValidOperands($3, $5))
1990 GEN_ERROR("Invalid extractelement operands");
1991 $$ = ConstantExpr::getExtractElement($3, $5);
1992 CHECK_FOR_ERROR
1993 }
1994 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1995 if (!InsertElementInst::isValidOperands($3, $5, $7))
1996 GEN_ERROR("Invalid insertelement operands");
1997 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1998 CHECK_FOR_ERROR
1999 }
2000 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2001 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
2002 GEN_ERROR("Invalid shufflevector operands");
2003 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
2004 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002005 }
Dan Gohmane5febe42008-05-31 00:58:22 +00002006 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002007 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2008 GEN_ERROR("ExtractValue requires an aggregate operand");
2009
Dan Gohmane5febe42008-05-31 00:58:22 +00002010 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002011 delete $4;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002012 CHECK_FOR_ERROR
2013 }
Dan Gohmane5febe42008-05-31 00:58:22 +00002014 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002015 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2016 GEN_ERROR("InsertValue requires an aggregate operand");
2017
Dan Gohmane5febe42008-05-31 00:58:22 +00002018 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002019 delete $6;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00002020 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021 };
2022
2023
2024// ConstVector - A list of comma separated constants.
2025ConstVector : ConstVector ',' ConstVal {
2026 ($$ = $1)->push_back($3);
2027 CHECK_FOR_ERROR
2028 }
2029 | ConstVal {
2030 $$ = new std::vector<Constant*>();
2031 $$->push_back($1);
2032 CHECK_FOR_ERROR
2033 };
2034
2035
2036// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2037GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2038
Eric Christopher329d2672008-09-24 04:55:49 +00002039// ThreadLocal
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002040ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2041
2042// AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2043AliaseeRef : ResultTypes SymbolicValueRef {
2044 const Type* VTy = $1->get();
2045 Value *V = getVal(VTy, $2);
Chris Lattnerbb856a32007-08-06 21:00:46 +00002046 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2048 if (!Aliasee)
2049 GEN_ERROR("Aliases can be created only to global values");
2050
2051 $$ = Aliasee;
2052 CHECK_FOR_ERROR
2053 delete $1;
2054 }
2055 | BITCAST '(' AliaseeRef TO Types ')' {
2056 Constant *Val = $3;
2057 const Type *DestTy = $5->get();
2058 if (!CastInst::castIsValid($1, $3, DestTy))
2059 GEN_ERROR("invalid cast opcode for cast from '" +
2060 Val->getType()->getDescription() + "' to '" +
2061 DestTy->getDescription() + "'");
Eric Christopher329d2672008-09-24 04:55:49 +00002062
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 $$ = ConstantExpr::getCast($1, $3, DestTy);
2064 CHECK_FOR_ERROR
2065 delete $5;
2066 };
2067
2068//===----------------------------------------------------------------------===//
2069// Rules to match Modules
2070//===----------------------------------------------------------------------===//
2071
2072// Module rule: Capture the result of parsing the whole file into a result
2073// variable...
2074//
Eric Christopher329d2672008-09-24 04:55:49 +00002075Module
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076 : DefinitionList {
2077 $$ = ParserResult = CurModule.CurrentModule;
2078 CurModule.ModuleDone();
2079 CHECK_FOR_ERROR;
2080 }
2081 | /*empty*/ {
2082 $$ = ParserResult = CurModule.CurrentModule;
2083 CurModule.ModuleDone();
2084 CHECK_FOR_ERROR;
2085 }
2086 ;
2087
2088DefinitionList
2089 : Definition
2090 | DefinitionList Definition
2091 ;
2092
Eric Christopher329d2672008-09-24 04:55:49 +00002093Definition
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002094 : DEFINE { CurFun.isDeclare = false; } Function {
2095 CurFun.FunctionDone();
2096 CHECK_FOR_ERROR
2097 }
2098 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2099 CHECK_FOR_ERROR
2100 }
2101 | MODULE ASM_TOK AsmBlock {
2102 CHECK_FOR_ERROR
Eric Christopher329d2672008-09-24 04:55:49 +00002103 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 | OptLocalAssign TYPE Types {
2105 if (!UpRefs.empty())
2106 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2107 // Eagerly resolve types. This is not an optimization, this is a
2108 // requirement that is due to the fact that we could have this:
2109 //
2110 // %list = type { %list * }
2111 // %list = type { %list * } ; repeated type decl
2112 //
2113 // If types are not resolved eagerly, then the two types will not be
2114 // determined to be the same type!
2115 //
2116 ResolveTypeTo($1, *$3);
2117
2118 if (!setTypeName(*$3, $1) && !$1) {
2119 CHECK_FOR_ERROR
2120 // If this is a named type that is not a redefinition, add it to the slot
2121 // table.
2122 CurModule.Types.push_back(*$3);
2123 }
2124
2125 delete $3;
2126 CHECK_FOR_ERROR
2127 }
2128 | OptLocalAssign TYPE VOID {
2129 ResolveTypeTo($1, $3);
2130
2131 if (!setTypeName($3, $1) && !$1) {
2132 CHECK_FOR_ERROR
2133 // If this is a named type that is not a redefinition, add it to the slot
2134 // table.
2135 CurModule.Types.push_back($3);
2136 }
2137 CHECK_FOR_ERROR
2138 }
Eric Christopher329d2672008-09-24 04:55:49 +00002139 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2140 OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141 /* "Externally Visible" Linkage */
Eric Christopher329d2672008-09-24 04:55:49 +00002142 if ($5 == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143 GEN_ERROR("Global value initializer is not a constant");
2144 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
Christopher Lamb668d9a02007-12-12 08:45:45 +00002145 $2, $4, $5->getType(), $5, $3, $6);
Christopher Lamb0a243582007-12-11 09:02:08 +00002146 CHECK_FOR_ERROR
2147 } GlobalVarAttributes {
2148 CurGV = 0;
2149 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002150 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002151 ConstVal OptAddrSpace {
Eric Christopher329d2672008-09-24 04:55:49 +00002152 if ($6 == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002153 GEN_ERROR("Global value initializer is not a constant");
Christopher Lamb668d9a02007-12-12 08:45:45 +00002154 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 CHECK_FOR_ERROR
2156 } GlobalVarAttributes {
2157 CurGV = 0;
2158 }
2159 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
Christopher Lamb668d9a02007-12-12 08:45:45 +00002160 Types OptAddrSpace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161 if (!UpRefs.empty())
2162 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
Christopher Lamb668d9a02007-12-12 08:45:45 +00002163 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002164 CHECK_FOR_ERROR
2165 delete $6;
2166 } GlobalVarAttributes {
2167 CurGV = 0;
2168 CHECK_FOR_ERROR
2169 }
2170 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2171 std::string Name;
2172 if ($1) {
2173 Name = *$1;
2174 delete $1;
2175 }
2176 if (Name.empty())
2177 GEN_ERROR("Alias name cannot be empty");
Eric Christopher329d2672008-09-24 04:55:49 +00002178
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002179 Constant* Aliasee = $5;
2180 if (Aliasee == 0)
2181 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2182
2183 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2184 CurModule.CurrentModule);
2185 GA->setVisibility($2);
2186 InsertValue(GA, CurModule.Values);
Eric Christopher329d2672008-09-24 04:55:49 +00002187
2188
Chris Lattner5eefce32007-09-10 23:24:14 +00002189 // If there was a forward reference of this alias, resolve it now.
Eric Christopher329d2672008-09-24 04:55:49 +00002190
Chris Lattner5eefce32007-09-10 23:24:14 +00002191 ValID ID;
2192 if (!Name.empty())
2193 ID = ValID::createGlobalName(Name);
2194 else
2195 ID = ValID::createGlobalID(CurModule.Values.size()-1);
Eric Christopher329d2672008-09-24 04:55:49 +00002196
Chris Lattner5eefce32007-09-10 23:24:14 +00002197 if (GlobalValue *FWGV =
2198 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2199 // Replace uses of the fwdref with the actual alias.
2200 FWGV->replaceAllUsesWith(GA);
2201 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2202 GV->eraseFromParent();
2203 else
2204 cast<Function>(FWGV)->eraseFromParent();
2205 }
2206 ID.destroy();
Eric Christopher329d2672008-09-24 04:55:49 +00002207
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002208 CHECK_FOR_ERROR
2209 }
Eric Christopher329d2672008-09-24 04:55:49 +00002210 | TARGET TargetDefinition {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002211 CHECK_FOR_ERROR
2212 }
2213 | DEPLIBS '=' LibrariesDefinition {
2214 CHECK_FOR_ERROR
2215 }
2216 ;
2217
2218
2219AsmBlock : STRINGCONSTANT {
2220 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2221 if (AsmSoFar.empty())
2222 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2223 else
2224 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2225 delete $1;
2226 CHECK_FOR_ERROR
2227};
2228
2229TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2230 CurModule.CurrentModule->setTargetTriple(*$3);
2231 delete $3;
2232 }
2233 | DATALAYOUT '=' STRINGCONSTANT {
2234 CurModule.CurrentModule->setDataLayout(*$3);
2235 delete $3;
2236 };
2237
2238LibrariesDefinition : '[' LibList ']';
2239
2240LibList : LibList ',' STRINGCONSTANT {
2241 CurModule.CurrentModule->addLibrary(*$3);
2242 delete $3;
2243 CHECK_FOR_ERROR
2244 }
2245 | STRINGCONSTANT {
2246 CurModule.CurrentModule->addLibrary(*$1);
2247 delete $1;
2248 CHECK_FOR_ERROR
2249 }
2250 | /* empty: end of list */ {
2251 CHECK_FOR_ERROR
2252 }
2253 ;
2254
2255//===----------------------------------------------------------------------===//
2256// Rules to match Function Headers
2257//===----------------------------------------------------------------------===//
2258
Devang Pateld222f862008-09-25 21:00:45 +00002259ArgListH : ArgListH ',' Types OptAttributes OptLocalName {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 if (!UpRefs.empty())
2261 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00002262 if (!(*$3)->isFirstClassType())
2263 GEN_ERROR("Argument types must be first-class");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2265 $$ = $1;
2266 $1->push_back(E);
2267 CHECK_FOR_ERROR
2268 }
Devang Pateld222f862008-09-25 21:00:45 +00002269 | Types OptAttributes OptLocalName {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002270 if (!UpRefs.empty())
2271 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00002272 if (!(*$1)->isFirstClassType())
2273 GEN_ERROR("Argument types must be first-class");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2275 $$ = new ArgListType;
2276 $$->push_back(E);
2277 CHECK_FOR_ERROR
2278 };
2279
2280ArgList : ArgListH {
2281 $$ = $1;
2282 CHECK_FOR_ERROR
2283 }
2284 | ArgListH ',' DOTDOTDOT {
2285 $$ = $1;
2286 struct ArgListEntry E;
2287 E.Ty = new PATypeHolder(Type::VoidTy);
2288 E.Name = 0;
Devang Pateld222f862008-09-25 21:00:45 +00002289 E.Attrs = Attribute::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290 $$->push_back(E);
2291 CHECK_FOR_ERROR
2292 }
2293 | DOTDOTDOT {
2294 $$ = new ArgListType;
2295 struct ArgListEntry E;
2296 E.Ty = new PATypeHolder(Type::VoidTy);
2297 E.Name = 0;
Devang Pateld222f862008-09-25 21:00:45 +00002298 E.Attrs = Attribute::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299 $$->push_back(E);
2300 CHECK_FOR_ERROR
2301 }
2302 | /* empty */ {
2303 $$ = 0;
2304 CHECK_FOR_ERROR
2305 };
2306
Eric Christopher329d2672008-09-24 04:55:49 +00002307FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
Devang Patel008cd3e2008-09-26 23:51:19 +00002308 OptFuncAttrs OptSection OptAlign OptGC {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309 std::string FunctionName(*$3);
2310 delete $3; // Free strdup'd memory!
Eric Christopher329d2672008-09-24 04:55:49 +00002311
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002312 // Check the function result for abstractness if this is a define. We should
2313 // have no abstract types at this point
2314 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2315 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2316
Chris Lattner73de3c02008-04-23 05:37:08 +00002317 if (!FunctionType::isValidReturnType(*$2))
2318 GEN_ERROR("Invalid result type for LLVM function");
Eric Christopher329d2672008-09-24 04:55:49 +00002319
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002320 std::vector<const Type*> ParamTypeList;
Devang Pateld222f862008-09-25 21:00:45 +00002321 SmallVector<AttributeWithIndex, 8> Attrs;
Devang Patelf2a4a922008-09-26 22:53:05 +00002322 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2323 //attributes.
2324 Attributes RetAttrs = 0;
2325 if ($7 != Attribute::None) {
2326 if ($7 & Attribute::ZExt) {
2327 RetAttrs = RetAttrs | Attribute::ZExt;
2328 $7 = $7 ^ Attribute::ZExt;
2329 }
2330 if ($7 & Attribute::SExt) {
2331 RetAttrs = RetAttrs | Attribute::SExt;
2332 $7 = $7 ^ Attribute::SExt;
2333 }
2334 if ($7 & Attribute::InReg) {
2335 RetAttrs = RetAttrs | Attribute::InReg;
2336 $7 = $7 ^ Attribute::InReg;
2337 }
2338 if (RetAttrs != Attribute::None)
2339 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341 if ($5) { // If there are arguments...
2342 unsigned index = 1;
2343 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2344 const Type* Ty = I->Ty->get();
2345 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2346 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2347 ParamTypeList.push_back(Ty);
Devang Pateld222f862008-09-25 21:00:45 +00002348 if (Ty != Type::VoidTy && I->Attrs != Attribute::None)
2349 Attrs.push_back(AttributeWithIndex::get(index, I->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 }
2351 }
Devang Patelf2a4a922008-09-26 22:53:05 +00002352 if ($7 != Attribute::None)
2353 Attrs.push_back(AttributeWithIndex::get(~0, $7));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002354
2355 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2356 if (isVarArg) ParamTypeList.pop_back();
2357
Devang Pateld222f862008-09-25 21:00:45 +00002358 AttrListPtr PAL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002359 if (!Attrs.empty())
Devang Pateld222f862008-09-25 21:00:45 +00002360 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002361
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002362 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
Christopher Lambfb623c62007-12-17 01:17:35 +00002363 const PointerType *PFT = PointerType::getUnqual(FT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002364 delete $2;
2365
2366 ValID ID;
2367 if (!FunctionName.empty()) {
2368 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2369 } else {
2370 ID = ValID::createGlobalID(CurModule.Values.size());
2371 }
2372
2373 Function *Fn = 0;
2374 // See if this function was forward referenced. If so, recycle the object.
2375 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
Eric Christopher329d2672008-09-24 04:55:49 +00002376 // Move the function to the end of the list, from whereever it was
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002377 // previously inserted.
2378 Fn = cast<Function>(FWRef);
Devang Pateld222f862008-09-25 21:00:45 +00002379 assert(Fn->getAttributes().isEmpty() &&
Chris Lattner1c8733e2008-03-12 17:45:29 +00002380 "Forward reference has parameter attributes!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002381 CurModule.CurrentModule->getFunctionList().remove(Fn);
2382 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2383 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2384 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002385 if (Fn->getFunctionType() != FT ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386 // The existing function doesn't have the same type. This is an overload
2387 // error.
2388 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Devang Pateld222f862008-09-25 21:00:45 +00002389 } else if (Fn->getAttributes() != PAL) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002390 // The existing function doesn't have the same parameter attributes.
2391 // This is an overload error.
2392 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002393 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2394 // Neither the existing or the current function is a declaration and they
2395 // have the same name and same type. Clearly this is a redefinition.
2396 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002397 } else if (Fn->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002398 // Make sure to strip off any argument names so we can't get conflicts.
2399 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2400 AI != AE; ++AI)
2401 AI->setName("");
2402 }
2403 } else { // Not already defined?
Gabor Greif89f01162008-04-06 23:07:54 +00002404 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2405 CurModule.CurrentModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002406 InsertValue(Fn, CurModule.Values);
2407 }
2408
2409 CurFun.FunctionStart(Fn);
2410
2411 if (CurFun.isDeclare) {
2412 // If we have declaration, always overwrite linkage. This will allow us to
2413 // correctly handle cases, when pointer to function is passed as argument to
2414 // another function.
2415 Fn->setLinkage(CurFun.Linkage);
2416 Fn->setVisibility(CurFun.Visibility);
2417 }
2418 Fn->setCallingConv($1);
Devang Pateld222f862008-09-25 21:00:45 +00002419 Fn->setAttributes(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002420 Fn->setAlignment($9);
2421 if ($8) {
2422 Fn->setSection(*$8);
2423 delete $8;
2424 }
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002425 if ($10) {
Gordon Henriksen8bccc832008-08-17 18:48:50 +00002426 Fn->setGC($10->c_str());
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00002427 delete $10;
2428 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429
2430 // Add all of the arguments we parsed to the function...
2431 if ($5) { // Is null if empty...
2432 if (isVarArg) { // Nuke the last entry
2433 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2434 "Not a varargs marker!");
2435 delete $5->back().Ty;
2436 $5->pop_back(); // Delete the last entry
2437 }
2438 Function::arg_iterator ArgIt = Fn->arg_begin();
2439 Function::arg_iterator ArgEnd = Fn->arg_end();
2440 unsigned Idx = 1;
Eric Christopher329d2672008-09-24 04:55:49 +00002441 for (ArgListType::iterator I = $5->begin();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2443 delete I->Ty; // Delete the typeholder...
2444 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2445 CHECK_FOR_ERROR
2446 InsertValue(ArgIt);
2447 Idx++;
2448 }
2449
2450 delete $5; // We're now done with the argument list
2451 }
2452 CHECK_FOR_ERROR
2453};
2454
2455BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2456
2457FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2458 $$ = CurFun.CurrentFunction;
2459
2460 // Make sure that we keep track of the linkage type even if there was a
2461 // previous "declare".
2462 $$->setLinkage($1);
2463 $$->setVisibility($2);
2464};
2465
2466END : ENDTOK | '}'; // Allow end of '}' to end a function
2467
2468Function : BasicBlockList END {
2469 $$ = $1;
2470 CHECK_FOR_ERROR
2471};
2472
2473FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2474 CurFun.CurrentFunction->setLinkage($1);
2475 CurFun.CurrentFunction->setVisibility($2);
2476 $$ = CurFun.CurrentFunction;
2477 CurFun.FunctionDone();
2478 CHECK_FOR_ERROR
2479 };
2480
2481//===----------------------------------------------------------------------===//
2482// Rules to match Basic Blocks
2483//===----------------------------------------------------------------------===//
2484
2485OptSideEffect : /* empty */ {
2486 $$ = false;
2487 CHECK_FOR_ERROR
2488 }
2489 | SIDEEFFECT {
2490 $$ = true;
2491 CHECK_FOR_ERROR
2492 };
2493
2494ConstValueRef : ESINT64VAL { // A reference to a direct constant
2495 $$ = ValID::create($1);
2496 CHECK_FOR_ERROR
2497 }
2498 | EUINT64VAL {
2499 $$ = ValID::create($1);
2500 CHECK_FOR_ERROR
2501 }
Chris Lattnerf3d40022008-07-11 00:30:39 +00002502 | ESAPINTVAL { // arbitrary precision integer constants
2503 $$ = ValID::create(*$1, true);
2504 delete $1;
2505 CHECK_FOR_ERROR
Eric Christopher329d2672008-09-24 04:55:49 +00002506 }
Chris Lattnerf3d40022008-07-11 00:30:39 +00002507 | EUAPINTVAL { // arbitrary precision integer constants
2508 $$ = ValID::create(*$1, false);
2509 delete $1;
2510 CHECK_FOR_ERROR
2511 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002512 | FPVAL { // Perhaps it's an FP constant?
2513 $$ = ValID::create($1);
2514 CHECK_FOR_ERROR
2515 }
2516 | TRUETOK {
2517 $$ = ValID::create(ConstantInt::getTrue());
2518 CHECK_FOR_ERROR
Eric Christopher329d2672008-09-24 04:55:49 +00002519 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520 | FALSETOK {
2521 $$ = ValID::create(ConstantInt::getFalse());
2522 CHECK_FOR_ERROR
2523 }
2524 | NULL_TOK {
2525 $$ = ValID::createNull();
2526 CHECK_FOR_ERROR
2527 }
2528 | UNDEF {
2529 $$ = ValID::createUndef();
2530 CHECK_FOR_ERROR
2531 }
2532 | ZEROINITIALIZER { // A vector zero constant.
2533 $$ = ValID::createZeroInit();
2534 CHECK_FOR_ERROR
2535 }
2536 | '<' ConstVector '>' { // Nonempty unsized packed vector
2537 const Type *ETy = (*$2)[0]->getType();
Eric Christopher329d2672008-09-24 04:55:49 +00002538 unsigned NumElements = $2->size();
Dan Gohmane5febe42008-05-31 00:58:22 +00002539
2540 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2541 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
Eric Christopher329d2672008-09-24 04:55:49 +00002542
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002543 VectorType* pt = VectorType::get(ETy, NumElements);
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002544 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
Eric Christopher329d2672008-09-24 04:55:49 +00002545
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002546 // Verify all elements are correct type!
2547 for (unsigned i = 0; i < $2->size(); i++) {
2548 if (ETy != (*$2)[i]->getType())
Eric Christopher329d2672008-09-24 04:55:49 +00002549 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 ETy->getDescription() +"' as required!\nIt is of type '" +
2551 (*$2)[i]->getType()->getDescription() + "'.");
2552 }
2553
2554 $$ = ValID::create(ConstantVector::get(pt, *$2));
2555 delete PTy; delete $2;
2556 CHECK_FOR_ERROR
2557 }
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002558 | '[' ConstVector ']' { // Nonempty unsized arr
2559 const Type *ETy = (*$2)[0]->getType();
Eric Christopher329d2672008-09-24 04:55:49 +00002560 uint64_t NumElements = $2->size();
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002561
2562 if (!ETy->isFirstClassType())
2563 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2564
2565 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2566 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2567
2568 // Verify all elements are correct type!
2569 for (unsigned i = 0; i < $2->size(); i++) {
2570 if (ETy != (*$2)[i]->getType())
Eric Christopher329d2672008-09-24 04:55:49 +00002571 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002572 ETy->getDescription() +"' as required!\nIt is of type '"+
2573 (*$2)[i]->getType()->getDescription() + "'.");
2574 }
2575
2576 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2577 delete PTy; delete $2;
2578 CHECK_FOR_ERROR
2579 }
2580 | '[' ']' {
Dan Gohman7185e4b2008-06-23 18:43:26 +00002581 // Use undef instead of an array because it's inconvenient to determine
2582 // the element type at this point, there being no elements to examine.
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002583 $$ = ValID::createUndef();
2584 CHECK_FOR_ERROR
2585 }
2586 | 'c' STRINGCONSTANT {
Dan Gohman7185e4b2008-06-23 18:43:26 +00002587 uint64_t NumElements = $2->length();
Dan Gohman9fc6cb02008-06-09 14:45:02 +00002588 const Type *ETy = Type::Int8Ty;
2589
2590 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2591
2592 std::vector<Constant*> Vals;
2593 for (unsigned i = 0; i < $2->length(); ++i)
2594 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2595 delete $2;
2596 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2597 CHECK_FOR_ERROR
2598 }
2599 | '{' ConstVector '}' {
2600 std::vector<const Type*> Elements($2->size());
2601 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2602 Elements[i] = (*$2)[i]->getType();
2603
2604 const StructType *STy = StructType::get(Elements);
2605 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2606
2607 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2608 delete PTy; delete $2;
2609 CHECK_FOR_ERROR
2610 }
2611 | '{' '}' {
2612 const StructType *STy = StructType::get(std::vector<const Type*>());
2613 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2614 CHECK_FOR_ERROR
2615 }
2616 | '<' '{' ConstVector '}' '>' {
2617 std::vector<const Type*> Elements($3->size());
2618 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2619 Elements[i] = (*$3)[i]->getType();
2620
2621 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2622 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2623
2624 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2625 delete PTy; delete $3;
2626 CHECK_FOR_ERROR
2627 }
2628 | '<' '{' '}' '>' {
2629 const StructType *STy = StructType::get(std::vector<const Type*>(),
2630 /*isPacked=*/true);
2631 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2632 CHECK_FOR_ERROR
2633 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002634 | ConstExpr {
2635 $$ = ValID::create($1);
2636 CHECK_FOR_ERROR
2637 }
2638 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2639 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2640 delete $3;
2641 delete $5;
2642 CHECK_FOR_ERROR
2643 };
2644
2645// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2646// another value.
2647//
2648SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2649 $$ = ValID::createLocalID($1);
2650 CHECK_FOR_ERROR
2651 }
2652 | GLOBALVAL_ID {
2653 $$ = ValID::createGlobalID($1);
2654 CHECK_FOR_ERROR
2655 }
2656 | LocalName { // Is it a named reference...?
2657 $$ = ValID::createLocalName(*$1);
2658 delete $1;
2659 CHECK_FOR_ERROR
2660 }
2661 | GlobalName { // Is it a named reference...?
2662 $$ = ValID::createGlobalName(*$1);
2663 delete $1;
2664 CHECK_FOR_ERROR
2665 };
2666
2667// ValueRef - A reference to a definition... either constant or symbolic
2668ValueRef : SymbolicValueRef | ConstValueRef;
2669
2670
2671// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2672// type immediately preceeds the value reference, and allows complex constant
2673// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2674ResolvedVal : Types ValueRef {
2675 if (!UpRefs.empty())
2676 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Eric Christopher329d2672008-09-24 04:55:49 +00002677 $$ = getVal(*$1, $2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 delete $1;
2679 CHECK_FOR_ERROR
2680 }
2681 ;
2682
Devang Patelbf507402008-02-20 22:40:23 +00002683ReturnedVal : ResolvedVal {
2684 $$ = new std::vector<Value *>();
Eric Christopher329d2672008-09-24 04:55:49 +00002685 $$->push_back($1);
Devang Patelbf507402008-02-20 22:40:23 +00002686 CHECK_FOR_ERROR
2687 }
Devang Patel087fe2b2008-02-23 00:38:56 +00002688 | ReturnedVal ',' ResolvedVal {
Eric Christopher329d2672008-09-24 04:55:49 +00002689 ($$=$1)->push_back($3);
Devang Patelbf507402008-02-20 22:40:23 +00002690 CHECK_FOR_ERROR
2691 };
2692
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693BasicBlockList : BasicBlockList BasicBlock {
2694 $$ = $1;
2695 CHECK_FOR_ERROR
2696 }
Eric Christopher329d2672008-09-24 04:55:49 +00002697 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002698 $$ = $1;
2699 CHECK_FOR_ERROR
2700 };
2701
2702
Eric Christopher329d2672008-09-24 04:55:49 +00002703// Basic blocks are terminated by branching instructions:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002704// br, br/cc, switch, ret
2705//
Chris Lattner906773a2008-08-29 17:20:18 +00002706BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002707 setValueName($3, $2);
2708 CHECK_FOR_ERROR
2709 InsertValue($3);
2710 $1->getInstList().push_back($3);
2711 $$ = $1;
2712 CHECK_FOR_ERROR
2713 };
2714
Chris Lattner906773a2008-08-29 17:20:18 +00002715BasicBlock : InstructionList LocalNumber BBTerminatorInst {
2716 CHECK_FOR_ERROR
2717 int ValNum = InsertValue($3);
2718 if (ValNum != (int)$2)
2719 GEN_ERROR("Result value number %" + utostr($2) +
2720 " is incorrect, expected %" + utostr((unsigned)ValNum));
Eric Christopher329d2672008-09-24 04:55:49 +00002721
Chris Lattner906773a2008-08-29 17:20:18 +00002722 $1->getInstList().push_back($3);
2723 $$ = $1;
2724 CHECK_FOR_ERROR
2725};
2726
2727
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728InstructionList : InstructionList Inst {
2729 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2730 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2731 if (CI2->getParent() == 0)
2732 $1->getInstList().push_back(CI2);
2733 $1->getInstList().push_back($2);
2734 $$ = $1;
2735 CHECK_FOR_ERROR
2736 }
2737 | /* empty */ { // Empty space between instruction lists
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002738 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 CHECK_FOR_ERROR
2740 }
2741 | LABELSTR { // Labelled (named) basic block
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002742 $$ = defineBBVal(ValID::createLocalName(*$1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002743 delete $1;
2744 CHECK_FOR_ERROR
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00002745
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002746 };
2747
Eric Christopher329d2672008-09-24 04:55:49 +00002748BBTerminatorInst :
Devang Patelbf507402008-02-20 22:40:23 +00002749 RET ReturnedVal { // Return with a result...
Devang Patelda2c8d52008-02-26 22:17:48 +00002750 ValueList &VL = *$2;
Devang Patelb4851dc2008-02-26 23:19:08 +00002751 assert(!VL.empty() && "Invalid ret operands!");
Dan Gohmanb94a0ba2008-07-23 00:54:54 +00002752 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2753 if (VL.size() > 1 ||
2754 (isa<StructType>(ReturnType) &&
2755 (VL.empty() || VL[0]->getType() != ReturnType))) {
2756 Value *RV = UndefValue::get(ReturnType);
2757 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2758 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2759 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2760 RV = I;
2761 }
2762 $$ = ReturnInst::Create(RV);
2763 } else {
2764 $$ = ReturnInst::Create(VL[0]);
2765 }
Devang Patelbf507402008-02-20 22:40:23 +00002766 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002767 CHECK_FOR_ERROR
2768 }
2769 | RET VOID { // Return with no result...
Gabor Greif89f01162008-04-06 23:07:54 +00002770 $$ = ReturnInst::Create();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 CHECK_FOR_ERROR
2772 }
2773 | BR LABEL ValueRef { // Unconditional Branch...
2774 BasicBlock* tmpBB = getBBVal($3);
2775 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002776 $$ = BranchInst::Create(tmpBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 } // Conditional Branch...
Eric Christopher329d2672008-09-24 04:55:49 +00002778 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
Dan Gohmane5febe42008-05-31 00:58:22 +00002779 if (cast<IntegerType>($2)->getBitWidth() != 1)
2780 GEN_ERROR("Branch condition must have type i1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002781 BasicBlock* tmpBBA = getBBVal($6);
2782 CHECK_FOR_ERROR
2783 BasicBlock* tmpBBB = getBBVal($9);
2784 CHECK_FOR_ERROR
2785 Value* tmpVal = getVal(Type::Int1Ty, $3);
2786 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002787 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788 }
2789 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2790 Value* tmpVal = getVal($2, $3);
2791 CHECK_FOR_ERROR
2792 BasicBlock* tmpBB = getBBVal($6);
2793 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002794 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795 $$ = S;
2796
2797 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2798 E = $8->end();
2799 for (; I != E; ++I) {
2800 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2801 S->addCase(CI, I->second);
2802 else
2803 GEN_ERROR("Switch case is constant, but not a simple integer");
2804 }
2805 delete $8;
2806 CHECK_FOR_ERROR
2807 }
2808 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2809 Value* tmpVal = getVal($2, $3);
2810 CHECK_FOR_ERROR
2811 BasicBlock* tmpBB = getBBVal($6);
2812 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00002813 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002814 $$ = S;
2815 CHECK_FOR_ERROR
2816 }
Dale Johannesencfb19e62007-11-05 21:20:28 +00002817 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002818 TO LABEL ValueRef UNWIND LABEL ValueRef {
2819
2820 // Handle the short syntax
2821 const PointerType *PFTy = 0;
2822 const FunctionType *Ty = 0;
2823 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2824 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2825 // Pull out the types of all of the arguments...
2826 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00002827 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002828 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002829 const Type *Ty = I->Val->getType();
2830 if (Ty == Type::VoidTy)
2831 GEN_ERROR("Short call syntax cannot be used with varargs");
2832 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002833 }
Eric Christopher329d2672008-09-24 04:55:49 +00002834
Chris Lattner73de3c02008-04-23 05:37:08 +00002835 if (!FunctionType::isValidReturnType(*$3))
2836 GEN_ERROR("Invalid result type for LLVM function");
2837
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002838 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00002839 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 }
2841
2842 delete $3;
2843
2844 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2845 CHECK_FOR_ERROR
2846 BasicBlock *Normal = getBBVal($11);
2847 CHECK_FOR_ERROR
2848 BasicBlock *Except = getBBVal($14);
2849 CHECK_FOR_ERROR
2850
Devang Pateld222f862008-09-25 21:00:45 +00002851 SmallVector<AttributeWithIndex, 8> Attrs;
Devang Patelf2a4a922008-09-26 22:53:05 +00002852 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2853 //attributes.
2854 Attributes RetAttrs = 0;
2855 if ($8 != Attribute::None) {
2856 if ($8 & Attribute::ZExt) {
2857 RetAttrs = RetAttrs | Attribute::ZExt;
2858 $8 = $8 ^ Attribute::ZExt;
2859 }
2860 if ($8 & Attribute::SExt) {
2861 RetAttrs = RetAttrs | Attribute::SExt;
2862 $8 = $8 ^ Attribute::SExt;
2863 }
2864 if ($8 & Attribute::InReg) {
2865 RetAttrs = RetAttrs | Attribute::InReg;
2866 $8 = $8 ^ Attribute::InReg;
2867 }
2868 if (RetAttrs != Attribute::None)
2869 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2870 }
2871
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002872 // Check the arguments
2873 ValueList Args;
2874 if ($6->empty()) { // Has no arguments?
2875 // Make sure no arguments is a good thing!
2876 if (Ty->getNumParams() != 0)
2877 GEN_ERROR("No arguments passed to a function that "
2878 "expects arguments");
2879 } else { // Has arguments?
2880 // Loop through FunctionType's arguments and ensure they are specified
2881 // correctly!
2882 FunctionType::param_iterator I = Ty->param_begin();
2883 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00002884 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002885 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002887 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 if (ArgI->Val->getType() != *I)
2889 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2890 (*I)->getDescription() + "'");
2891 Args.push_back(ArgI->Val);
Devang Pateld222f862008-09-25 21:00:45 +00002892 if (ArgI->Attrs != Attribute::None)
2893 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002894 }
2895
2896 if (Ty->isVarArg()) {
2897 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00002898 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899 Args.push_back(ArgI->Val); // push the remaining varargs
Devang Pateld222f862008-09-25 21:00:45 +00002900 if (ArgI->Attrs != Attribute::None)
2901 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
Chris Lattner59363a32008-02-19 04:36:25 +00002902 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 } else if (I != E || ArgI != ArgE)
2904 GEN_ERROR("Invalid number of parameters detected");
2905 }
Devang Patelf2a4a922008-09-26 22:53:05 +00002906 if ($8 != Attribute::None)
2907 Attrs.push_back(AttributeWithIndex::get(~0, $8));
Devang Pateld222f862008-09-25 21:00:45 +00002908 AttrListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002909 if (!Attrs.empty())
Devang Pateld222f862008-09-25 21:00:45 +00002910 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002911
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002912 // Create the InvokeInst
Dan Gohman8055f772008-05-15 19:50:34 +00002913 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2914 Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002915 II->setCallingConv($2);
Devang Pateld222f862008-09-25 21:00:45 +00002916 II->setAttributes(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917 $$ = II;
2918 delete $6;
2919 CHECK_FOR_ERROR
2920 }
2921 | UNWIND {
2922 $$ = new UnwindInst();
2923 CHECK_FOR_ERROR
2924 }
2925 | UNREACHABLE {
2926 $$ = new UnreachableInst();
2927 CHECK_FOR_ERROR
2928 };
2929
2930
2931
2932JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2933 $$ = $1;
2934 Constant *V = cast<Constant>(getExistingVal($2, $3));
2935 CHECK_FOR_ERROR
2936 if (V == 0)
2937 GEN_ERROR("May only switch on a constant pool value");
2938
2939 BasicBlock* tmpBB = getBBVal($6);
2940 CHECK_FOR_ERROR
2941 $$->push_back(std::make_pair(V, tmpBB));
2942 }
2943 | IntType ConstValueRef ',' LABEL ValueRef {
2944 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2945 Constant *V = cast<Constant>(getExistingVal($1, $2));
2946 CHECK_FOR_ERROR
2947
2948 if (V == 0)
2949 GEN_ERROR("May only switch on a constant pool value");
2950
2951 BasicBlock* tmpBB = getBBVal($5);
2952 CHECK_FOR_ERROR
Eric Christopher329d2672008-09-24 04:55:49 +00002953 $$->push_back(std::make_pair(V, tmpBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002954 };
2955
2956Inst : OptLocalAssign InstVal {
2957 // Is this definition named?? if so, assign the name...
2958 setValueName($2, $1);
2959 CHECK_FOR_ERROR
2960 InsertValue($2);
2961 $$ = $2;
2962 CHECK_FOR_ERROR
2963 };
2964
Chris Lattner906773a2008-08-29 17:20:18 +00002965Inst : LocalNumber InstVal {
2966 CHECK_FOR_ERROR
2967 int ValNum = InsertValue($2);
Eric Christopher329d2672008-09-24 04:55:49 +00002968
Chris Lattner906773a2008-08-29 17:20:18 +00002969 if (ValNum != (int)$1)
2970 GEN_ERROR("Result value number %" + utostr($1) +
2971 " is incorrect, expected %" + utostr((unsigned)ValNum));
2972
2973 $$ = $2;
2974 CHECK_FOR_ERROR
2975 };
2976
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977
2978PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2979 if (!UpRefs.empty())
2980 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2981 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2982 Value* tmpVal = getVal(*$1, $3);
2983 CHECK_FOR_ERROR
2984 BasicBlock* tmpBB = getBBVal($5);
2985 CHECK_FOR_ERROR
2986 $$->push_back(std::make_pair(tmpVal, tmpBB));
2987 delete $1;
2988 }
2989 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2990 $$ = $1;
2991 Value* tmpVal = getVal($1->front().first->getType(), $4);
2992 CHECK_FOR_ERROR
2993 BasicBlock* tmpBB = getBBVal($6);
2994 CHECK_FOR_ERROR
2995 $1->push_back(std::make_pair(tmpVal, tmpBB));
2996 };
2997
2998
Devang Pateld222f862008-09-25 21:00:45 +00002999ParamList : Types OptAttributes ValueRef OptAttributes {
3000 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001 if (!UpRefs.empty())
3002 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
3003 // Used for call and invoke instructions
Dale Johannesencfb19e62007-11-05 21:20:28 +00003004 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003005 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003006 $$->push_back(E);
3007 delete $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003008 CHECK_FOR_ERROR
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009 }
Devang Pateld222f862008-09-25 21:00:45 +00003010 | LABEL OptAttributes ValueRef OptAttributes {
3011 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00003012 // Labels are only valid in ASMs
3013 $$ = new ParamList();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003014 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
Dale Johannesencfb19e62007-11-05 21:20:28 +00003015 $$->push_back(E);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003016 CHECK_FOR_ERROR
Dale Johannesencfb19e62007-11-05 21:20:28 +00003017 }
Devang Pateld222f862008-09-25 21:00:45 +00003018 | ParamList ',' Types OptAttributes ValueRef OptAttributes {
3019 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 if (!UpRefs.empty())
3021 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3022 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003023 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003024 $$->push_back(E);
3025 delete $3;
3026 CHECK_FOR_ERROR
3027 }
Devang Pateld222f862008-09-25 21:00:45 +00003028 | ParamList ',' LABEL OptAttributes ValueRef OptAttributes {
3029 // FIXME: Remove trailing OptAttributes in LLVM 3.0, it was a mistake in 2.0
Dale Johannesencfb19e62007-11-05 21:20:28 +00003030 $$ = $1;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003031 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
Dale Johannesencfb19e62007-11-05 21:20:28 +00003032 $$->push_back(E);
3033 CHECK_FOR_ERROR
3034 }
3035 | /*empty*/ { $$ = new ParamList(); };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036
3037IndexList // Used for gep instructions and constant expressions
3038 : /*empty*/ { $$ = new std::vector<Value*>(); }
3039 | IndexList ',' ResolvedVal {
3040 $$ = $1;
3041 $$->push_back($3);
3042 CHECK_FOR_ERROR
3043 }
3044 ;
3045
Dan Gohmane5febe42008-05-31 00:58:22 +00003046ConstantIndexList // Used for insertvalue and extractvalue instructions
3047 : ',' EUINT64VAL {
3048 $$ = new std::vector<unsigned>();
3049 if ((unsigned)$2 != $2)
3050 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
3051 $$->push_back($2);
3052 }
3053 | ConstantIndexList ',' EUINT64VAL {
3054 $$ = $1;
3055 if ((unsigned)$3 != $3)
3056 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
3057 $$->push_back($3);
3058 CHECK_FOR_ERROR
3059 }
3060 ;
3061
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003062OptTailCall : TAIL CALL {
3063 $$ = true;
3064 CHECK_FOR_ERROR
3065 }
3066 | CALL {
3067 $$ = false;
3068 CHECK_FOR_ERROR
3069 };
3070
3071InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
3072 if (!UpRefs.empty())
3073 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
Eric Christopher329d2672008-09-24 04:55:49 +00003074 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 !isa<VectorType>((*$2).get()))
3076 GEN_ERROR(
3077 "Arithmetic operator requires integer, FP, or packed operands");
Eric Christopher329d2672008-09-24 04:55:49 +00003078 Value* val1 = getVal(*$2, $3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003079 CHECK_FOR_ERROR
3080 Value* val2 = getVal(*$2, $5);
3081 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003082 $$ = BinaryOperator::Create($1, val1, val2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003083 if ($$ == 0)
3084 GEN_ERROR("binary operator returned null");
3085 delete $2;
3086 }
3087 | LogicalOps Types ValueRef ',' ValueRef {
3088 if (!UpRefs.empty())
3089 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3090 if (!(*$2)->isInteger()) {
Nate Begemanbb1ce942008-07-29 15:49:41 +00003091 if (!isa<VectorType>($2->get()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003092 !cast<VectorType>($2->get())->getElementType()->isInteger())
3093 GEN_ERROR("Logical operator requires integral operands");
3094 }
3095 Value* tmpVal1 = getVal(*$2, $3);
3096 CHECK_FOR_ERROR
3097 Value* tmpVal2 = getVal(*$2, $5);
3098 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003099 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003100 if ($$ == 0)
3101 GEN_ERROR("binary operator returned null");
3102 delete $2;
3103 }
3104 | ICMP IPredicates Types ValueRef ',' ValueRef {
3105 if (!UpRefs.empty())
3106 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 Value* tmpVal1 = getVal(*$3, $4);
3108 CHECK_FOR_ERROR
3109 Value* tmpVal2 = getVal(*$3, $6);
3110 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003111 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112 if ($$ == 0)
3113 GEN_ERROR("icmp operator returned null");
3114 delete $3;
3115 }
3116 | FCMP FPredicates Types ValueRef ',' ValueRef {
3117 if (!UpRefs.empty())
3118 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003119 Value* tmpVal1 = getVal(*$3, $4);
3120 CHECK_FOR_ERROR
3121 Value* tmpVal2 = getVal(*$3, $6);
3122 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003123 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003124 if ($$ == 0)
3125 GEN_ERROR("fcmp operator returned null");
3126 delete $3;
3127 }
Nate Begeman646fa482008-05-12 19:01:56 +00003128 | VICMP IPredicates Types ValueRef ',' ValueRef {
3129 if (!UpRefs.empty())
3130 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3131 if (!isa<VectorType>((*$3).get()))
3132 GEN_ERROR("Scalar types not supported by vicmp instruction");
3133 Value* tmpVal1 = getVal(*$3, $4);
3134 CHECK_FOR_ERROR
3135 Value* tmpVal2 = getVal(*$3, $6);
3136 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003137 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Nate Begeman646fa482008-05-12 19:01:56 +00003138 if ($$ == 0)
Dan Gohman181f4e42008-09-09 01:13:24 +00003139 GEN_ERROR("vicmp operator returned null");
Nate Begeman646fa482008-05-12 19:01:56 +00003140 delete $3;
3141 }
3142 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3143 if (!UpRefs.empty())
3144 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3145 if (!isa<VectorType>((*$3).get()))
3146 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3147 Value* tmpVal1 = getVal(*$3, $4);
3148 CHECK_FOR_ERROR
3149 Value* tmpVal2 = getVal(*$3, $6);
3150 CHECK_FOR_ERROR
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003151 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
Nate Begeman646fa482008-05-12 19:01:56 +00003152 if ($$ == 0)
Dan Gohman181f4e42008-09-09 01:13:24 +00003153 GEN_ERROR("vfcmp operator returned null");
Nate Begeman646fa482008-05-12 19:01:56 +00003154 delete $3;
3155 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 | CastOps ResolvedVal TO Types {
3157 if (!UpRefs.empty())
3158 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3159 Value* Val = $2;
3160 const Type* DestTy = $4->get();
3161 if (!CastInst::castIsValid($1, Val, DestTy))
3162 GEN_ERROR("invalid cast opcode for cast from '" +
3163 Val->getType()->getDescription() + "' to '" +
Eric Christopher329d2672008-09-24 04:55:49 +00003164 DestTy->getDescription() + "'");
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003165 $$ = CastInst::Create($1, Val, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003166 delete $4;
3167 }
3168 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Dan Gohman181f4e42008-09-09 01:13:24 +00003169 if (isa<VectorType>($2->getType())) {
3170 // vector select
3171 if (!isa<VectorType>($4->getType())
3172 || !isa<VectorType>($6->getType()) )
3173 GEN_ERROR("vector select value types must be vector types");
3174 const VectorType* cond_type = cast<VectorType>($2->getType());
3175 const VectorType* select_type = cast<VectorType>($4->getType());
3176 if (cond_type->getElementType() != Type::Int1Ty)
3177 GEN_ERROR("vector select condition element type must be boolean");
3178 if (cond_type->getNumElements() != select_type->getNumElements())
3179 GEN_ERROR("vector select number of elements must be the same");
3180 } else {
3181 if ($2->getType() != Type::Int1Ty)
3182 GEN_ERROR("select condition must be boolean");
3183 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 if ($4->getType() != $6->getType())
Dan Gohman181f4e42008-09-09 01:13:24 +00003185 GEN_ERROR("select value types must match");
Gabor Greif89f01162008-04-06 23:07:54 +00003186 $$ = SelectInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003187 CHECK_FOR_ERROR
3188 }
3189 | VAARG ResolvedVal ',' Types {
3190 if (!UpRefs.empty())
3191 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3192 $$ = new VAArgInst($2, *$4);
3193 delete $4;
3194 CHECK_FOR_ERROR
3195 }
3196 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3197 if (!ExtractElementInst::isValidOperands($2, $4))
3198 GEN_ERROR("Invalid extractelement operands");
3199 $$ = new ExtractElementInst($2, $4);
3200 CHECK_FOR_ERROR
3201 }
3202 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3203 if (!InsertElementInst::isValidOperands($2, $4, $6))
3204 GEN_ERROR("Invalid insertelement operands");
Gabor Greif89f01162008-04-06 23:07:54 +00003205 $$ = InsertElementInst::Create($2, $4, $6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003206 CHECK_FOR_ERROR
3207 }
3208 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3209 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3210 GEN_ERROR("Invalid shufflevector operands");
3211 $$ = new ShuffleVectorInst($2, $4, $6);
3212 CHECK_FOR_ERROR
3213 }
3214 | PHI_TOK PHIList {
3215 const Type *Ty = $2->front().first->getType();
3216 if (!Ty->isFirstClassType())
3217 GEN_ERROR("PHI node operands must be of first class type");
Gabor Greif89f01162008-04-06 23:07:54 +00003218 $$ = PHINode::Create(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 ((PHINode*)$$)->reserveOperandSpace($2->size());
3220 while ($2->begin() != $2->end()) {
Eric Christopher329d2672008-09-24 04:55:49 +00003221 if ($2->front().first->getType() != Ty)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003222 GEN_ERROR("All elements of a PHI node must be of the same type");
3223 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3224 $2->pop_front();
3225 }
3226 delete $2; // Free the list...
3227 CHECK_FOR_ERROR
3228 }
Eric Christopher329d2672008-09-24 04:55:49 +00003229 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003230 OptFuncAttrs {
3231
3232 // Handle the short syntax
3233 const PointerType *PFTy = 0;
3234 const FunctionType *Ty = 0;
3235 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3236 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3237 // Pull out the types of all of the arguments...
3238 std::vector<const Type*> ParamTypes;
Dale Johannesencfb19e62007-11-05 21:20:28 +00003239 ParamList::iterator I = $6->begin(), E = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003240 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003241 const Type *Ty = I->Val->getType();
3242 if (Ty == Type::VoidTy)
3243 GEN_ERROR("Short call syntax cannot be used with varargs");
3244 ParamTypes.push_back(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003245 }
Chris Lattner73de3c02008-04-23 05:37:08 +00003246
3247 if (!FunctionType::isValidReturnType(*$3))
3248 GEN_ERROR("Invalid result type for LLVM function");
3249
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003250 Ty = FunctionType::get($3->get(), ParamTypes, false);
Christopher Lambfb623c62007-12-17 01:17:35 +00003251 PFTy = PointerType::getUnqual(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003252 }
3253
3254 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3255 CHECK_FOR_ERROR
3256
3257 // Check for call to invalid intrinsic to avoid crashing later.
3258 if (Function *theF = dyn_cast<Function>(V)) {
3259 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3260 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3261 !theF->getIntrinsicID(true))
3262 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3263 theF->getName() + "'");
3264 }
3265
Devang Pateld222f862008-09-25 21:00:45 +00003266 // Set up the Attributes for the function
3267 SmallVector<AttributeWithIndex, 8> Attrs;
Devang Patelf2a4a922008-09-26 22:53:05 +00003268 //FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
3269 //attributes.
3270 Attributes RetAttrs = 0;
Devang Patelf2a4a922008-09-26 22:53:05 +00003271 if ($8 != Attribute::None) {
3272 if ($8 & Attribute::ZExt) {
3273 RetAttrs = RetAttrs | Attribute::ZExt;
3274 $8 = $8 ^ Attribute::ZExt;
3275 }
3276 if ($8 & Attribute::SExt) {
3277 RetAttrs = RetAttrs | Attribute::SExt;
3278 $8 = $8 ^ Attribute::SExt;
3279 }
3280 if ($8 & Attribute::InReg) {
3281 RetAttrs = RetAttrs | Attribute::InReg;
3282 $8 = $8 ^ Attribute::InReg;
3283 }
3284 if (RetAttrs != Attribute::None)
3285 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3286 }
3287
Eric Christopher329d2672008-09-24 04:55:49 +00003288 // Check the arguments
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003289 ValueList Args;
3290 if ($6->empty()) { // Has no arguments?
3291 // Make sure no arguments is a good thing!
3292 if (Ty->getNumParams() != 0)
3293 GEN_ERROR("No arguments passed to a function that "
3294 "expects arguments");
3295 } else { // Has arguments?
3296 // Loop through FunctionType's arguments and ensure they are specified
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003297 // correctly. Also, gather any parameter attributes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003298 FunctionType::param_iterator I = Ty->param_begin();
3299 FunctionType::param_iterator E = Ty->param_end();
Dale Johannesencfb19e62007-11-05 21:20:28 +00003300 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003301 unsigned index = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003303 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003304 if (ArgI->Val->getType() != *I)
3305 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3306 (*I)->getDescription() + "'");
3307 Args.push_back(ArgI->Val);
Devang Pateld222f862008-09-25 21:00:45 +00003308 if (ArgI->Attrs != Attribute::None)
3309 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003310 }
3311 if (Ty->isVarArg()) {
3312 if (I == E)
Chris Lattner59363a32008-02-19 04:36:25 +00003313 for (; ArgI != ArgE; ++ArgI, ++index) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003314 Args.push_back(ArgI->Val); // push the remaining varargs
Devang Pateld222f862008-09-25 21:00:45 +00003315 if (ArgI->Attrs != Attribute::None)
3316 Attrs.push_back(AttributeWithIndex::get(index, ArgI->Attrs));
Chris Lattner59363a32008-02-19 04:36:25 +00003317 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318 } else if (I != E || ArgI != ArgE)
3319 GEN_ERROR("Invalid number of parameters detected");
3320 }
Devang Patelf2a4a922008-09-26 22:53:05 +00003321 if ($8 != Attribute::None)
3322 Attrs.push_back(AttributeWithIndex::get(~0, $8));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003323
Devang Pateld222f862008-09-25 21:00:45 +00003324 // Finish off the Attributes and check them
3325 AttrListPtr PAL;
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003326 if (!Attrs.empty())
Devang Pateld222f862008-09-25 21:00:45 +00003327 PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003328
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329 // Create the call node
Gabor Greif89f01162008-04-06 23:07:54 +00003330 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003331 CI->setTailCall($1);
3332 CI->setCallingConv($2);
Devang Pateld222f862008-09-25 21:00:45 +00003333 CI->setAttributes(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003334 $$ = CI;
3335 delete $6;
3336 delete $3;
3337 CHECK_FOR_ERROR
3338 }
3339 | MemoryInst {
3340 $$ = $1;
3341 CHECK_FOR_ERROR
3342 };
3343
3344OptVolatile : VOLATILE {
3345 $$ = true;
3346 CHECK_FOR_ERROR
3347 }
3348 | /* empty */ {
3349 $$ = false;
3350 CHECK_FOR_ERROR
3351 };
3352
3353
3354
3355MemoryInst : MALLOC Types OptCAlign {
3356 if (!UpRefs.empty())
3357 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3358 $$ = new MallocInst(*$2, 0, $3);
3359 delete $2;
3360 CHECK_FOR_ERROR
3361 }
3362 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3363 if (!UpRefs.empty())
3364 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00003365 if ($4 != Type::Int32Ty)
3366 GEN_ERROR("Malloc array size is not a 32-bit integer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003367 Value* tmpVal = getVal($4, $5);
3368 CHECK_FOR_ERROR
3369 $$ = new MallocInst(*$2, tmpVal, $6);
3370 delete $2;
3371 }
3372 | ALLOCA Types OptCAlign {
3373 if (!UpRefs.empty())
3374 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3375 $$ = new AllocaInst(*$2, 0, $3);
3376 delete $2;
3377 CHECK_FOR_ERROR
3378 }
3379 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3380 if (!UpRefs.empty())
3381 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
Dan Gohmane5febe42008-05-31 00:58:22 +00003382 if ($4 != Type::Int32Ty)
3383 GEN_ERROR("Alloca array size is not a 32-bit integer!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 Value* tmpVal = getVal($4, $5);
3385 CHECK_FOR_ERROR
3386 $$ = new AllocaInst(*$2, tmpVal, $6);
3387 delete $2;
3388 }
3389 | FREE ResolvedVal {
3390 if (!isa<PointerType>($2->getType()))
Eric Christopher329d2672008-09-24 04:55:49 +00003391 GEN_ERROR("Trying to free nonpointer type " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003392 $2->getType()->getDescription() + "");
3393 $$ = new FreeInst($2);
3394 CHECK_FOR_ERROR
3395 }
3396
3397 | OptVolatile LOAD Types ValueRef OptCAlign {
3398 if (!UpRefs.empty())
3399 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3400 if (!isa<PointerType>($3->get()))
3401 GEN_ERROR("Can't load from nonpointer type: " +
3402 (*$3)->getDescription());
3403 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3404 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3405 (*$3)->getDescription());
3406 Value* tmpVal = getVal(*$3, $4);
3407 CHECK_FOR_ERROR
3408 $$ = new LoadInst(tmpVal, "", $1, $5);
3409 delete $3;
3410 }
3411 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3412 if (!UpRefs.empty())
3413 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3414 const PointerType *PT = dyn_cast<PointerType>($5->get());
3415 if (!PT)
3416 GEN_ERROR("Can't store to a nonpointer type: " +
3417 (*$5)->getDescription());
3418 const Type *ElTy = PT->getElementType();
3419 if (ElTy != $3->getType())
3420 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3421 "' into space of type '" + ElTy->getDescription() + "'");
3422
3423 Value* tmpVal = getVal(*$5, $6);
3424 CHECK_FOR_ERROR
3425 $$ = new StoreInst($3, tmpVal, $1, $7);
3426 delete $5;
3427 }
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003428 | GETRESULT Types ValueRef ',' EUINT64VAL {
Dan Gohmanb94a0ba2008-07-23 00:54:54 +00003429 if (!UpRefs.empty())
3430 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3431 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3432 GEN_ERROR("getresult insn requires an aggregate operand");
3433 if (!ExtractValueInst::getIndexedType(*$2, $5))
3434 GEN_ERROR("Invalid getresult index for type '" +
3435 (*$2)->getDescription()+ "'");
3436
3437 Value *tmpVal = getVal(*$2, $3);
Devang Patel3b8849c2008-02-19 22:27:01 +00003438 CHECK_FOR_ERROR
Dan Gohmanb94a0ba2008-07-23 00:54:54 +00003439 $$ = ExtractValueInst::Create(tmpVal, $5);
3440 delete $2;
Devang Patel3b8849c2008-02-19 22:27:01 +00003441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 | GETELEMENTPTR Types ValueRef IndexList {
3443 if (!UpRefs.empty())
3444 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3445 if (!isa<PointerType>($2->get()))
3446 GEN_ERROR("getelementptr insn requires pointer operand");
3447
Dan Gohman8055f772008-05-15 19:50:34 +00003448 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003449 GEN_ERROR("Invalid getelementptr indices for type '" +
3450 (*$2)->getDescription()+ "'");
3451 Value* tmpVal = getVal(*$2, $3);
3452 CHECK_FOR_ERROR
Gabor Greif89f01162008-04-06 23:07:54 +00003453 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
Eric Christopher329d2672008-09-24 04:55:49 +00003454 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455 delete $4;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003456 }
Dan Gohmane5febe42008-05-31 00:58:22 +00003457 | EXTRACTVALUE Types ValueRef ConstantIndexList {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003458 if (!UpRefs.empty())
3459 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3460 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3461 GEN_ERROR("extractvalue insn requires an aggregate operand");
3462
3463 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3464 GEN_ERROR("Invalid extractvalue indices for type '" +
3465 (*$2)->getDescription()+ "'");
3466 Value* tmpVal = getVal(*$2, $3);
3467 CHECK_FOR_ERROR
3468 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
Eric Christopher329d2672008-09-24 04:55:49 +00003469 delete $2;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003470 delete $4;
3471 }
Dan Gohmane5febe42008-05-31 00:58:22 +00003472 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003473 if (!UpRefs.empty())
3474 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3475 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3476 GEN_ERROR("extractvalue insn requires an aggregate operand");
3477
3478 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3479 GEN_ERROR("Invalid insertvalue indices for type '" +
3480 (*$2)->getDescription()+ "'");
3481 Value* aggVal = getVal(*$2, $3);
3482 Value* tmpVal = getVal(*$5, $6);
3483 CHECK_FOR_ERROR
3484 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
Eric Christopher329d2672008-09-24 04:55:49 +00003485 delete $2;
Dan Gohmane6b1ee62008-05-23 01:55:30 +00003486 delete $5;
3487 delete $7;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003488 };
3489
3490
3491%%
3492
3493// common code from the two 'RunVMAsmParser' functions
3494static Module* RunParser(Module * M) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 CurModule.CurrentModule = M;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003496 // Check to make sure the parser succeeded
3497 if (yyparse()) {
3498 if (ParserResult)
3499 delete ParserResult;
3500 return 0;
3501 }
3502
3503 // Emit an error if there are any unresolved types left.
3504 if (!CurModule.LateResolveTypes.empty()) {
3505 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3506 if (DID.Type == ValID::LocalName) {
3507 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3508 } else {
3509 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3510 }
3511 if (ParserResult)
3512 delete ParserResult;
3513 return 0;
3514 }
3515
3516 // Emit an error if there are any unresolved values left.
3517 if (!CurModule.LateResolveValues.empty()) {
3518 Value *V = CurModule.LateResolveValues.back();
3519 std::map<Value*, std::pair<ValID, int> >::iterator I =
3520 CurModule.PlaceHolderInfo.find(V);
3521
3522 if (I != CurModule.PlaceHolderInfo.end()) {
3523 ValID &DID = I->second.first;
3524 if (DID.Type == ValID::LocalName) {
3525 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3526 } else {
3527 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3528 }
3529 if (ParserResult)
3530 delete ParserResult;
3531 return 0;
3532 }
3533 }
3534
3535 // Check to make sure that parsing produced a result
3536 if (!ParserResult)
3537 return 0;
3538
3539 // Reset ParserResult variable while saving its value for the result.
3540 Module *Result = ParserResult;
3541 ParserResult = 0;
3542
3543 return Result;
3544}
3545
3546void llvm::GenerateError(const std::string &message, int LineNo) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003547 if (LineNo == -1) LineNo = LLLgetLineNo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003548 // TODO: column number in exception
3549 if (TheParseError)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003550 TheParseError->setError(LLLgetFilename(), message, LineNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003551 TriggerError = 1;
3552}
3553
3554int yyerror(const char *ErrorMsg) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003555 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003556 std::string errMsg = where + "error: " + std::string(ErrorMsg);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003557 if (yychar != YYEMPTY && yychar != 0) {
3558 errMsg += " while reading token: '";
Eric Christopher329d2672008-09-24 04:55:49 +00003559 errMsg += std::string(LLLgetTokenStart(),
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003560 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3561 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003562 GenerateError(errMsg);
3563 return 0;
3564}