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