blob: 5f607b265a20cc02f29ef9dcff591149edb69d06 [file] [log] [blame]
Reid Spencer950bf602007-01-26 08:19:09 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
Reid Spencere7c3c602006-11-30 06:36:44 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer950bf602007-01-26 08:19:09 +00005// 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.
Reid Spencere7c3c602006-11-30 06:36:44 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencer950bf602007-01-26 08:19:09 +000010// This file implements the bison parser for LLVM assembly languages files.
Reid Spencere7c3c602006-11-30 06:36:44 +000011//
12//===----------------------------------------------------------------------===//
13
14%{
Reid Spencer319a7302007-01-05 17:20:02 +000015#include "UpgradeInternals.h"
Reid Spencer950bf602007-01-26 08:19:09 +000016#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/Support/GetElementPtrTypeIterator.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/Support/MathExtras.h"
Reid Spencere7c3c602006-11-30 06:36:44 +000024#include <algorithm>
Reid Spencere7c3c602006-11-30 06:36:44 +000025#include <iostream>
Reid Spencer950bf602007-01-26 08:19:09 +000026#include <list>
27#include <utility>
28
29// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30// relating to upreferences in the input stream.
31//
32//#define DEBUG_UPREFS 1
33#ifdef DEBUG_UPREFS
34#define UR_OUT(X) std::cerr << X
35#else
36#define UR_OUT(X)
37#endif
Reid Spencere7c3c602006-11-30 06:36:44 +000038
Reid Spencere77e35e2006-12-01 20:26:20 +000039#define YYERROR_VERBOSE 1
Reid Spencer96839be2006-11-30 16:50:26 +000040#define YYINCLUDED_STDLIB_H
Reid Spencere77e35e2006-12-01 20:26:20 +000041#define YYDEBUG 1
Reid Spencere7c3c602006-11-30 06:36:44 +000042
Reid Spencer950bf602007-01-26 08:19:09 +000043int yylex();
Reid Spencere7c3c602006-11-30 06:36:44 +000044int yyparse();
45
Reid Spencer950bf602007-01-26 08:19:09 +000046int yyerror(const char*);
47static void warning(const std::string& WarningMsg);
48
49namespace llvm {
50
Reid Spencer950bf602007-01-26 08:19:09 +000051std::istream* LexInput;
Reid Spencere7c3c602006-11-30 06:36:44 +000052static std::string CurFilename;
Reid Spencer96839be2006-11-30 16:50:26 +000053
Reid Spencer71d2ec92006-12-31 06:02:26 +000054// This bool controls whether attributes are ever added to function declarations
55// definitions and calls.
56static bool AddAttributes = false;
57
Reid Spencer950bf602007-01-26 08:19:09 +000058static Module *ParserResult;
59static bool ObsoleteVarArgs;
60static bool NewVarArgs;
61static BasicBlock *CurBB;
62static GlobalVariable *CurGV;
Reid Spencera50d5962006-12-02 04:11:07 +000063
Reid Spencer950bf602007-01-26 08:19:09 +000064// 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
68
69typedef std::pair<std::string,const Type*> RenameMapKey;
70typedef std::map<RenameMapKey,std::string> RenameMapType;
71
72static void
73ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
75
76static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
85
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
95 //
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
97 GlobalRefsType;
98 GlobalRefsType GlobalRefs;
99
100 void ModuleDone() {
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
104 //
105 ResolveDefinitions(LateResolveValues);
106
107 // Check to make sure that all global value forward references have been
108 // resolved!
109 //
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
112
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
114 I != E; ++I) {
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
117 }
118 error(UndefinedReferences);
119 return;
120 }
121
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
128 dataLayout += "-";
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
131 }
132 CurrentModule->setDataLayout(dataLayout);
133 }
134
135 Values.clear(); // Clear out function local definitions
136 Types.clear();
137 CurrentModule = 0;
138 }
139
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
149 Ret = I->second;
150 GlobalRefs.erase(I);
151 }
152 return Ret;
153 }
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
156} CurModule;
157
158Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
160
161static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
163
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
168
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
Reid Spencer950bf602007-01-26 08:19:09 +0000174 unsigned NextBBNum;
175
176 inline PerFunctionInfo() {
177 CurrentFunction = 0;
178 isDeclare = false;
179 Linkage = GlobalValue::ExternalLinkage;
180 }
181
182 inline void FunctionStart(Function *M) {
183 CurrentFunction = M;
184 NextBBNum = 0;
185 }
186
187 void FunctionDone() {
188 NumberedBlocks.clear();
189
190 // Any forward referenced blocks left?
191 if (!BBForwardRefs.empty()) {
192 error("Undefined reference to label " +
193 BBForwardRefs.begin()->first->getName());
194 return;
195 }
196
197 // Resolve all forward references now.
198 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
199
200 Values.clear(); // Clear out function local definitions
201 RenameMap.clear();
Reid Spencer950bf602007-01-26 08:19:09 +0000202 CurrentFunction = 0;
203 isDeclare = false;
204 Linkage = GlobalValue::ExternalLinkage;
205 }
206} CurFun; // Info for the current function...
207
208static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
209
210
211//===----------------------------------------------------------------------===//
212// Code to handle definitions of all the types
213//===----------------------------------------------------------------------===//
214
215static int InsertValue(Value *V,
216 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
217 if (V->hasName()) return -1; // Is this a numbered definition?
218
219 // Yes, insert the value into the value table...
220 ValueList &List = ValueTab[V->getType()];
221 List.push_back(V);
222 return List.size()-1;
223}
224
Reid Spencerd7c4f8c2007-01-26 19:59:25 +0000225static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
Reid Spencer950bf602007-01-26 08:19:09 +0000226 switch (D.Type) {
227 case ValID::NumberVal: // Is it a numbered definition?
228 // Module constants occupy the lowest numbered slots...
229 if ((unsigned)D.Num < CurModule.Types.size()) {
230 return CurModule.Types[(unsigned)D.Num];
231 }
232 break;
233 case ValID::NameVal: // Is it a named definition?
234 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
235 D.destroy(); // Free old strdup'd memory...
236 return N;
237 }
238 break;
239 default:
240 error("Internal parser error: Invalid symbol type reference");
241 return 0;
242 }
243
244 // If we reached here, we referenced either a symbol that we don't know about
245 // or an id number that hasn't been read yet. We may be referencing something
246 // forward, so just create an entry to be resolved later and get to it...
247 //
248 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
249
250
251 if (inFunctionScope()) {
252 if (D.Type == ValID::NameVal) {
253 error("Reference to an undefined type: '" + D.getName() + "'");
254 return 0;
255 } else {
256 error("Reference to an undefined type: #" + itostr(D.Num));
257 return 0;
258 }
259 }
260
261 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
262 if (I != CurModule.LateResolveTypes.end())
263 return I->second;
264
265 Type *Typ = OpaqueType::get();
266 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
267 return Typ;
268 }
269
270// getExistingValue - Look up the value specified by the provided type and
271// the provided ValID. If the value exists and has already been defined, return
272// it. Otherwise return null.
273//
274static Value *getExistingValue(const Type *Ty, const ValID &D) {
275 if (isa<FunctionType>(Ty)) {
276 error("Functions are not values and must be referenced as pointers");
277 }
278
279 switch (D.Type) {
280 case ValID::NumberVal: { // Is it a numbered definition?
281 unsigned Num = (unsigned)D.Num;
282
283 // Module constants occupy the lowest numbered slots...
284 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
285 if (VI != CurModule.Values.end()) {
286 if (Num < VI->second.size())
287 return VI->second[Num];
288 Num -= VI->second.size();
289 }
290
291 // Make sure that our type is within bounds
292 VI = CurFun.Values.find(Ty);
293 if (VI == CurFun.Values.end()) return 0;
294
295 // Check that the number is within bounds...
296 if (VI->second.size() <= Num) return 0;
297
298 return VI->second[Num];
299 }
300
301 case ValID::NameVal: { // Is it a named definition?
302 // Get the name out of the ID
303 std::string Name(D.Name);
304 Value* V = 0;
305 RenameMapKey Key = std::make_pair(Name, Ty);
306 if (inFunctionScope()) {
307 // See if the name was renamed
308 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
309 std::string LookupName;
310 if (I != CurFun.RenameMap.end())
311 LookupName = I->second;
312 else
313 LookupName = Name;
314 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
315 V = SymTab.lookup(Ty, LookupName);
316 }
317 if (!V) {
318 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
319 std::string LookupName;
320 if (I != CurModule.RenameMap.end())
321 LookupName = I->second;
322 else
323 LookupName = Name;
324 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
325 }
326 if (V == 0)
327 return 0;
328
329 D.destroy(); // Free old strdup'd memory...
330 return V;
331 }
332
333 // Check to make sure that "Ty" is an integral type, and that our
334 // value will fit into the specified type...
335 case ValID::ConstSIntVal: // Is it a constant pool reference??
336 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
337 error("Signed integral constant '" + itostr(D.ConstPool64) +
338 "' is invalid for type '" + Ty->getDescription() + "'");
339 }
340 return ConstantInt::get(Ty, D.ConstPool64);
341
342 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
343 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
344 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
345 error("Integral constant '" + utostr(D.UConstPool64) +
346 "' is invalid or out of range");
347 else // This is really a signed reference. Transmogrify.
348 return ConstantInt::get(Ty, D.ConstPool64);
349 } else
350 return ConstantInt::get(Ty, D.UConstPool64);
351
352 case ValID::ConstFPVal: // Is it a floating point const pool reference?
353 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
354 error("FP constant invalid for type");
355 return ConstantFP::get(Ty, D.ConstPoolFP);
356
357 case ValID::ConstNullVal: // Is it a null value?
358 if (!isa<PointerType>(Ty))
359 error("Cannot create a a non pointer null");
360 return ConstantPointerNull::get(cast<PointerType>(Ty));
361
362 case ValID::ConstUndefVal: // Is it an undef value?
363 return UndefValue::get(Ty);
364
365 case ValID::ConstZeroVal: // Is it a zero value?
366 return Constant::getNullValue(Ty);
367
368 case ValID::ConstantVal: // Fully resolved constant?
369 if (D.ConstantValue->getType() != Ty)
370 error("Constant expression type different from required type");
371 return D.ConstantValue;
372
373 case ValID::InlineAsmVal: { // Inline asm expression
374 const PointerType *PTy = dyn_cast<PointerType>(Ty);
375 const FunctionType *FTy =
376 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
377 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
378 error("Invalid type for asm constraint string");
379 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
380 D.IAD->HasSideEffects);
381 D.destroy(); // Free InlineAsmDescriptor.
382 return IA;
383 }
384 default:
385 assert(0 && "Unhandled case");
386 return 0;
387 } // End of switch
388
389 assert(0 && "Unhandled case");
390 return 0;
391}
392
393// getVal - This function is identical to getExistingValue, except that if a
394// value is not already defined, it "improvises" by creating a placeholder var
395// that looks and acts just like the requested variable. When the value is
396// defined later, all uses of the placeholder variable are replaced with the
397// real thing.
398//
399static Value *getVal(const Type *Ty, const ValID &ID) {
400 if (Ty == Type::LabelTy)
401 error("Cannot use a basic block here");
402
403 // See if the value has already been defined.
404 Value *V = getExistingValue(Ty, ID);
405 if (V) return V;
406
407 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
408 error("Invalid use of a composite type");
409
410 // If we reached here, we referenced either a symbol that we don't know about
411 // or an id number that hasn't been read yet. We may be referencing something
412 // forward, so just create an entry to be resolved later and get to it...
Reid Spencer950bf602007-01-26 08:19:09 +0000413 V = new Argument(Ty);
414
415 // Remember where this forward reference came from. FIXME, shouldn't we try
416 // to recycle these things??
417 CurModule.PlaceHolderInfo.insert(
418 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
419
420 if (inFunctionScope())
421 InsertValue(V, CurFun.LateResolveValues);
422 else
423 InsertValue(V, CurModule.LateResolveValues);
424 return V;
425}
426
427/// getBBVal - This is used for two purposes:
428/// * If isDefinition is true, a new basic block with the specified ID is being
429/// defined.
430/// * If isDefinition is true, this is a reference to a basic block, which may
431/// or may not be a forward reference.
432///
433static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
434 assert(inFunctionScope() && "Can't get basic block at global scope");
435
436 std::string Name;
437 BasicBlock *BB = 0;
438 switch (ID.Type) {
439 default:
440 error("Illegal label reference " + ID.getName());
441 break;
442 case ValID::NumberVal: // Is it a numbered definition?
443 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
444 CurFun.NumberedBlocks.resize(ID.Num+1);
445 BB = CurFun.NumberedBlocks[ID.Num];
446 break;
447 case ValID::NameVal: // Is it a named definition?
448 Name = ID.Name;
449 if (Value *N = CurFun.CurrentFunction->
450 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
451 if (N->getType() != Type::LabelTy)
452 error("Name '" + Name + "' does not refer to a BasicBlock");
453 BB = cast<BasicBlock>(N);
454 }
455 break;
456 }
457
458 // See if the block has already been defined.
459 if (BB) {
460 // If this is the definition of the block, make sure the existing value was
461 // just a forward reference. If it was a forward reference, there will be
462 // an entry for it in the PlaceHolderInfo map.
463 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
464 // The existing value was a definition, not a forward reference.
465 error("Redefinition of label " + ID.getName());
466
467 ID.destroy(); // Free strdup'd memory.
468 return BB;
469 }
470
471 // Otherwise this block has not been seen before.
472 BB = new BasicBlock("", CurFun.CurrentFunction);
473 if (ID.Type == ValID::NameVal) {
474 BB->setName(ID.Name);
475 } else {
476 CurFun.NumberedBlocks[ID.Num] = BB;
477 }
478
479 // If this is not a definition, keep track of it so we can use it as a forward
480 // reference.
481 if (!isDefinition) {
482 // Remember where this forward reference came from.
483 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
484 } else {
485 // The forward declaration could have been inserted anywhere in the
486 // function: insert it into the correct place now.
487 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
488 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
489 }
490 ID.destroy();
491 return BB;
492}
493
494
495//===----------------------------------------------------------------------===//
496// Code to handle forward references in instructions
497//===----------------------------------------------------------------------===//
498//
499// This code handles the late binding needed with statements that reference
500// values not defined yet... for example, a forward branch, or the PHI node for
501// a loop body.
502//
503// This keeps a table (CurFun.LateResolveValues) of all such forward references
504// and back patchs after we are done.
505//
506
507// ResolveDefinitions - If we could not resolve some defs at parsing
508// time (forward branches, phi functions for loops, etc...) resolve the
509// defs now...
510//
511static void
512ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
513 std::map<const Type*,ValueList> *FutureLateResolvers) {
514 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
515 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
516 E = LateResolvers.end(); LRI != E; ++LRI) {
517 ValueList &List = LRI->second;
518 while (!List.empty()) {
519 Value *V = List.back();
520 List.pop_back();
521
522 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
523 CurModule.PlaceHolderInfo.find(V);
524 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
525
526 ValID &DID = PHI->second.first;
527
528 Value *TheRealValue = getExistingValue(LRI->first, DID);
529 if (TheRealValue) {
530 V->replaceAllUsesWith(TheRealValue);
531 delete V;
532 CurModule.PlaceHolderInfo.erase(PHI);
533 } else if (FutureLateResolvers) {
534 // Functions have their unresolved items forwarded to the module late
535 // resolver table
536 InsertValue(V, *FutureLateResolvers);
537 } else {
538 if (DID.Type == ValID::NameVal) {
539 error("Reference to an invalid definition: '" +DID.getName()+
540 "' of type '" + V->getType()->getDescription() + "'",
541 PHI->second.second);
542 return;
543 } else {
544 error("Reference to an invalid definition: #" +
545 itostr(DID.Num) + " of type '" +
546 V->getType()->getDescription() + "'", PHI->second.second);
547 return;
548 }
549 }
550 }
551 }
552
553 LateResolvers.clear();
554}
555
556// ResolveTypeTo - A brand new type was just declared. This means that (if
557// name is not null) things referencing Name can be resolved. Otherwise, things
558// refering to the number can be resolved. Do this now.
559//
560static void ResolveTypeTo(char *Name, const Type *ToTy) {
561 ValID D;
562 if (Name) D = ValID::create(Name);
563 else D = ValID::create((int)CurModule.Types.size());
564
565 std::map<ValID, PATypeHolder>::iterator I =
566 CurModule.LateResolveTypes.find(D);
567 if (I != CurModule.LateResolveTypes.end()) {
568 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
569 CurModule.LateResolveTypes.erase(I);
570 }
571}
572
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000573/// @brief This just makes any name given to it unique, up to MAX_UINT times.
Reid Spencer950bf602007-01-26 08:19:09 +0000574static std::string makeNameUnique(const std::string& Name) {
575 static unsigned UniqueNameCounter = 1;
576 std::string Result(Name);
577 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
578 return Result;
579}
580
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000581/// This is the implementation portion of TypeHasInteger. It traverses the
582/// type given, avoiding recursive types, and returns true as soon as it finds
583/// an integer type. If no integer type is found, it returns false.
584static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
585 // Handle some easy cases
586 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
587 return false;
588 if (Ty->isInteger())
589 return true;
590 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
591 return STy->getElementType()->isInteger();
592
593 // Avoid type structure recursion
594 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
595 I != E; ++I)
596 if (Ty == *I)
597 return false;
598
599 // Push us on the type stack
600 Stack.push_back(Ty);
601
602 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
603 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
604 return true;
605 FunctionType::param_iterator I = FTy->param_begin();
606 FunctionType::param_iterator E = FTy->param_end();
607 for (; I != E; ++I)
608 if (TypeHasIntegerI(*I, Stack))
609 return true;
610 return false;
611 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
612 StructType::element_iterator I = STy->element_begin();
613 StructType::element_iterator E = STy->element_end();
614 for (; I != E; ++I) {
615 if (TypeHasIntegerI(*I, Stack))
616 return true;
617 }
618 return false;
619 }
620 // There shouldn't be anything else, but its definitely not integer
621 assert(0 && "What type is this?");
622 return false;
623}
624
625/// This is the interface to TypeHasIntegerI. It just provides the type stack,
626/// to avoid recursion, and then calls TypeHasIntegerI.
627static inline bool TypeHasInteger(const Type *Ty) {
628 std::vector<const Type*> TyStack;
629 return TypeHasIntegerI(Ty, TyStack);
630}
631
Reid Spencer950bf602007-01-26 08:19:09 +0000632// setValueName - Set the specified value to the name given. The name may be
633// null potentially, in which case this is a noop. The string passed in is
634// assumed to be a malloc'd string buffer, and is free'd by this function.
635//
636static void setValueName(Value *V, char *NameStr) {
637 if (NameStr) {
638 std::string Name(NameStr); // Copy string
639 free(NameStr); // Free old string
640
641 if (V->getType() == Type::VoidTy) {
642 error("Can't assign name '" + Name + "' to value with void type");
643 return;
644 }
645
Reid Spencer950bf602007-01-26 08:19:09 +0000646 assert(inFunctionScope() && "Must be in function scope");
647
648 // Search the function's symbol table for an existing value of this name
649 Value* Existing = 0;
650 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
651 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
652 for ( ; PI != PE; ++PI) {
653 SymbolTable::value_const_iterator VI = PI->second.find(Name);
654 if (VI != PI->second.end()) {
655 Existing = VI->second;
656 break;
657 }
658 }
659 if (Existing) {
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000660 // An existing value of the same name was found. This might have happened
661 // because of the integer type planes collapsing in LLVM 2.0.
662 if (Existing->getType() == V->getType() &&
663 !TypeHasInteger(Existing->getType())) {
664 // If the type does not contain any integers in them then this can't be
665 // a type plane collapsing issue. It truly is a redefinition and we
666 // should error out as the assembly is invalid.
667 error("Redefinition of value named '" + Name + "' of type '" +
668 V->getType()->getDescription() + "'");
669 return;
Reid Spencer950bf602007-01-26 08:19:09 +0000670 }
671 // In LLVM 2.0 we don't allow names to be re-used for any values in a
672 // function, regardless of Type. Previously re-use of names was okay as
673 // long as they were distinct types. With type planes collapsing because
674 // of the signedness change and because of PR411, this can no longer be
675 // supported. We must search the entire symbol table for a conflicting
676 // name and make the name unique. No warning is needed as this can't
677 // cause a problem.
678 std::string NewName = makeNameUnique(Name);
679 // We're changing the name but it will probably be used by other
680 // instructions as operands later on. Consequently we have to retain
681 // a mapping of the renaming that we're doing.
682 RenameMapKey Key = std::make_pair(Name,V->getType());
683 CurFun.RenameMap[Key] = NewName;
684 Name = NewName;
685 }
686
687 // Set the name.
688 V->setName(Name);
689 }
690}
691
692/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
693/// this is a declaration, otherwise it is a definition.
694static GlobalVariable *
695ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
696 bool isConstantGlobal, const Type *Ty,
697 Constant *Initializer) {
698 if (isa<FunctionType>(Ty))
699 error("Cannot declare global vars of function type");
700
701 const PointerType *PTy = PointerType::get(Ty);
702
703 std::string Name;
704 if (NameStr) {
705 Name = NameStr; // Copy string
706 free(NameStr); // Free old string
707 }
708
709 // See if this global value was forward referenced. If so, recycle the
710 // object.
711 ValID ID;
712 if (!Name.empty()) {
713 ID = ValID::create((char*)Name.c_str());
714 } else {
715 ID = ValID::create((int)CurModule.Values[PTy].size());
716 }
717
718 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
719 // Move the global to the end of the list, from whereever it was
720 // previously inserted.
721 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
722 CurModule.CurrentModule->getGlobalList().remove(GV);
723 CurModule.CurrentModule->getGlobalList().push_back(GV);
724 GV->setInitializer(Initializer);
725 GV->setLinkage(Linkage);
726 GV->setConstant(isConstantGlobal);
727 InsertValue(GV, CurModule.Values);
728 return GV;
729 }
730
731 // If this global has a name, check to see if there is already a definition
732 // of this global in the module and emit warnings if there are conflicts.
733 if (!Name.empty()) {
734 // The global has a name. See if there's an existing one of the same name.
735 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
736 // We found an existing global ov the same name. This isn't allowed
737 // in LLVM 2.0. Consequently, we must alter the name of the global so it
738 // can at least compile. This can happen because of type planes
739 // There is alread a global of the same name which means there is a
740 // conflict. Let's see what we can do about it.
741 std::string NewName(makeNameUnique(Name));
742 if (Linkage == GlobalValue::InternalLinkage) {
743 // The linkage type is internal so just warn about the rename without
744 // invoking "scarey language" about linkage failures. GVars with
745 // InternalLinkage can be renamed at will.
746 warning("Global variable '" + Name + "' was renamed to '"+
747 NewName + "'");
748 } else {
749 // The linkage of this gval is external so we can't reliably rename
750 // it because it could potentially create a linking problem.
751 // However, we can't leave the name conflict in the output either or
752 // it won't assemble with LLVM 2.0. So, all we can do is rename
753 // this one to something unique and emit a warning about the problem.
754 warning("Renaming global variable '" + Name + "' to '" + NewName +
755 "' may cause linkage errors");
756 }
757
758 // Put the renaming in the global rename map
759 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
760 CurModule.RenameMap[Key] = NewName;
761
762 // Rename it
763 Name = NewName;
764 }
765 }
766
767 // Otherwise there is no existing GV to use, create one now.
768 GlobalVariable *GV =
769 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
770 CurModule.CurrentModule);
771 InsertValue(GV, CurModule.Values);
772 return GV;
773}
774
775// setTypeName - Set the specified type to the name given. The name may be
776// null potentially, in which case this is a noop. The string passed in is
777// assumed to be a malloc'd string buffer, and is freed by this function.
778//
779// This function returns true if the type has already been defined, but is
780// allowed to be redefined in the specified context. If the name is a new name
781// for the type plane, it is inserted and false is returned.
782static bool setTypeName(const Type *T, char *NameStr) {
783 assert(!inFunctionScope() && "Can't give types function-local names");
784 if (NameStr == 0) return false;
785
786 std::string Name(NameStr); // Copy string
787 free(NameStr); // Free old string
788
789 // We don't allow assigning names to void type
790 if (T == Type::VoidTy) {
791 error("Can't assign name '" + Name + "' to the void type");
792 return false;
793 }
794
795 // Set the type name, checking for conflicts as we do so.
796 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
797
798 if (AlreadyExists) { // Inserting a name that is already defined???
799 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
800 assert(Existing && "Conflict but no matching type?");
801
802 // There is only one case where this is allowed: when we are refining an
803 // opaque type. In this case, Existing will be an opaque type.
804 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
805 // We ARE replacing an opaque type!
806 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
807 return true;
808 }
809
810 // Otherwise, this is an attempt to redefine a type. That's okay if
811 // the redefinition is identical to the original. This will be so if
812 // Existing and T point to the same Type object. In this one case we
813 // allow the equivalent redefinition.
814 if (Existing == T) return true; // Yes, it's equal.
815
816 // Any other kind of (non-equivalent) redefinition is an error.
817 error("Redefinition of type named '" + Name + "' in the '" +
818 T->getDescription() + "' type plane");
819 }
820
821 return false;
822}
823
824//===----------------------------------------------------------------------===//
825// Code for handling upreferences in type names...
826//
827
828// TypeContains - Returns true if Ty directly contains E in it.
829//
830static bool TypeContains(const Type *Ty, const Type *E) {
831 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
832 E) != Ty->subtype_end();
833}
834
835namespace {
836 struct UpRefRecord {
837 // NestingLevel - The number of nesting levels that need to be popped before
838 // this type is resolved.
839 unsigned NestingLevel;
840
841 // LastContainedTy - This is the type at the current binding level for the
842 // type. Every time we reduce the nesting level, this gets updated.
843 const Type *LastContainedTy;
844
845 // UpRefTy - This is the actual opaque type that the upreference is
846 // represented with.
847 OpaqueType *UpRefTy;
848
849 UpRefRecord(unsigned NL, OpaqueType *URTy)
850 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
851 };
852}
853
854// UpRefs - A list of the outstanding upreferences that need to be resolved.
855static std::vector<UpRefRecord> UpRefs;
856
857/// HandleUpRefs - Every time we finish a new layer of types, this function is
858/// called. It loops through the UpRefs vector, which is a list of the
859/// currently active types. For each type, if the up reference is contained in
860/// the newly completed type, we decrement the level count. When the level
861/// count reaches zero, the upreferenced type is the type that is passed in:
862/// thus we can complete the cycle.
863///
864static PATypeHolder HandleUpRefs(const Type *ty) {
865 // If Ty isn't abstract, or if there are no up-references in it, then there is
866 // nothing to resolve here.
867 if (!ty->isAbstract() || UpRefs.empty()) return ty;
868
869 PATypeHolder Ty(ty);
870 UR_OUT("Type '" << Ty->getDescription() <<
871 "' newly formed. Resolving upreferences.\n" <<
872 UpRefs.size() << " upreferences active!\n");
873
874 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
875 // to zero), we resolve them all together before we resolve them to Ty. At
876 // the end of the loop, if there is anything to resolve to Ty, it will be in
877 // this variable.
878 OpaqueType *TypeToResolve = 0;
879
880 for (unsigned i = 0; i != UpRefs.size(); ++i) {
881 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
882 << UpRefs[i].second->getDescription() << ") = "
883 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
884 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
885 // Decrement level of upreference
886 unsigned Level = --UpRefs[i].NestingLevel;
887 UpRefs[i].LastContainedTy = Ty;
888 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
889 if (Level == 0) { // Upreference should be resolved!
890 if (!TypeToResolve) {
891 TypeToResolve = UpRefs[i].UpRefTy;
892 } else {
893 UR_OUT(" * Resolving upreference for "
894 << UpRefs[i].second->getDescription() << "\n";
895 std::string OldName = UpRefs[i].UpRefTy->getDescription());
896 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
897 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
898 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
899 }
900 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
901 --i; // Do not skip the next element...
902 }
903 }
904 }
905
906 if (TypeToResolve) {
907 UR_OUT(" * Resolving upreference for "
908 << UpRefs[i].second->getDescription() << "\n";
909 std::string OldName = TypeToResolve->getDescription());
910 TypeToResolve->refineAbstractTypeTo(Ty);
911 }
912
913 return Ty;
914}
915
916static inline Instruction::TermOps
917getTermOp(TermOps op) {
918 switch (op) {
919 default : assert(0 && "Invalid OldTermOp");
920 case RetOp : return Instruction::Ret;
921 case BrOp : return Instruction::Br;
922 case SwitchOp : return Instruction::Switch;
923 case InvokeOp : return Instruction::Invoke;
924 case UnwindOp : return Instruction::Unwind;
925 case UnreachableOp: return Instruction::Unreachable;
926 }
927}
928
929static inline Instruction::BinaryOps
930getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
931 switch (op) {
932 default : assert(0 && "Invalid OldBinaryOps");
933 case SetEQ :
934 case SetNE :
935 case SetLE :
936 case SetGE :
937 case SetLT :
938 case SetGT : assert(0 && "Should use getCompareOp");
939 case AddOp : return Instruction::Add;
940 case SubOp : return Instruction::Sub;
941 case MulOp : return Instruction::Mul;
942 case DivOp : {
943 // This is an obsolete instruction so we must upgrade it based on the
944 // types of its operands.
945 bool isFP = Ty->isFloatingPoint();
946 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
947 // If its a packed type we want to use the element type
948 isFP = PTy->getElementType()->isFloatingPoint();
949 if (isFP)
950 return Instruction::FDiv;
951 else if (Sign == Signed)
952 return Instruction::SDiv;
953 return Instruction::UDiv;
954 }
955 case UDivOp : return Instruction::UDiv;
956 case SDivOp : return Instruction::SDiv;
957 case FDivOp : return Instruction::FDiv;
958 case RemOp : {
959 // This is an obsolete instruction so we must upgrade it based on the
960 // types of its operands.
961 bool isFP = Ty->isFloatingPoint();
962 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
963 // If its a packed type we want to use the element type
964 isFP = PTy->getElementType()->isFloatingPoint();
965 // Select correct opcode
966 if (isFP)
967 return Instruction::FRem;
968 else if (Sign == Signed)
969 return Instruction::SRem;
970 return Instruction::URem;
971 }
972 case URemOp : return Instruction::URem;
973 case SRemOp : return Instruction::SRem;
974 case FRemOp : return Instruction::FRem;
975 case AndOp : return Instruction::And;
976 case OrOp : return Instruction::Or;
977 case XorOp : return Instruction::Xor;
978 }
979}
980
981static inline Instruction::OtherOps
982getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
983 Signedness Sign) {
984 bool isSigned = Sign == Signed;
985 bool isFP = Ty->isFloatingPoint();
986 switch (op) {
987 default : assert(0 && "Invalid OldSetCC");
988 case SetEQ :
989 if (isFP) {
990 predicate = FCmpInst::FCMP_OEQ;
991 return Instruction::FCmp;
992 } else {
993 predicate = ICmpInst::ICMP_EQ;
994 return Instruction::ICmp;
995 }
996 case SetNE :
997 if (isFP) {
998 predicate = FCmpInst::FCMP_UNE;
999 return Instruction::FCmp;
1000 } else {
1001 predicate = ICmpInst::ICMP_NE;
1002 return Instruction::ICmp;
1003 }
1004 case SetLE :
1005 if (isFP) {
1006 predicate = FCmpInst::FCMP_OLE;
1007 return Instruction::FCmp;
1008 } else {
1009 if (isSigned)
1010 predicate = ICmpInst::ICMP_SLE;
1011 else
1012 predicate = ICmpInst::ICMP_ULE;
1013 return Instruction::ICmp;
1014 }
1015 case SetGE :
1016 if (isFP) {
1017 predicate = FCmpInst::FCMP_OGE;
1018 return Instruction::FCmp;
1019 } else {
1020 if (isSigned)
1021 predicate = ICmpInst::ICMP_SGE;
1022 else
1023 predicate = ICmpInst::ICMP_UGE;
1024 return Instruction::ICmp;
1025 }
1026 case SetLT :
1027 if (isFP) {
1028 predicate = FCmpInst::FCMP_OLT;
1029 return Instruction::FCmp;
1030 } else {
1031 if (isSigned)
1032 predicate = ICmpInst::ICMP_SLT;
1033 else
1034 predicate = ICmpInst::ICMP_ULT;
1035 return Instruction::ICmp;
1036 }
1037 case SetGT :
1038 if (isFP) {
1039 predicate = FCmpInst::FCMP_OGT;
1040 return Instruction::FCmp;
1041 } else {
1042 if (isSigned)
1043 predicate = ICmpInst::ICMP_SGT;
1044 else
1045 predicate = ICmpInst::ICMP_UGT;
1046 return Instruction::ICmp;
1047 }
1048 }
1049}
1050
1051static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1052 switch (op) {
1053 default : assert(0 && "Invalid OldMemoryOps");
1054 case MallocOp : return Instruction::Malloc;
1055 case FreeOp : return Instruction::Free;
1056 case AllocaOp : return Instruction::Alloca;
1057 case LoadOp : return Instruction::Load;
1058 case StoreOp : return Instruction::Store;
1059 case GetElementPtrOp : return Instruction::GetElementPtr;
1060 }
1061}
1062
1063static inline Instruction::OtherOps
1064getOtherOp(OtherOps op, Signedness Sign) {
1065 switch (op) {
1066 default : assert(0 && "Invalid OldOtherOps");
1067 case PHIOp : return Instruction::PHI;
1068 case CallOp : return Instruction::Call;
1069 case ShlOp : return Instruction::Shl;
1070 case ShrOp :
1071 if (Sign == Signed)
1072 return Instruction::AShr;
1073 return Instruction::LShr;
1074 case SelectOp : return Instruction::Select;
1075 case UserOp1 : return Instruction::UserOp1;
1076 case UserOp2 : return Instruction::UserOp2;
1077 case VAArg : return Instruction::VAArg;
1078 case ExtractElementOp : return Instruction::ExtractElement;
1079 case InsertElementOp : return Instruction::InsertElement;
1080 case ShuffleVectorOp : return Instruction::ShuffleVector;
1081 case ICmpOp : return Instruction::ICmp;
1082 case FCmpOp : return Instruction::FCmp;
1083 case LShrOp : return Instruction::LShr;
1084 case AShrOp : return Instruction::AShr;
1085 };
1086}
1087
1088static inline Value*
1089getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1090 Signedness DstSign, bool ForceInstruction = false) {
1091 Instruction::CastOps Opcode;
1092 const Type* SrcTy = Src->getType();
1093 if (op == CastOp) {
1094 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1095 // fp -> ptr cast is no longer supported but we must upgrade this
1096 // by doing a double cast: fp -> int -> ptr
1097 SrcTy = Type::Int64Ty;
1098 Opcode = Instruction::IntToPtr;
1099 if (isa<Constant>(Src)) {
1100 Src = ConstantExpr::getCast(Instruction::FPToUI,
1101 cast<Constant>(Src), SrcTy);
1102 } else {
1103 std::string NewName(makeNameUnique(Src->getName()));
1104 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1105 }
1106 } else if (isa<IntegerType>(DstTy) &&
1107 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1108 // cast type %x to bool was previously defined as setne type %x, null
1109 // The cast semantic is now to truncate, not compare so we must retain
1110 // the original intent by replacing the cast with a setne
1111 Constant* Null = Constant::getNullValue(SrcTy);
1112 Instruction::OtherOps Opcode = Instruction::ICmp;
1113 unsigned short predicate = ICmpInst::ICMP_NE;
1114 if (SrcTy->isFloatingPoint()) {
1115 Opcode = Instruction::FCmp;
1116 predicate = FCmpInst::FCMP_ONE;
1117 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1118 error("Invalid cast to bool");
1119 }
1120 if (isa<Constant>(Src) && !ForceInstruction)
1121 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1122 else
1123 return CmpInst::create(Opcode, predicate, Src, Null);
1124 }
1125 // Determine the opcode to use by calling CastInst::getCastOpcode
1126 Opcode =
1127 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1128
1129 } else switch (op) {
1130 default: assert(0 && "Invalid cast token");
1131 case TruncOp: Opcode = Instruction::Trunc; break;
1132 case ZExtOp: Opcode = Instruction::ZExt; break;
1133 case SExtOp: Opcode = Instruction::SExt; break;
1134 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1135 case FPExtOp: Opcode = Instruction::FPExt; break;
1136 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1137 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1138 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1139 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1140 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1141 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1142 case BitCastOp: Opcode = Instruction::BitCast; break;
1143 }
1144
1145 if (isa<Constant>(Src) && !ForceInstruction)
1146 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1147 return CastInst::create(Opcode, Src, DstTy);
1148}
1149
1150static Instruction *
1151upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1152 std::vector<Value*>& Args) {
1153
1154 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1155 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1156 if (Args.size() != 2)
1157 error("Invalid prototype for " + Name + " prototype");
1158 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1159 } else {
1160 static unsigned upgradeCount = 1;
1161 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1162 std::vector<const Type*> Params;
1163 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1164 if (Args.size() != 1)
1165 error("Invalid prototype for " + Name + " prototype");
1166 Params.push_back(PtrTy);
1167 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1168 const PointerType *PFTy = PointerType::get(FTy);
1169 Value* Func = getVal(PFTy, ID);
1170 std::string InstName("va_upgrade");
1171 InstName += llvm::utostr(upgradeCount++);
1172 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1173 return new CallInst(Func, Args);
1174 } else if (Name == "llvm.va_copy") {
1175 if (Args.size() != 2)
1176 error("Invalid prototype for " + Name + " prototype");
1177 Params.push_back(PtrTy);
1178 Params.push_back(PtrTy);
1179 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1180 const PointerType *PFTy = PointerType::get(FTy);
1181 Value* Func = getVal(PFTy, ID);
1182 std::string InstName0("va_upgrade");
1183 InstName0 += llvm::utostr(upgradeCount++);
1184 std::string InstName1("va_upgrade");
1185 InstName1 += llvm::utostr(upgradeCount++);
1186 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1187 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1188 return new CallInst(Func, Args);
1189 }
1190 }
1191 return 0;
1192}
1193
1194const Type* upgradeGEPIndices(const Type* PTy,
1195 std::vector<ValueInfo> *Indices,
1196 std::vector<Value*> &VIndices,
1197 std::vector<Constant*> *CIndices = 0) {
1198 // Traverse the indices with a gep_type_iterator so we can build the list
1199 // of constant and value indices for use later. Also perform upgrades
1200 VIndices.clear();
1201 if (CIndices) CIndices->clear();
1202 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1203 VIndices.push_back((*Indices)[i].V);
1204 generic_gep_type_iterator<std::vector<Value*>::iterator>
1205 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1206 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1207 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1208 Value *Index = VIndices[i];
1209 if (CIndices && !isa<Constant>(Index))
1210 error("Indices to constant getelementptr must be constants");
1211 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1212 // struct indices to i32 struct indices with ZExt for compatibility.
1213 else if (isa<StructType>(*GTI)) { // Only change struct indices
1214 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1215 if (CUI->getType()->getBitWidth() == 8)
1216 Index =
1217 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1218 } else {
1219 // Make sure that unsigned SequentialType indices are zext'd to
1220 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1221 // all indices for SequentialType elements. We must retain the same
1222 // semantic (zext) for unsigned types.
1223 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
Reid Spencer38f682b2007-01-26 20:31:18 +00001224 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
Reid Spencer950bf602007-01-26 08:19:09 +00001225 if (CIndices)
1226 Index = ConstantExpr::getCast(Instruction::ZExt,
1227 cast<Constant>(Index), Type::Int64Ty);
1228 else
1229 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001230 makeNameUnique("gep_upgrade"), CurBB);
Reid Spencer38f682b2007-01-26 20:31:18 +00001231 VIndices[i] = Index;
1232 }
Reid Spencer950bf602007-01-26 08:19:09 +00001233 }
1234 // Add to the CIndices list, if requested.
1235 if (CIndices)
1236 CIndices->push_back(cast<Constant>(Index));
1237 }
1238
1239 const Type *IdxTy =
1240 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1241 if (!IdxTy)
1242 error("Index list invalid for constant getelementptr");
1243 return IdxTy;
1244}
1245
1246Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1247 bool debug, bool addAttrs)
Reid Spencere7c3c602006-11-30 06:36:44 +00001248{
1249 Upgradelineno = 1;
1250 CurFilename = infile;
Reid Spencer96839be2006-11-30 16:50:26 +00001251 LexInput = &in;
Reid Spencere77e35e2006-12-01 20:26:20 +00001252 yydebug = debug;
Reid Spencer71d2ec92006-12-31 06:02:26 +00001253 AddAttributes = addAttrs;
Reid Spencer950bf602007-01-26 08:19:09 +00001254 ObsoleteVarArgs = false;
1255 NewVarArgs = false;
Reid Spencere7c3c602006-11-30 06:36:44 +00001256
Reid Spencer950bf602007-01-26 08:19:09 +00001257 CurModule.CurrentModule = new Module(CurFilename);
1258
1259 // Check to make sure the parser succeeded
Reid Spencere7c3c602006-11-30 06:36:44 +00001260 if (yyparse()) {
Reid Spencer950bf602007-01-26 08:19:09 +00001261 if (ParserResult)
1262 delete ParserResult;
Reid Spencer30d0c582007-01-15 00:26:18 +00001263 std::cerr << "llvm-upgrade: parse failed.\n";
Reid Spencer30d0c582007-01-15 00:26:18 +00001264 return 0;
1265 }
1266
Reid Spencer950bf602007-01-26 08:19:09 +00001267 // Check to make sure that parsing produced a result
1268 if (!ParserResult) {
1269 std::cerr << "llvm-upgrade: no parse result.\n";
1270 return 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001271 }
1272
Reid Spencer950bf602007-01-26 08:19:09 +00001273 // Reset ParserResult variable while saving its value for the result.
1274 Module *Result = ParserResult;
1275 ParserResult = 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001276
Reid Spencer950bf602007-01-26 08:19:09 +00001277 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
Reid Spencer30d0c582007-01-15 00:26:18 +00001278 {
Reid Spencer950bf602007-01-26 08:19:09 +00001279 Function* F;
1280 if ((F = Result->getNamedFunction("llvm.va_start"))
1281 && F->getFunctionType()->getNumParams() == 0)
1282 ObsoleteVarArgs = true;
1283 if((F = Result->getNamedFunction("llvm.va_copy"))
1284 && F->getFunctionType()->getNumParams() == 1)
1285 ObsoleteVarArgs = true;
Reid Spencer280d8012006-12-01 23:40:53 +00001286 }
Reid Spencer319a7302007-01-05 17:20:02 +00001287
Reid Spencer950bf602007-01-26 08:19:09 +00001288 if (ObsoleteVarArgs && NewVarArgs) {
1289 error("This file is corrupt: it uses both new and old style varargs");
1290 return 0;
Reid Spencer319a7302007-01-05 17:20:02 +00001291 }
Reid Spencer319a7302007-01-05 17:20:02 +00001292
Reid Spencer950bf602007-01-26 08:19:09 +00001293 if(ObsoleteVarArgs) {
1294 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1295 if (F->arg_size() != 0) {
1296 error("Obsolete va_start takes 0 argument");
Reid Spencer319a7302007-01-05 17:20:02 +00001297 return 0;
1298 }
Reid Spencer950bf602007-01-26 08:19:09 +00001299
1300 //foo = va_start()
1301 // ->
1302 //bar = alloca typeof(foo)
1303 //va_start(bar)
1304 //foo = load bar
Reid Spencer319a7302007-01-05 17:20:02 +00001305
Reid Spencer950bf602007-01-26 08:19:09 +00001306 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1307 const Type* ArgTy = F->getFunctionType()->getReturnType();
1308 const Type* ArgTyPtr = PointerType::get(ArgTy);
1309 Function* NF = cast<Function>(Result->getOrInsertFunction(
1310 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1311
1312 while (!F->use_empty()) {
1313 CallInst* CI = cast<CallInst>(F->use_back());
1314 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1315 new CallInst(NF, bar, "", CI);
1316 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1317 CI->replaceAllUsesWith(foo);
1318 CI->getParent()->getInstList().erase(CI);
Reid Spencerf8383de2007-01-06 06:04:32 +00001319 }
Reid Spencer950bf602007-01-26 08:19:09 +00001320 Result->getFunctionList().erase(F);
Reid Spencerf8383de2007-01-06 06:04:32 +00001321 }
Reid Spencer950bf602007-01-26 08:19:09 +00001322
1323 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1324 if(F->arg_size() != 1) {
1325 error("Obsolete va_end takes 1 argument");
1326 return 0;
Reid Spencerf8383de2007-01-06 06:04:32 +00001327 }
Reid Spencerf8383de2007-01-06 06:04:32 +00001328
Reid Spencer950bf602007-01-26 08:19:09 +00001329 //vaend foo
1330 // ->
1331 //bar = alloca 1 of typeof(foo)
1332 //vaend bar
1333 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1334 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1335 const Type* ArgTyPtr = PointerType::get(ArgTy);
1336 Function* NF = cast<Function>(Result->getOrInsertFunction(
1337 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
Reid Spencerf8383de2007-01-06 06:04:32 +00001338
Reid Spencer950bf602007-01-26 08:19:09 +00001339 while (!F->use_empty()) {
1340 CallInst* CI = cast<CallInst>(F->use_back());
1341 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1342 new StoreInst(CI->getOperand(1), bar, CI);
1343 new CallInst(NF, bar, "", CI);
1344 CI->getParent()->getInstList().erase(CI);
Reid Spencere77e35e2006-12-01 20:26:20 +00001345 }
Reid Spencer950bf602007-01-26 08:19:09 +00001346 Result->getFunctionList().erase(F);
Reid Spencere77e35e2006-12-01 20:26:20 +00001347 }
Reid Spencer950bf602007-01-26 08:19:09 +00001348
1349 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1350 if(F->arg_size() != 1) {
1351 error("Obsolete va_copy takes 1 argument");
1352 return 0;
Reid Spencere77e35e2006-12-01 20:26:20 +00001353 }
Reid Spencer950bf602007-01-26 08:19:09 +00001354 //foo = vacopy(bar)
1355 // ->
1356 //a = alloca 1 of typeof(foo)
1357 //b = alloca 1 of typeof(foo)
1358 //store bar -> b
1359 //vacopy(a, b)
1360 //foo = load a
1361
1362 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1363 const Type* ArgTy = F->getFunctionType()->getReturnType();
1364 const Type* ArgTyPtr = PointerType::get(ArgTy);
1365 Function* NF = cast<Function>(Result->getOrInsertFunction(
1366 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
Reid Spencere77e35e2006-12-01 20:26:20 +00001367
Reid Spencer950bf602007-01-26 08:19:09 +00001368 while (!F->use_empty()) {
1369 CallInst* CI = cast<CallInst>(F->use_back());
1370 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1371 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1372 new StoreInst(CI->getOperand(1), b, CI);
1373 new CallInst(NF, a, b, "", CI);
1374 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1375 CI->replaceAllUsesWith(foo);
1376 CI->getParent()->getInstList().erase(CI);
1377 }
1378 Result->getFunctionList().erase(F);
Reid Spencer319a7302007-01-05 17:20:02 +00001379 }
1380 }
1381
Reid Spencer52402b02007-01-02 05:45:11 +00001382 return Result;
1383}
1384
Reid Spencer950bf602007-01-26 08:19:09 +00001385} // end llvm namespace
Reid Spencer319a7302007-01-05 17:20:02 +00001386
Reid Spencer950bf602007-01-26 08:19:09 +00001387using namespace llvm;
Reid Spencer30d0c582007-01-15 00:26:18 +00001388
Reid Spencere7c3c602006-11-30 06:36:44 +00001389%}
1390
Reid Spencere77e35e2006-12-01 20:26:20 +00001391%union {
Reid Spencer950bf602007-01-26 08:19:09 +00001392 llvm::Module *ModuleVal;
1393 llvm::Function *FunctionVal;
1394 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1395 llvm::BasicBlock *BasicBlockVal;
1396 llvm::TerminatorInst *TermInstVal;
1397 llvm::InstrInfo InstVal;
1398 llvm::ConstInfo ConstVal;
1399 llvm::ValueInfo ValueVal;
1400 llvm::PATypeInfo TypeVal;
1401 llvm::TypeInfo PrimType;
1402 llvm::PHIListInfo PHIList;
1403 std::list<llvm::PATypeInfo> *TypeList;
1404 std::vector<llvm::ValueInfo> *ValueList;
1405 std::vector<llvm::ConstInfo> *ConstVector;
1406
1407
1408 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1409 // Represent the RHS of PHI node
1410 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1411
1412 llvm::GlobalValue::LinkageTypes Linkage;
1413 int64_t SInt64Val;
1414 uint64_t UInt64Val;
1415 int SIntVal;
1416 unsigned UIntVal;
1417 double FPVal;
1418 bool BoolVal;
1419
1420 char *StrVal; // This memory is strdup'd!
1421 llvm::ValID ValIDVal; // strdup'd memory maybe!
1422
1423 llvm::BinaryOps BinaryOpVal;
1424 llvm::TermOps TermOpVal;
1425 llvm::MemoryOps MemOpVal;
1426 llvm::OtherOps OtherOpVal;
1427 llvm::CastOps CastOpVal;
1428 llvm::ICmpInst::Predicate IPred;
1429 llvm::FCmpInst::Predicate FPred;
1430 llvm::Module::Endianness Endianness;
Reid Spencere77e35e2006-12-01 20:26:20 +00001431}
1432
Reid Spencer950bf602007-01-26 08:19:09 +00001433%type <ModuleVal> Module FunctionList
1434%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1435%type <BasicBlockVal> BasicBlock InstructionList
1436%type <TermInstVal> BBTerminatorInst
1437%type <InstVal> Inst InstVal MemoryInst
1438%type <ConstVal> ConstVal ConstExpr
1439%type <ConstVector> ConstVector
1440%type <ArgList> ArgList ArgListH
1441%type <ArgVal> ArgVal
1442%type <PHIList> PHIList
1443%type <ValueList> ValueRefList ValueRefListE // For call param lists
1444%type <ValueList> IndexList // For GEP derived indices
1445%type <TypeList> TypeListI ArgTypeListI
1446%type <JumpTable> JumpTable
1447%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1448%type <BoolVal> OptVolatile // 'volatile' or not
1449%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1450%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1451%type <Linkage> OptLinkage
1452%type <Endianness> BigOrLittle
Reid Spencere77e35e2006-12-01 20:26:20 +00001453
Reid Spencer950bf602007-01-26 08:19:09 +00001454// ValueRef - Unresolved reference to a definition or BB
1455%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1456%type <ValueVal> ResolvedVal // <type> <valref> pair
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001457
Reid Spencer950bf602007-01-26 08:19:09 +00001458// Tokens and types for handling constant integer values
1459//
1460// ESINT64VAL - A negative number within long long range
1461%token <SInt64Val> ESINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001462
Reid Spencer950bf602007-01-26 08:19:09 +00001463// EUINT64VAL - A positive number within uns. long long range
1464%token <UInt64Val> EUINT64VAL
1465%type <SInt64Val> EINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001466
Reid Spencer950bf602007-01-26 08:19:09 +00001467%token <SIntVal> SINTVAL // Signed 32 bit ints...
1468%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1469%type <SIntVal> INTVAL
1470%token <FPVal> FPVAL // Float or Double constant
Reid Spencere77e35e2006-12-01 20:26:20 +00001471
Reid Spencer950bf602007-01-26 08:19:09 +00001472// Built in types...
1473%type <TypeVal> Types TypesV UpRTypes UpRTypesV
1474%type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1475%token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1476%token <PrimType> FLOAT DOUBLE TYPE LABEL
Reid Spencere77e35e2006-12-01 20:26:20 +00001477
Reid Spencer950bf602007-01-26 08:19:09 +00001478%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1479%type <StrVal> Name OptName OptAssign
1480%type <UIntVal> OptAlign OptCAlign
1481%type <StrVal> OptSection SectionString
1482
1483%token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1484%token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1485%token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1486%token DLLIMPORT DLLEXPORT EXTERN_WEAK
1487%token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1488%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1489%token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1490%token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1491%token DATALAYOUT
1492%type <UIntVal> OptCallingConv
1493
1494// Basic Block Terminating Operators
1495%token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1496%token UNWIND EXCEPT
1497
1498// Binary Operators
1499%type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1500%token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1501%token <BinaryOpVal> AND OR XOR
1502%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1503%token <OtherOpVal> ICMP FCMP
1504
1505// Memory Instructions
1506%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1507
1508// Other Operators
1509%type <OtherOpVal> ShiftOps
1510%token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1511%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1512%token VAARG_old VANEXT_old //OBSOLETE
1513
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001514// Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
Reid Spencer950bf602007-01-26 08:19:09 +00001515%type <IPred> IPredicates
1516%type <FPred> FPredicates
1517%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1518%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1519
1520%token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1521%token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1522%type <CastOpVal> CastOps
Reid Spencere7c3c602006-11-30 06:36:44 +00001523
1524%start Module
1525
1526%%
1527
1528// Handle constant integer size restriction and conversion...
Reid Spencer950bf602007-01-26 08:19:09 +00001529//
1530INTVAL
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001531 : SINTVAL
Reid Spencer950bf602007-01-26 08:19:09 +00001532 | UINTVAL {
1533 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1534 error("Value too large for type");
1535 $$ = (int32_t)$1;
1536 }
1537 ;
1538
1539EINT64VAL
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001540 : ESINT64VAL // These have same type and can't cause problems...
Reid Spencer950bf602007-01-26 08:19:09 +00001541 | EUINT64VAL {
1542 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1543 error("Value too large for type");
1544 $$ = (int64_t)$1;
1545 };
Reid Spencere7c3c602006-11-30 06:36:44 +00001546
1547// Operations that are notably excluded from this list include:
1548// RET, BR, & SWITCH because they end basic blocks and are treated specially.
Reid Spencer950bf602007-01-26 08:19:09 +00001549//
1550ArithmeticOps
1551 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1552 ;
1553
1554LogicalOps
1555 : AND | OR | XOR
1556 ;
1557
1558SetCondOps
1559 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1560 ;
1561
1562IPredicates
1563 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1564 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1565 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1566 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1567 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1568 ;
1569
1570FPredicates
1571 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1572 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1573 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1574 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1575 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1576 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1577 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1578 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1579 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1580 ;
1581ShiftOps
1582 : SHL | SHR | ASHR | LSHR
1583 ;
1584
1585CastOps
1586 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1587 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1588 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001589
1590// These are some types that allow classification if we only want a particular
1591// thing... for example, only a signed, unsigned, or integral type.
Reid Spencer950bf602007-01-26 08:19:09 +00001592SIntType
1593 : LONG | INT | SHORT | SBYTE
1594 ;
1595
1596UIntType
1597 : ULONG | UINT | USHORT | UBYTE
1598 ;
1599
1600IntType
1601 : SIntType | UIntType
1602 ;
1603
1604FPType
1605 : FLOAT | DOUBLE
1606 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001607
1608// OptAssign - Value producing statements have an optional assignment component
Reid Spencer950bf602007-01-26 08:19:09 +00001609OptAssign
1610 : Name '=' {
Reid Spencere7c3c602006-11-30 06:36:44 +00001611 $$ = $1;
1612 }
1613 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001614 $$ = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00001615 };
1616
1617OptLinkage
Reid Spencer950bf602007-01-26 08:19:09 +00001618 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1619 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1620 | WEAK { $$ = GlobalValue::WeakLinkage; }
1621 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1622 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1623 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1624 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1625 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1626 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001627
1628OptCallingConv
Reid Spencer950bf602007-01-26 08:19:09 +00001629 : /*empty*/ { $$ = CallingConv::C; }
1630 | CCC_TOK { $$ = CallingConv::C; }
Anton Korobeynikovc4c87a32007-01-28 13:36:18 +00001631 | CSRETCC_TOK { $$ = CallingConv::C; }
Reid Spencer950bf602007-01-26 08:19:09 +00001632 | FASTCC_TOK { $$ = CallingConv::Fast; }
1633 | COLDCC_TOK { $$ = CallingConv::Cold; }
1634 | X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; }
1635 | X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; }
1636 | CC_TOK EUINT64VAL {
1637 if ((unsigned)$2 != $2)
1638 error("Calling conv too large");
1639 $$ = $2;
1640 }
1641 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001642
1643// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1644// a comma before it.
1645OptAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001646 : /*empty*/ { $$ = 0; }
1647 | ALIGN EUINT64VAL {
1648 $$ = $2;
1649 if ($$ != 0 && !isPowerOf2_32($$))
1650 error("Alignment must be a power of two");
1651 }
1652 ;
Reid Spencerf0cf1322006-12-07 04:23:03 +00001653
Reid Spencere7c3c602006-11-30 06:36:44 +00001654OptCAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001655 : /*empty*/ { $$ = 0; }
1656 | ',' ALIGN EUINT64VAL {
1657 $$ = $3;
1658 if ($$ != 0 && !isPowerOf2_32($$))
1659 error("Alignment must be a power of two");
1660 }
1661 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001662
1663SectionString
Reid Spencer950bf602007-01-26 08:19:09 +00001664 : SECTION STRINGCONSTANT {
1665 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1666 if ($2[i] == '"' || $2[i] == '\\')
1667 error("Invalid character in section name");
1668 $$ = $2;
1669 }
1670 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001671
Reid Spencer950bf602007-01-26 08:19:09 +00001672OptSection
1673 : /*empty*/ { $$ = 0; }
1674 | SectionString { $$ = $1; }
1675 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001676
Reid Spencer950bf602007-01-26 08:19:09 +00001677// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1678// is set to be the global we are processing.
1679//
Reid Spencere7c3c602006-11-30 06:36:44 +00001680GlobalVarAttributes
Reid Spencer950bf602007-01-26 08:19:09 +00001681 : /* empty */ {}
1682 | ',' GlobalVarAttribute GlobalVarAttributes {}
1683 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001684
Reid Spencer950bf602007-01-26 08:19:09 +00001685GlobalVarAttribute
1686 : SectionString {
1687 CurGV->setSection($1);
1688 free($1);
1689 }
1690 | ALIGN EUINT64VAL {
1691 if ($2 != 0 && !isPowerOf2_32($2))
1692 error("Alignment must be a power of two");
1693 CurGV->setAlignment($2);
1694
1695 }
1696 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001697
1698//===----------------------------------------------------------------------===//
1699// Types includes all predefined types... except void, because it can only be
1700// used in specific contexts (function returning void for example). To have
1701// access to it, a user must explicitly use TypesV.
1702//
1703
1704// TypesV includes all of 'Types', but it also includes the void type.
Reid Spencer950bf602007-01-26 08:19:09 +00001705TypesV
1706 : Types
1707 | VOID {
1708 $$.T = new PATypeHolder($1.T);
1709 $$.S = Signless;
1710 }
1711 ;
1712
1713UpRTypesV
1714 : UpRTypes
1715 | VOID {
1716 $$.T = new PATypeHolder($1.T);
1717 $$.S = Signless;
1718 }
1719 ;
1720
1721Types
1722 : UpRTypes {
1723 if (!UpRefs.empty())
1724 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1725 $$ = $1;
1726 }
1727 ;
1728
1729PrimType
1730 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1731 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1732 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001733
1734// Derived types are added later...
Reid Spencera50d5962006-12-02 04:11:07 +00001735UpRTypes
Reid Spencer950bf602007-01-26 08:19:09 +00001736 : PrimType {
1737 $$.T = new PATypeHolder($1.T);
1738 $$.S = $1.S;
Reid Spencera50d5962006-12-02 04:11:07 +00001739 }
Reid Spencer950bf602007-01-26 08:19:09 +00001740 | OPAQUE {
1741 $$.T = new PATypeHolder(OpaqueType::get());
1742 $$.S = Signless;
1743 }
1744 | SymbolicValueRef { // Named types are also simple types...
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001745 const Type* tmp = getType($1);
Reid Spencer950bf602007-01-26 08:19:09 +00001746 $$.T = new PATypeHolder(tmp);
1747 $$.S = Signless; // FIXME: what if its signed?
Reid Spencer78720742006-12-02 20:21:22 +00001748 }
1749 | '\\' EUINT64VAL { // Type UpReference
Reid Spencer950bf602007-01-26 08:19:09 +00001750 if ($2 > (uint64_t)~0U)
1751 error("Value out of range");
1752 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1753 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1754 $$.T = new PATypeHolder(OT);
1755 $$.S = Signless;
1756 UR_OUT("New Upreference!\n");
Reid Spencere7c3c602006-11-30 06:36:44 +00001757 }
1758 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
Reid Spencer950bf602007-01-26 08:19:09 +00001759 std::vector<const Type*> Params;
1760 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1761 E = $3->end(); I != E; ++I) {
1762 Params.push_back(I->T->get());
1763 delete I->T;
Reid Spencer52402b02007-01-02 05:45:11 +00001764 }
Reid Spencer950bf602007-01-26 08:19:09 +00001765 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1766 if (isVarArg) Params.pop_back();
1767
1768 $$.T = new PATypeHolder(HandleUpRefs(
1769 FunctionType::get($1.T->get(),Params,isVarArg)));
1770 $$.S = $1.S;
1771 delete $1.T; // Delete the return type handle
1772 delete $3; // Delete the argument list
Reid Spencere7c3c602006-11-30 06:36:44 +00001773 }
1774 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
Reid Spencer950bf602007-01-26 08:19:09 +00001775 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1776 (unsigned)$2)));
1777 $$.S = $4.S;
1778 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001779 }
1780 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
Reid Spencer950bf602007-01-26 08:19:09 +00001781 const llvm::Type* ElemTy = $4.T->get();
1782 if ((unsigned)$2 != $2)
1783 error("Unsigned result not equal to signed result");
1784 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1785 error("Elements of a PackedType must be integer or floating point");
1786 if (!isPowerOf2_32($2))
1787 error("PackedType length should be a power of 2");
1788 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1789 (unsigned)$2)));
1790 $$.S = $4.S;
1791 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001792 }
1793 | '{' TypeListI '}' { // Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001794 std::vector<const Type*> Elements;
1795 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1796 E = $2->end(); I != E; ++I)
1797 Elements.push_back(I->T->get());
1798 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1799 $$.S = Signless;
1800 delete $2;
Reid Spencere7c3c602006-11-30 06:36:44 +00001801 }
1802 | '{' '}' { // Empty structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001803 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1804 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00001805 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001806 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001807 std::vector<const Type*> Elements;
1808 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1809 E = $3->end(); I != E; ++I) {
1810 Elements.push_back(I->T->get());
1811 delete I->T;
Reid Spencer52402b02007-01-02 05:45:11 +00001812 }
Reid Spencer950bf602007-01-26 08:19:09 +00001813 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1814 $$.S = Signless;
1815 delete $3;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001816 }
1817 | '<' '{' '}' '>' { // Empty packed structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001818 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1819 $$.S = Signless;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001820 }
Reid Spencere7c3c602006-11-30 06:36:44 +00001821 | UpRTypes '*' { // Pointer type?
Reid Spencer950bf602007-01-26 08:19:09 +00001822 if ($1.T->get() == Type::LabelTy)
1823 error("Cannot form a pointer to a basic block");
1824 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1825 $$.S = $1.S;
1826 delete $1.T;
1827 }
1828 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001829
1830// TypeList - Used for struct declarations and as a basis for function type
1831// declaration type lists
1832//
Reid Spencere77e35e2006-12-01 20:26:20 +00001833TypeListI
1834 : UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001835 $$ = new std::list<PATypeInfo>();
1836 $$->push_back($1);
Reid Spencere77e35e2006-12-01 20:26:20 +00001837 }
1838 | TypeListI ',' UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001839 ($$=$1)->push_back($3);
1840 }
1841 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001842
1843// ArgTypeList - List of types for a function type declaration...
Reid Spencere77e35e2006-12-01 20:26:20 +00001844ArgTypeListI
Reid Spencer950bf602007-01-26 08:19:09 +00001845 : TypeListI
Reid Spencere7c3c602006-11-30 06:36:44 +00001846 | TypeListI ',' DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001847 PATypeInfo VoidTI;
1848 VoidTI.T = new PATypeHolder(Type::VoidTy);
1849 VoidTI.S = Signless;
1850 ($$=$1)->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001851 }
1852 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001853 $$ = new std::list<PATypeInfo>();
1854 PATypeInfo VoidTI;
1855 VoidTI.T = new PATypeHolder(Type::VoidTy);
1856 VoidTI.S = Signless;
1857 $$->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001858 }
1859 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001860 $$ = new std::list<PATypeInfo>();
1861 }
1862 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001863
1864// ConstVal - The various declarations that go into the constant pool. This
1865// production is used ONLY to represent constants that show up AFTER a 'const',
1866// 'constant' or 'global' token at global scope. Constants that can be inlined
1867// into other expressions (such as integers and constexprs) are handled by the
1868// ResolvedVal, ValueRef and ConstValueRef productions.
1869//
Reid Spencer950bf602007-01-26 08:19:09 +00001870ConstVal
1871 : Types '[' ConstVector ']' { // Nonempty unsized arr
1872 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1873 if (ATy == 0)
1874 error("Cannot make array constant with type: '" +
1875 $1.T->get()->getDescription() + "'");
1876 const Type *ETy = ATy->getElementType();
1877 int NumElements = ATy->getNumElements();
1878
1879 // Verify that we have the correct size...
1880 if (NumElements != -1 && NumElements != (int)$3->size())
1881 error("Type mismatch: constant sized array initialized with " +
1882 utostr($3->size()) + " arguments, but has size of " +
1883 itostr(NumElements) + "");
1884
1885 // Verify all elements are correct type!
1886 std::vector<Constant*> Elems;
1887 for (unsigned i = 0; i < $3->size(); i++) {
1888 Constant *C = (*$3)[i].C;
1889 const Type* ValTy = C->getType();
1890 if (ETy != ValTy)
1891 error("Element #" + utostr(i) + " is not of type '" +
1892 ETy->getDescription() +"' as required!\nIt is of type '"+
1893 ValTy->getDescription() + "'");
1894 Elems.push_back(C);
1895 }
1896 $$.C = ConstantArray::get(ATy, Elems);
1897 $$.S = $1.S;
1898 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001899 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00001900 }
1901 | Types '[' ']' {
Reid Spencer950bf602007-01-26 08:19:09 +00001902 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1903 if (ATy == 0)
1904 error("Cannot make array constant with type: '" +
1905 $1.T->get()->getDescription() + "'");
1906 int NumElements = ATy->getNumElements();
1907 if (NumElements != -1 && NumElements != 0)
1908 error("Type mismatch: constant sized array initialized with 0"
1909 " arguments, but has size of " + itostr(NumElements) +"");
1910 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1911 $$.S = $1.S;
1912 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001913 }
1914 | Types 'c' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00001915 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1916 if (ATy == 0)
1917 error("Cannot make array constant with type: '" +
1918 $1.T->get()->getDescription() + "'");
1919 int NumElements = ATy->getNumElements();
1920 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1921 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1922 error("String arrays require type i8, not '" + ETy->getDescription() +
1923 "'");
1924 char *EndStr = UnEscapeLexed($3, true);
1925 if (NumElements != -1 && NumElements != (EndStr-$3))
1926 error("Can't build string constant of size " +
1927 itostr((int)(EndStr-$3)) + " when array has size " +
1928 itostr(NumElements) + "");
1929 std::vector<Constant*> Vals;
1930 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1931 Vals.push_back(ConstantInt::get(ETy, *C));
1932 free($3);
1933 $$.C = ConstantArray::get(ATy, Vals);
1934 $$.S = $1.S;
1935 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001936 }
1937 | Types '<' ConstVector '>' { // Nonempty unsized arr
Reid Spencer950bf602007-01-26 08:19:09 +00001938 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1939 if (PTy == 0)
1940 error("Cannot make packed constant with type: '" +
1941 $1.T->get()->getDescription() + "'");
1942 const Type *ETy = PTy->getElementType();
1943 int NumElements = PTy->getNumElements();
1944 // Verify that we have the correct size...
1945 if (NumElements != -1 && NumElements != (int)$3->size())
1946 error("Type mismatch: constant sized packed initialized with " +
1947 utostr($3->size()) + " arguments, but has size of " +
1948 itostr(NumElements) + "");
1949 // Verify all elements are correct type!
1950 std::vector<Constant*> Elems;
1951 for (unsigned i = 0; i < $3->size(); i++) {
1952 Constant *C = (*$3)[i].C;
1953 const Type* ValTy = C->getType();
1954 if (ETy != ValTy)
1955 error("Element #" + utostr(i) + " is not of type '" +
1956 ETy->getDescription() +"' as required!\nIt is of type '"+
1957 ValTy->getDescription() + "'");
1958 Elems.push_back(C);
1959 }
1960 $$.C = ConstantPacked::get(PTy, Elems);
1961 $$.S = $1.S;
1962 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001963 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00001964 }
1965 | Types '{' ConstVector '}' {
Reid Spencer950bf602007-01-26 08:19:09 +00001966 const StructType *STy = dyn_cast<StructType>($1.T->get());
1967 if (STy == 0)
1968 error("Cannot make struct constant with type: '" +
1969 $1.T->get()->getDescription() + "'");
1970 if ($3->size() != STy->getNumContainedTypes())
1971 error("Illegal number of initializers for structure type");
1972
1973 // Check to ensure that constants are compatible with the type initializer!
1974 std::vector<Constant*> Fields;
1975 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
1976 Constant *C = (*$3)[i].C;
1977 if (C->getType() != STy->getElementType(i))
1978 error("Expected type '" + STy->getElementType(i)->getDescription() +
1979 "' for element #" + utostr(i) + " of structure initializer");
1980 Fields.push_back(C);
1981 }
1982 $$.C = ConstantStruct::get(STy, Fields);
1983 $$.S = $1.S;
1984 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001985 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00001986 }
1987 | Types '{' '}' {
Reid Spencer950bf602007-01-26 08:19:09 +00001988 const StructType *STy = dyn_cast<StructType>($1.T->get());
1989 if (STy == 0)
1990 error("Cannot make struct constant with type: '" +
1991 $1.T->get()->getDescription() + "'");
1992 if (STy->getNumContainedTypes() != 0)
1993 error("Illegal number of initializers for structure type");
1994 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1995 $$.S = $1.S;
1996 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001997 }
Reid Spencer950bf602007-01-26 08:19:09 +00001998 | Types '<' '{' ConstVector '}' '>' {
1999 const StructType *STy = dyn_cast<StructType>($1.T->get());
2000 if (STy == 0)
2001 error("Cannot make packed struct constant with type: '" +
2002 $1.T->get()->getDescription() + "'");
2003 if ($4->size() != STy->getNumContainedTypes())
2004 error("Illegal number of initializers for packed structure type");
Reid Spencere7c3c602006-11-30 06:36:44 +00002005
Reid Spencer950bf602007-01-26 08:19:09 +00002006 // Check to ensure that constants are compatible with the type initializer!
2007 std::vector<Constant*> Fields;
2008 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2009 Constant *C = (*$4)[i].C;
2010 if (C->getType() != STy->getElementType(i))
2011 error("Expected type '" + STy->getElementType(i)->getDescription() +
2012 "' for element #" + utostr(i) + " of packed struct initializer");
2013 Fields.push_back(C);
Reid Spencer280d8012006-12-01 23:40:53 +00002014 }
Reid Spencer950bf602007-01-26 08:19:09 +00002015 $$.C = ConstantStruct::get(STy, Fields);
2016 $$.S = $1.S;
2017 delete $1.T;
Reid Spencere77e35e2006-12-01 20:26:20 +00002018 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00002019 }
Reid Spencer950bf602007-01-26 08:19:09 +00002020 | Types '<' '{' '}' '>' {
2021 const StructType *STy = dyn_cast<StructType>($1.T->get());
2022 if (STy == 0)
2023 error("Cannot make packed struct constant with type: '" +
2024 $1.T->get()->getDescription() + "'");
2025 if (STy->getNumContainedTypes() != 0)
2026 error("Illegal number of initializers for packed structure type");
2027 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2028 $$.S = $1.S;
2029 delete $1.T;
2030 }
2031 | Types NULL_TOK {
2032 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
2033 if (PTy == 0)
2034 error("Cannot make null pointer constant with type: '" +
2035 $1.T->get()->getDescription() + "'");
2036 $$.C = ConstantPointerNull::get(PTy);
2037 $$.S = $1.S;
2038 delete $1.T;
2039 }
2040 | Types UNDEF {
2041 $$.C = UndefValue::get($1.T->get());
2042 $$.S = $1.S;
2043 delete $1.T;
2044 }
2045 | Types SymbolicValueRef {
2046 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
2047 if (Ty == 0)
2048 error("Global const reference must be a pointer type, not" +
2049 $1.T->get()->getDescription());
2050
2051 // ConstExprs can exist in the body of a function, thus creating
2052 // GlobalValues whenever they refer to a variable. Because we are in
2053 // the context of a function, getExistingValue will search the functions
2054 // symbol table instead of the module symbol table for the global symbol,
2055 // which throws things all off. To get around this, we just tell
2056 // getExistingValue that we are at global scope here.
2057 //
2058 Function *SavedCurFn = CurFun.CurrentFunction;
2059 CurFun.CurrentFunction = 0;
2060 Value *V = getExistingValue(Ty, $2);
2061 CurFun.CurrentFunction = SavedCurFn;
2062
2063 // If this is an initializer for a constant pointer, which is referencing a
2064 // (currently) undefined variable, create a stub now that shall be replaced
2065 // in the future with the right type of variable.
2066 //
2067 if (V == 0) {
2068 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2069 const PointerType *PT = cast<PointerType>(Ty);
2070
2071 // First check to see if the forward references value is already created!
2072 PerModuleInfo::GlobalRefsType::iterator I =
2073 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2074
2075 if (I != CurModule.GlobalRefs.end()) {
2076 V = I->second; // Placeholder already exists, use it...
2077 $2.destroy();
2078 } else {
2079 std::string Name;
2080 if ($2.Type == ValID::NameVal) Name = $2.Name;
2081
2082 // Create the forward referenced global.
2083 GlobalValue *GV;
2084 if (const FunctionType *FTy =
2085 dyn_cast<FunctionType>(PT->getElementType())) {
2086 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2087 CurModule.CurrentModule);
2088 } else {
2089 GV = new GlobalVariable(PT->getElementType(), false,
2090 GlobalValue::ExternalLinkage, 0,
2091 Name, CurModule.CurrentModule);
2092 }
2093
2094 // Keep track of the fact that we have a forward ref to recycle it
2095 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2096 V = GV;
2097 }
2098 }
2099 $$.C = cast<GlobalValue>(V);
2100 $$.S = $1.S;
2101 delete $1.T; // Free the type handle
2102 }
2103 | Types ConstExpr {
2104 if ($1.T->get() != $2.C->getType())
2105 error("Mismatched types for constant expression");
2106 $$ = $2;
2107 $$.S = $1.S;
2108 delete $1.T;
2109 }
2110 | Types ZEROINITIALIZER {
2111 const Type *Ty = $1.T->get();
2112 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2113 error("Cannot create a null initialized value of this type");
2114 $$.C = Constant::getNullValue(Ty);
2115 $$.S = $1.S;
2116 delete $1.T;
2117 }
2118 | SIntType EINT64VAL { // integral constants
2119 const Type *Ty = $1.T;
2120 if (!ConstantInt::isValueValidForType(Ty, $2))
2121 error("Constant value doesn't fit in type");
2122 $$.C = ConstantInt::get(Ty, $2);
2123 $$.S = Signed;
2124 }
2125 | UIntType EUINT64VAL { // integral constants
2126 const Type *Ty = $1.T;
2127 if (!ConstantInt::isValueValidForType(Ty, $2))
2128 error("Constant value doesn't fit in type");
2129 $$.C = ConstantInt::get(Ty, $2);
2130 $$.S = Unsigned;
2131 }
2132 | BOOL TRUETOK { // Boolean constants
2133 $$.C = ConstantInt::get(Type::Int1Ty, true);
2134 $$.S = Unsigned;
2135 }
2136 | BOOL FALSETOK { // Boolean constants
2137 $$.C = ConstantInt::get(Type::Int1Ty, false);
2138 $$.S = Unsigned;
2139 }
2140 | FPType FPVAL { // Float & Double constants
2141 if (!ConstantFP::isValueValidForType($1.T, $2))
2142 error("Floating point constant invalid for type");
2143 $$.C = ConstantFP::get($1.T, $2);
2144 $$.S = Signless;
2145 }
2146 ;
2147
2148ConstExpr
2149 : CastOps '(' ConstVal TO Types ')' {
2150 const Type* SrcTy = $3.C->getType();
2151 const Type* DstTy = $5.T->get();
2152 Signedness SrcSign = $3.S;
2153 Signedness DstSign = $5.S;
2154 if (!SrcTy->isFirstClassType())
2155 error("cast constant expression from a non-primitive type: '" +
2156 SrcTy->getDescription() + "'");
2157 if (!DstTy->isFirstClassType())
2158 error("cast constant expression to a non-primitive type: '" +
2159 DstTy->getDescription() + "'");
2160 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2161 $$.S = DstSign;
2162 delete $5.T;
2163 }
2164 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2165 const Type *Ty = $3.C->getType();
2166 if (!isa<PointerType>(Ty))
2167 error("GetElementPtr requires a pointer operand");
2168
2169 std::vector<Value*> VIndices;
2170 std::vector<Constant*> CIndices;
2171 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2172
2173 delete $4;
2174 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2175 $$.S = Signless;
2176 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002177 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002178 if (!$3.C->getType()->isInteger() ||
2179 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2180 error("Select condition must be bool type");
2181 if ($5.C->getType() != $7.C->getType())
2182 error("Select operand types must match");
2183 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2184 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002185 }
2186 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002187 const Type *Ty = $3.C->getType();
2188 if (Ty != $5.C->getType())
2189 error("Binary operator types must match");
2190 // First, make sure we're dealing with the right opcode by upgrading from
2191 // obsolete versions.
2192 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2193
2194 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2195 // To retain backward compatibility with these early compilers, we emit a
2196 // cast to the appropriate integer type automatically if we are in the
2197 // broken case. See PR424 for more information.
2198 if (!isa<PointerType>(Ty)) {
2199 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2200 } else {
2201 const Type *IntPtrTy = 0;
2202 switch (CurModule.CurrentModule->getPointerSize()) {
2203 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2204 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2205 default: error("invalid pointer binary constant expr");
2206 }
2207 $$.C = ConstantExpr::get(Opcode,
2208 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2209 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2210 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2211 }
2212 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002213 }
2214 | LogicalOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002215 const Type* Ty = $3.C->getType();
2216 if (Ty != $5.C->getType())
2217 error("Logical operator types must match");
2218 if (!Ty->isInteger()) {
2219 if (!isa<PackedType>(Ty) ||
2220 !cast<PackedType>(Ty)->getElementType()->isInteger())
2221 error("Logical operator requires integer operands");
2222 }
2223 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2224 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2225 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002226 }
2227 | SetCondOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002228 const Type* Ty = $3.C->getType();
2229 if (Ty != $5.C->getType())
2230 error("setcc operand types must match");
2231 unsigned short pred;
2232 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2233 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2234 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002235 }
Reid Spencer57f28f92006-12-03 07:10:26 +00002236 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002237 if ($4.C->getType() != $6.C->getType())
2238 error("icmp operand types must match");
2239 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2240 $$.S = Unsigned;
Reid Spencer57f28f92006-12-03 07:10:26 +00002241 }
2242 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002243 if ($4.C->getType() != $6.C->getType())
2244 error("fcmp operand types must match");
2245 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2246 $$.S = Unsigned;
Reid Spencer229e9362006-12-02 22:14:11 +00002247 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002248 | ShiftOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002249 if (!$5.C->getType()->isInteger() ||
2250 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2251 error("Shift count for shift constant must be unsigned byte");
2252 if (!$3.C->getType()->isInteger())
2253 error("Shift constant expression requires integer operand");
2254 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2255 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002256 }
2257 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002258 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2259 error("Invalid extractelement operands");
2260 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2261 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002262 }
2263 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002264 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2265 error("Invalid insertelement operands");
2266 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2267 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002268 }
2269 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002270 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2271 error("Invalid shufflevector operands");
2272 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2273 $$.S = $3.S;
2274 }
2275 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002276
2277
2278// ConstVector - A list of comma separated constants.
Reid Spencere77e35e2006-12-01 20:26:20 +00002279ConstVector
Reid Spencer950bf602007-01-26 08:19:09 +00002280 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2281 | ConstVal {
2282 $$ = new std::vector<ConstInfo>();
2283 $$->push_back($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002284 }
Reid Spencere77e35e2006-12-01 20:26:20 +00002285 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002286
2287
2288// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
Reid Spencer950bf602007-01-26 08:19:09 +00002289GlobalType
2290 : GLOBAL { $$ = false; }
2291 | CONSTANT { $$ = true; }
2292 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002293
2294
2295//===----------------------------------------------------------------------===//
2296// Rules to match Modules
2297//===----------------------------------------------------------------------===//
2298
2299// Module rule: Capture the result of parsing the whole file into a result
2300// variable...
2301//
Reid Spencer950bf602007-01-26 08:19:09 +00002302Module
2303 : FunctionList {
2304 $$ = ParserResult = $1;
2305 CurModule.ModuleDone();
Reid Spencere7c3c602006-11-30 06:36:44 +00002306 }
Jeff Cohenac2dca92007-01-21 19:30:52 +00002307 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002308
Reid Spencer950bf602007-01-26 08:19:09 +00002309// FunctionList - A list of functions, preceeded by a constant pool.
2310//
2311FunctionList
2312 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2313 | FunctionList FunctionProto { $$ = $1; }
2314 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2315 | FunctionList IMPLEMENTATION { $$ = $1; }
2316 | ConstPool {
2317 $$ = CurModule.CurrentModule;
2318 // Emit an error if there are any unresolved types left.
2319 if (!CurModule.LateResolveTypes.empty()) {
2320 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2321 if (DID.Type == ValID::NameVal) {
2322 error("Reference to an undefined type: '"+DID.getName() + "'");
2323 } else {
2324 error("Reference to an undefined type: #" + itostr(DID.Num));
2325 }
2326 }
2327 }
2328 ;
Reid Spencer78720742006-12-02 20:21:22 +00002329
Reid Spencere7c3c602006-11-30 06:36:44 +00002330// ConstPool - Constants with optional names assigned to them.
Reid Spencer950bf602007-01-26 08:19:09 +00002331ConstPool
2332 : ConstPool OptAssign TYPE TypesV {
2333 // Eagerly resolve types. This is not an optimization, this is a
2334 // requirement that is due to the fact that we could have this:
2335 //
2336 // %list = type { %list * }
2337 // %list = type { %list * } ; repeated type decl
2338 //
2339 // If types are not resolved eagerly, then the two types will not be
2340 // determined to be the same type!
2341 //
2342 const Type* Ty = $4.T->get();
2343 ResolveTypeTo($2, Ty);
2344
2345 if (!setTypeName(Ty, $2) && !$2) {
2346 // If this is a named type that is not a redefinition, add it to the slot
2347 // table.
2348 CurModule.Types.push_back(Ty);
Reid Spencera50d5962006-12-02 04:11:07 +00002349 }
Reid Spencer950bf602007-01-26 08:19:09 +00002350 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002351 }
2352 | ConstPool FunctionProto { // Function prototypes can be in const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002353 }
2354 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002355 }
Reid Spencer950bf602007-01-26 08:19:09 +00002356 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2357 if ($5.C == 0)
2358 error("Global value initializer is not a constant");
2359 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2360 } GlobalVarAttributes {
2361 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002362 }
Reid Spencer950bf602007-01-26 08:19:09 +00002363 | ConstPool OptAssign EXTERNAL GlobalType Types {
2364 const Type *Ty = $5.T->get();
2365 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2366 delete $5.T;
2367 } GlobalVarAttributes {
2368 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002369 }
Reid Spencer950bf602007-01-26 08:19:09 +00002370 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2371 const Type *Ty = $5.T->get();
2372 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2373 delete $5.T;
2374 } GlobalVarAttributes {
2375 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002376 }
Reid Spencer950bf602007-01-26 08:19:09 +00002377 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2378 const Type *Ty = $5.T->get();
2379 CurGV =
2380 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2381 delete $5.T;
2382 } GlobalVarAttributes {
2383 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002384 }
2385 | ConstPool TARGET TargetDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002386 }
2387 | ConstPool DEPLIBS '=' LibrariesDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002388 }
2389 | /* empty: end of list */ {
Reid Spencer950bf602007-01-26 08:19:09 +00002390 }
2391 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002392
Reid Spencer950bf602007-01-26 08:19:09 +00002393AsmBlock
2394 : STRINGCONSTANT {
2395 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2396 char *EndStr = UnEscapeLexed($1, true);
2397 std::string NewAsm($1, EndStr);
2398 free($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002399
Reid Spencer950bf602007-01-26 08:19:09 +00002400 if (AsmSoFar.empty())
2401 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2402 else
2403 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2404 }
2405 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002406
Reid Spencer950bf602007-01-26 08:19:09 +00002407BigOrLittle
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00002408 : BIG { $$ = Module::BigEndian; }
Reid Spencer950bf602007-01-26 08:19:09 +00002409 | LITTLE { $$ = Module::LittleEndian; }
2410 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002411
2412TargetDefinition
2413 : ENDIAN '=' BigOrLittle {
Reid Spencer950bf602007-01-26 08:19:09 +00002414 CurModule.setEndianness($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002415 }
2416 | POINTERSIZE '=' EUINT64VAL {
Reid Spencer950bf602007-01-26 08:19:09 +00002417 if ($3 == 32)
2418 CurModule.setPointerSize(Module::Pointer32);
2419 else if ($3 == 64)
2420 CurModule.setPointerSize(Module::Pointer64);
2421 else
2422 error("Invalid pointer size: '" + utostr($3) + "'");
Reid Spencere7c3c602006-11-30 06:36:44 +00002423 }
2424 | TRIPLE '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002425 CurModule.CurrentModule->setTargetTriple($3);
2426 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002427 }
2428 | DATALAYOUT '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002429 CurModule.CurrentModule->setDataLayout($3);
2430 free($3);
2431 }
2432 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002433
2434LibrariesDefinition
Reid Spencer950bf602007-01-26 08:19:09 +00002435 : '[' LibList ']'
2436 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002437
2438LibList
2439 : LibList ',' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002440 CurModule.CurrentModule->addLibrary($3);
2441 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002442 }
Reid Spencer950bf602007-01-26 08:19:09 +00002443 | STRINGCONSTANT {
2444 CurModule.CurrentModule->addLibrary($1);
2445 free($1);
2446 }
2447 | /* empty: end of list */ { }
2448 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002449
2450//===----------------------------------------------------------------------===//
2451// Rules to match Function Headers
2452//===----------------------------------------------------------------------===//
2453
Reid Spencer950bf602007-01-26 08:19:09 +00002454Name
2455 : VAR_ID | STRINGCONSTANT
2456 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002457
Reid Spencer950bf602007-01-26 08:19:09 +00002458OptName
2459 : Name
2460 | /*empty*/ { $$ = 0; }
2461 ;
2462
2463ArgVal
2464 : Types OptName {
2465 if ($1.T->get() == Type::VoidTy)
2466 error("void typed arguments are invalid");
2467 $$ = new std::pair<PATypeInfo, char*>($1, $2);
Reid Spencer52402b02007-01-02 05:45:11 +00002468 }
Reid Spencer950bf602007-01-26 08:19:09 +00002469 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002470
Reid Spencer950bf602007-01-26 08:19:09 +00002471ArgListH
2472 : ArgListH ',' ArgVal {
2473 $$ = $1;
2474 $$->push_back(*$3);
Reid Spencere77e35e2006-12-01 20:26:20 +00002475 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002476 }
2477 | ArgVal {
Reid Spencer950bf602007-01-26 08:19:09 +00002478 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2479 $$->push_back(*$1);
2480 delete $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002481 }
Reid Spencer950bf602007-01-26 08:19:09 +00002482 ;
2483
2484ArgList
2485 : ArgListH { $$ = $1; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002486 | ArgListH ',' DOTDOTDOT {
Reid Spencere7c3c602006-11-30 06:36:44 +00002487 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00002488 PATypeInfo VoidTI;
2489 VoidTI.T = new PATypeHolder(Type::VoidTy);
2490 VoidTI.S = Signless;
2491 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002492 }
2493 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00002494 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2495 PATypeInfo VoidTI;
2496 VoidTI.T = new PATypeHolder(Type::VoidTy);
2497 VoidTI.S = Signless;
2498 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002499 }
Reid Spencer950bf602007-01-26 08:19:09 +00002500 | /* empty */ { $$ = 0; }
2501 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002502
Reid Spencer71d2ec92006-12-31 06:02:26 +00002503FunctionHeaderH
2504 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00002505 UnEscapeLexed($3);
2506 std::string FunctionName($3);
2507 free($3); // Free strdup'd memory!
Reid Spencere7c3c602006-11-30 06:36:44 +00002508
Reid Spencer950bf602007-01-26 08:19:09 +00002509 const Type* RetTy = $2.T->get();
2510
2511 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2512 error("LLVM functions cannot return aggregate types");
2513
2514 std::vector<const Type*> ParamTypeList;
2515
2516 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2517 // i8*. We check here for those names and override the parameter list
2518 // types to ensure the prototype is correct.
2519 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2520 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2521 } else if (FunctionName == "llvm.va_copy") {
2522 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2523 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2524 } else if ($5) { // If there are arguments...
2525 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2526 I = $5->begin(), E = $5->end(); I != E; ++I) {
2527 const Type *Ty = I->first.T->get();
2528 ParamTypeList.push_back(Ty);
2529 }
2530 }
2531
2532 bool isVarArg =
2533 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2534 if (isVarArg) ParamTypeList.pop_back();
2535
2536 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg);
2537 const PointerType *PFT = PointerType::get(FT);
2538 delete $2.T;
2539
2540 ValID ID;
2541 if (!FunctionName.empty()) {
2542 ID = ValID::create((char*)FunctionName.c_str());
2543 } else {
2544 ID = ValID::create((int)CurModule.Values[PFT].size());
2545 }
2546
2547 Function *Fn = 0;
2548 // See if this function was forward referenced. If so, recycle the object.
2549 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2550 // Move the function to the end of the list, from whereever it was
2551 // previously inserted.
2552 Fn = cast<Function>(FWRef);
2553 CurModule.CurrentModule->getFunctionList().remove(Fn);
2554 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2555 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2556 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2557 // If this is the case, either we need to be a forward decl, or it needs
2558 // to be.
2559 if (!CurFun.isDeclare && !Fn->isExternal())
2560 error("Redefinition of function '" + FunctionName + "'");
2561
2562 // Make sure to strip off any argument names so we can't get conflicts.
2563 if (Fn->isExternal())
2564 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2565 AI != AE; ++AI)
2566 AI->setName("");
2567 } else { // Not already defined?
2568 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2569 CurModule.CurrentModule);
2570
2571 InsertValue(Fn, CurModule.Values);
2572 }
2573
2574 CurFun.FunctionStart(Fn);
2575
2576 if (CurFun.isDeclare) {
2577 // If we have declaration, always overwrite linkage. This will allow us
2578 // to correctly handle cases, when pointer to function is passed as
2579 // argument to another function.
2580 Fn->setLinkage(CurFun.Linkage);
2581 }
2582 Fn->setCallingConv($1);
2583 Fn->setAlignment($8);
2584 if ($7) {
2585 Fn->setSection($7);
2586 free($7);
2587 }
2588
2589 // Add all of the arguments we parsed to the function...
2590 if ($5) { // Is null if empty...
2591 if (isVarArg) { // Nuke the last entry
2592 assert($5->back().first.T->get() == Type::VoidTy &&
2593 $5->back().second == 0 && "Not a varargs marker");
2594 delete $5->back().first.T;
2595 $5->pop_back(); // Delete the last entry
2596 }
2597 Function::arg_iterator ArgIt = Fn->arg_begin();
2598 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2599 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2600 delete I->first.T; // Delete the typeholder...
2601 setValueName(ArgIt, I->second); // Insert arg into symtab...
2602 InsertValue(ArgIt);
2603 }
2604 delete $5; // We're now done with the argument list
2605 }
2606 }
2607 ;
2608
2609BEGIN
2610 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
Jeff Cohenac2dca92007-01-21 19:30:52 +00002611 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002612
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002613FunctionHeader
2614 : OptLinkage FunctionHeaderH BEGIN {
Reid Spencer950bf602007-01-26 08:19:09 +00002615 $$ = CurFun.CurrentFunction;
2616
2617 // Make sure that we keep track of the linkage type even if there was a
2618 // previous "declare".
2619 $$->setLinkage($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002620 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002621 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002622
Reid Spencer950bf602007-01-26 08:19:09 +00002623END
2624 : ENDTOK | '}' // Allow end of '}' to end a function
2625 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002626
Reid Spencer950bf602007-01-26 08:19:09 +00002627Function
2628 : BasicBlockList END {
2629 $$ = $1;
2630 };
Reid Spencere7c3c602006-11-30 06:36:44 +00002631
Reid Spencere77e35e2006-12-01 20:26:20 +00002632FnDeclareLinkage
Reid Spencer950bf602007-01-26 08:19:09 +00002633 : /*default*/
2634 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2635 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002636 ;
2637
2638FunctionProto
Reid Spencer950bf602007-01-26 08:19:09 +00002639 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2640 $$ = CurFun.CurrentFunction;
2641 CurFun.FunctionDone();
2642
2643 }
2644 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002645
2646//===----------------------------------------------------------------------===//
2647// Rules to match Basic Blocks
2648//===----------------------------------------------------------------------===//
2649
Reid Spencer950bf602007-01-26 08:19:09 +00002650OptSideEffect
2651 : /* empty */ { $$ = false; }
2652 | SIDEEFFECT { $$ = true; }
2653 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002654
Reid Spencere77e35e2006-12-01 20:26:20 +00002655ConstValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002656 // A reference to a direct constant
2657 : ESINT64VAL { $$ = ValID::create($1); }
2658 | EUINT64VAL { $$ = ValID::create($1); }
2659 | FPVAL { $$ = ValID::create($1); }
2660 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2661 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2662 | NULL_TOK { $$ = ValID::createNull(); }
2663 | UNDEF { $$ = ValID::createUndef(); }
2664 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2665 | '<' ConstVector '>' { // Nonempty unsized packed vector
2666 const Type *ETy = (*$2)[0].C->getType();
2667 int NumElements = $2->size();
2668 PackedType* pt = PackedType::get(ETy, NumElements);
2669 PATypeHolder* PTy = new PATypeHolder(
2670 HandleUpRefs(PackedType::get(ETy, NumElements)));
2671
2672 // Verify all elements are correct type!
2673 std::vector<Constant*> Elems;
2674 for (unsigned i = 0; i < $2->size(); i++) {
2675 Constant *C = (*$2)[i].C;
2676 const Type *CTy = C->getType();
2677 if (ETy != CTy)
2678 error("Element #" + utostr(i) + " is not of type '" +
2679 ETy->getDescription() +"' as required!\nIt is of type '" +
2680 CTy->getDescription() + "'");
2681 Elems.push_back(C);
Reid Spencere7c3c602006-11-30 06:36:44 +00002682 }
Reid Spencer950bf602007-01-26 08:19:09 +00002683 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2684 delete PTy; delete $2;
2685 }
2686 | ConstExpr {
2687 $$ = ValID::create($1.C);
2688 }
2689 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2690 char *End = UnEscapeLexed($3, true);
2691 std::string AsmStr = std::string($3, End);
2692 End = UnEscapeLexed($5, true);
2693 std::string Constraints = std::string($5, End);
2694 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2695 free($3);
2696 free($5);
2697 }
2698 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002699
Reid Spencer950bf602007-01-26 08:19:09 +00002700// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2701// another value.
2702//
2703SymbolicValueRef
2704 : INTVAL { $$ = ValID::create($1); }
2705 | Name { $$ = ValID::create($1); }
2706 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002707
2708// ValueRef - A reference to a definition... either constant or symbolic
Reid Spencerf459d392006-12-02 16:19:52 +00002709ValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002710 : SymbolicValueRef | ConstValueRef
Reid Spencerf459d392006-12-02 16:19:52 +00002711 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002712
Reid Spencer950bf602007-01-26 08:19:09 +00002713
Reid Spencere7c3c602006-11-30 06:36:44 +00002714// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2715// type immediately preceeds the value reference, and allows complex constant
2716// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
Reid Spencer950bf602007-01-26 08:19:09 +00002717ResolvedVal
2718 : Types ValueRef {
2719 const Type *Ty = $1.T->get();
2720 $$.S = $1.S;
2721 $$.V = getVal(Ty, $2);
2722 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002723 }
Reid Spencer950bf602007-01-26 08:19:09 +00002724 ;
2725
2726BasicBlockList
2727 : BasicBlockList BasicBlock {
2728 $$ = $1;
2729 }
2730 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2731 $$ = $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002732 };
2733
2734
2735// Basic blocks are terminated by branching instructions:
2736// br, br/cc, switch, ret
2737//
Reid Spencer950bf602007-01-26 08:19:09 +00002738BasicBlock
2739 : InstructionList OptAssign BBTerminatorInst {
2740 setValueName($3, $2);
2741 InsertValue($3);
2742 $1->getInstList().push_back($3);
2743 InsertValue($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002744 $$ = $1;
2745 }
Reid Spencer950bf602007-01-26 08:19:09 +00002746 ;
2747
2748InstructionList
2749 : InstructionList Inst {
2750 if ($2.I)
2751 $1->getInstList().push_back($2.I);
2752 $$ = $1;
2753 }
2754 | /* empty */ {
2755 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2756 // Make sure to move the basic block to the correct location in the
2757 // function, instead of leaving it inserted wherever it was first
2758 // referenced.
2759 Function::BasicBlockListType &BBL =
2760 CurFun.CurrentFunction->getBasicBlockList();
2761 BBL.splice(BBL.end(), BBL, $$);
2762 }
2763 | LABELSTR {
2764 $$ = CurBB = getBBVal(ValID::create($1), true);
2765 // Make sure to move the basic block to the correct location in the
2766 // function, instead of leaving it inserted wherever it was first
2767 // referenced.
2768 Function::BasicBlockListType &BBL =
2769 CurFun.CurrentFunction->getBasicBlockList();
2770 BBL.splice(BBL.end(), BBL, $$);
2771 }
2772 ;
2773
2774Unwind : UNWIND | EXCEPT;
2775
2776BBTerminatorInst
2777 : RET ResolvedVal { // Return with a result...
2778 $$ = new ReturnInst($2.V);
2779 }
2780 | RET VOID { // Return with no result...
2781 $$ = new ReturnInst();
2782 }
2783 | BR LABEL ValueRef { // Unconditional Branch...
2784 BasicBlock* tmpBB = getBBVal($3);
2785 $$ = new BranchInst(tmpBB);
2786 } // Conditional Branch...
2787 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2788 BasicBlock* tmpBBA = getBBVal($6);
2789 BasicBlock* tmpBBB = getBBVal($9);
2790 Value* tmpVal = getVal(Type::Int1Ty, $3);
2791 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2792 }
2793 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2794 Value* tmpVal = getVal($2.T, $3);
2795 BasicBlock* tmpBB = getBBVal($6);
2796 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2797 $$ = S;
2798 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2799 E = $8->end();
2800 for (; I != E; ++I) {
2801 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2802 S->addCase(CI, I->second);
2803 else
2804 error("Switch case is constant, but not a simple integer");
2805 }
2806 delete $8;
2807 }
2808 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2809 Value* tmpVal = getVal($2.T, $3);
2810 BasicBlock* tmpBB = getBBVal($6);
2811 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2812 $$ = S;
2813 }
2814 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2815 TO LABEL ValueRef Unwind LABEL ValueRef {
2816 const PointerType *PFTy;
2817 const FunctionType *Ty;
2818
2819 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2820 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2821 // Pull out the types of all of the arguments...
2822 std::vector<const Type*> ParamTypes;
2823 if ($6) {
2824 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2825 I != E; ++I)
2826 ParamTypes.push_back((*I).V->getType());
2827 }
2828 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2829 if (isVarArg) ParamTypes.pop_back();
2830 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg);
2831 PFTy = PointerType::get(Ty);
2832 }
2833 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2834 BasicBlock *Normal = getBBVal($10);
2835 BasicBlock *Except = getBBVal($13);
2836
2837 // Create the call node...
2838 if (!$6) { // Has no arguments?
2839 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2840 } else { // Has arguments?
2841 // Loop through FunctionType's arguments and ensure they are specified
2842 // correctly!
2843 //
2844 FunctionType::param_iterator I = Ty->param_begin();
2845 FunctionType::param_iterator E = Ty->param_end();
2846 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2847
2848 std::vector<Value*> Args;
2849 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2850 if ((*ArgI).V->getType() != *I)
2851 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2852 (*I)->getDescription() + "'");
2853 Args.push_back((*ArgI).V);
2854 }
2855
2856 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2857 error("Invalid number of parameters detected");
2858
2859 $$ = new InvokeInst(V, Normal, Except, Args);
2860 }
2861 cast<InvokeInst>($$)->setCallingConv($2);
2862 delete $3.T;
2863 delete $6;
2864 }
2865 | Unwind {
2866 $$ = new UnwindInst();
2867 }
2868 | UNREACHABLE {
2869 $$ = new UnreachableInst();
2870 }
2871 ;
2872
2873JumpTable
2874 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2875 $$ = $1;
2876 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2877
2878 if (V == 0)
2879 error("May only switch on a constant pool value");
2880
2881 BasicBlock* tmpBB = getBBVal($6);
2882 $$->push_back(std::make_pair(V, tmpBB));
2883 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002884 | IntType ConstValueRef ',' LABEL ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00002885 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2886 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2887
2888 if (V == 0)
2889 error("May only switch on a constant pool value");
2890
2891 BasicBlock* tmpBB = getBBVal($5);
2892 $$->push_back(std::make_pair(V, tmpBB));
2893 }
2894 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002895
2896Inst
2897 : OptAssign InstVal {
Reid Spencer950bf602007-01-26 08:19:09 +00002898 bool omit = false;
2899 if ($1)
2900 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2901 if (BCI->getSrcTy() == BCI->getDestTy() &&
2902 BCI->getOperand(0)->getName() == $1)
2903 // This is a useless bit cast causing a name redefinition. It is
2904 // a bit cast from a type to the same type of an operand with the
2905 // same name as the name we would give this instruction. Since this
2906 // instruction results in no code generation, it is safe to omit
2907 // the instruction. This situation can occur because of collapsed
2908 // type planes. For example:
2909 // %X = add int %Y, %Z
2910 // %X = cast int %Y to uint
2911 // After upgrade, this looks like:
2912 // %X = add i32 %Y, %Z
2913 // %X = bitcast i32 to i32
2914 // The bitcast is clearly useless so we omit it.
2915 omit = true;
2916 if (omit) {
2917 $$.I = 0;
2918 $$.S = Signless;
2919 } else {
2920 setValueName($2.I, $1);
2921 InsertValue($2.I);
2922 $$ = $2;
Reid Spencerf5626a32007-01-01 01:20:41 +00002923 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002924 };
2925
Reid Spencer950bf602007-01-26 08:19:09 +00002926PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2927 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2928 $$.S = $1.S;
2929 Value* tmpVal = getVal($1.T->get(), $3);
2930 BasicBlock* tmpBB = getBBVal($5);
2931 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
2932 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002933 }
2934 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
Reid Spencere7c3c602006-11-30 06:36:44 +00002935 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00002936 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
2937 BasicBlock* tmpBB = getBBVal($6);
2938 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
2939 }
2940 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002941
Reid Spencer950bf602007-01-26 08:19:09 +00002942ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2943 $$ = new std::vector<ValueInfo>();
Reid Spencerf8483652006-12-02 15:16:01 +00002944 $$->push_back($1);
2945 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002946 | ValueRefList ',' ResolvedVal {
Reid Spencere7c3c602006-11-30 06:36:44 +00002947 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00002948 $1->push_back($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002949 };
2950
2951// ValueRefListE - Just like ValueRefList, except that it may also be empty!
2952ValueRefListE
Reid Spencer950bf602007-01-26 08:19:09 +00002953 : ValueRefList
2954 | /*empty*/ { $$ = 0; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002955 ;
2956
2957OptTailCall
2958 : TAIL CALL {
Reid Spencer950bf602007-01-26 08:19:09 +00002959 $$ = true;
Reid Spencere7c3c602006-11-30 06:36:44 +00002960 }
Reid Spencer950bf602007-01-26 08:19:09 +00002961 | CALL {
2962 $$ = false;
2963 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002964 ;
2965
Reid Spencer950bf602007-01-26 08:19:09 +00002966InstVal
2967 : ArithmeticOps Types ValueRef ',' ValueRef {
2968 const Type* Ty = $2.T->get();
2969 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
2970 error("Arithmetic operator requires integer, FP, or packed operands");
2971 if (isa<PackedType>(Ty) &&
2972 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
2973 error("Remainder not supported on packed types");
2974 // Upgrade the opcode from obsolete versions before we do anything with it.
2975 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2976 Value* val1 = getVal(Ty, $3);
2977 Value* val2 = getVal(Ty, $5);
2978 $$.I = BinaryOperator::create(Opcode, val1, val2);
2979 if ($$.I == 0)
2980 error("binary operator returned null");
2981 $$.S = $2.S;
2982 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002983 }
2984 | LogicalOps Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00002985 const Type *Ty = $2.T->get();
2986 if (!Ty->isInteger()) {
2987 if (!isa<PackedType>(Ty) ||
2988 !cast<PackedType>(Ty)->getElementType()->isInteger())
2989 error("Logical operator requires integral operands");
2990 }
2991 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2992 Value* tmpVal1 = getVal(Ty, $3);
2993 Value* tmpVal2 = getVal(Ty, $5);
2994 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
2995 if ($$.I == 0)
2996 error("binary operator returned null");
2997 $$.S = $2.S;
2998 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002999 }
3000 | SetCondOps Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003001 const Type* Ty = $2.T->get();
3002 if(isa<PackedType>(Ty))
3003 error("PackedTypes currently not supported in setcc instructions");
3004 unsigned short pred;
3005 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3006 Value* tmpVal1 = getVal(Ty, $3);
3007 Value* tmpVal2 = getVal(Ty, $5);
3008 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3009 if ($$.I == 0)
3010 error("binary operator returned null");
3011 $$.S = Unsigned;
3012 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003013 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003014 | ICMP IPredicates Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003015 const Type *Ty = $3.T->get();
3016 if (isa<PackedType>(Ty))
3017 error("PackedTypes currently not supported in icmp instructions");
3018 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3019 error("icmp requires integer or pointer typed operands");
3020 Value* tmpVal1 = getVal(Ty, $4);
3021 Value* tmpVal2 = getVal(Ty, $6);
3022 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3023 $$.S = Unsigned;
3024 delete $3.T;
Reid Spencer57f28f92006-12-03 07:10:26 +00003025 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003026 | FCMP FPredicates Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003027 const Type *Ty = $3.T->get();
3028 if (isa<PackedType>(Ty))
3029 error("PackedTypes currently not supported in fcmp instructions");
3030 else if (!Ty->isFloatingPoint())
3031 error("fcmp instruction requires floating point operands");
3032 Value* tmpVal1 = getVal(Ty, $4);
3033 Value* tmpVal2 = getVal(Ty, $6);
3034 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3035 $$.S = Unsigned;
3036 delete $3.T;
3037 }
3038 | NOT ResolvedVal {
3039 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3040 const Type *Ty = $2.V->getType();
3041 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3042 if (Ones == 0)
3043 error("Expected integral type for not instruction");
3044 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3045 if ($$.I == 0)
3046 error("Could not create a xor instruction");
3047 $$.S = $2.S
Reid Spencer229e9362006-12-02 22:14:11 +00003048 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003049 | ShiftOps ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003050 if (!$4.V->getType()->isInteger() ||
3051 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3052 error("Shift amount must be int8");
3053 if (!$2.V->getType()->isInteger())
3054 error("Shift constant expression requires integer operand");
3055 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3056 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003057 }
Reid Spencerfcb5df82006-12-01 22:34:43 +00003058 | CastOps ResolvedVal TO Types {
Reid Spencer950bf602007-01-26 08:19:09 +00003059 const Type *DstTy = $4.T->get();
3060 if (!DstTy->isFirstClassType())
3061 error("cast instruction to a non-primitive type: '" +
3062 DstTy->getDescription() + "'");
3063 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3064 $$.S = $4.S;
3065 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003066 }
3067 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003068 if (!$2.V->getType()->isInteger() ||
3069 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3070 error("select condition must be bool");
3071 if ($4.V->getType() != $6.V->getType())
3072 error("select value types should match");
3073 $$.I = new SelectInst($2.V, $4.V, $6.V);
3074 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003075 }
3076 | VAARG ResolvedVal ',' Types {
Reid Spencer950bf602007-01-26 08:19:09 +00003077 const Type *Ty = $4.T->get();
3078 NewVarArgs = true;
3079 $$.I = new VAArgInst($2.V, Ty);
3080 $$.S = $4.S;
3081 delete $4.T;
3082 }
3083 | VAARG_old ResolvedVal ',' Types {
3084 const Type* ArgTy = $2.V->getType();
3085 const Type* DstTy = $4.T->get();
3086 ObsoleteVarArgs = true;
3087 Function* NF = cast<Function>(CurModule.CurrentModule->
3088 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3089
3090 //b = vaarg a, t ->
3091 //foo = alloca 1 of t
3092 //bar = vacopy a
3093 //store bar -> foo
3094 //b = vaarg foo, t
3095 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3096 CurBB->getInstList().push_back(foo);
3097 CallInst* bar = new CallInst(NF, $2.V);
3098 CurBB->getInstList().push_back(bar);
3099 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3100 $$.I = new VAArgInst(foo, DstTy);
3101 $$.S = $4.S;
3102 delete $4.T;
3103 }
3104 | VANEXT_old ResolvedVal ',' Types {
3105 const Type* ArgTy = $2.V->getType();
3106 const Type* DstTy = $4.T->get();
3107 ObsoleteVarArgs = true;
3108 Function* NF = cast<Function>(CurModule.CurrentModule->
3109 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3110
3111 //b = vanext a, t ->
3112 //foo = alloca 1 of t
3113 //bar = vacopy a
3114 //store bar -> foo
3115 //tmp = vaarg foo, t
3116 //b = load foo
3117 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3118 CurBB->getInstList().push_back(foo);
3119 CallInst* bar = new CallInst(NF, $2.V);
3120 CurBB->getInstList().push_back(bar);
3121 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3122 Instruction* tmp = new VAArgInst(foo, DstTy);
3123 CurBB->getInstList().push_back(tmp);
3124 $$.I = new LoadInst(foo);
3125 $$.S = $4.S;
3126 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003127 }
3128 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003129 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3130 error("Invalid extractelement operands");
3131 $$.I = new ExtractElementInst($2.V, $4.V);
3132 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003133 }
3134 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003135 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3136 error("Invalid insertelement operands");
3137 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3138 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003139 }
3140 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003141 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3142 error("Invalid shufflevector operands");
3143 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3144 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003145 }
3146 | PHI_TOK PHIList {
Reid Spencer950bf602007-01-26 08:19:09 +00003147 const Type *Ty = $2.P->front().first->getType();
3148 if (!Ty->isFirstClassType())
3149 error("PHI node operands must be of first class type");
3150 PHINode *PHI = new PHINode(Ty);
3151 PHI->reserveOperandSpace($2.P->size());
3152 while ($2.P->begin() != $2.P->end()) {
3153 if ($2.P->front().first->getType() != Ty)
3154 error("All elements of a PHI node must be of the same type");
3155 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3156 $2.P->pop_front();
3157 }
3158 $$.I = PHI;
3159 $$.S = $2.S;
3160 delete $2.P; // Free the list...
Reid Spencere7c3c602006-11-30 06:36:44 +00003161 }
3162 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00003163
3164 // Handle the short call syntax
3165 const PointerType *PFTy;
3166 const FunctionType *FTy;
3167 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3168 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3169 // Pull out the types of all of the arguments...
3170 std::vector<const Type*> ParamTypes;
3171 if ($6) {
3172 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3173 I != E; ++I)
3174 ParamTypes.push_back((*I).V->getType());
Reid Spencerc4d96252007-01-13 00:03:30 +00003175 }
Reid Spencer950bf602007-01-26 08:19:09 +00003176
3177 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3178 if (isVarArg) ParamTypes.pop_back();
3179
3180 const Type *RetTy = $3.T->get();
3181 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3182 error("Functions cannot return aggregate types");
3183
3184 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3185 PFTy = PointerType::get(FTy);
Reid Spencerf8483652006-12-02 15:16:01 +00003186 }
Reid Spencer950bf602007-01-26 08:19:09 +00003187
3188 // First upgrade any intrinsic calls.
3189 std::vector<Value*> Args;
3190 if ($6)
3191 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3192 Args.push_back((*$6)[i].V);
3193 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3194
3195 // If we got an upgraded intrinsic
3196 if (Inst) {
3197 $$.I = Inst;
3198 $$.S = Signless;
3199 } else {
3200 // Get the function we're calling
3201 Value *V = getVal(PFTy, $4);
3202
3203 // Check the argument values match
3204 if (!$6) { // Has no arguments?
3205 // Make sure no arguments is a good thing!
3206 if (FTy->getNumParams() != 0)
3207 error("No arguments passed to a function that expects arguments");
3208 } else { // Has arguments?
3209 // Loop through FunctionType's arguments and ensure they are specified
3210 // correctly!
3211 //
3212 FunctionType::param_iterator I = FTy->param_begin();
3213 FunctionType::param_iterator E = FTy->param_end();
3214 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3215
3216 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3217 if ((*ArgI).V->getType() != *I)
3218 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3219 (*I)->getDescription() + "'");
3220
3221 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3222 error("Invalid number of parameters detected");
3223 }
3224
3225 // Create the call instruction
3226 CallInst *CI = new CallInst(V, Args);
3227 CI->setTailCall($1);
3228 CI->setCallingConv($2);
3229 $$.I = CI;
3230 $$.S = $3.S;
3231 }
3232 delete $3.T;
3233 delete $6;
Reid Spencere7c3c602006-11-30 06:36:44 +00003234 }
Reid Spencer950bf602007-01-26 08:19:09 +00003235 | MemoryInst {
3236 $$ = $1;
3237 }
3238 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003239
3240
3241// IndexList - List of indices for GEP based instructions...
3242IndexList
Reid Spencer950bf602007-01-26 08:19:09 +00003243 : ',' ValueRefList { $$ = $2; }
3244 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
Reid Spencere7c3c602006-11-30 06:36:44 +00003245 ;
3246
3247OptVolatile
Reid Spencer950bf602007-01-26 08:19:09 +00003248 : VOLATILE { $$ = true; }
3249 | /* empty */ { $$ = false; }
Reid Spencere7c3c602006-11-30 06:36:44 +00003250 ;
3251
Reid Spencer950bf602007-01-26 08:19:09 +00003252MemoryInst
3253 : MALLOC Types OptCAlign {
3254 const Type *Ty = $2.T->get();
3255 $$.S = $2.S;
3256 $$.I = new MallocInst(Ty, 0, $3);
3257 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003258 }
3259 | MALLOC Types ',' UINT ValueRef OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003260 const Type *Ty = $2.T->get();
3261 $$.S = $2.S;
3262 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3263 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003264 }
3265 | ALLOCA Types OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003266 const Type *Ty = $2.T->get();
3267 $$.S = $2.S;
3268 $$.I = new AllocaInst(Ty, 0, $3);
3269 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003270 }
3271 | ALLOCA Types ',' UINT ValueRef OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003272 const Type *Ty = $2.T->get();
3273 $$.S = $2.S;
3274 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3275 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003276 }
3277 | FREE ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003278 const Type *PTy = $2.V->getType();
3279 if (!isa<PointerType>(PTy))
3280 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3281 $$.I = new FreeInst($2.V);
3282 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00003283 }
3284 | OptVolatile LOAD Types ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003285 const Type* Ty = $3.T->get();
3286 $$.S = $3.S;
3287 if (!isa<PointerType>(Ty))
3288 error("Can't load from nonpointer type: " + Ty->getDescription());
3289 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3290 error("Can't load from pointer of non-first-class type: " +
3291 Ty->getDescription());
3292 Value* tmpVal = getVal(Ty, $4);
3293 $$.I = new LoadInst(tmpVal, "", $1);
3294 delete $3.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003295 }
3296 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003297 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3298 if (!PTy)
3299 error("Can't store to a nonpointer type: " +
3300 $5.T->get()->getDescription());
3301 const Type *ElTy = PTy->getElementType();
3302 if (ElTy != $3.V->getType())
3303 error("Can't store '" + $3.V->getType()->getDescription() +
3304 "' into space of type '" + ElTy->getDescription() + "'");
3305 Value* tmpVal = getVal(PTy, $6);
3306 $$.I = new StoreInst($3.V, tmpVal, $1);
3307 $$.S = Signless;
3308 delete $5.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003309 }
3310 | GETELEMENTPTR Types ValueRef IndexList {
Reid Spencer950bf602007-01-26 08:19:09 +00003311 const Type* Ty = $2.T->get();
3312 if (!isa<PointerType>(Ty))
3313 error("getelementptr insn requires pointer operand");
3314
3315 std::vector<Value*> VIndices;
3316 upgradeGEPIndices(Ty, $4, VIndices);
3317
3318 Value* tmpVal = getVal(Ty, $3);
3319 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3320 $$.S = Signless;
3321 delete $2.T;
Reid Spencer30d0c582007-01-15 00:26:18 +00003322 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00003323 };
3324
Reid Spencer950bf602007-01-26 08:19:09 +00003325
Reid Spencere7c3c602006-11-30 06:36:44 +00003326%%
3327
3328int yyerror(const char *ErrorMsg) {
3329 std::string where
3330 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencer950bf602007-01-26 08:19:09 +00003331 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3332 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3333 if (yychar != YYEMPTY && yychar != 0)
3334 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3335 "'.";
Reid Spencer71d2ec92006-12-31 06:02:26 +00003336 std::cerr << "llvm-upgrade: " << errMsg << '\n';
Reid Spencer950bf602007-01-26 08:19:09 +00003337 std::cout << "llvm-upgrade: parse failed.\n";
Reid Spencere7c3c602006-11-30 06:36:44 +00003338 exit(1);
3339}
Reid Spencer319a7302007-01-05 17:20:02 +00003340
Reid Spencer30d0c582007-01-15 00:26:18 +00003341void warning(const std::string& ErrorMsg) {
Reid Spencer319a7302007-01-05 17:20:02 +00003342 std::string where
3343 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencer950bf602007-01-26 08:19:09 +00003344 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3345 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3346 if (yychar != YYEMPTY && yychar != 0)
3347 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3348 "'.";
Reid Spencer319a7302007-01-05 17:20:02 +00003349 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3350}
Reid Spencer950bf602007-01-26 08:19:09 +00003351
3352void error(const std::string& ErrorMsg, int LineNo) {
3353 if (LineNo == -1) LineNo = Upgradelineno;
3354 Upgradelineno = LineNo;
3355 yyerror(ErrorMsg.c_str());
3356}
3357