blob: f09b99a5f0383de7414a2c170855069712eca95a [file] [log] [blame]
Chris Lattnerf20e61f2006-02-15 07:22:58 +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/SymbolTable.h"
21#include "llvm/Assembly/AutoUpgrade.h"
22#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/MathExtras.h"
25#include <algorithm>
26#include <iostream>
27#include <list>
28#include <utility>
29
Reid Spencer713eedc2006-08-18 08:43:06 +000030static bool TriggerError = false;
31#define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYERROR; } }
32
33#define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
34
Chris Lattnerf20e61f2006-02-15 07:22:58 +000035int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
36int yylex(); // declaration" of xxx warnings.
37int yyparse();
38
39namespace llvm {
40 std::string CurFilename;
41}
42using namespace llvm;
43
44static Module *ParserResult;
45
46// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
47// relating to upreferences in the input stream.
48//
49//#define DEBUG_UPREFS 1
50#ifdef DEBUG_UPREFS
51#define UR_OUT(X) std::cerr << X
52#else
53#define UR_OUT(X)
54#endif
55
56#define YYERROR_VERBOSE 1
57
58static bool ObsoleteVarArgs;
59static bool NewVarArgs;
60static BasicBlock *CurBB;
61static GlobalVariable *CurGV;
62
63
64// This contains info used when building the body of a function. It is
65// destroyed when the function is completed.
66//
67typedef std::vector<Value *> ValueList; // Numbered defs
68static void
69ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
70 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
71
72static struct PerModuleInfo {
73 Module *CurrentModule;
74 std::map<const Type *, ValueList> Values; // Module level numbered definitions
75 std::map<const Type *,ValueList> LateResolveValues;
76 std::vector<PATypeHolder> Types;
77 std::map<ValID, PATypeHolder> LateResolveTypes;
78
79 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
Chris Lattner7aa45902006-06-21 16:53:00 +000080 /// how they were referenced and on which line of the input they came from so
Chris Lattnerf20e61f2006-02-15 07:22:58 +000081 /// that we can resolve them later and print error messages as appropriate.
82 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
83
84 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
85 // references to global values. Global values may be referenced before they
86 // are defined, and if so, the temporary object that they represent is held
87 // here. This is used for forward references of GlobalValues.
88 //
89 typedef std::map<std::pair<const PointerType *,
90 ValID>, GlobalValue*> GlobalRefsType;
91 GlobalRefsType GlobalRefs;
92
93 void ModuleDone() {
94 // If we could not resolve some functions at function compilation time
95 // (calls to functions before they are defined), resolve them now... Types
96 // are resolved when the constant pool has been completely parsed.
97 //
98 ResolveDefinitions(LateResolveValues);
99
100 // Check to make sure that all global value forward references have been
101 // resolved!
102 //
103 if (!GlobalRefs.empty()) {
104 std::string UndefinedReferences = "Unresolved global references exist:\n";
105
106 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
107 I != E; ++I) {
108 UndefinedReferences += " " + I->first.first->getDescription() + " " +
109 I->first.second.getName() + "\n";
110 }
Reid Spencer713eedc2006-08-18 08:43:06 +0000111 GenerateError(UndefinedReferences);
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000112 }
113
114 // Look for intrinsic functions and CallInst that need to be upgraded
Chris Lattner9ff96a72006-04-08 01:18:56 +0000115 for (Module::iterator FI = CurrentModule->begin(),
116 FE = CurrentModule->end(); FI != FE; )
Chris Lattneradf5ec62006-03-04 07:53:41 +0000117 UpgradeCallsToIntrinsic(FI++);
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000118
119 Values.clear(); // Clear out function local definitions
120 Types.clear();
121 CurrentModule = 0;
122 }
123
124 // GetForwardRefForGlobal - Check to see if there is a forward reference
125 // for this global. If so, remove it from the GlobalRefs map and return it.
126 // If not, just return null.
127 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
128 // Check to see if there is a forward reference to this global variable...
129 // if there is, eliminate it and patch the reference to use the new def'n.
130 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
131 GlobalValue *Ret = 0;
132 if (I != GlobalRefs.end()) {
133 Ret = I->second;
134 GlobalRefs.erase(I);
135 }
136 return Ret;
137 }
138} CurModule;
139
140static struct PerFunctionInfo {
141 Function *CurrentFunction; // Pointer to current function being created
142
143 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
144 std::map<const Type*, ValueList> LateResolveValues;
145 bool isDeclare; // Is this function a forward declararation?
146
147 /// BBForwardRefs - When we see forward references to basic blocks, keep
148 /// track of them here.
149 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
150 std::vector<BasicBlock*> NumberedBlocks;
151 unsigned NextBBNum;
152
153 inline PerFunctionInfo() {
154 CurrentFunction = 0;
155 isDeclare = false;
156 }
157
158 inline void FunctionStart(Function *M) {
159 CurrentFunction = M;
160 NextBBNum = 0;
161 }
162
163 void FunctionDone() {
164 NumberedBlocks.clear();
165
166 // Any forward referenced blocks left?
167 if (!BBForwardRefs.empty())
Reid Spencer713eedc2006-08-18 08:43:06 +0000168 GenerateError("Undefined reference to label " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000169 BBForwardRefs.begin()->first->getName());
170
171 // Resolve all forward references now.
172 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
173
174 Values.clear(); // Clear out function local definitions
175 CurrentFunction = 0;
176 isDeclare = false;
177 }
178} CurFun; // Info for the current function...
179
180static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
181
182
183//===----------------------------------------------------------------------===//
184// Code to handle definitions of all the types
185//===----------------------------------------------------------------------===//
186
187static int InsertValue(Value *V,
188 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
189 if (V->hasName()) return -1; // Is this a numbered definition?
190
191 // Yes, insert the value into the value table...
192 ValueList &List = ValueTab[V->getType()];
193 List.push_back(V);
194 return List.size()-1;
195}
196
197static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
198 switch (D.Type) {
199 case ValID::NumberVal: // Is it a numbered definition?
200 // Module constants occupy the lowest numbered slots...
201 if ((unsigned)D.Num < CurModule.Types.size())
202 return CurModule.Types[(unsigned)D.Num];
203 break;
204 case ValID::NameVal: // Is it a named definition?
205 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
206 D.destroy(); // Free old strdup'd memory...
207 return N;
208 }
209 break;
210 default:
Reid Spencer713eedc2006-08-18 08:43:06 +0000211 GenerateError("Internal parser error: Invalid symbol type reference!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000212 }
213
214 // If we reached here, we referenced either a symbol that we don't know about
215 // or an id number that hasn't been read yet. We may be referencing something
216 // forward, so just create an entry to be resolved later and get to it...
217 //
218 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
219
220
221 if (inFunctionScope()) {
222 if (D.Type == ValID::NameVal)
Reid Spencer713eedc2006-08-18 08:43:06 +0000223 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000224 else
Reid Spencer713eedc2006-08-18 08:43:06 +0000225 GenerateError("Reference to an undefined type: #" + itostr(D.Num));
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000226 }
227
228 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
229 if (I != CurModule.LateResolveTypes.end())
230 return I->second;
231
232 Type *Typ = OpaqueType::get();
233 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
234 return Typ;
235 }
236
237static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
238 SymbolTable &SymTab =
239 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
240 CurModule.CurrentModule->getSymbolTable();
241 return SymTab.lookup(Ty, Name);
242}
243
244// getValNonImprovising - Look up the value specified by the provided type and
245// the provided ValID. If the value exists and has already been defined, return
246// it. Otherwise return null.
247//
248static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
249 if (isa<FunctionType>(Ty))
Reid Spencer713eedc2006-08-18 08:43:06 +0000250 GenerateError("Functions are not values and "
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000251 "must be referenced as pointers");
252
253 switch (D.Type) {
254 case ValID::NumberVal: { // Is it a numbered definition?
255 unsigned Num = (unsigned)D.Num;
256
257 // Module constants occupy the lowest numbered slots...
258 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
259 if (VI != CurModule.Values.end()) {
260 if (Num < VI->second.size())
261 return VI->second[Num];
262 Num -= VI->second.size();
263 }
264
265 // Make sure that our type is within bounds
266 VI = CurFun.Values.find(Ty);
267 if (VI == CurFun.Values.end()) return 0;
268
269 // Check that the number is within bounds...
270 if (VI->second.size() <= Num) return 0;
271
272 return VI->second[Num];
273 }
274
275 case ValID::NameVal: { // Is it a named definition?
276 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
277 if (N == 0) return 0;
278
279 D.destroy(); // Free old strdup'd memory...
280 return N;
281 }
282
283 // Check to make sure that "Ty" is an integral type, and that our
284 // value will fit into the specified type...
285 case ValID::ConstSIntVal: // Is it a constant pool reference??
286 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
Reid Spencer713eedc2006-08-18 08:43:06 +0000287 GenerateError("Signed integral constant '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000288 itostr(D.ConstPool64) + "' is invalid for type '" +
289 Ty->getDescription() + "'!");
290 return ConstantSInt::get(Ty, D.ConstPool64);
291
292 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
293 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
294 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
Reid Spencer713eedc2006-08-18 08:43:06 +0000295 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000296 "' is invalid or out of range!");
297 } else { // This is really a signed reference. Transmogrify.
298 return ConstantSInt::get(Ty, D.ConstPool64);
299 }
300 } else {
301 return ConstantUInt::get(Ty, D.UConstPool64);
302 }
303
304 case ValID::ConstFPVal: // Is it a floating point const pool reference?
305 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
Reid Spencer713eedc2006-08-18 08:43:06 +0000306 GenerateError("FP constant invalid for type!!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000307 return ConstantFP::get(Ty, D.ConstPoolFP);
308
309 case ValID::ConstNullVal: // Is it a null value?
310 if (!isa<PointerType>(Ty))
Reid Spencer713eedc2006-08-18 08:43:06 +0000311 GenerateError("Cannot create a a non pointer null!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000312 return ConstantPointerNull::get(cast<PointerType>(Ty));
313
314 case ValID::ConstUndefVal: // Is it an undef value?
315 return UndefValue::get(Ty);
316
317 case ValID::ConstZeroVal: // Is it a zero value?
318 return Constant::getNullValue(Ty);
319
320 case ValID::ConstantVal: // Fully resolved constant?
321 if (D.ConstantValue->getType() != Ty)
Reid Spencer713eedc2006-08-18 08:43:06 +0000322 GenerateError("Constant expression type different from required type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000323 return D.ConstantValue;
324
325 case ValID::InlineAsmVal: { // Inline asm expression
326 const PointerType *PTy = dyn_cast<PointerType>(Ty);
327 const FunctionType *FTy =
328 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
329 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
Reid Spencer713eedc2006-08-18 08:43:06 +0000330 GenerateError("Invalid type for asm constraint string!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000331 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
332 D.IAD->HasSideEffects);
333 D.destroy(); // Free InlineAsmDescriptor.
334 return IA;
335 }
336 default:
337 assert(0 && "Unhandled case!");
338 return 0;
339 } // End of switch
340
341 assert(0 && "Unhandled case!");
342 return 0;
343}
344
345// getVal - This function is identical to getValNonImprovising, except that if a
346// value is not already defined, it "improvises" by creating a placeholder var
347// that looks and acts just like the requested variable. When the value is
348// defined later, all uses of the placeholder variable are replaced with the
349// real thing.
350//
351static Value *getVal(const Type *Ty, const ValID &ID) {
352 if (Ty == Type::LabelTy)
Reid Spencer713eedc2006-08-18 08:43:06 +0000353 GenerateError("Cannot use a basic block here");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000354
355 // See if the value has already been defined.
356 Value *V = getValNonImprovising(Ty, ID);
357 if (V) return V;
358
359 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
Reid Spencer713eedc2006-08-18 08:43:06 +0000360 GenerateError("Invalid use of a composite type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000361
362 // If we reached here, we referenced either a symbol that we don't know about
363 // or an id number that hasn't been read yet. We may be referencing something
364 // forward, so just create an entry to be resolved later and get to it...
365 //
366 V = new Argument(Ty);
367
368 // Remember where this forward reference came from. FIXME, shouldn't we try
369 // to recycle these things??
370 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
371 llvmAsmlineno)));
372
373 if (inFunctionScope())
374 InsertValue(V, CurFun.LateResolveValues);
375 else
376 InsertValue(V, CurModule.LateResolveValues);
377 return V;
378}
379
380/// getBBVal - This is used for two purposes:
381/// * If isDefinition is true, a new basic block with the specified ID is being
382/// defined.
383/// * If isDefinition is true, this is a reference to a basic block, which may
384/// or may not be a forward reference.
385///
386static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
387 assert(inFunctionScope() && "Can't get basic block at global scope!");
388
389 std::string Name;
390 BasicBlock *BB = 0;
391 switch (ID.Type) {
Reid Spencer713eedc2006-08-18 08:43:06 +0000392 default: GenerateError("Illegal label reference " + ID.getName());
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000393 case ValID::NumberVal: // Is it a numbered definition?
394 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
395 CurFun.NumberedBlocks.resize(ID.Num+1);
396 BB = CurFun.NumberedBlocks[ID.Num];
397 break;
398 case ValID::NameVal: // Is it a named definition?
399 Name = ID.Name;
400 if (Value *N = CurFun.CurrentFunction->
401 getSymbolTable().lookup(Type::LabelTy, Name))
402 BB = cast<BasicBlock>(N);
403 break;
404 }
405
406 // See if the block has already been defined.
407 if (BB) {
408 // If this is the definition of the block, make sure the existing value was
409 // just a forward reference. If it was a forward reference, there will be
410 // an entry for it in the PlaceHolderInfo map.
411 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
412 // The existing value was a definition, not a forward reference.
Reid Spencer713eedc2006-08-18 08:43:06 +0000413 GenerateError("Redefinition of label " + ID.getName());
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000414
415 ID.destroy(); // Free strdup'd memory.
416 return BB;
417 }
418
419 // Otherwise this block has not been seen before.
420 BB = new BasicBlock("", CurFun.CurrentFunction);
421 if (ID.Type == ValID::NameVal) {
422 BB->setName(ID.Name);
423 } else {
424 CurFun.NumberedBlocks[ID.Num] = BB;
425 }
426
427 // If this is not a definition, keep track of it so we can use it as a forward
428 // reference.
429 if (!isDefinition) {
430 // Remember where this forward reference came from.
431 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
432 } else {
433 // The forward declaration could have been inserted anywhere in the
434 // function: insert it into the correct place now.
435 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
436 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
437 }
438 ID.destroy();
439 return BB;
440}
441
442
443//===----------------------------------------------------------------------===//
444// Code to handle forward references in instructions
445//===----------------------------------------------------------------------===//
446//
447// This code handles the late binding needed with statements that reference
448// values not defined yet... for example, a forward branch, or the PHI node for
449// a loop body.
450//
451// This keeps a table (CurFun.LateResolveValues) of all such forward references
452// and back patchs after we are done.
453//
454
455// ResolveDefinitions - If we could not resolve some defs at parsing
456// time (forward branches, phi functions for loops, etc...) resolve the
457// defs now...
458//
459static void
460ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
461 std::map<const Type*,ValueList> *FutureLateResolvers) {
462 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
463 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
464 E = LateResolvers.end(); LRI != E; ++LRI) {
465 ValueList &List = LRI->second;
466 while (!List.empty()) {
467 Value *V = List.back();
468 List.pop_back();
469
470 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
471 CurModule.PlaceHolderInfo.find(V);
472 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
473
474 ValID &DID = PHI->second.first;
475
476 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
477 if (TheRealValue) {
478 V->replaceAllUsesWith(TheRealValue);
479 delete V;
480 CurModule.PlaceHolderInfo.erase(PHI);
481 } else if (FutureLateResolvers) {
482 // Functions have their unresolved items forwarded to the module late
483 // resolver table
484 InsertValue(V, *FutureLateResolvers);
485 } else {
486 if (DID.Type == ValID::NameVal)
Reid Spencer713eedc2006-08-18 08:43:06 +0000487 GenerateError("Reference to an invalid definition: '" +DID.getName()+
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000488 "' of type '" + V->getType()->getDescription() + "'",
489 PHI->second.second);
490 else
Reid Spencer713eedc2006-08-18 08:43:06 +0000491 GenerateError("Reference to an invalid definition: #" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000492 itostr(DID.Num) + " of type '" +
493 V->getType()->getDescription() + "'",
494 PHI->second.second);
495 }
496 }
497 }
498
499 LateResolvers.clear();
500}
501
502// ResolveTypeTo - A brand new type was just declared. This means that (if
503// name is not null) things referencing Name can be resolved. Otherwise, things
504// refering to the number can be resolved. Do this now.
505//
506static void ResolveTypeTo(char *Name, const Type *ToTy) {
507 ValID D;
508 if (Name) D = ValID::create(Name);
509 else D = ValID::create((int)CurModule.Types.size());
510
511 std::map<ValID, PATypeHolder>::iterator I =
512 CurModule.LateResolveTypes.find(D);
513 if (I != CurModule.LateResolveTypes.end()) {
514 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
515 CurModule.LateResolveTypes.erase(I);
516 }
517}
518
519// setValueName - Set the specified value to the name given. The name may be
520// null potentially, in which case this is a noop. The string passed in is
521// assumed to be a malloc'd string buffer, and is free'd by this function.
522//
523static void setValueName(Value *V, char *NameStr) {
524 if (NameStr) {
525 std::string Name(NameStr); // Copy string
526 free(NameStr); // Free old string
527
528 if (V->getType() == Type::VoidTy)
Reid Spencer713eedc2006-08-18 08:43:06 +0000529 GenerateError("Can't assign name '" + Name+"' to value with void type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000530
531 assert(inFunctionScope() && "Must be in function scope!");
532 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
533 if (ST.lookup(V->getType(), Name))
Reid Spencer713eedc2006-08-18 08:43:06 +0000534 GenerateError("Redefinition of value named '" + Name + "' in the '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000535 V->getType()->getDescription() + "' type plane!");
536
537 // Set the name.
538 V->setName(Name);
539 }
540}
541
542/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
543/// this is a declaration, otherwise it is a definition.
544static GlobalVariable *
545ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
546 bool isConstantGlobal, const Type *Ty,
547 Constant *Initializer) {
548 if (isa<FunctionType>(Ty))
Reid Spencer713eedc2006-08-18 08:43:06 +0000549 GenerateError("Cannot declare global vars of function type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000550
551 const PointerType *PTy = PointerType::get(Ty);
552
553 std::string Name;
554 if (NameStr) {
555 Name = NameStr; // Copy string
556 free(NameStr); // Free old string
557 }
558
559 // See if this global value was forward referenced. If so, recycle the
560 // object.
561 ValID ID;
562 if (!Name.empty()) {
563 ID = ValID::create((char*)Name.c_str());
564 } else {
565 ID = ValID::create((int)CurModule.Values[PTy].size());
566 }
567
568 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
569 // Move the global to the end of the list, from whereever it was
570 // previously inserted.
571 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
572 CurModule.CurrentModule->getGlobalList().remove(GV);
573 CurModule.CurrentModule->getGlobalList().push_back(GV);
574 GV->setInitializer(Initializer);
575 GV->setLinkage(Linkage);
576 GV->setConstant(isConstantGlobal);
577 InsertValue(GV, CurModule.Values);
578 return GV;
579 }
580
581 // If this global has a name, check to see if there is already a definition
582 // of this global in the module. If so, merge as appropriate. Note that
583 // this is really just a hack around problems in the CFE. :(
584 if (!Name.empty()) {
585 // We are a simple redefinition of a value, check to see if it is defined
586 // the same as the old one.
587 if (GlobalVariable *EGV =
588 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
589 // We are allowed to redefine a global variable in two circumstances:
590 // 1. If at least one of the globals is uninitialized or
591 // 2. If both initializers have the same value.
592 //
593 if (!EGV->hasInitializer() || !Initializer ||
594 EGV->getInitializer() == Initializer) {
595
596 // Make sure the existing global version gets the initializer! Make
597 // sure that it also gets marked const if the new version is.
598 if (Initializer && !EGV->hasInitializer())
599 EGV->setInitializer(Initializer);
600 if (isConstantGlobal)
601 EGV->setConstant(true);
602 EGV->setLinkage(Linkage);
603 return EGV;
604 }
605
Reid Spencer713eedc2006-08-18 08:43:06 +0000606 GenerateError("Redefinition of global variable named '" + Name +
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000607 "' in the '" + Ty->getDescription() + "' type plane!");
608 }
609 }
610
611 // Otherwise there is no existing GV to use, create one now.
612 GlobalVariable *GV =
613 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
614 CurModule.CurrentModule);
615 InsertValue(GV, CurModule.Values);
616 return GV;
617}
618
619// setTypeName - Set the specified type to the name given. The name may be
620// null potentially, in which case this is a noop. The string passed in is
621// assumed to be a malloc'd string buffer, and is freed by this function.
622//
623// This function returns true if the type has already been defined, but is
624// allowed to be redefined in the specified context. If the name is a new name
625// for the type plane, it is inserted and false is returned.
626static bool setTypeName(const Type *T, char *NameStr) {
627 assert(!inFunctionScope() && "Can't give types function-local names!");
628 if (NameStr == 0) return false;
629
630 std::string Name(NameStr); // Copy string
631 free(NameStr); // Free old string
632
633 // We don't allow assigning names to void type
634 if (T == Type::VoidTy)
Reid Spencer713eedc2006-08-18 08:43:06 +0000635 GenerateError("Can't assign name '" + Name + "' to the void type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000636
637 // Set the type name, checking for conflicts as we do so.
638 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
639
640 if (AlreadyExists) { // Inserting a name that is already defined???
641 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
642 assert(Existing && "Conflict but no matching type?");
643
644 // There is only one case where this is allowed: when we are refining an
645 // opaque type. In this case, Existing will be an opaque type.
646 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
647 // We ARE replacing an opaque type!
648 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
649 return true;
650 }
651
652 // Otherwise, this is an attempt to redefine a type. That's okay if
653 // the redefinition is identical to the original. This will be so if
654 // Existing and T point to the same Type object. In this one case we
655 // allow the equivalent redefinition.
656 if (Existing == T) return true; // Yes, it's equal.
657
658 // Any other kind of (non-equivalent) redefinition is an error.
Reid Spencer713eedc2006-08-18 08:43:06 +0000659 GenerateError("Redefinition of type named '" + Name + "' in the '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000660 T->getDescription() + "' type plane!");
661 }
662
663 return false;
664}
665
666//===----------------------------------------------------------------------===//
667// Code for handling upreferences in type names...
668//
669
670// TypeContains - Returns true if Ty directly contains E in it.
671//
672static bool TypeContains(const Type *Ty, const Type *E) {
673 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
674 E) != Ty->subtype_end();
675}
676
677namespace {
678 struct UpRefRecord {
679 // NestingLevel - The number of nesting levels that need to be popped before
680 // this type is resolved.
681 unsigned NestingLevel;
682
683 // LastContainedTy - This is the type at the current binding level for the
684 // type. Every time we reduce the nesting level, this gets updated.
685 const Type *LastContainedTy;
686
687 // UpRefTy - This is the actual opaque type that the upreference is
688 // represented with.
689 OpaqueType *UpRefTy;
690
691 UpRefRecord(unsigned NL, OpaqueType *URTy)
692 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
693 };
694}
695
696// UpRefs - A list of the outstanding upreferences that need to be resolved.
697static std::vector<UpRefRecord> UpRefs;
698
699/// HandleUpRefs - Every time we finish a new layer of types, this function is
700/// called. It loops through the UpRefs vector, which is a list of the
701/// currently active types. For each type, if the up reference is contained in
702/// the newly completed type, we decrement the level count. When the level
703/// count reaches zero, the upreferenced type is the type that is passed in:
704/// thus we can complete the cycle.
705///
706static PATypeHolder HandleUpRefs(const Type *ty) {
707 if (!ty->isAbstract()) return ty;
708 PATypeHolder Ty(ty);
709 UR_OUT("Type '" << Ty->getDescription() <<
710 "' newly formed. Resolving upreferences.\n" <<
711 UpRefs.size() << " upreferences active!\n");
712
713 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
714 // to zero), we resolve them all together before we resolve them to Ty. At
715 // the end of the loop, if there is anything to resolve to Ty, it will be in
716 // this variable.
717 OpaqueType *TypeToResolve = 0;
718
719 for (unsigned i = 0; i != UpRefs.size(); ++i) {
720 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
721 << UpRefs[i].second->getDescription() << ") = "
722 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
723 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
724 // Decrement level of upreference
725 unsigned Level = --UpRefs[i].NestingLevel;
726 UpRefs[i].LastContainedTy = Ty;
727 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
728 if (Level == 0) { // Upreference should be resolved!
729 if (!TypeToResolve) {
730 TypeToResolve = UpRefs[i].UpRefTy;
731 } else {
732 UR_OUT(" * Resolving upreference for "
733 << UpRefs[i].second->getDescription() << "\n";
734 std::string OldName = UpRefs[i].UpRefTy->getDescription());
735 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
736 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
737 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
738 }
739 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
740 --i; // Do not skip the next element...
741 }
742 }
743 }
744
745 if (TypeToResolve) {
746 UR_OUT(" * Resolving upreference for "
747 << UpRefs[i].second->getDescription() << "\n";
748 std::string OldName = TypeToResolve->getDescription());
749 TypeToResolve->refineAbstractTypeTo(Ty);
750 }
751
752 return Ty;
753}
754
755
756// common code from the two 'RunVMAsmParser' functions
757 static Module * RunParser(Module * M) {
758
759 llvmAsmlineno = 1; // Reset the current line number...
760 ObsoleteVarArgs = false;
761 NewVarArgs = false;
762
763 CurModule.CurrentModule = M;
764 yyparse(); // Parse the file, potentially throwing exception
Reid Spencer713eedc2006-08-18 08:43:06 +0000765 if (!ParserResult)
766 return 0;
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000767
768 Module *Result = ParserResult;
769 ParserResult = 0;
770
771 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
772 {
773 Function* F;
774 if ((F = Result->getNamedFunction("llvm.va_start"))
775 && F->getFunctionType()->getNumParams() == 0)
776 ObsoleteVarArgs = true;
777 if((F = Result->getNamedFunction("llvm.va_copy"))
778 && F->getFunctionType()->getNumParams() == 1)
779 ObsoleteVarArgs = true;
780 }
781
782 if (ObsoleteVarArgs && NewVarArgs)
Reid Spencer713eedc2006-08-18 08:43:06 +0000783 GenerateError("This file is corrupt: it uses both new and old style varargs");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000784
785 if(ObsoleteVarArgs) {
786 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
787 if (F->arg_size() != 0)
Reid Spencer713eedc2006-08-18 08:43:06 +0000788 GenerateError("Obsolete va_start takes 0 argument!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000789
790 //foo = va_start()
791 // ->
792 //bar = alloca typeof(foo)
793 //va_start(bar)
794 //foo = load bar
795
796 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
797 const Type* ArgTy = F->getFunctionType()->getReturnType();
798 const Type* ArgTyPtr = PointerType::get(ArgTy);
799 Function* NF = Result->getOrInsertFunction("llvm.va_start",
800 RetTy, ArgTyPtr, (Type *)0);
801
802 while (!F->use_empty()) {
803 CallInst* CI = cast<CallInst>(F->use_back());
804 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
805 new CallInst(NF, bar, "", CI);
806 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
807 CI->replaceAllUsesWith(foo);
808 CI->getParent()->getInstList().erase(CI);
809 }
810 Result->getFunctionList().erase(F);
811 }
812
813 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
814 if(F->arg_size() != 1)
Reid Spencer713eedc2006-08-18 08:43:06 +0000815 GenerateError("Obsolete va_end takes 1 argument!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000816
817 //vaend foo
818 // ->
819 //bar = alloca 1 of typeof(foo)
820 //vaend bar
821 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
822 const Type* ArgTy = F->getFunctionType()->getParamType(0);
823 const Type* ArgTyPtr = PointerType::get(ArgTy);
824 Function* NF = Result->getOrInsertFunction("llvm.va_end",
825 RetTy, ArgTyPtr, (Type *)0);
826
827 while (!F->use_empty()) {
828 CallInst* CI = cast<CallInst>(F->use_back());
829 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
830 new StoreInst(CI->getOperand(1), bar, CI);
831 new CallInst(NF, bar, "", CI);
832 CI->getParent()->getInstList().erase(CI);
833 }
834 Result->getFunctionList().erase(F);
835 }
836
837 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
838 if(F->arg_size() != 1)
Reid Spencer713eedc2006-08-18 08:43:06 +0000839 GenerateError("Obsolete va_copy takes 1 argument!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000840 //foo = vacopy(bar)
841 // ->
842 //a = alloca 1 of typeof(foo)
843 //b = alloca 1 of typeof(foo)
844 //store bar -> b
845 //vacopy(a, b)
846 //foo = load a
847
848 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
849 const Type* ArgTy = F->getFunctionType()->getReturnType();
850 const Type* ArgTyPtr = PointerType::get(ArgTy);
851 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
852 RetTy, ArgTyPtr, ArgTyPtr,
853 (Type *)0);
854
855 while (!F->use_empty()) {
856 CallInst* CI = cast<CallInst>(F->use_back());
857 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
858 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
859 new StoreInst(CI->getOperand(1), b, CI);
860 new CallInst(NF, a, b, "", CI);
861 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
862 CI->replaceAllUsesWith(foo);
863 CI->getParent()->getInstList().erase(CI);
864 }
865 Result->getFunctionList().erase(F);
866 }
867 }
868
869 return Result;
870
871 }
872
873//===----------------------------------------------------------------------===//
874// RunVMAsmParser - Define an interface to this parser
875//===----------------------------------------------------------------------===//
876//
877Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
878 set_scan_file(F);
879
880 CurFilename = Filename;
881 return RunParser(new Module(CurFilename));
882}
883
884Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
885 set_scan_string(AsmString);
886
887 CurFilename = "from_memory";
888 if (M == NULL) {
889 return RunParser(new Module (CurFilename));
890 } else {
891 return RunParser(M);
892 }
893}
894
895%}
896
897%union {
898 llvm::Module *ModuleVal;
899 llvm::Function *FunctionVal;
900 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
901 llvm::BasicBlock *BasicBlockVal;
902 llvm::TerminatorInst *TermInstVal;
903 llvm::Instruction *InstVal;
904 llvm::Constant *ConstVal;
905
906 const llvm::Type *PrimType;
907 llvm::PATypeHolder *TypeVal;
908 llvm::Value *ValueVal;
909
910 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
911 std::vector<llvm::Value*> *ValueList;
912 std::list<llvm::PATypeHolder> *TypeList;
913 // Represent the RHS of PHI node
914 std::list<std::pair<llvm::Value*,
915 llvm::BasicBlock*> > *PHIList;
916 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
917 std::vector<llvm::Constant*> *ConstVector;
918
919 llvm::GlobalValue::LinkageTypes Linkage;
920 int64_t SInt64Val;
921 uint64_t UInt64Val;
922 int SIntVal;
923 unsigned UIntVal;
924 double FPVal;
925 bool BoolVal;
926
927 char *StrVal; // This memory is strdup'd!
928 llvm::ValID ValIDVal; // strdup'd memory maybe!
929
930 llvm::Instruction::BinaryOps BinaryOpVal;
931 llvm::Instruction::TermOps TermOpVal;
932 llvm::Instruction::MemoryOps MemOpVal;
933 llvm::Instruction::OtherOps OtherOpVal;
934 llvm::Module::Endianness Endianness;
935}
936
937%type <ModuleVal> Module FunctionList
938%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
939%type <BasicBlockVal> BasicBlock InstructionList
940%type <TermInstVal> BBTerminatorInst
941%type <InstVal> Inst InstVal MemoryInst
942%type <ConstVal> ConstVal ConstExpr
943%type <ConstVector> ConstVector
944%type <ArgList> ArgList ArgListH
945%type <ArgVal> ArgVal
946%type <PHIList> PHIList
947%type <ValueList> ValueRefList ValueRefListE // For call param lists
948%type <ValueList> IndexList // For GEP derived indices
949%type <TypeList> TypeListI ArgTypeListI
950%type <JumpTable> JumpTable
951%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
952%type <BoolVal> OptVolatile // 'volatile' or not
953%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
954%type <BoolVal> OptSideEffect // 'sideeffect' or not.
955%type <Linkage> OptLinkage
956%type <Endianness> BigOrLittle
957
958// ValueRef - Unresolved reference to a definition or BB
959%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
960%type <ValueVal> ResolvedVal // <type> <valref> pair
961// Tokens and types for handling constant integer values
962//
963// ESINT64VAL - A negative number within long long range
964%token <SInt64Val> ESINT64VAL
965
966// EUINT64VAL - A positive number within uns. long long range
967%token <UInt64Val> EUINT64VAL
968%type <SInt64Val> EINT64VAL
969
970%token <SIntVal> SINTVAL // Signed 32 bit ints...
971%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
972%type <SIntVal> INTVAL
973%token <FPVal> FPVAL // Float or Double constant
974
975// Built in types...
976%type <TypeVal> Types TypesV UpRTypes UpRTypesV
977%type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
978%token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
979%token <PrimType> FLOAT DOUBLE TYPE LABEL
980
981%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
982%type <StrVal> Name OptName OptAssign
983%type <UIntVal> OptAlign OptCAlign
984%type <StrVal> OptSection SectionString
985
986%token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
987%token DECLARE GLOBAL CONSTANT SECTION VOLATILE
988%token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
989%token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
990%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
Chris Lattner09c0e992006-05-19 21:28:53 +0000991%token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
Chris Lattnerf20e61f2006-02-15 07:22:58 +0000992%type <UIntVal> OptCallingConv
993
994// Basic Block Terminating Operators
995%token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
996
997// Binary Operators
998%type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
999%token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
1000%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
1001
1002// Memory Instructions
1003%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1004
1005// Other Operators
1006%type <OtherOpVal> ShiftOps
1007%token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
Chris Lattner9ff96a72006-04-08 01:18:56 +00001008%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001009%token VAARG_old VANEXT_old //OBSOLETE
1010
1011
1012%start Module
1013%%
1014
1015// Handle constant integer size restriction and conversion...
1016//
1017INTVAL : SINTVAL;
1018INTVAL : UINTVAL {
1019 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
Reid Spencer713eedc2006-08-18 08:43:06 +00001020 GEN_ERROR("Value too large for type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001021 $$ = (int32_t)$1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001022 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001023};
1024
1025
1026EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1027EINT64VAL : EUINT64VAL {
1028 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
Reid Spencer713eedc2006-08-18 08:43:06 +00001029 GEN_ERROR("Value too large for type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001030 $$ = (int64_t)$1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001031 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001032};
1033
1034// Operations that are notably excluded from this list include:
1035// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1036//
1037ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1038LogicalOps : AND | OR | XOR;
1039SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1040
1041ShiftOps : SHL | SHR;
1042
1043// These are some types that allow classification if we only want a particular
1044// thing... for example, only a signed, unsigned, or integral type.
1045SIntType : LONG | INT | SHORT | SBYTE;
1046UIntType : ULONG | UINT | USHORT | UBYTE;
1047IntType : SIntType | UIntType;
1048FPType : FLOAT | DOUBLE;
1049
1050// OptAssign - Value producing statements have an optional assignment component
1051OptAssign : Name '=' {
1052 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001053 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001054 }
1055 | /*empty*/ {
1056 $$ = 0;
Reid Spencer713eedc2006-08-18 08:43:06 +00001057 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001058 };
1059
1060OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1061 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1062 WEAK { $$ = GlobalValue::WeakLinkage; } |
1063 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1064 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1065
1066OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1067 CCC_TOK { $$ = CallingConv::C; } |
Chris Lattner09c0e992006-05-19 21:28:53 +00001068 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001069 FASTCC_TOK { $$ = CallingConv::Fast; } |
1070 COLDCC_TOK { $$ = CallingConv::Cold; } |
1071 CC_TOK EUINT64VAL {
1072 if ((unsigned)$2 != $2)
Reid Spencer713eedc2006-08-18 08:43:06 +00001073 GEN_ERROR("Calling conv too large!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001074 $$ = $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00001075 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001076 };
1077
1078// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1079// a comma before it.
1080OptAlign : /*empty*/ { $$ = 0; } |
1081 ALIGN EUINT64VAL {
1082 $$ = $2;
1083 if ($$ != 0 && !isPowerOf2_32($$))
Reid Spencer713eedc2006-08-18 08:43:06 +00001084 GEN_ERROR("Alignment must be a power of two!");
1085 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001086};
1087OptCAlign : /*empty*/ { $$ = 0; } |
1088 ',' ALIGN EUINT64VAL {
1089 $$ = $3;
1090 if ($$ != 0 && !isPowerOf2_32($$))
Reid Spencer713eedc2006-08-18 08:43:06 +00001091 GEN_ERROR("Alignment must be a power of two!");
1092 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001093};
1094
1095
1096SectionString : SECTION STRINGCONSTANT {
1097 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1098 if ($2[i] == '"' || $2[i] == '\\')
Reid Spencer713eedc2006-08-18 08:43:06 +00001099 GEN_ERROR("Invalid character in section name!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001100 $$ = $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00001101 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001102};
1103
1104OptSection : /*empty*/ { $$ = 0; } |
1105 SectionString { $$ = $1; };
1106
1107// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1108// is set to be the global we are processing.
1109//
1110GlobalVarAttributes : /* empty */ {} |
1111 ',' GlobalVarAttribute GlobalVarAttributes {};
1112GlobalVarAttribute : SectionString {
1113 CurGV->setSection($1);
1114 free($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00001115 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001116 }
1117 | ALIGN EUINT64VAL {
1118 if ($2 != 0 && !isPowerOf2_32($2))
Reid Spencer713eedc2006-08-18 08:43:06 +00001119 GEN_ERROR("Alignment must be a power of two!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001120 CurGV->setAlignment($2);
Reid Spencer713eedc2006-08-18 08:43:06 +00001121 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001122 };
1123
1124//===----------------------------------------------------------------------===//
1125// Types includes all predefined types... except void, because it can only be
1126// used in specific contexts (function returning void for example). To have
1127// access to it, a user must explicitly use TypesV.
1128//
1129
1130// TypesV includes all of 'Types', but it also includes the void type.
1131TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1132UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1133
1134Types : UpRTypes {
1135 if (!UpRefs.empty())
Reid Spencer713eedc2006-08-18 08:43:06 +00001136 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001137 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001138 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001139 };
1140
1141
1142// Derived types are added later...
1143//
1144PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1145PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1146UpRTypes : OPAQUE {
1147 $$ = new PATypeHolder(OpaqueType::get());
Reid Spencer713eedc2006-08-18 08:43:06 +00001148 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001149 }
1150 | PrimType {
1151 $$ = new PATypeHolder($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00001152 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001153 };
1154UpRTypes : SymbolicValueRef { // Named types are also simple types...
1155 $$ = new PATypeHolder(getTypeVal($1));
Reid Spencer713eedc2006-08-18 08:43:06 +00001156 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001157};
1158
1159// Include derived types in the Types production.
1160//
1161UpRTypes : '\\' EUINT64VAL { // Type UpReference
Reid Spencer713eedc2006-08-18 08:43:06 +00001162 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001163 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1164 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1165 $$ = new PATypeHolder(OT);
1166 UR_OUT("New Upreference!\n");
Reid Spencer713eedc2006-08-18 08:43:06 +00001167 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001168 }
1169 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1170 std::vector<const Type*> Params;
1171 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1172 E = $3->end(); I != E; ++I)
1173 Params.push_back(*I);
1174 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1175 if (isVarArg) Params.pop_back();
1176
1177 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1178 delete $3; // Delete the argument list
1179 delete $1; // Delete the return type handle
Reid Spencer713eedc2006-08-18 08:43:06 +00001180 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001181 }
1182 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1183 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1184 delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00001185 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001186 }
1187 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1188 const llvm::Type* ElemTy = $4->get();
1189 if ((unsigned)$2 != $2)
Reid Spencer713eedc2006-08-18 08:43:06 +00001190 GEN_ERROR("Unsigned result not equal to signed result");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001191 if (!ElemTy->isPrimitiveType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001192 GEN_ERROR("Elemental type of a PackedType must be primitive");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001193 if (!isPowerOf2_32($2))
Reid Spencer713eedc2006-08-18 08:43:06 +00001194 GEN_ERROR("Vector length should be a power of 2!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001195 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1196 delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00001197 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001198 }
1199 | '{' TypeListI '}' { // Structure type?
1200 std::vector<const Type*> Elements;
1201 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1202 E = $2->end(); I != E; ++I)
1203 Elements.push_back(*I);
1204
1205 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1206 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00001207 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001208 }
1209 | '{' '}' { // Empty structure type?
1210 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
Reid Spencer713eedc2006-08-18 08:43:06 +00001211 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001212 }
1213 | UpRTypes '*' { // Pointer type?
1214 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1215 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001216 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001217 };
1218
1219// TypeList - Used for struct declarations and as a basis for function type
1220// declaration type lists
1221//
1222TypeListI : UpRTypes {
1223 $$ = new std::list<PATypeHolder>();
1224 $$->push_back(*$1); delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001225 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001226 }
1227 | TypeListI ',' UpRTypes {
1228 ($$=$1)->push_back(*$3); delete $3;
Reid Spencer713eedc2006-08-18 08:43:06 +00001229 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001230 };
1231
1232// ArgTypeList - List of types for a function type declaration...
1233ArgTypeListI : TypeListI
1234 | TypeListI ',' DOTDOTDOT {
1235 ($$=$1)->push_back(Type::VoidTy);
Reid Spencer713eedc2006-08-18 08:43:06 +00001236 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001237 }
1238 | DOTDOTDOT {
1239 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
Reid Spencer713eedc2006-08-18 08:43:06 +00001240 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001241 }
1242 | /*empty*/ {
1243 $$ = new std::list<PATypeHolder>();
Reid Spencer713eedc2006-08-18 08:43:06 +00001244 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001245 };
1246
1247// ConstVal - The various declarations that go into the constant pool. This
1248// production is used ONLY to represent constants that show up AFTER a 'const',
1249// 'constant' or 'global' token at global scope. Constants that can be inlined
1250// into other expressions (such as integers and constexprs) are handled by the
1251// ResolvedVal, ValueRef and ConstValueRef productions.
1252//
1253ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1254 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1255 if (ATy == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001256 GEN_ERROR("Cannot make array constant with type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001257 (*$1)->getDescription() + "'!");
1258 const Type *ETy = ATy->getElementType();
1259 int NumElements = ATy->getNumElements();
1260
1261 // Verify that we have the correct size...
1262 if (NumElements != -1 && NumElements != (int)$3->size())
Reid Spencer713eedc2006-08-18 08:43:06 +00001263 GEN_ERROR("Type mismatch: constant sized array initialized with " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001264 utostr($3->size()) + " arguments, but has size of " +
1265 itostr(NumElements) + "!");
1266
1267 // Verify all elements are correct type!
1268 for (unsigned i = 0; i < $3->size(); i++) {
1269 if (ETy != (*$3)[i]->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001270 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001271 ETy->getDescription() +"' as required!\nIt is of type '"+
1272 (*$3)[i]->getType()->getDescription() + "'.");
1273 }
1274
1275 $$ = ConstantArray::get(ATy, *$3);
1276 delete $1; delete $3;
Reid Spencer713eedc2006-08-18 08:43:06 +00001277 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001278 }
1279 | Types '[' ']' {
1280 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1281 if (ATy == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001282 GEN_ERROR("Cannot make array constant with type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001283 (*$1)->getDescription() + "'!");
1284
1285 int NumElements = ATy->getNumElements();
1286 if (NumElements != -1 && NumElements != 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001287 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001288 " arguments, but has size of " + itostr(NumElements) +"!");
1289 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1290 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001291 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001292 }
1293 | Types 'c' STRINGCONSTANT {
1294 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1295 if (ATy == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001296 GEN_ERROR("Cannot make array constant with type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001297 (*$1)->getDescription() + "'!");
1298
1299 int NumElements = ATy->getNumElements();
1300 const Type *ETy = ATy->getElementType();
1301 char *EndStr = UnEscapeLexed($3, true);
1302 if (NumElements != -1 && NumElements != (EndStr-$3))
Reid Spencer713eedc2006-08-18 08:43:06 +00001303 GEN_ERROR("Can't build string constant of size " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001304 itostr((int)(EndStr-$3)) +
1305 " when array has size " + itostr(NumElements) + "!");
1306 std::vector<Constant*> Vals;
1307 if (ETy == Type::SByteTy) {
1308 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1309 Vals.push_back(ConstantSInt::get(ETy, *C));
1310 } else if (ETy == Type::UByteTy) {
1311 for (unsigned char *C = (unsigned char *)$3;
1312 C != (unsigned char*)EndStr; ++C)
1313 Vals.push_back(ConstantUInt::get(ETy, *C));
1314 } else {
1315 free($3);
Reid Spencer713eedc2006-08-18 08:43:06 +00001316 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001317 }
1318 free($3);
1319 $$ = ConstantArray::get(ATy, Vals);
1320 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001321 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001322 }
1323 | Types '<' ConstVector '>' { // Nonempty unsized arr
1324 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1325 if (PTy == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001326 GEN_ERROR("Cannot make packed constant with type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001327 (*$1)->getDescription() + "'!");
1328 const Type *ETy = PTy->getElementType();
1329 int NumElements = PTy->getNumElements();
1330
1331 // Verify that we have the correct size...
1332 if (NumElements != -1 && NumElements != (int)$3->size())
Reid Spencer713eedc2006-08-18 08:43:06 +00001333 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001334 utostr($3->size()) + " arguments, but has size of " +
1335 itostr(NumElements) + "!");
1336
1337 // Verify all elements are correct type!
1338 for (unsigned i = 0; i < $3->size(); i++) {
1339 if (ETy != (*$3)[i]->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001340 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001341 ETy->getDescription() +"' as required!\nIt is of type '"+
1342 (*$3)[i]->getType()->getDescription() + "'.");
1343 }
1344
1345 $$ = ConstantPacked::get(PTy, *$3);
1346 delete $1; delete $3;
Reid Spencer713eedc2006-08-18 08:43:06 +00001347 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001348 }
1349 | Types '{' ConstVector '}' {
1350 const StructType *STy = dyn_cast<StructType>($1->get());
1351 if (STy == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001352 GEN_ERROR("Cannot make struct constant with type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001353 (*$1)->getDescription() + "'!");
1354
1355 if ($3->size() != STy->getNumContainedTypes())
Reid Spencer713eedc2006-08-18 08:43:06 +00001356 GEN_ERROR("Illegal number of initializers for structure type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001357
1358 // Check to ensure that constants are compatible with the type initializer!
1359 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1360 if ((*$3)[i]->getType() != STy->getElementType(i))
Reid Spencer713eedc2006-08-18 08:43:06 +00001361 GEN_ERROR("Expected type '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001362 STy->getElementType(i)->getDescription() +
1363 "' for element #" + utostr(i) +
1364 " of structure initializer!");
1365
1366 $$ = ConstantStruct::get(STy, *$3);
1367 delete $1; delete $3;
Reid Spencer713eedc2006-08-18 08:43:06 +00001368 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001369 }
1370 | Types '{' '}' {
1371 const StructType *STy = dyn_cast<StructType>($1->get());
1372 if (STy == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001373 GEN_ERROR("Cannot make struct constant with type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001374 (*$1)->getDescription() + "'!");
1375
1376 if (STy->getNumContainedTypes() != 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001377 GEN_ERROR("Illegal number of initializers for structure type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001378
1379 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1380 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001381 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001382 }
1383 | Types NULL_TOK {
1384 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1385 if (PTy == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001386 GEN_ERROR("Cannot make null pointer constant with type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001387 (*$1)->getDescription() + "'!");
1388
1389 $$ = ConstantPointerNull::get(PTy);
1390 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001391 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001392 }
1393 | Types UNDEF {
1394 $$ = UndefValue::get($1->get());
1395 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001396 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001397 }
1398 | Types SymbolicValueRef {
1399 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1400 if (Ty == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00001401 GEN_ERROR("Global const reference must be a pointer type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001402
1403 // ConstExprs can exist in the body of a function, thus creating
1404 // GlobalValues whenever they refer to a variable. Because we are in
1405 // the context of a function, getValNonImprovising will search the functions
1406 // symbol table instead of the module symbol table for the global symbol,
1407 // which throws things all off. To get around this, we just tell
1408 // getValNonImprovising that we are at global scope here.
1409 //
1410 Function *SavedCurFn = CurFun.CurrentFunction;
1411 CurFun.CurrentFunction = 0;
1412
1413 Value *V = getValNonImprovising(Ty, $2);
1414
1415 CurFun.CurrentFunction = SavedCurFn;
1416
1417 // If this is an initializer for a constant pointer, which is referencing a
1418 // (currently) undefined variable, create a stub now that shall be replaced
1419 // in the future with the right type of variable.
1420 //
1421 if (V == 0) {
1422 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1423 const PointerType *PT = cast<PointerType>(Ty);
1424
1425 // First check to see if the forward references value is already created!
1426 PerModuleInfo::GlobalRefsType::iterator I =
1427 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1428
1429 if (I != CurModule.GlobalRefs.end()) {
1430 V = I->second; // Placeholder already exists, use it...
1431 $2.destroy();
1432 } else {
1433 std::string Name;
1434 if ($2.Type == ValID::NameVal) Name = $2.Name;
1435
1436 // Create the forward referenced global.
1437 GlobalValue *GV;
1438 if (const FunctionType *FTy =
1439 dyn_cast<FunctionType>(PT->getElementType())) {
1440 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1441 CurModule.CurrentModule);
1442 } else {
1443 GV = new GlobalVariable(PT->getElementType(), false,
1444 GlobalValue::ExternalLinkage, 0,
1445 Name, CurModule.CurrentModule);
1446 }
1447
1448 // Keep track of the fact that we have a forward ref to recycle it
1449 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1450 V = GV;
1451 }
1452 }
1453
1454 $$ = cast<GlobalValue>(V);
1455 delete $1; // Free the type handle
Reid Spencer713eedc2006-08-18 08:43:06 +00001456 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001457 }
1458 | Types ConstExpr {
1459 if ($1->get() != $2->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001460 GEN_ERROR("Mismatched types for constant expression!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001461 $$ = $2;
1462 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001463 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001464 }
1465 | Types ZEROINITIALIZER {
1466 const Type *Ty = $1->get();
1467 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
Reid Spencer713eedc2006-08-18 08:43:06 +00001468 GEN_ERROR("Cannot create a null initialized value of this type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001469 $$ = Constant::getNullValue(Ty);
1470 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001471 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001472 };
1473
1474ConstVal : SIntType EINT64VAL { // integral constants
1475 if (!ConstantSInt::isValueValidForType($1, $2))
Reid Spencer713eedc2006-08-18 08:43:06 +00001476 GEN_ERROR("Constant value doesn't fit in type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001477 $$ = ConstantSInt::get($1, $2);
Reid Spencer713eedc2006-08-18 08:43:06 +00001478 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001479 }
1480 | UIntType EUINT64VAL { // integral constants
1481 if (!ConstantUInt::isValueValidForType($1, $2))
Reid Spencer713eedc2006-08-18 08:43:06 +00001482 GEN_ERROR("Constant value doesn't fit in type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001483 $$ = ConstantUInt::get($1, $2);
Reid Spencer713eedc2006-08-18 08:43:06 +00001484 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001485 }
1486 | BOOL TRUETOK { // Boolean constants
1487 $$ = ConstantBool::True;
Reid Spencer713eedc2006-08-18 08:43:06 +00001488 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001489 }
1490 | BOOL FALSETOK { // Boolean constants
1491 $$ = ConstantBool::False;
Reid Spencer713eedc2006-08-18 08:43:06 +00001492 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001493 }
1494 | FPType FPVAL { // Float & Double constants
1495 if (!ConstantFP::isValueValidForType($1, $2))
Reid Spencer713eedc2006-08-18 08:43:06 +00001496 GEN_ERROR("Floating point constant invalid for type!!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001497 $$ = ConstantFP::get($1, $2);
Reid Spencer713eedc2006-08-18 08:43:06 +00001498 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001499 };
1500
1501
1502ConstExpr: CAST '(' ConstVal TO Types ')' {
1503 if (!$3->getType()->isFirstClassType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001504 GEN_ERROR("cast constant expression from a non-primitive type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001505 $3->getType()->getDescription() + "'!");
1506 if (!$5->get()->isFirstClassType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001507 GEN_ERROR("cast constant expression to a non-primitive type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001508 $5->get()->getDescription() + "'!");
1509 $$ = ConstantExpr::getCast($3, $5->get());
1510 delete $5;
Reid Spencer713eedc2006-08-18 08:43:06 +00001511 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001512 }
1513 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1514 if (!isa<PointerType>($3->getType()))
Reid Spencer713eedc2006-08-18 08:43:06 +00001515 GEN_ERROR("GetElementPtr requires a pointer operand!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001516
1517 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1518 // indices to uint struct indices for compatibility.
1519 generic_gep_type_iterator<std::vector<Value*>::iterator>
1520 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1521 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1522 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1523 if (isa<StructType>(*GTI)) // Only change struct indices
1524 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1525 if (CUI->getType() == Type::UByteTy)
1526 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1527
1528 const Type *IdxTy =
1529 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1530 if (!IdxTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00001531 GEN_ERROR("Index list invalid for constant getelementptr!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001532
1533 std::vector<Constant*> IdxVec;
1534 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1535 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1536 IdxVec.push_back(C);
1537 else
Reid Spencer713eedc2006-08-18 08:43:06 +00001538 GEN_ERROR("Indices to constant getelementptr must be constants!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001539
1540 delete $4;
1541
1542 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
Reid Spencer713eedc2006-08-18 08:43:06 +00001543 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001544 }
1545 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1546 if ($3->getType() != Type::BoolTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00001547 GEN_ERROR("Select condition must be of boolean type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001548 if ($5->getType() != $7->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001549 GEN_ERROR("Select operand types must match!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001550 $$ = ConstantExpr::getSelect($3, $5, $7);
Reid Spencer713eedc2006-08-18 08:43:06 +00001551 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001552 }
1553 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1554 if ($3->getType() != $5->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001555 GEN_ERROR("Binary operator types must match!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001556 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1557 // To retain backward compatibility with these early compilers, we emit a
1558 // cast to the appropriate integer type automatically if we are in the
1559 // broken case. See PR424 for more information.
1560 if (!isa<PointerType>($3->getType())) {
1561 $$ = ConstantExpr::get($1, $3, $5);
1562 } else {
1563 const Type *IntPtrTy = 0;
1564 switch (CurModule.CurrentModule->getPointerSize()) {
1565 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1566 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
Reid Spencer713eedc2006-08-18 08:43:06 +00001567 default: GEN_ERROR("invalid pointer binary constant expr!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001568 }
1569 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1570 ConstantExpr::getCast($5, IntPtrTy));
1571 $$ = ConstantExpr::getCast($$, $3->getType());
1572 }
Reid Spencer713eedc2006-08-18 08:43:06 +00001573 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001574 }
1575 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1576 if ($3->getType() != $5->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001577 GEN_ERROR("Logical operator types must match!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001578 if (!$3->getType()->isIntegral()) {
1579 if (!isa<PackedType>($3->getType()) ||
1580 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
Reid Spencer713eedc2006-08-18 08:43:06 +00001581 GEN_ERROR("Logical operator requires integral operands!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001582 }
1583 $$ = ConstantExpr::get($1, $3, $5);
Reid Spencer713eedc2006-08-18 08:43:06 +00001584 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001585 }
1586 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1587 if ($3->getType() != $5->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00001588 GEN_ERROR("setcc operand types must match!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001589 $$ = ConstantExpr::get($1, $3, $5);
Reid Spencer713eedc2006-08-18 08:43:06 +00001590 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001591 }
1592 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1593 if ($5->getType() != Type::UByteTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00001594 GEN_ERROR("Shift count for shift constant must be unsigned byte!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001595 if (!$3->getType()->isInteger())
Reid Spencer713eedc2006-08-18 08:43:06 +00001596 GEN_ERROR("Shift constant expression requires integer operand!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001597 $$ = ConstantExpr::get($1, $3, $5);
Reid Spencer713eedc2006-08-18 08:43:06 +00001598 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001599 }
1600 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
Chris Lattner931565c2006-04-08 04:09:02 +00001601 if (!ExtractElementInst::isValidOperands($3, $5))
Reid Spencer713eedc2006-08-18 08:43:06 +00001602 GEN_ERROR("Invalid extractelement operands!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001603 $$ = ConstantExpr::getExtractElement($3, $5);
Reid Spencer713eedc2006-08-18 08:43:06 +00001604 CHECK_FOR_ERROR
Chris Lattneraebccf82006-04-08 03:55:17 +00001605 }
1606 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Chris Lattner931565c2006-04-08 04:09:02 +00001607 if (!InsertElementInst::isValidOperands($3, $5, $7))
Reid Spencer713eedc2006-08-18 08:43:06 +00001608 GEN_ERROR("Invalid insertelement operands!");
Chris Lattneraebccf82006-04-08 03:55:17 +00001609 $$ = ConstantExpr::getInsertElement($3, $5, $7);
Reid Spencer713eedc2006-08-18 08:43:06 +00001610 CHECK_FOR_ERROR
Chris Lattneraebccf82006-04-08 03:55:17 +00001611 }
1612 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1613 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
Reid Spencer713eedc2006-08-18 08:43:06 +00001614 GEN_ERROR("Invalid shufflevector operands!");
Chris Lattneraebccf82006-04-08 03:55:17 +00001615 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
Reid Spencer713eedc2006-08-18 08:43:06 +00001616 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001617 };
1618
Chris Lattneraebccf82006-04-08 03:55:17 +00001619
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001620// ConstVector - A list of comma separated constants.
1621ConstVector : ConstVector ',' ConstVal {
1622 ($$ = $1)->push_back($3);
Reid Spencer713eedc2006-08-18 08:43:06 +00001623 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001624 }
1625 | ConstVal {
1626 $$ = new std::vector<Constant*>();
1627 $$->push_back($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00001628 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001629 };
1630
1631
1632// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1633GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1634
1635
1636//===----------------------------------------------------------------------===//
1637// Rules to match Modules
1638//===----------------------------------------------------------------------===//
1639
1640// Module rule: Capture the result of parsing the whole file into a result
1641// variable...
1642//
1643Module : FunctionList {
1644 $$ = ParserResult = $1;
1645 CurModule.ModuleDone();
Reid Spencer713eedc2006-08-18 08:43:06 +00001646 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001647};
1648
1649// FunctionList - A list of functions, preceeded by a constant pool.
1650//
1651FunctionList : FunctionList Function {
1652 $$ = $1;
1653 CurFun.FunctionDone();
Reid Spencer713eedc2006-08-18 08:43:06 +00001654 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001655 }
1656 | FunctionList FunctionProto {
1657 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001658 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001659 }
1660 | FunctionList MODULE ASM_TOK AsmBlock {
1661 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001662 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001663 }
1664 | FunctionList IMPLEMENTATION {
1665 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001666 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001667 }
1668 | ConstPool {
1669 $$ = CurModule.CurrentModule;
1670 // Emit an error if there are any unresolved types left.
1671 if (!CurModule.LateResolveTypes.empty()) {
1672 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
Reid Spencer713eedc2006-08-18 08:43:06 +00001673 if (DID.Type == ValID::NameVal) {
1674 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1675 } else {
1676 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1677 }
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001678 }
Reid Spencer713eedc2006-08-18 08:43:06 +00001679 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001680 };
1681
1682// ConstPool - Constants with optional names assigned to them.
1683ConstPool : ConstPool OptAssign TYPE TypesV {
1684 // Eagerly resolve types. This is not an optimization, this is a
1685 // requirement that is due to the fact that we could have this:
1686 //
1687 // %list = type { %list * }
1688 // %list = type { %list * } ; repeated type decl
1689 //
1690 // If types are not resolved eagerly, then the two types will not be
1691 // determined to be the same type!
1692 //
1693 ResolveTypeTo($2, *$4);
1694
1695 if (!setTypeName(*$4, $2) && !$2) {
1696 // If this is a named type that is not a redefinition, add it to the slot
1697 // table.
1698 CurModule.Types.push_back(*$4);
1699 }
1700
1701 delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00001702 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001703 }
1704 | ConstPool FunctionProto { // Function prototypes can be in const pool
Reid Spencer713eedc2006-08-18 08:43:06 +00001705 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001706 }
1707 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
Reid Spencer713eedc2006-08-18 08:43:06 +00001708 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001709 }
1710 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
Reid Spencer713eedc2006-08-18 08:43:06 +00001711 if ($5 == 0) GEN_ERROR("Global value initializer is not a constant!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001712 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1713 } GlobalVarAttributes {
1714 CurGV = 0;
Reid Spencer713eedc2006-08-18 08:43:06 +00001715 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001716 }
1717 | ConstPool OptAssign EXTERNAL GlobalType Types {
1718 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1719 $4, *$5, 0);
1720 delete $5;
1721 } GlobalVarAttributes {
1722 CurGV = 0;
Reid Spencer713eedc2006-08-18 08:43:06 +00001723 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001724 }
1725 | ConstPool TARGET TargetDefinition {
Reid Spencer713eedc2006-08-18 08:43:06 +00001726 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001727 }
1728 | ConstPool DEPLIBS '=' LibrariesDefinition {
Reid Spencer713eedc2006-08-18 08:43:06 +00001729 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001730 }
1731 | /* empty: end of list */ {
1732 };
1733
1734
1735AsmBlock : STRINGCONSTANT {
1736 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1737 char *EndStr = UnEscapeLexed($1, true);
1738 std::string NewAsm($1, EndStr);
1739 free($1);
1740
1741 if (AsmSoFar.empty())
1742 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1743 else
1744 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
Reid Spencer713eedc2006-08-18 08:43:06 +00001745 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001746};
1747
1748BigOrLittle : BIG { $$ = Module::BigEndian; };
1749BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1750
1751TargetDefinition : ENDIAN '=' BigOrLittle {
1752 CurModule.CurrentModule->setEndianness($3);
Reid Spencer713eedc2006-08-18 08:43:06 +00001753 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001754 }
1755 | POINTERSIZE '=' EUINT64VAL {
1756 if ($3 == 32)
1757 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1758 else if ($3 == 64)
1759 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1760 else
Reid Spencer713eedc2006-08-18 08:43:06 +00001761 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1762 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001763 }
1764 | TRIPLE '=' STRINGCONSTANT {
1765 CurModule.CurrentModule->setTargetTriple($3);
1766 free($3);
Reid Spencer713eedc2006-08-18 08:43:06 +00001767 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001768 };
1769
1770LibrariesDefinition : '[' LibList ']';
1771
1772LibList : LibList ',' STRINGCONSTANT {
1773 CurModule.CurrentModule->addLibrary($3);
1774 free($3);
Reid Spencer713eedc2006-08-18 08:43:06 +00001775 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001776 }
1777 | STRINGCONSTANT {
1778 CurModule.CurrentModule->addLibrary($1);
1779 free($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00001780 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001781 }
1782 | /* empty: end of list */ {
Reid Spencer713eedc2006-08-18 08:43:06 +00001783 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001784 }
1785 ;
1786
1787//===----------------------------------------------------------------------===//
1788// Rules to match Function Headers
1789//===----------------------------------------------------------------------===//
1790
1791Name : VAR_ID | STRINGCONSTANT;
1792OptName : Name | /*empty*/ { $$ = 0; };
1793
1794ArgVal : Types OptName {
1795 if (*$1 == Type::VoidTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00001796 GEN_ERROR("void typed arguments are invalid!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001797 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
Reid Spencer713eedc2006-08-18 08:43:06 +00001798 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001799};
1800
1801ArgListH : ArgListH ',' ArgVal {
1802 $$ = $1;
1803 $1->push_back(*$3);
1804 delete $3;
Reid Spencer713eedc2006-08-18 08:43:06 +00001805 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001806 }
1807 | ArgVal {
1808 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1809 $$->push_back(*$1);
1810 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001811 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001812 };
1813
1814ArgList : ArgListH {
1815 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001816 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001817 }
1818 | ArgListH ',' DOTDOTDOT {
1819 $$ = $1;
1820 $$->push_back(std::pair<PATypeHolder*,
1821 char*>(new PATypeHolder(Type::VoidTy), 0));
Reid Spencer713eedc2006-08-18 08:43:06 +00001822 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001823 }
1824 | DOTDOTDOT {
1825 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1826 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
Reid Spencer713eedc2006-08-18 08:43:06 +00001827 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001828 }
1829 | /* empty */ {
1830 $$ = 0;
Reid Spencer713eedc2006-08-18 08:43:06 +00001831 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001832 };
1833
1834FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1835 OptSection OptAlign {
1836 UnEscapeLexed($3);
1837 std::string FunctionName($3);
1838 free($3); // Free strdup'd memory!
1839
1840 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00001841 GEN_ERROR("LLVM functions cannot return aggregate types!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001842
1843 std::vector<const Type*> ParamTypeList;
1844 if ($5) { // If there are arguments...
1845 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1846 I != $5->end(); ++I)
1847 ParamTypeList.push_back(I->first->get());
1848 }
1849
1850 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1851 if (isVarArg) ParamTypeList.pop_back();
1852
1853 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1854 const PointerType *PFT = PointerType::get(FT);
1855 delete $2;
1856
1857 ValID ID;
1858 if (!FunctionName.empty()) {
1859 ID = ValID::create((char*)FunctionName.c_str());
1860 } else {
1861 ID = ValID::create((int)CurModule.Values[PFT].size());
1862 }
1863
1864 Function *Fn = 0;
1865 // See if this function was forward referenced. If so, recycle the object.
1866 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1867 // Move the function to the end of the list, from whereever it was
1868 // previously inserted.
1869 Fn = cast<Function>(FWRef);
1870 CurModule.CurrentModule->getFunctionList().remove(Fn);
1871 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1872 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1873 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1874 // If this is the case, either we need to be a forward decl, or it needs
1875 // to be.
1876 if (!CurFun.isDeclare && !Fn->isExternal())
Reid Spencer713eedc2006-08-18 08:43:06 +00001877 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001878
1879 // Make sure to strip off any argument names so we can't get conflicts.
1880 if (Fn->isExternal())
1881 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1882 AI != AE; ++AI)
1883 AI->setName("");
1884
1885 } else { // Not already defined?
1886 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1887 CurModule.CurrentModule);
1888 InsertValue(Fn, CurModule.Values);
1889 }
1890
1891 CurFun.FunctionStart(Fn);
1892 Fn->setCallingConv($1);
1893 Fn->setAlignment($8);
1894 if ($7) {
1895 Fn->setSection($7);
1896 free($7);
1897 }
1898
1899 // Add all of the arguments we parsed to the function...
1900 if ($5) { // Is null if empty...
1901 if (isVarArg) { // Nuke the last entry
1902 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1903 "Not a varargs marker!");
1904 delete $5->back().first;
1905 $5->pop_back(); // Delete the last entry
1906 }
1907 Function::arg_iterator ArgIt = Fn->arg_begin();
1908 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1909 I != $5->end(); ++I, ++ArgIt) {
1910 delete I->first; // Delete the typeholder...
1911
1912 setValueName(ArgIt, I->second); // Insert arg into symtab...
1913 InsertValue(ArgIt);
1914 }
1915
1916 delete $5; // We're now done with the argument list
1917 }
Reid Spencer713eedc2006-08-18 08:43:06 +00001918 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001919};
1920
1921BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1922
1923FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1924 $$ = CurFun.CurrentFunction;
1925
1926 // Make sure that we keep track of the linkage type even if there was a
1927 // previous "declare".
1928 $$->setLinkage($1);
1929};
1930
1931END : ENDTOK | '}'; // Allow end of '}' to end a function
1932
1933Function : BasicBlockList END {
1934 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00001935 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001936};
1937
1938FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1939 $$ = CurFun.CurrentFunction;
1940 CurFun.FunctionDone();
Reid Spencer713eedc2006-08-18 08:43:06 +00001941 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001942};
1943
1944//===----------------------------------------------------------------------===//
1945// Rules to match Basic Blocks
1946//===----------------------------------------------------------------------===//
1947
1948OptSideEffect : /* empty */ {
1949 $$ = false;
Reid Spencer713eedc2006-08-18 08:43:06 +00001950 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001951 }
1952 | SIDEEFFECT {
1953 $$ = true;
Reid Spencer713eedc2006-08-18 08:43:06 +00001954 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001955 };
1956
1957ConstValueRef : ESINT64VAL { // A reference to a direct constant
1958 $$ = ValID::create($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00001959 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001960 }
1961 | EUINT64VAL {
1962 $$ = ValID::create($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00001963 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001964 }
1965 | FPVAL { // Perhaps it's an FP constant?
1966 $$ = ValID::create($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00001967 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001968 }
1969 | TRUETOK {
1970 $$ = ValID::create(ConstantBool::True);
Reid Spencer713eedc2006-08-18 08:43:06 +00001971 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001972 }
1973 | FALSETOK {
1974 $$ = ValID::create(ConstantBool::False);
Reid Spencer713eedc2006-08-18 08:43:06 +00001975 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001976 }
1977 | NULL_TOK {
1978 $$ = ValID::createNull();
Reid Spencer713eedc2006-08-18 08:43:06 +00001979 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001980 }
1981 | UNDEF {
1982 $$ = ValID::createUndef();
Reid Spencer713eedc2006-08-18 08:43:06 +00001983 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001984 }
1985 | ZEROINITIALIZER { // A vector zero constant.
1986 $$ = ValID::createZeroInit();
Reid Spencer713eedc2006-08-18 08:43:06 +00001987 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00001988 }
1989 | '<' ConstVector '>' { // Nonempty unsized packed vector
1990 const Type *ETy = (*$2)[0]->getType();
1991 int NumElements = $2->size();
1992
1993 PackedType* pt = PackedType::get(ETy, NumElements);
1994 PATypeHolder* PTy = new PATypeHolder(
1995 HandleUpRefs(
1996 PackedType::get(
1997 ETy,
1998 NumElements)
1999 )
2000 );
2001
2002 // Verify all elements are correct type!
2003 for (unsigned i = 0; i < $2->size(); i++) {
2004 if (ETy != (*$2)[i]->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00002005 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002006 ETy->getDescription() +"' as required!\nIt is of type '" +
2007 (*$2)[i]->getType()->getDescription() + "'.");
2008 }
2009
2010 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2011 delete PTy; delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002012 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002013 }
2014 | ConstExpr {
2015 $$ = ValID::create($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00002016 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002017 }
2018 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2019 char *End = UnEscapeLexed($3, true);
2020 std::string AsmStr = std::string($3, End);
2021 End = UnEscapeLexed($5, true);
2022 std::string Constraints = std::string($5, End);
2023 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2024 free($3);
2025 free($5);
Reid Spencer713eedc2006-08-18 08:43:06 +00002026 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002027 };
2028
2029// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2030// another value.
2031//
2032SymbolicValueRef : INTVAL { // Is it an integer reference...?
2033 $$ = ValID::create($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00002034 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002035 }
2036 | Name { // Is it a named reference...?
2037 $$ = ValID::create($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00002038 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002039 };
2040
2041// ValueRef - A reference to a definition... either constant or symbolic
2042ValueRef : SymbolicValueRef | ConstValueRef;
2043
2044
2045// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2046// type immediately preceeds the value reference, and allows complex constant
2047// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2048ResolvedVal : Types ValueRef {
2049 $$ = getVal(*$1, $2); delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00002050 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002051 };
2052
2053BasicBlockList : BasicBlockList BasicBlock {
2054 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00002055 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002056 }
2057 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2058 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00002059 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002060 };
2061
2062
2063// Basic blocks are terminated by branching instructions:
2064// br, br/cc, switch, ret
2065//
2066BasicBlock : InstructionList OptAssign BBTerminatorInst {
2067 setValueName($3, $2);
2068 InsertValue($3);
2069
2070 $1->getInstList().push_back($3);
2071 InsertValue($1);
2072 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00002073 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002074 };
2075
2076InstructionList : InstructionList Inst {
2077 $1->getInstList().push_back($2);
2078 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00002079 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002080 }
2081 | /* empty */ {
2082 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2083
2084 // Make sure to move the basic block to the correct location in the
2085 // function, instead of leaving it inserted wherever it was first
2086 // referenced.
2087 Function::BasicBlockListType &BBL =
2088 CurFun.CurrentFunction->getBasicBlockList();
2089 BBL.splice(BBL.end(), BBL, $$);
Reid Spencer713eedc2006-08-18 08:43:06 +00002090 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002091 }
2092 | LABELSTR {
2093 $$ = CurBB = getBBVal(ValID::create($1), true);
2094
2095 // Make sure to move the basic block to the correct location in the
2096 // function, instead of leaving it inserted wherever it was first
2097 // referenced.
2098 Function::BasicBlockListType &BBL =
2099 CurFun.CurrentFunction->getBasicBlockList();
2100 BBL.splice(BBL.end(), BBL, $$);
Reid Spencer713eedc2006-08-18 08:43:06 +00002101 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002102 };
2103
2104BBTerminatorInst : RET ResolvedVal { // Return with a result...
2105 $$ = new ReturnInst($2);
Reid Spencer713eedc2006-08-18 08:43:06 +00002106 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002107 }
2108 | RET VOID { // Return with no result...
2109 $$ = new ReturnInst();
Reid Spencer713eedc2006-08-18 08:43:06 +00002110 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002111 }
2112 | BR LABEL ValueRef { // Unconditional Branch...
2113 $$ = new BranchInst(getBBVal($3));
Reid Spencer713eedc2006-08-18 08:43:06 +00002114 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002115 } // Conditional Branch...
2116 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2117 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
Reid Spencer713eedc2006-08-18 08:43:06 +00002118 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002119 }
2120 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2121 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
2122 $$ = S;
2123
2124 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2125 E = $8->end();
2126 for (; I != E; ++I) {
2127 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2128 S->addCase(CI, I->second);
2129 else
Reid Spencer713eedc2006-08-18 08:43:06 +00002130 GEN_ERROR("Switch case is constant, but not a simple integer!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002131 }
2132 delete $8;
Reid Spencer713eedc2006-08-18 08:43:06 +00002133 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002134 }
2135 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2136 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
2137 $$ = S;
Reid Spencer713eedc2006-08-18 08:43:06 +00002138 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002139 }
2140 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2141 TO LABEL ValueRef UNWIND LABEL ValueRef {
2142 const PointerType *PFTy;
2143 const FunctionType *Ty;
2144
2145 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2146 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2147 // Pull out the types of all of the arguments...
2148 std::vector<const Type*> ParamTypes;
2149 if ($6) {
2150 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2151 I != E; ++I)
2152 ParamTypes.push_back((*I)->getType());
2153 }
2154
2155 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2156 if (isVarArg) ParamTypes.pop_back();
2157
2158 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2159 PFTy = PointerType::get(Ty);
2160 }
2161
2162 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2163
2164 BasicBlock *Normal = getBBVal($10);
2165 BasicBlock *Except = getBBVal($13);
2166
2167 // Create the call node...
2168 if (!$6) { // Has no arguments?
2169 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2170 } else { // Has arguments?
2171 // Loop through FunctionType's arguments and ensure they are specified
2172 // correctly!
2173 //
2174 FunctionType::param_iterator I = Ty->param_begin();
2175 FunctionType::param_iterator E = Ty->param_end();
2176 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2177
2178 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2179 if ((*ArgI)->getType() != *I)
Reid Spencer713eedc2006-08-18 08:43:06 +00002180 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002181 (*I)->getDescription() + "'!");
2182
2183 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
Reid Spencer713eedc2006-08-18 08:43:06 +00002184 GEN_ERROR("Invalid number of parameters detected!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002185
2186 $$ = new InvokeInst(V, Normal, Except, *$6);
2187 }
2188 cast<InvokeInst>($$)->setCallingConv($2);
2189
2190 delete $3;
2191 delete $6;
Reid Spencer713eedc2006-08-18 08:43:06 +00002192 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002193 }
2194 | UNWIND {
2195 $$ = new UnwindInst();
Reid Spencer713eedc2006-08-18 08:43:06 +00002196 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002197 }
2198 | UNREACHABLE {
2199 $$ = new UnreachableInst();
Reid Spencer713eedc2006-08-18 08:43:06 +00002200 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002201 };
2202
2203
2204
2205JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2206 $$ = $1;
2207 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2208 if (V == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002209 GEN_ERROR("May only switch on a constant pool value!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002210
2211 $$->push_back(std::make_pair(V, getBBVal($6)));
Reid Spencer713eedc2006-08-18 08:43:06 +00002212 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002213 }
2214 | IntType ConstValueRef ',' LABEL ValueRef {
2215 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2216 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2217
2218 if (V == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002219 GEN_ERROR("May only switch on a constant pool value!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002220
2221 $$->push_back(std::make_pair(V, getBBVal($5)));
Reid Spencer713eedc2006-08-18 08:43:06 +00002222 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002223 };
2224
2225Inst : OptAssign InstVal {
2226 // Is this definition named?? if so, assign the name...
2227 setValueName($2, $1);
2228 InsertValue($2);
2229 $$ = $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002230 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002231};
2232
2233PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2234 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2235 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2236 delete $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00002237 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002238 }
2239 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2240 $$ = $1;
2241 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2242 getBBVal($6)));
Reid Spencer713eedc2006-08-18 08:43:06 +00002243 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002244 };
2245
2246
2247ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2248 $$ = new std::vector<Value*>();
2249 $$->push_back($1);
Reid Spencer713eedc2006-08-18 08:43:06 +00002250 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002251 }
2252 | ValueRefList ',' ResolvedVal {
2253 $$ = $1;
2254 $1->push_back($3);
Reid Spencer713eedc2006-08-18 08:43:06 +00002255 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002256 };
2257
2258// ValueRefListE - Just like ValueRefList, except that it may also be empty!
2259ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2260
2261OptTailCall : TAIL CALL {
2262 $$ = true;
Reid Spencer713eedc2006-08-18 08:43:06 +00002263 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002264 }
2265 | CALL {
2266 $$ = false;
Reid Spencer713eedc2006-08-18 08:43:06 +00002267 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002268 };
2269
2270
2271
2272InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2273 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2274 !isa<PackedType>((*$2).get()))
Reid Spencer713eedc2006-08-18 08:43:06 +00002275 GEN_ERROR(
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002276 "Arithmetic operator requires integer, FP, or packed operands!");
2277 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
Reid Spencer713eedc2006-08-18 08:43:06 +00002278 GEN_ERROR("Rem not supported on packed types!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002279 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2280 if ($$ == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002281 GEN_ERROR("binary operator returned null!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002282 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002283 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002284 }
2285 | LogicalOps Types ValueRef ',' ValueRef {
2286 if (!(*$2)->isIntegral()) {
2287 if (!isa<PackedType>($2->get()) ||
2288 !cast<PackedType>($2->get())->getElementType()->isIntegral())
Reid Spencer713eedc2006-08-18 08:43:06 +00002289 GEN_ERROR("Logical operator requires integral operands!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002290 }
2291 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2292 if ($$ == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002293 GEN_ERROR("binary operator returned null!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002294 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002295 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002296 }
2297 | SetCondOps Types ValueRef ',' ValueRef {
2298 if(isa<PackedType>((*$2).get())) {
Reid Spencer713eedc2006-08-18 08:43:06 +00002299 GEN_ERROR(
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002300 "PackedTypes currently not supported in setcc instructions!");
2301 }
2302 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2303 if ($$ == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002304 GEN_ERROR("binary operator returned null!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002305 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002306 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002307 }
2308 | NOT ResolvedVal {
2309 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2310 << " Replacing with 'xor'.\n";
2311
2312 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2313 if (Ones == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002314 GEN_ERROR("Expected integral type for not instruction!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002315
2316 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2317 if ($$ == 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002318 GEN_ERROR("Could not create a xor instruction!");
2319 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002320 }
2321 | ShiftOps ResolvedVal ',' ResolvedVal {
2322 if ($4->getType() != Type::UByteTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00002323 GEN_ERROR("Shift amount must be ubyte!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002324 if (!$2->getType()->isInteger())
Reid Spencer713eedc2006-08-18 08:43:06 +00002325 GEN_ERROR("Shift constant expression requires integer operand!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002326 $$ = new ShiftInst($1, $2, $4);
Reid Spencer713eedc2006-08-18 08:43:06 +00002327 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002328 }
2329 | CAST ResolvedVal TO Types {
2330 if (!$4->get()->isFirstClassType())
Reid Spencer713eedc2006-08-18 08:43:06 +00002331 GEN_ERROR("cast instruction to a non-primitive type: '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002332 $4->get()->getDescription() + "'!");
2333 $$ = new CastInst($2, *$4);
2334 delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00002335 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002336 }
2337 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2338 if ($2->getType() != Type::BoolTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00002339 GEN_ERROR("select condition must be boolean!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002340 if ($4->getType() != $6->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00002341 GEN_ERROR("select value types should match!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002342 $$ = new SelectInst($2, $4, $6);
Reid Spencer713eedc2006-08-18 08:43:06 +00002343 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002344 }
2345 | VAARG ResolvedVal ',' Types {
2346 NewVarArgs = true;
2347 $$ = new VAArgInst($2, *$4);
2348 delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00002349 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002350 }
2351 | VAARG_old ResolvedVal ',' Types {
2352 ObsoleteVarArgs = true;
2353 const Type* ArgTy = $2->getType();
2354 Function* NF = CurModule.CurrentModule->
2355 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2356
2357 //b = vaarg a, t ->
2358 //foo = alloca 1 of t
2359 //bar = vacopy a
2360 //store bar -> foo
2361 //b = vaarg foo, t
2362 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2363 CurBB->getInstList().push_back(foo);
2364 CallInst* bar = new CallInst(NF, $2);
2365 CurBB->getInstList().push_back(bar);
2366 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2367 $$ = new VAArgInst(foo, *$4);
2368 delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00002369 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002370 }
2371 | VANEXT_old ResolvedVal ',' Types {
2372 ObsoleteVarArgs = true;
2373 const Type* ArgTy = $2->getType();
2374 Function* NF = CurModule.CurrentModule->
2375 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2376
2377 //b = vanext a, t ->
2378 //foo = alloca 1 of t
2379 //bar = vacopy a
2380 //store bar -> foo
2381 //tmp = vaarg foo, t
2382 //b = load foo
2383 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2384 CurBB->getInstList().push_back(foo);
2385 CallInst* bar = new CallInst(NF, $2);
2386 CurBB->getInstList().push_back(bar);
2387 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2388 Instruction* tmp = new VAArgInst(foo, *$4);
2389 CurBB->getInstList().push_back(tmp);
2390 $$ = new LoadInst(foo);
2391 delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00002392 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002393 }
2394 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
Chris Lattner931565c2006-04-08 04:09:02 +00002395 if (!ExtractElementInst::isValidOperands($2, $4))
Reid Spencer713eedc2006-08-18 08:43:06 +00002396 GEN_ERROR("Invalid extractelement operands!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002397 $$ = new ExtractElementInst($2, $4);
Reid Spencer713eedc2006-08-18 08:43:06 +00002398 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002399 }
2400 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Chris Lattner931565c2006-04-08 04:09:02 +00002401 if (!InsertElementInst::isValidOperands($2, $4, $6))
Reid Spencer713eedc2006-08-18 08:43:06 +00002402 GEN_ERROR("Invalid insertelement operands!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002403 $$ = new InsertElementInst($2, $4, $6);
Reid Spencer713eedc2006-08-18 08:43:06 +00002404 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002405 }
Chris Lattner9ff96a72006-04-08 01:18:56 +00002406 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Chris Lattneraebccf82006-04-08 03:55:17 +00002407 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
Reid Spencer713eedc2006-08-18 08:43:06 +00002408 GEN_ERROR("Invalid shufflevector operands!");
Chris Lattner9ff96a72006-04-08 01:18:56 +00002409 $$ = new ShuffleVectorInst($2, $4, $6);
Reid Spencer713eedc2006-08-18 08:43:06 +00002410 CHECK_FOR_ERROR
Chris Lattner9ff96a72006-04-08 01:18:56 +00002411 }
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002412 | PHI_TOK PHIList {
2413 const Type *Ty = $2->front().first->getType();
2414 if (!Ty->isFirstClassType())
Reid Spencer713eedc2006-08-18 08:43:06 +00002415 GEN_ERROR("PHI node operands must be of first class type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002416 $$ = new PHINode(Ty);
2417 ((PHINode*)$$)->reserveOperandSpace($2->size());
2418 while ($2->begin() != $2->end()) {
2419 if ($2->front().first->getType() != Ty)
Reid Spencer713eedc2006-08-18 08:43:06 +00002420 GEN_ERROR("All elements of a PHI node must be of the same type!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002421 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2422 $2->pop_front();
2423 }
2424 delete $2; // Free the list...
Reid Spencer713eedc2006-08-18 08:43:06 +00002425 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002426 }
2427 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2428 const PointerType *PFTy;
2429 const FunctionType *Ty;
2430
2431 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2432 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2433 // Pull out the types of all of the arguments...
2434 std::vector<const Type*> ParamTypes;
2435 if ($6) {
2436 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2437 I != E; ++I)
2438 ParamTypes.push_back((*I)->getType());
2439 }
2440
2441 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2442 if (isVarArg) ParamTypes.pop_back();
2443
2444 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
Reid Spencer713eedc2006-08-18 08:43:06 +00002445 GEN_ERROR("LLVM functions cannot return aggregate types!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002446
2447 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2448 PFTy = PointerType::get(Ty);
2449 }
2450
2451 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2452
2453 // Create the call node...
2454 if (!$6) { // Has no arguments?
2455 // Make sure no arguments is a good thing!
2456 if (Ty->getNumParams() != 0)
Reid Spencer713eedc2006-08-18 08:43:06 +00002457 GEN_ERROR("No arguments passed to a function that "
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002458 "expects arguments!");
2459
2460 $$ = new CallInst(V, std::vector<Value*>());
2461 } else { // Has arguments?
2462 // Loop through FunctionType's arguments and ensure they are specified
2463 // correctly!
2464 //
2465 FunctionType::param_iterator I = Ty->param_begin();
2466 FunctionType::param_iterator E = Ty->param_end();
2467 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2468
2469 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2470 if ((*ArgI)->getType() != *I)
Reid Spencer713eedc2006-08-18 08:43:06 +00002471 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002472 (*I)->getDescription() + "'!");
2473
2474 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
Reid Spencer713eedc2006-08-18 08:43:06 +00002475 GEN_ERROR("Invalid number of parameters detected!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002476
2477 $$ = new CallInst(V, *$6);
2478 }
2479 cast<CallInst>($$)->setTailCall($1);
2480 cast<CallInst>($$)->setCallingConv($2);
2481 delete $3;
2482 delete $6;
Reid Spencer713eedc2006-08-18 08:43:06 +00002483 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002484 }
2485 | MemoryInst {
2486 $$ = $1;
Reid Spencer713eedc2006-08-18 08:43:06 +00002487 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002488 };
2489
2490
2491// IndexList - List of indices for GEP based instructions...
2492IndexList : ',' ValueRefList {
2493 $$ = $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002494 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002495 } | /* empty */ {
2496 $$ = new std::vector<Value*>();
Reid Spencer713eedc2006-08-18 08:43:06 +00002497 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002498 };
2499
2500OptVolatile : VOLATILE {
2501 $$ = true;
Reid Spencer713eedc2006-08-18 08:43:06 +00002502 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002503 }
2504 | /* empty */ {
2505 $$ = false;
Reid Spencer713eedc2006-08-18 08:43:06 +00002506 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002507 };
2508
2509
2510
2511MemoryInst : MALLOC Types OptCAlign {
2512 $$ = new MallocInst(*$2, 0, $3);
2513 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002514 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002515 }
2516 | MALLOC Types ',' UINT ValueRef OptCAlign {
2517 $$ = new MallocInst(*$2, getVal($4, $5), $6);
2518 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002519 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002520 }
2521 | ALLOCA Types OptCAlign {
2522 $$ = new AllocaInst(*$2, 0, $3);
2523 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002524 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002525 }
2526 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2527 $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2528 delete $2;
Reid Spencer713eedc2006-08-18 08:43:06 +00002529 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002530 }
2531 | FREE ResolvedVal {
2532 if (!isa<PointerType>($2->getType()))
Reid Spencer713eedc2006-08-18 08:43:06 +00002533 GEN_ERROR("Trying to free nonpointer type " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002534 $2->getType()->getDescription() + "!");
2535 $$ = new FreeInst($2);
Reid Spencer713eedc2006-08-18 08:43:06 +00002536 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002537 }
2538
2539 | OptVolatile LOAD Types ValueRef {
2540 if (!isa<PointerType>($3->get()))
Reid Spencer713eedc2006-08-18 08:43:06 +00002541 GEN_ERROR("Can't load from nonpointer type: " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002542 (*$3)->getDescription());
2543 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
Reid Spencer713eedc2006-08-18 08:43:06 +00002544 GEN_ERROR("Can't load from pointer of non-first-class type: " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002545 (*$3)->getDescription());
2546 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2547 delete $3;
Reid Spencer713eedc2006-08-18 08:43:06 +00002548 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002549 }
2550 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2551 const PointerType *PT = dyn_cast<PointerType>($5->get());
2552 if (!PT)
Reid Spencer713eedc2006-08-18 08:43:06 +00002553 GEN_ERROR("Can't store to a nonpointer type: " +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002554 (*$5)->getDescription());
2555 const Type *ElTy = PT->getElementType();
2556 if (ElTy != $3->getType())
Reid Spencer713eedc2006-08-18 08:43:06 +00002557 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002558 "' into space of type '" + ElTy->getDescription() + "'!");
2559
2560 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2561 delete $5;
Reid Spencer713eedc2006-08-18 08:43:06 +00002562 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002563 }
2564 | GETELEMENTPTR Types ValueRef IndexList {
2565 if (!isa<PointerType>($2->get()))
Reid Spencer713eedc2006-08-18 08:43:06 +00002566 GEN_ERROR("getelementptr insn requires pointer operand!");
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002567
2568 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2569 // indices to uint struct indices for compatibility.
2570 generic_gep_type_iterator<std::vector<Value*>::iterator>
2571 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2572 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2573 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2574 if (isa<StructType>(*GTI)) // Only change struct indices
2575 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2576 if (CUI->getType() == Type::UByteTy)
2577 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2578
2579 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
Reid Spencer713eedc2006-08-18 08:43:06 +00002580 GEN_ERROR("Invalid getelementptr indices for type '" +
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002581 (*$2)->getDescription()+ "'!");
2582 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2583 delete $2; delete $4;
Reid Spencer713eedc2006-08-18 08:43:06 +00002584 CHECK_FOR_ERROR
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002585 };
2586
2587
2588%%
Reid Spencer713eedc2006-08-18 08:43:06 +00002589
2590void llvm::GenerateError(const std::string &message, int LineNo) {
2591 if (LineNo == -1) LineNo = llvmAsmlineno;
2592 // TODO: column number in exception
2593 if (TheParseError)
2594 TheParseError->setError(CurFilename, message, LineNo);
2595 TriggerError = 1;
2596}
2597
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002598int yyerror(const char *ErrorMsg) {
2599 std::string where
2600 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2601 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2602 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2603 if (yychar == YYEMPTY || yychar == 0)
2604 errMsg += "end-of-file.";
2605 else
2606 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
Reid Spencer713eedc2006-08-18 08:43:06 +00002607 GenerateError(errMsg);
Chris Lattnerf20e61f2006-02-15 07:22:58 +00002608 return 0;
2609}