blob: ad72b3996ad5b8cad237bc9c5eeed21a7dea311e [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"
Reid Spenceref9b9a72007-02-05 20:47:22 +000020#include "llvm/ValueSymbolTable.h"
Reid Spencer950bf602007-01-26 08:19:09 +000021#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
Reid Spencered96d1e2007-02-08 09:08:52 +0000270/// This function determines if two function types differ only in their use of
271/// the sret parameter attribute in the first argument. If they are identical
272/// in all other respects, it returns true. Otherwise, it returns false.
273bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
274 const FunctionType *F2) {
275 if (F1->getReturnType() != F2->getReturnType() ||
276 F1->getNumParams() != F2->getNumParams() ||
277 F1->getParamAttrs(0) != F2->getParamAttrs(0))
278 return false;
279 unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
280 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
281 if (F1->getParamType(i) != F2->getParamType(i) ||
282 unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
283 unsigned(F2->getParamAttrs(i+1)) & SRetMask)
284 return false;
285 }
286 return true;
287}
288
289// The upgrade of csretcc to sret param attribute may have caused a function
290// to not be found because the param attribute changed the type of the called
291// function. This helper function, used in getExistingValue, detects that
292// situation and returns V if it occurs and 0 otherwise.
293static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
294 // Handle degenerate cases
295 if (!V)
296 return 0;
297 if (V->getType() == Ty)
298 return V;
299
300 Value* Result = 0;
301 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
302 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
303 if (PF1 && PF2) {
304 const FunctionType *FT1 =
305 dyn_cast<FunctionType>(PF1->getElementType());
306 const FunctionType *FT2 =
307 dyn_cast<FunctionType>(PF2->getElementType());
308 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
309 if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
310 Result = V;
311 else if (Constant *C = dyn_cast<Constant>(V))
312 Result = ConstantExpr::getBitCast(C, PF1);
313 else
314 Result = new BitCastInst(V, PF1, "upgrd.cast", CurBB);
315 }
316 return Result;
317}
318
Reid Spencer950bf602007-01-26 08:19:09 +0000319// getExistingValue - Look up the value specified by the provided type and
320// the provided ValID. If the value exists and has already been defined, return
321// it. Otherwise return null.
322//
323static Value *getExistingValue(const Type *Ty, const ValID &D) {
324 if (isa<FunctionType>(Ty)) {
325 error("Functions are not values and must be referenced as pointers");
326 }
327
328 switch (D.Type) {
329 case ValID::NumberVal: { // Is it a numbered definition?
330 unsigned Num = (unsigned)D.Num;
331
332 // Module constants occupy the lowest numbered slots...
333 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
334 if (VI != CurModule.Values.end()) {
335 if (Num < VI->second.size())
336 return VI->second[Num];
337 Num -= VI->second.size();
338 }
339
340 // Make sure that our type is within bounds
341 VI = CurFun.Values.find(Ty);
342 if (VI == CurFun.Values.end()) return 0;
343
344 // Check that the number is within bounds...
345 if (VI->second.size() <= Num) return 0;
346
347 return VI->second[Num];
348 }
349
350 case ValID::NameVal: { // Is it a named definition?
351 // Get the name out of the ID
352 std::string Name(D.Name);
353 Value* V = 0;
354 RenameMapKey Key = std::make_pair(Name, Ty);
355 if (inFunctionScope()) {
356 // See if the name was renamed
357 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
358 std::string LookupName;
359 if (I != CurFun.RenameMap.end())
360 LookupName = I->second;
361 else
362 LookupName = Name;
Reid Spenceref9b9a72007-02-05 20:47:22 +0000363 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
364 V = SymTab.lookup(LookupName);
Reid Spencered96d1e2007-02-08 09:08:52 +0000365 V = handleSRetFuncTypeMerge(V, Ty);
Reid Spencer950bf602007-01-26 08:19:09 +0000366 }
367 if (!V) {
368 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
369 std::string LookupName;
370 if (I != CurModule.RenameMap.end())
371 LookupName = I->second;
372 else
373 LookupName = Name;
Reid Spenceref9b9a72007-02-05 20:47:22 +0000374 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
Reid Spencered96d1e2007-02-08 09:08:52 +0000375 V = handleSRetFuncTypeMerge(V, Ty);
Reid Spencer950bf602007-01-26 08:19:09 +0000376 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000377 if (!V)
Reid Spencer950bf602007-01-26 08:19:09 +0000378 return 0;
379
380 D.destroy(); // Free old strdup'd memory...
381 return V;
382 }
383
384 // Check to make sure that "Ty" is an integral type, and that our
385 // value will fit into the specified type...
386 case ValID::ConstSIntVal: // Is it a constant pool reference??
387 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
388 error("Signed integral constant '" + itostr(D.ConstPool64) +
389 "' is invalid for type '" + Ty->getDescription() + "'");
390 }
391 return ConstantInt::get(Ty, D.ConstPool64);
392
393 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
394 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
395 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
396 error("Integral constant '" + utostr(D.UConstPool64) +
397 "' is invalid or out of range");
398 else // This is really a signed reference. Transmogrify.
399 return ConstantInt::get(Ty, D.ConstPool64);
400 } else
401 return ConstantInt::get(Ty, D.UConstPool64);
402
403 case ValID::ConstFPVal: // Is it a floating point const pool reference?
404 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
405 error("FP constant invalid for type");
406 return ConstantFP::get(Ty, D.ConstPoolFP);
407
408 case ValID::ConstNullVal: // Is it a null value?
409 if (!isa<PointerType>(Ty))
410 error("Cannot create a a non pointer null");
411 return ConstantPointerNull::get(cast<PointerType>(Ty));
412
413 case ValID::ConstUndefVal: // Is it an undef value?
414 return UndefValue::get(Ty);
415
416 case ValID::ConstZeroVal: // Is it a zero value?
417 return Constant::getNullValue(Ty);
418
419 case ValID::ConstantVal: // Fully resolved constant?
420 if (D.ConstantValue->getType() != Ty)
421 error("Constant expression type different from required type");
422 return D.ConstantValue;
423
424 case ValID::InlineAsmVal: { // Inline asm expression
425 const PointerType *PTy = dyn_cast<PointerType>(Ty);
426 const FunctionType *FTy =
427 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
428 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
429 error("Invalid type for asm constraint string");
430 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
431 D.IAD->HasSideEffects);
432 D.destroy(); // Free InlineAsmDescriptor.
433 return IA;
434 }
435 default:
436 assert(0 && "Unhandled case");
437 return 0;
438 } // End of switch
439
440 assert(0 && "Unhandled case");
441 return 0;
442}
443
444// getVal - This function is identical to getExistingValue, except that if a
445// value is not already defined, it "improvises" by creating a placeholder var
446// that looks and acts just like the requested variable. When the value is
447// defined later, all uses of the placeholder variable are replaced with the
448// real thing.
449//
450static Value *getVal(const Type *Ty, const ValID &ID) {
451 if (Ty == Type::LabelTy)
452 error("Cannot use a basic block here");
453
454 // See if the value has already been defined.
455 Value *V = getExistingValue(Ty, ID);
456 if (V) return V;
457
458 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
459 error("Invalid use of a composite type");
460
461 // If we reached here, we referenced either a symbol that we don't know about
462 // or an id number that hasn't been read yet. We may be referencing something
463 // forward, so just create an entry to be resolved later and get to it...
Reid Spencer950bf602007-01-26 08:19:09 +0000464 V = new Argument(Ty);
465
466 // Remember where this forward reference came from. FIXME, shouldn't we try
467 // to recycle these things??
468 CurModule.PlaceHolderInfo.insert(
Reid Spenceref9b9a72007-02-05 20:47:22 +0000469 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
Reid Spencer950bf602007-01-26 08:19:09 +0000470
471 if (inFunctionScope())
472 InsertValue(V, CurFun.LateResolveValues);
473 else
474 InsertValue(V, CurModule.LateResolveValues);
475 return V;
476}
477
Reid Spencered96d1e2007-02-08 09:08:52 +0000478/// @brief This just makes any name given to it unique, up to MAX_UINT times.
479static std::string makeNameUnique(const std::string& Name) {
480 static unsigned UniqueNameCounter = 1;
481 std::string Result(Name);
482 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
483 return Result;
484}
485
Reid Spencer950bf602007-01-26 08:19:09 +0000486/// getBBVal - This is used for two purposes:
487/// * If isDefinition is true, a new basic block with the specified ID is being
488/// defined.
489/// * If isDefinition is true, this is a reference to a basic block, which may
490/// or may not be a forward reference.
491///
492static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
493 assert(inFunctionScope() && "Can't get basic block at global scope");
494
495 std::string Name;
496 BasicBlock *BB = 0;
497 switch (ID.Type) {
498 default:
499 error("Illegal label reference " + ID.getName());
500 break;
501 case ValID::NumberVal: // Is it a numbered definition?
502 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
503 CurFun.NumberedBlocks.resize(ID.Num+1);
504 BB = CurFun.NumberedBlocks[ID.Num];
505 break;
506 case ValID::NameVal: // Is it a named definition?
507 Name = ID.Name;
508 if (Value *N = CurFun.CurrentFunction->
Reid Spenceref9b9a72007-02-05 20:47:22 +0000509 getValueSymbolTable().lookup(Name)) {
Reid Spencered96d1e2007-02-08 09:08:52 +0000510 if (N->getType() != Type::LabelTy) {
511 // Register names didn't use to conflict with basic block names
512 // because of type planes. Now they all have to be unique. So, we just
513 // rename the register and treat this name as if no basic block
514 // had been found.
515 RenameMapKey Key = std::make_pair(N->getName(),N->getType());
516 N->setName(makeNameUnique(N->getName()));
517 CurModule.RenameMap[Key] = N->getName();
518 BB = 0;
519 } else {
520 BB = cast<BasicBlock>(N);
521 }
Reid Spencer950bf602007-01-26 08:19:09 +0000522 }
523 break;
524 }
525
526 // See if the block has already been defined.
527 if (BB) {
528 // If this is the definition of the block, make sure the existing value was
529 // just a forward reference. If it was a forward reference, there will be
530 // an entry for it in the PlaceHolderInfo map.
531 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
532 // The existing value was a definition, not a forward reference.
533 error("Redefinition of label " + ID.getName());
534
535 ID.destroy(); // Free strdup'd memory.
536 return BB;
537 }
538
539 // Otherwise this block has not been seen before.
540 BB = new BasicBlock("", CurFun.CurrentFunction);
541 if (ID.Type == ValID::NameVal) {
542 BB->setName(ID.Name);
543 } else {
544 CurFun.NumberedBlocks[ID.Num] = BB;
545 }
546
547 // If this is not a definition, keep track of it so we can use it as a forward
548 // reference.
549 if (!isDefinition) {
550 // Remember where this forward reference came from.
551 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
552 } else {
553 // The forward declaration could have been inserted anywhere in the
554 // function: insert it into the correct place now.
555 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
556 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
557 }
558 ID.destroy();
559 return BB;
560}
561
562
563//===----------------------------------------------------------------------===//
564// Code to handle forward references in instructions
565//===----------------------------------------------------------------------===//
566//
567// This code handles the late binding needed with statements that reference
568// values not defined yet... for example, a forward branch, or the PHI node for
569// a loop body.
570//
571// This keeps a table (CurFun.LateResolveValues) of all such forward references
572// and back patchs after we are done.
573//
574
575// ResolveDefinitions - If we could not resolve some defs at parsing
576// time (forward branches, phi functions for loops, etc...) resolve the
577// defs now...
578//
579static void
580ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
581 std::map<const Type*,ValueList> *FutureLateResolvers) {
Reid Spencered96d1e2007-02-08 09:08:52 +0000582
Reid Spencer950bf602007-01-26 08:19:09 +0000583 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
584 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
585 E = LateResolvers.end(); LRI != E; ++LRI) {
Reid Spencered96d1e2007-02-08 09:08:52 +0000586 const Type* Ty = LRI->first;
Reid Spencer950bf602007-01-26 08:19:09 +0000587 ValueList &List = LRI->second;
588 while (!List.empty()) {
589 Value *V = List.back();
590 List.pop_back();
591
592 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
593 CurModule.PlaceHolderInfo.find(V);
594 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
595
596 ValID &DID = PHI->second.first;
597
Reid Spencered96d1e2007-02-08 09:08:52 +0000598 Value *TheRealValue = getExistingValue(Ty, DID);
Reid Spencer950bf602007-01-26 08:19:09 +0000599 if (TheRealValue) {
600 V->replaceAllUsesWith(TheRealValue);
601 delete V;
602 CurModule.PlaceHolderInfo.erase(PHI);
603 } else if (FutureLateResolvers) {
604 // Functions have their unresolved items forwarded to the module late
605 // resolver table
606 InsertValue(V, *FutureLateResolvers);
607 } else {
608 if (DID.Type == ValID::NameVal) {
Reid Spencered96d1e2007-02-08 09:08:52 +0000609 error("Reference to an invalid definition: '" + DID.getName() +
610 "' of type '" + V->getType()->getDescription() + "'",
611 PHI->second.second);
Reid Spencer7de2e012007-01-29 19:08:46 +0000612 return;
Reid Spencer950bf602007-01-26 08:19:09 +0000613 } else {
614 error("Reference to an invalid definition: #" +
615 itostr(DID.Num) + " of type '" +
616 V->getType()->getDescription() + "'", PHI->second.second);
617 return;
618 }
619 }
620 }
621 }
622
623 LateResolvers.clear();
624}
625
626// ResolveTypeTo - A brand new type was just declared. This means that (if
627// name is not null) things referencing Name can be resolved. Otherwise, things
628// refering to the number can be resolved. Do this now.
629//
630static void ResolveTypeTo(char *Name, const Type *ToTy) {
631 ValID D;
632 if (Name) D = ValID::create(Name);
633 else D = ValID::create((int)CurModule.Types.size());
634
635 std::map<ValID, PATypeHolder>::iterator I =
636 CurModule.LateResolveTypes.find(D);
637 if (I != CurModule.LateResolveTypes.end()) {
638 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
639 CurModule.LateResolveTypes.erase(I);
640 }
641}
642
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000643/// This is the implementation portion of TypeHasInteger. It traverses the
644/// type given, avoiding recursive types, and returns true as soon as it finds
645/// an integer type. If no integer type is found, it returns false.
646static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
647 // Handle some easy cases
648 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
649 return false;
650 if (Ty->isInteger())
651 return true;
652 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
653 return STy->getElementType()->isInteger();
654
655 // Avoid type structure recursion
656 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
657 I != E; ++I)
658 if (Ty == *I)
659 return false;
660
661 // Push us on the type stack
662 Stack.push_back(Ty);
663
664 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
665 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
666 return true;
667 FunctionType::param_iterator I = FTy->param_begin();
668 FunctionType::param_iterator E = FTy->param_end();
669 for (; I != E; ++I)
670 if (TypeHasIntegerI(*I, Stack))
671 return true;
672 return false;
673 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
674 StructType::element_iterator I = STy->element_begin();
675 StructType::element_iterator E = STy->element_end();
676 for (; I != E; ++I) {
677 if (TypeHasIntegerI(*I, Stack))
678 return true;
679 }
680 return false;
681 }
682 // There shouldn't be anything else, but its definitely not integer
683 assert(0 && "What type is this?");
684 return false;
685}
686
687/// This is the interface to TypeHasIntegerI. It just provides the type stack,
688/// to avoid recursion, and then calls TypeHasIntegerI.
689static inline bool TypeHasInteger(const Type *Ty) {
690 std::vector<const Type*> TyStack;
691 return TypeHasIntegerI(Ty, TyStack);
692}
693
Reid Spencer950bf602007-01-26 08:19:09 +0000694// setValueName - Set the specified value to the name given. The name may be
695// null potentially, in which case this is a noop. The string passed in is
696// assumed to be a malloc'd string buffer, and is free'd by this function.
697//
698static void setValueName(Value *V, char *NameStr) {
699 if (NameStr) {
700 std::string Name(NameStr); // Copy string
701 free(NameStr); // Free old string
702
703 if (V->getType() == Type::VoidTy) {
704 error("Can't assign name '" + Name + "' to value with void type");
705 return;
706 }
707
Reid Spencer950bf602007-01-26 08:19:09 +0000708 assert(inFunctionScope() && "Must be in function scope");
709
710 // Search the function's symbol table for an existing value of this name
Reid Spenceref9b9a72007-02-05 20:47:22 +0000711 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
712 Value* Existing = ST.lookup(Name);
Reid Spencer950bf602007-01-26 08:19:09 +0000713 if (Existing) {
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000714 // An existing value of the same name was found. This might have happened
715 // because of the integer type planes collapsing in LLVM 2.0.
716 if (Existing->getType() == V->getType() &&
717 !TypeHasInteger(Existing->getType())) {
718 // If the type does not contain any integers in them then this can't be
719 // a type plane collapsing issue. It truly is a redefinition and we
720 // should error out as the assembly is invalid.
721 error("Redefinition of value named '" + Name + "' of type '" +
722 V->getType()->getDescription() + "'");
723 return;
Reid Spencer950bf602007-01-26 08:19:09 +0000724 }
725 // In LLVM 2.0 we don't allow names to be re-used for any values in a
726 // function, regardless of Type. Previously re-use of names was okay as
727 // long as they were distinct types. With type planes collapsing because
728 // of the signedness change and because of PR411, this can no longer be
729 // supported. We must search the entire symbol table for a conflicting
730 // name and make the name unique. No warning is needed as this can't
731 // cause a problem.
732 std::string NewName = makeNameUnique(Name);
733 // We're changing the name but it will probably be used by other
734 // instructions as operands later on. Consequently we have to retain
735 // a mapping of the renaming that we're doing.
736 RenameMapKey Key = std::make_pair(Name,V->getType());
737 CurFun.RenameMap[Key] = NewName;
738 Name = NewName;
739 }
740
741 // Set the name.
742 V->setName(Name);
743 }
744}
745
746/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
747/// this is a declaration, otherwise it is a definition.
748static GlobalVariable *
749ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
750 bool isConstantGlobal, const Type *Ty,
751 Constant *Initializer) {
752 if (isa<FunctionType>(Ty))
753 error("Cannot declare global vars of function type");
754
755 const PointerType *PTy = PointerType::get(Ty);
756
757 std::string Name;
758 if (NameStr) {
759 Name = NameStr; // Copy string
760 free(NameStr); // Free old string
761 }
762
763 // See if this global value was forward referenced. If so, recycle the
764 // object.
765 ValID ID;
766 if (!Name.empty()) {
767 ID = ValID::create((char*)Name.c_str());
768 } else {
769 ID = ValID::create((int)CurModule.Values[PTy].size());
770 }
771
772 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
773 // Move the global to the end of the list, from whereever it was
774 // previously inserted.
775 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
776 CurModule.CurrentModule->getGlobalList().remove(GV);
777 CurModule.CurrentModule->getGlobalList().push_back(GV);
778 GV->setInitializer(Initializer);
779 GV->setLinkage(Linkage);
780 GV->setConstant(isConstantGlobal);
781 InsertValue(GV, CurModule.Values);
782 return GV;
783 }
784
785 // If this global has a name, check to see if there is already a definition
786 // of this global in the module and emit warnings if there are conflicts.
787 if (!Name.empty()) {
788 // The global has a name. See if there's an existing one of the same name.
789 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
790 // We found an existing global ov the same name. This isn't allowed
791 // in LLVM 2.0. Consequently, we must alter the name of the global so it
792 // can at least compile. This can happen because of type planes
793 // There is alread a global of the same name which means there is a
794 // conflict. Let's see what we can do about it.
795 std::string NewName(makeNameUnique(Name));
796 if (Linkage == GlobalValue::InternalLinkage) {
797 // The linkage type is internal so just warn about the rename without
798 // invoking "scarey language" about linkage failures. GVars with
799 // InternalLinkage can be renamed at will.
800 warning("Global variable '" + Name + "' was renamed to '"+
801 NewName + "'");
802 } else {
803 // The linkage of this gval is external so we can't reliably rename
804 // it because it could potentially create a linking problem.
805 // However, we can't leave the name conflict in the output either or
806 // it won't assemble with LLVM 2.0. So, all we can do is rename
807 // this one to something unique and emit a warning about the problem.
808 warning("Renaming global variable '" + Name + "' to '" + NewName +
809 "' may cause linkage errors");
810 }
811
812 // Put the renaming in the global rename map
813 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
814 CurModule.RenameMap[Key] = NewName;
815
816 // Rename it
817 Name = NewName;
818 }
819 }
820
821 // Otherwise there is no existing GV to use, create one now.
822 GlobalVariable *GV =
823 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
824 CurModule.CurrentModule);
825 InsertValue(GV, CurModule.Values);
826 return GV;
827}
828
829// setTypeName - Set the specified type to the name given. The name may be
830// null potentially, in which case this is a noop. The string passed in is
831// assumed to be a malloc'd string buffer, and is freed by this function.
832//
833// This function returns true if the type has already been defined, but is
834// allowed to be redefined in the specified context. If the name is a new name
835// for the type plane, it is inserted and false is returned.
836static bool setTypeName(const Type *T, char *NameStr) {
837 assert(!inFunctionScope() && "Can't give types function-local names");
838 if (NameStr == 0) return false;
839
840 std::string Name(NameStr); // Copy string
841 free(NameStr); // Free old string
842
843 // We don't allow assigning names to void type
844 if (T == Type::VoidTy) {
845 error("Can't assign name '" + Name + "' to the void type");
846 return false;
847 }
848
849 // Set the type name, checking for conflicts as we do so.
850 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
851
852 if (AlreadyExists) { // Inserting a name that is already defined???
853 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
854 assert(Existing && "Conflict but no matching type?");
855
856 // There is only one case where this is allowed: when we are refining an
857 // opaque type. In this case, Existing will be an opaque type.
858 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
859 // We ARE replacing an opaque type!
860 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
861 return true;
862 }
863
864 // Otherwise, this is an attempt to redefine a type. That's okay if
865 // the redefinition is identical to the original. This will be so if
866 // Existing and T point to the same Type object. In this one case we
867 // allow the equivalent redefinition.
868 if (Existing == T) return true; // Yes, it's equal.
869
870 // Any other kind of (non-equivalent) redefinition is an error.
871 error("Redefinition of type named '" + Name + "' in the '" +
872 T->getDescription() + "' type plane");
873 }
874
875 return false;
876}
877
878//===----------------------------------------------------------------------===//
879// Code for handling upreferences in type names...
880//
881
882// TypeContains - Returns true if Ty directly contains E in it.
883//
884static bool TypeContains(const Type *Ty, const Type *E) {
885 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
886 E) != Ty->subtype_end();
887}
888
889namespace {
890 struct UpRefRecord {
891 // NestingLevel - The number of nesting levels that need to be popped before
892 // this type is resolved.
893 unsigned NestingLevel;
894
895 // LastContainedTy - This is the type at the current binding level for the
896 // type. Every time we reduce the nesting level, this gets updated.
897 const Type *LastContainedTy;
898
899 // UpRefTy - This is the actual opaque type that the upreference is
900 // represented with.
901 OpaqueType *UpRefTy;
902
903 UpRefRecord(unsigned NL, OpaqueType *URTy)
904 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
905 };
906}
907
908// UpRefs - A list of the outstanding upreferences that need to be resolved.
909static std::vector<UpRefRecord> UpRefs;
910
911/// HandleUpRefs - Every time we finish a new layer of types, this function is
912/// called. It loops through the UpRefs vector, which is a list of the
913/// currently active types. For each type, if the up reference is contained in
914/// the newly completed type, we decrement the level count. When the level
915/// count reaches zero, the upreferenced type is the type that is passed in:
916/// thus we can complete the cycle.
917///
918static PATypeHolder HandleUpRefs(const Type *ty) {
919 // If Ty isn't abstract, or if there are no up-references in it, then there is
920 // nothing to resolve here.
921 if (!ty->isAbstract() || UpRefs.empty()) return ty;
922
923 PATypeHolder Ty(ty);
924 UR_OUT("Type '" << Ty->getDescription() <<
925 "' newly formed. Resolving upreferences.\n" <<
926 UpRefs.size() << " upreferences active!\n");
927
928 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
929 // to zero), we resolve them all together before we resolve them to Ty. At
930 // the end of the loop, if there is anything to resolve to Ty, it will be in
931 // this variable.
932 OpaqueType *TypeToResolve = 0;
933
934 for (unsigned i = 0; i != UpRefs.size(); ++i) {
935 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
936 << UpRefs[i].second->getDescription() << ") = "
937 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
938 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
939 // Decrement level of upreference
940 unsigned Level = --UpRefs[i].NestingLevel;
941 UpRefs[i].LastContainedTy = Ty;
942 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
943 if (Level == 0) { // Upreference should be resolved!
944 if (!TypeToResolve) {
945 TypeToResolve = UpRefs[i].UpRefTy;
946 } else {
947 UR_OUT(" * Resolving upreference for "
948 << UpRefs[i].second->getDescription() << "\n";
949 std::string OldName = UpRefs[i].UpRefTy->getDescription());
950 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
951 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
952 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
953 }
954 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
955 --i; // Do not skip the next element...
956 }
957 }
958 }
959
960 if (TypeToResolve) {
961 UR_OUT(" * Resolving upreference for "
962 << UpRefs[i].second->getDescription() << "\n";
963 std::string OldName = TypeToResolve->getDescription());
964 TypeToResolve->refineAbstractTypeTo(Ty);
965 }
966
967 return Ty;
968}
969
970static inline Instruction::TermOps
971getTermOp(TermOps op) {
972 switch (op) {
973 default : assert(0 && "Invalid OldTermOp");
974 case RetOp : return Instruction::Ret;
975 case BrOp : return Instruction::Br;
976 case SwitchOp : return Instruction::Switch;
977 case InvokeOp : return Instruction::Invoke;
978 case UnwindOp : return Instruction::Unwind;
979 case UnreachableOp: return Instruction::Unreachable;
980 }
981}
982
983static inline Instruction::BinaryOps
984getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
985 switch (op) {
986 default : assert(0 && "Invalid OldBinaryOps");
987 case SetEQ :
988 case SetNE :
989 case SetLE :
990 case SetGE :
991 case SetLT :
992 case SetGT : assert(0 && "Should use getCompareOp");
993 case AddOp : return Instruction::Add;
994 case SubOp : return Instruction::Sub;
995 case MulOp : return Instruction::Mul;
996 case DivOp : {
997 // This is an obsolete instruction so we must upgrade it based on the
998 // types of its operands.
999 bool isFP = Ty->isFloatingPoint();
1000 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1001 // If its a packed type we want to use the element type
1002 isFP = PTy->getElementType()->isFloatingPoint();
1003 if (isFP)
1004 return Instruction::FDiv;
1005 else if (Sign == Signed)
1006 return Instruction::SDiv;
1007 return Instruction::UDiv;
1008 }
1009 case UDivOp : return Instruction::UDiv;
1010 case SDivOp : return Instruction::SDiv;
1011 case FDivOp : return Instruction::FDiv;
1012 case RemOp : {
1013 // This is an obsolete instruction so we must upgrade it based on the
1014 // types of its operands.
1015 bool isFP = Ty->isFloatingPoint();
1016 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1017 // If its a packed type we want to use the element type
1018 isFP = PTy->getElementType()->isFloatingPoint();
1019 // Select correct opcode
1020 if (isFP)
1021 return Instruction::FRem;
1022 else if (Sign == Signed)
1023 return Instruction::SRem;
1024 return Instruction::URem;
1025 }
1026 case URemOp : return Instruction::URem;
1027 case SRemOp : return Instruction::SRem;
1028 case FRemOp : return Instruction::FRem;
Reid Spencer832254e2007-02-02 02:16:23 +00001029 case LShrOp : return Instruction::LShr;
1030 case AShrOp : return Instruction::AShr;
1031 case ShlOp : return Instruction::Shl;
1032 case ShrOp :
1033 if (Sign == Signed)
1034 return Instruction::AShr;
1035 return Instruction::LShr;
Reid Spencer950bf602007-01-26 08:19:09 +00001036 case AndOp : return Instruction::And;
1037 case OrOp : return Instruction::Or;
1038 case XorOp : return Instruction::Xor;
1039 }
1040}
1041
1042static inline Instruction::OtherOps
1043getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1044 Signedness Sign) {
1045 bool isSigned = Sign == Signed;
1046 bool isFP = Ty->isFloatingPoint();
1047 switch (op) {
1048 default : assert(0 && "Invalid OldSetCC");
1049 case SetEQ :
1050 if (isFP) {
1051 predicate = FCmpInst::FCMP_OEQ;
1052 return Instruction::FCmp;
1053 } else {
1054 predicate = ICmpInst::ICMP_EQ;
1055 return Instruction::ICmp;
1056 }
1057 case SetNE :
1058 if (isFP) {
1059 predicate = FCmpInst::FCMP_UNE;
1060 return Instruction::FCmp;
1061 } else {
1062 predicate = ICmpInst::ICMP_NE;
1063 return Instruction::ICmp;
1064 }
1065 case SetLE :
1066 if (isFP) {
1067 predicate = FCmpInst::FCMP_OLE;
1068 return Instruction::FCmp;
1069 } else {
1070 if (isSigned)
1071 predicate = ICmpInst::ICMP_SLE;
1072 else
1073 predicate = ICmpInst::ICMP_ULE;
1074 return Instruction::ICmp;
1075 }
1076 case SetGE :
1077 if (isFP) {
1078 predicate = FCmpInst::FCMP_OGE;
1079 return Instruction::FCmp;
1080 } else {
1081 if (isSigned)
1082 predicate = ICmpInst::ICMP_SGE;
1083 else
1084 predicate = ICmpInst::ICMP_UGE;
1085 return Instruction::ICmp;
1086 }
1087 case SetLT :
1088 if (isFP) {
1089 predicate = FCmpInst::FCMP_OLT;
1090 return Instruction::FCmp;
1091 } else {
1092 if (isSigned)
1093 predicate = ICmpInst::ICMP_SLT;
1094 else
1095 predicate = ICmpInst::ICMP_ULT;
1096 return Instruction::ICmp;
1097 }
1098 case SetGT :
1099 if (isFP) {
1100 predicate = FCmpInst::FCMP_OGT;
1101 return Instruction::FCmp;
1102 } else {
1103 if (isSigned)
1104 predicate = ICmpInst::ICMP_SGT;
1105 else
1106 predicate = ICmpInst::ICMP_UGT;
1107 return Instruction::ICmp;
1108 }
1109 }
1110}
1111
1112static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1113 switch (op) {
1114 default : assert(0 && "Invalid OldMemoryOps");
1115 case MallocOp : return Instruction::Malloc;
1116 case FreeOp : return Instruction::Free;
1117 case AllocaOp : return Instruction::Alloca;
1118 case LoadOp : return Instruction::Load;
1119 case StoreOp : return Instruction::Store;
1120 case GetElementPtrOp : return Instruction::GetElementPtr;
1121 }
1122}
1123
1124static inline Instruction::OtherOps
1125getOtherOp(OtherOps op, Signedness Sign) {
1126 switch (op) {
1127 default : assert(0 && "Invalid OldOtherOps");
1128 case PHIOp : return Instruction::PHI;
1129 case CallOp : return Instruction::Call;
Reid Spencer950bf602007-01-26 08:19:09 +00001130 case SelectOp : return Instruction::Select;
1131 case UserOp1 : return Instruction::UserOp1;
1132 case UserOp2 : return Instruction::UserOp2;
1133 case VAArg : return Instruction::VAArg;
1134 case ExtractElementOp : return Instruction::ExtractElement;
1135 case InsertElementOp : return Instruction::InsertElement;
1136 case ShuffleVectorOp : return Instruction::ShuffleVector;
1137 case ICmpOp : return Instruction::ICmp;
1138 case FCmpOp : return Instruction::FCmp;
Reid Spencer950bf602007-01-26 08:19:09 +00001139 };
1140}
1141
1142static inline Value*
1143getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1144 Signedness DstSign, bool ForceInstruction = false) {
1145 Instruction::CastOps Opcode;
1146 const Type* SrcTy = Src->getType();
1147 if (op == CastOp) {
1148 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1149 // fp -> ptr cast is no longer supported but we must upgrade this
1150 // by doing a double cast: fp -> int -> ptr
1151 SrcTy = Type::Int64Ty;
1152 Opcode = Instruction::IntToPtr;
1153 if (isa<Constant>(Src)) {
1154 Src = ConstantExpr::getCast(Instruction::FPToUI,
1155 cast<Constant>(Src), SrcTy);
1156 } else {
1157 std::string NewName(makeNameUnique(Src->getName()));
1158 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1159 }
1160 } else if (isa<IntegerType>(DstTy) &&
1161 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1162 // cast type %x to bool was previously defined as setne type %x, null
1163 // The cast semantic is now to truncate, not compare so we must retain
1164 // the original intent by replacing the cast with a setne
1165 Constant* Null = Constant::getNullValue(SrcTy);
1166 Instruction::OtherOps Opcode = Instruction::ICmp;
1167 unsigned short predicate = ICmpInst::ICMP_NE;
1168 if (SrcTy->isFloatingPoint()) {
1169 Opcode = Instruction::FCmp;
1170 predicate = FCmpInst::FCMP_ONE;
1171 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1172 error("Invalid cast to bool");
1173 }
1174 if (isa<Constant>(Src) && !ForceInstruction)
1175 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1176 else
1177 return CmpInst::create(Opcode, predicate, Src, Null);
1178 }
1179 // Determine the opcode to use by calling CastInst::getCastOpcode
1180 Opcode =
1181 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1182
1183 } else switch (op) {
1184 default: assert(0 && "Invalid cast token");
1185 case TruncOp: Opcode = Instruction::Trunc; break;
1186 case ZExtOp: Opcode = Instruction::ZExt; break;
1187 case SExtOp: Opcode = Instruction::SExt; break;
1188 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1189 case FPExtOp: Opcode = Instruction::FPExt; break;
1190 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1191 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1192 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1193 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1194 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1195 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1196 case BitCastOp: Opcode = Instruction::BitCast; break;
1197 }
1198
1199 if (isa<Constant>(Src) && !ForceInstruction)
1200 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1201 return CastInst::create(Opcode, Src, DstTy);
1202}
1203
1204static Instruction *
1205upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1206 std::vector<Value*>& Args) {
1207
1208 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1209 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1210 if (Args.size() != 2)
1211 error("Invalid prototype for " + Name + " prototype");
1212 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1213 } else {
Reid Spencer950bf602007-01-26 08:19:09 +00001214 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1215 std::vector<const Type*> Params;
1216 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1217 if (Args.size() != 1)
1218 error("Invalid prototype for " + Name + " prototype");
1219 Params.push_back(PtrTy);
1220 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1221 const PointerType *PFTy = PointerType::get(FTy);
1222 Value* Func = getVal(PFTy, ID);
Reid Spencer832254e2007-02-02 02:16:23 +00001223 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
Reid Spencer950bf602007-01-26 08:19:09 +00001224 return new CallInst(Func, Args);
1225 } else if (Name == "llvm.va_copy") {
1226 if (Args.size() != 2)
1227 error("Invalid prototype for " + Name + " prototype");
1228 Params.push_back(PtrTy);
1229 Params.push_back(PtrTy);
1230 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1231 const PointerType *PFTy = PointerType::get(FTy);
1232 Value* Func = getVal(PFTy, ID);
Reid Spencer832254e2007-02-02 02:16:23 +00001233 std::string InstName0(makeNameUnique("va0"));
1234 std::string InstName1(makeNameUnique("va1"));
Reid Spencer950bf602007-01-26 08:19:09 +00001235 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1236 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1237 return new CallInst(Func, Args);
1238 }
1239 }
1240 return 0;
1241}
1242
1243const Type* upgradeGEPIndices(const Type* PTy,
1244 std::vector<ValueInfo> *Indices,
1245 std::vector<Value*> &VIndices,
1246 std::vector<Constant*> *CIndices = 0) {
1247 // Traverse the indices with a gep_type_iterator so we can build the list
1248 // of constant and value indices for use later. Also perform upgrades
1249 VIndices.clear();
1250 if (CIndices) CIndices->clear();
1251 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1252 VIndices.push_back((*Indices)[i].V);
1253 generic_gep_type_iterator<std::vector<Value*>::iterator>
1254 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1255 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1256 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1257 Value *Index = VIndices[i];
1258 if (CIndices && !isa<Constant>(Index))
1259 error("Indices to constant getelementptr must be constants");
1260 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1261 // struct indices to i32 struct indices with ZExt for compatibility.
1262 else if (isa<StructType>(*GTI)) { // Only change struct indices
1263 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1264 if (CUI->getType()->getBitWidth() == 8)
1265 Index =
1266 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1267 } else {
1268 // Make sure that unsigned SequentialType indices are zext'd to
1269 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1270 // all indices for SequentialType elements. We must retain the same
1271 // semantic (zext) for unsigned types.
1272 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
Reid Spencer38f682b2007-01-26 20:31:18 +00001273 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
Reid Spencer950bf602007-01-26 08:19:09 +00001274 if (CIndices)
1275 Index = ConstantExpr::getCast(Instruction::ZExt,
1276 cast<Constant>(Index), Type::Int64Ty);
1277 else
1278 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
Reid Spencer832254e2007-02-02 02:16:23 +00001279 makeNameUnique("gep"), CurBB);
Reid Spencer38f682b2007-01-26 20:31:18 +00001280 VIndices[i] = Index;
1281 }
Reid Spencer950bf602007-01-26 08:19:09 +00001282 }
1283 // Add to the CIndices list, if requested.
1284 if (CIndices)
1285 CIndices->push_back(cast<Constant>(Index));
1286 }
1287
1288 const Type *IdxTy =
1289 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1290 if (!IdxTy)
1291 error("Index list invalid for constant getelementptr");
1292 return IdxTy;
1293}
1294
Reid Spencerb7046c72007-01-29 05:41:34 +00001295unsigned upgradeCallingConv(unsigned CC) {
1296 switch (CC) {
1297 case OldCallingConv::C : return CallingConv::C;
1298 case OldCallingConv::CSRet : return CallingConv::C;
1299 case OldCallingConv::Fast : return CallingConv::Fast;
1300 case OldCallingConv::Cold : return CallingConv::Cold;
1301 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1302 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1303 default:
1304 return CC;
1305 }
1306}
1307
Reid Spencer950bf602007-01-26 08:19:09 +00001308Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1309 bool debug, bool addAttrs)
Reid Spencere7c3c602006-11-30 06:36:44 +00001310{
1311 Upgradelineno = 1;
1312 CurFilename = infile;
Reid Spencer96839be2006-11-30 16:50:26 +00001313 LexInput = &in;
Reid Spencere77e35e2006-12-01 20:26:20 +00001314 yydebug = debug;
Reid Spencer71d2ec92006-12-31 06:02:26 +00001315 AddAttributes = addAttrs;
Reid Spencer950bf602007-01-26 08:19:09 +00001316 ObsoleteVarArgs = false;
1317 NewVarArgs = false;
Reid Spencere7c3c602006-11-30 06:36:44 +00001318
Reid Spencer950bf602007-01-26 08:19:09 +00001319 CurModule.CurrentModule = new Module(CurFilename);
1320
1321 // Check to make sure the parser succeeded
Reid Spencere7c3c602006-11-30 06:36:44 +00001322 if (yyparse()) {
Reid Spencer950bf602007-01-26 08:19:09 +00001323 if (ParserResult)
1324 delete ParserResult;
Reid Spencer30d0c582007-01-15 00:26:18 +00001325 std::cerr << "llvm-upgrade: parse failed.\n";
Reid Spencer30d0c582007-01-15 00:26:18 +00001326 return 0;
1327 }
1328
Reid Spencer950bf602007-01-26 08:19:09 +00001329 // Check to make sure that parsing produced a result
1330 if (!ParserResult) {
1331 std::cerr << "llvm-upgrade: no parse result.\n";
1332 return 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001333 }
1334
Reid Spencer950bf602007-01-26 08:19:09 +00001335 // Reset ParserResult variable while saving its value for the result.
1336 Module *Result = ParserResult;
1337 ParserResult = 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001338
Reid Spencer950bf602007-01-26 08:19:09 +00001339 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
Reid Spencer30d0c582007-01-15 00:26:18 +00001340 {
Reid Spencer950bf602007-01-26 08:19:09 +00001341 Function* F;
Reid Spencer688b0492007-02-05 21:19:13 +00001342 if ((F = Result->getFunction("llvm.va_start"))
Reid Spencer950bf602007-01-26 08:19:09 +00001343 && F->getFunctionType()->getNumParams() == 0)
1344 ObsoleteVarArgs = true;
Reid Spencer688b0492007-02-05 21:19:13 +00001345 if((F = Result->getFunction("llvm.va_copy"))
Reid Spencer950bf602007-01-26 08:19:09 +00001346 && F->getFunctionType()->getNumParams() == 1)
1347 ObsoleteVarArgs = true;
Reid Spencer280d8012006-12-01 23:40:53 +00001348 }
Reid Spencer319a7302007-01-05 17:20:02 +00001349
Reid Spencer950bf602007-01-26 08:19:09 +00001350 if (ObsoleteVarArgs && NewVarArgs) {
1351 error("This file is corrupt: it uses both new and old style varargs");
1352 return 0;
Reid Spencer319a7302007-01-05 17:20:02 +00001353 }
Reid Spencer319a7302007-01-05 17:20:02 +00001354
Reid Spencer950bf602007-01-26 08:19:09 +00001355 if(ObsoleteVarArgs) {
Reid Spencer688b0492007-02-05 21:19:13 +00001356 if(Function* F = Result->getFunction("llvm.va_start")) {
Reid Spencer950bf602007-01-26 08:19:09 +00001357 if (F->arg_size() != 0) {
1358 error("Obsolete va_start takes 0 argument");
Reid Spencer319a7302007-01-05 17:20:02 +00001359 return 0;
1360 }
Reid Spencer950bf602007-01-26 08:19:09 +00001361
1362 //foo = va_start()
1363 // ->
1364 //bar = alloca typeof(foo)
1365 //va_start(bar)
1366 //foo = load bar
Reid Spencer319a7302007-01-05 17:20:02 +00001367
Reid Spencer950bf602007-01-26 08:19:09 +00001368 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1369 const Type* ArgTy = F->getFunctionType()->getReturnType();
1370 const Type* ArgTyPtr = PointerType::get(ArgTy);
1371 Function* NF = cast<Function>(Result->getOrInsertFunction(
1372 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1373
1374 while (!F->use_empty()) {
1375 CallInst* CI = cast<CallInst>(F->use_back());
1376 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1377 new CallInst(NF, bar, "", CI);
1378 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1379 CI->replaceAllUsesWith(foo);
1380 CI->getParent()->getInstList().erase(CI);
Reid Spencerf8383de2007-01-06 06:04:32 +00001381 }
Reid Spencer950bf602007-01-26 08:19:09 +00001382 Result->getFunctionList().erase(F);
Reid Spencerf8383de2007-01-06 06:04:32 +00001383 }
Reid Spencer950bf602007-01-26 08:19:09 +00001384
Reid Spencer688b0492007-02-05 21:19:13 +00001385 if(Function* F = Result->getFunction("llvm.va_end")) {
Reid Spencer950bf602007-01-26 08:19:09 +00001386 if(F->arg_size() != 1) {
1387 error("Obsolete va_end takes 1 argument");
1388 return 0;
Reid Spencerf8383de2007-01-06 06:04:32 +00001389 }
Reid Spencerf8383de2007-01-06 06:04:32 +00001390
Reid Spencer950bf602007-01-26 08:19:09 +00001391 //vaend foo
1392 // ->
1393 //bar = alloca 1 of typeof(foo)
1394 //vaend bar
1395 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1396 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1397 const Type* ArgTyPtr = PointerType::get(ArgTy);
1398 Function* NF = cast<Function>(Result->getOrInsertFunction(
1399 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
Reid Spencerf8383de2007-01-06 06:04:32 +00001400
Reid Spencer950bf602007-01-26 08:19:09 +00001401 while (!F->use_empty()) {
1402 CallInst* CI = cast<CallInst>(F->use_back());
1403 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1404 new StoreInst(CI->getOperand(1), bar, CI);
1405 new CallInst(NF, bar, "", CI);
1406 CI->getParent()->getInstList().erase(CI);
Reid Spencere77e35e2006-12-01 20:26:20 +00001407 }
Reid Spencer950bf602007-01-26 08:19:09 +00001408 Result->getFunctionList().erase(F);
Reid Spencere77e35e2006-12-01 20:26:20 +00001409 }
Reid Spencer950bf602007-01-26 08:19:09 +00001410
Reid Spencer688b0492007-02-05 21:19:13 +00001411 if(Function* F = Result->getFunction("llvm.va_copy")) {
Reid Spencer950bf602007-01-26 08:19:09 +00001412 if(F->arg_size() != 1) {
1413 error("Obsolete va_copy takes 1 argument");
1414 return 0;
Reid Spencere77e35e2006-12-01 20:26:20 +00001415 }
Reid Spencer950bf602007-01-26 08:19:09 +00001416 //foo = vacopy(bar)
1417 // ->
1418 //a = alloca 1 of typeof(foo)
1419 //b = alloca 1 of typeof(foo)
1420 //store bar -> b
1421 //vacopy(a, b)
1422 //foo = load a
1423
1424 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1425 const Type* ArgTy = F->getFunctionType()->getReturnType();
1426 const Type* ArgTyPtr = PointerType::get(ArgTy);
1427 Function* NF = cast<Function>(Result->getOrInsertFunction(
1428 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
Reid Spencere77e35e2006-12-01 20:26:20 +00001429
Reid Spencer950bf602007-01-26 08:19:09 +00001430 while (!F->use_empty()) {
1431 CallInst* CI = cast<CallInst>(F->use_back());
1432 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1433 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1434 new StoreInst(CI->getOperand(1), b, CI);
1435 new CallInst(NF, a, b, "", CI);
1436 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1437 CI->replaceAllUsesWith(foo);
1438 CI->getParent()->getInstList().erase(CI);
1439 }
1440 Result->getFunctionList().erase(F);
Reid Spencer319a7302007-01-05 17:20:02 +00001441 }
1442 }
1443
Reid Spencer52402b02007-01-02 05:45:11 +00001444 return Result;
1445}
1446
Reid Spencer950bf602007-01-26 08:19:09 +00001447} // end llvm namespace
Reid Spencer319a7302007-01-05 17:20:02 +00001448
Reid Spencer950bf602007-01-26 08:19:09 +00001449using namespace llvm;
Reid Spencer30d0c582007-01-15 00:26:18 +00001450
Reid Spencere7c3c602006-11-30 06:36:44 +00001451%}
1452
Reid Spencere77e35e2006-12-01 20:26:20 +00001453%union {
Reid Spencer950bf602007-01-26 08:19:09 +00001454 llvm::Module *ModuleVal;
1455 llvm::Function *FunctionVal;
1456 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1457 llvm::BasicBlock *BasicBlockVal;
1458 llvm::TerminatorInst *TermInstVal;
1459 llvm::InstrInfo InstVal;
1460 llvm::ConstInfo ConstVal;
1461 llvm::ValueInfo ValueVal;
1462 llvm::PATypeInfo TypeVal;
1463 llvm::TypeInfo PrimType;
1464 llvm::PHIListInfo PHIList;
1465 std::list<llvm::PATypeInfo> *TypeList;
1466 std::vector<llvm::ValueInfo> *ValueList;
1467 std::vector<llvm::ConstInfo> *ConstVector;
1468
1469
1470 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1471 // Represent the RHS of PHI node
1472 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1473
1474 llvm::GlobalValue::LinkageTypes Linkage;
1475 int64_t SInt64Val;
1476 uint64_t UInt64Val;
1477 int SIntVal;
1478 unsigned UIntVal;
1479 double FPVal;
1480 bool BoolVal;
1481
1482 char *StrVal; // This memory is strdup'd!
1483 llvm::ValID ValIDVal; // strdup'd memory maybe!
1484
1485 llvm::BinaryOps BinaryOpVal;
1486 llvm::TermOps TermOpVal;
1487 llvm::MemoryOps MemOpVal;
1488 llvm::OtherOps OtherOpVal;
1489 llvm::CastOps CastOpVal;
1490 llvm::ICmpInst::Predicate IPred;
1491 llvm::FCmpInst::Predicate FPred;
1492 llvm::Module::Endianness Endianness;
Reid Spencere77e35e2006-12-01 20:26:20 +00001493}
1494
Reid Spencer950bf602007-01-26 08:19:09 +00001495%type <ModuleVal> Module FunctionList
1496%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1497%type <BasicBlockVal> BasicBlock InstructionList
1498%type <TermInstVal> BBTerminatorInst
1499%type <InstVal> Inst InstVal MemoryInst
1500%type <ConstVal> ConstVal ConstExpr
1501%type <ConstVector> ConstVector
1502%type <ArgList> ArgList ArgListH
1503%type <ArgVal> ArgVal
1504%type <PHIList> PHIList
1505%type <ValueList> ValueRefList ValueRefListE // For call param lists
1506%type <ValueList> IndexList // For GEP derived indices
1507%type <TypeList> TypeListI ArgTypeListI
1508%type <JumpTable> JumpTable
1509%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1510%type <BoolVal> OptVolatile // 'volatile' or not
1511%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1512%type <BoolVal> OptSideEffect // 'sideeffect' or not.
Reid Spencered96d1e2007-02-08 09:08:52 +00001513%type <Linkage> OptLinkage FnDeclareLinkage
Reid Spencer950bf602007-01-26 08:19:09 +00001514%type <Endianness> BigOrLittle
Reid Spencere77e35e2006-12-01 20:26:20 +00001515
Reid Spencer950bf602007-01-26 08:19:09 +00001516// ValueRef - Unresolved reference to a definition or BB
1517%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1518%type <ValueVal> ResolvedVal // <type> <valref> pair
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001519
Reid Spencer950bf602007-01-26 08:19:09 +00001520// Tokens and types for handling constant integer values
1521//
1522// ESINT64VAL - A negative number within long long range
1523%token <SInt64Val> ESINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001524
Reid Spencer950bf602007-01-26 08:19:09 +00001525// EUINT64VAL - A positive number within uns. long long range
1526%token <UInt64Val> EUINT64VAL
1527%type <SInt64Val> EINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001528
Reid Spencer950bf602007-01-26 08:19:09 +00001529%token <SIntVal> SINTVAL // Signed 32 bit ints...
1530%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1531%type <SIntVal> INTVAL
1532%token <FPVal> FPVAL // Float or Double constant
Reid Spencere77e35e2006-12-01 20:26:20 +00001533
Reid Spencer950bf602007-01-26 08:19:09 +00001534// Built in types...
1535%type <TypeVal> Types TypesV UpRTypes UpRTypesV
1536%type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1537%token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1538%token <PrimType> FLOAT DOUBLE TYPE LABEL
Reid Spencere77e35e2006-12-01 20:26:20 +00001539
Reid Spencer950bf602007-01-26 08:19:09 +00001540%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1541%type <StrVal> Name OptName OptAssign
1542%type <UIntVal> OptAlign OptCAlign
1543%type <StrVal> OptSection SectionString
1544
1545%token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1546%token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1547%token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1548%token DLLIMPORT DLLEXPORT EXTERN_WEAK
1549%token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1550%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1551%token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1552%token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1553%token DATALAYOUT
1554%type <UIntVal> OptCallingConv
1555
1556// Basic Block Terminating Operators
1557%token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1558%token UNWIND EXCEPT
1559
1560// Binary Operators
1561%type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
Reid Spencer832254e2007-02-02 02:16:23 +00001562%type <BinaryOpVal> ShiftOps
Reid Spencer950bf602007-01-26 08:19:09 +00001563%token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
Reid Spencer832254e2007-02-02 02:16:23 +00001564%token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
Reid Spencer950bf602007-01-26 08:19:09 +00001565%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1566%token <OtherOpVal> ICMP FCMP
1567
1568// Memory Instructions
1569%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1570
1571// Other Operators
Reid Spencer832254e2007-02-02 02:16:23 +00001572%token <OtherOpVal> PHI_TOK SELECT VAARG
Reid Spencer950bf602007-01-26 08:19:09 +00001573%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1574%token VAARG_old VANEXT_old //OBSOLETE
1575
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001576// Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
Reid Spencer950bf602007-01-26 08:19:09 +00001577%type <IPred> IPredicates
1578%type <FPred> FPredicates
1579%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1580%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1581
1582%token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1583%token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1584%type <CastOpVal> CastOps
Reid Spencere7c3c602006-11-30 06:36:44 +00001585
1586%start Module
1587
1588%%
1589
1590// Handle constant integer size restriction and conversion...
Reid Spencer950bf602007-01-26 08:19:09 +00001591//
1592INTVAL
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001593 : SINTVAL
Reid Spencer950bf602007-01-26 08:19:09 +00001594 | UINTVAL {
1595 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1596 error("Value too large for type");
1597 $$ = (int32_t)$1;
1598 }
1599 ;
1600
1601EINT64VAL
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001602 : ESINT64VAL // These have same type and can't cause problems...
Reid Spencer950bf602007-01-26 08:19:09 +00001603 | EUINT64VAL {
1604 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1605 error("Value too large for type");
1606 $$ = (int64_t)$1;
1607 };
Reid Spencere7c3c602006-11-30 06:36:44 +00001608
1609// Operations that are notably excluded from this list include:
1610// RET, BR, & SWITCH because they end basic blocks and are treated specially.
Reid Spencer950bf602007-01-26 08:19:09 +00001611//
1612ArithmeticOps
1613 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1614 ;
1615
1616LogicalOps
1617 : AND | OR | XOR
1618 ;
1619
1620SetCondOps
1621 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1622 ;
1623
1624IPredicates
1625 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1626 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1627 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1628 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1629 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1630 ;
1631
1632FPredicates
1633 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1634 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1635 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1636 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1637 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1638 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1639 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1640 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1641 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1642 ;
1643ShiftOps
1644 : SHL | SHR | ASHR | LSHR
1645 ;
1646
1647CastOps
1648 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1649 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1650 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001651
1652// These are some types that allow classification if we only want a particular
1653// thing... for example, only a signed, unsigned, or integral type.
Reid Spencer950bf602007-01-26 08:19:09 +00001654SIntType
1655 : LONG | INT | SHORT | SBYTE
1656 ;
1657
1658UIntType
1659 : ULONG | UINT | USHORT | UBYTE
1660 ;
1661
1662IntType
1663 : SIntType | UIntType
1664 ;
1665
1666FPType
1667 : FLOAT | DOUBLE
1668 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001669
1670// OptAssign - Value producing statements have an optional assignment component
Reid Spencer950bf602007-01-26 08:19:09 +00001671OptAssign
1672 : Name '=' {
Reid Spencere7c3c602006-11-30 06:36:44 +00001673 $$ = $1;
1674 }
1675 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001676 $$ = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00001677 };
1678
1679OptLinkage
Reid Spencer785a5ae2007-02-08 00:21:40 +00001680 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
Reid Spencer950bf602007-01-26 08:19:09 +00001681 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1682 | WEAK { $$ = GlobalValue::WeakLinkage; }
1683 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1684 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1685 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
Reid Spencer785a5ae2007-02-08 00:21:40 +00001686 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
Reid Spencer950bf602007-01-26 08:19:09 +00001687 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1688 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001689
1690OptCallingConv
Reid Spencered96d1e2007-02-08 09:08:52 +00001691 : /*empty*/ { $$ = OldCallingConv::C; }
1692 | CCC_TOK { $$ = OldCallingConv::C; }
1693 | CSRETCC_TOK { $$ = OldCallingConv::CSRet; }
1694 | FASTCC_TOK { $$ = OldCallingConv::Fast; }
1695 | COLDCC_TOK { $$ = OldCallingConv::Cold; }
1696 | X86_STDCALLCC_TOK { $$ = OldCallingConv::X86_StdCall; }
1697 | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; }
Reid Spencer950bf602007-01-26 08:19:09 +00001698 | CC_TOK EUINT64VAL {
1699 if ((unsigned)$2 != $2)
1700 error("Calling conv too large");
1701 $$ = $2;
1702 }
1703 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001704
1705// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1706// a comma before it.
1707OptAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001708 : /*empty*/ { $$ = 0; }
1709 | ALIGN EUINT64VAL {
1710 $$ = $2;
1711 if ($$ != 0 && !isPowerOf2_32($$))
1712 error("Alignment must be a power of two");
1713 }
1714 ;
Reid Spencerf0cf1322006-12-07 04:23:03 +00001715
Reid Spencere7c3c602006-11-30 06:36:44 +00001716OptCAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001717 : /*empty*/ { $$ = 0; }
1718 | ',' ALIGN EUINT64VAL {
1719 $$ = $3;
1720 if ($$ != 0 && !isPowerOf2_32($$))
1721 error("Alignment must be a power of two");
1722 }
1723 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001724
1725SectionString
Reid Spencer950bf602007-01-26 08:19:09 +00001726 : SECTION STRINGCONSTANT {
1727 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1728 if ($2[i] == '"' || $2[i] == '\\')
1729 error("Invalid character in section name");
1730 $$ = $2;
1731 }
1732 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001733
Reid Spencer950bf602007-01-26 08:19:09 +00001734OptSection
1735 : /*empty*/ { $$ = 0; }
1736 | SectionString { $$ = $1; }
1737 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001738
Reid Spencer950bf602007-01-26 08:19:09 +00001739// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1740// is set to be the global we are processing.
1741//
Reid Spencere7c3c602006-11-30 06:36:44 +00001742GlobalVarAttributes
Reid Spencer950bf602007-01-26 08:19:09 +00001743 : /* empty */ {}
1744 | ',' GlobalVarAttribute GlobalVarAttributes {}
1745 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001746
Reid Spencer950bf602007-01-26 08:19:09 +00001747GlobalVarAttribute
1748 : SectionString {
1749 CurGV->setSection($1);
1750 free($1);
1751 }
1752 | ALIGN EUINT64VAL {
1753 if ($2 != 0 && !isPowerOf2_32($2))
1754 error("Alignment must be a power of two");
1755 CurGV->setAlignment($2);
1756
1757 }
1758 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001759
1760//===----------------------------------------------------------------------===//
1761// Types includes all predefined types... except void, because it can only be
1762// used in specific contexts (function returning void for example). To have
1763// access to it, a user must explicitly use TypesV.
1764//
1765
1766// TypesV includes all of 'Types', but it also includes the void type.
Reid Spencer950bf602007-01-26 08:19:09 +00001767TypesV
1768 : Types
1769 | VOID {
Reid Spencered96d1e2007-02-08 09:08:52 +00001770 $$.PAT = new PATypeHolder($1.T);
Reid Spencer950bf602007-01-26 08:19:09 +00001771 $$.S = Signless;
1772 }
1773 ;
1774
1775UpRTypesV
1776 : UpRTypes
1777 | VOID {
Reid Spencered96d1e2007-02-08 09:08:52 +00001778 $$.PAT = new PATypeHolder($1.T);
Reid Spencer950bf602007-01-26 08:19:09 +00001779 $$.S = Signless;
1780 }
1781 ;
1782
1783Types
1784 : UpRTypes {
1785 if (!UpRefs.empty())
Reid Spencered96d1e2007-02-08 09:08:52 +00001786 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
Reid Spencer950bf602007-01-26 08:19:09 +00001787 $$ = $1;
1788 }
1789 ;
1790
1791PrimType
1792 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1793 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1794 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001795
1796// Derived types are added later...
Reid Spencera50d5962006-12-02 04:11:07 +00001797UpRTypes
Reid Spencer950bf602007-01-26 08:19:09 +00001798 : PrimType {
Reid Spencered96d1e2007-02-08 09:08:52 +00001799 $$.PAT = new PATypeHolder($1.T);
Reid Spencer950bf602007-01-26 08:19:09 +00001800 $$.S = $1.S;
Reid Spencera50d5962006-12-02 04:11:07 +00001801 }
Reid Spencer950bf602007-01-26 08:19:09 +00001802 | OPAQUE {
Reid Spencered96d1e2007-02-08 09:08:52 +00001803 $$.PAT = new PATypeHolder(OpaqueType::get());
Reid Spencer950bf602007-01-26 08:19:09 +00001804 $$.S = Signless;
1805 }
1806 | SymbolicValueRef { // Named types are also simple types...
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001807 const Type* tmp = getType($1);
Reid Spencered96d1e2007-02-08 09:08:52 +00001808 $$.PAT = new PATypeHolder(tmp);
Reid Spencer950bf602007-01-26 08:19:09 +00001809 $$.S = Signless; // FIXME: what if its signed?
Reid Spencer78720742006-12-02 20:21:22 +00001810 }
1811 | '\\' EUINT64VAL { // Type UpReference
Reid Spencer950bf602007-01-26 08:19:09 +00001812 if ($2 > (uint64_t)~0U)
1813 error("Value out of range");
1814 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1815 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
Reid Spencered96d1e2007-02-08 09:08:52 +00001816 $$.PAT = new PATypeHolder(OT);
Reid Spencer950bf602007-01-26 08:19:09 +00001817 $$.S = Signless;
1818 UR_OUT("New Upreference!\n");
Reid Spencere7c3c602006-11-30 06:36:44 +00001819 }
1820 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
Reid Spencer950bf602007-01-26 08:19:09 +00001821 std::vector<const Type*> Params;
1822 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1823 E = $3->end(); I != E; ++I) {
Reid Spencered96d1e2007-02-08 09:08:52 +00001824 Params.push_back(I->PAT->get());
Reid Spencer52402b02007-01-02 05:45:11 +00001825 }
Reid Spencerb7046c72007-01-29 05:41:34 +00001826 FunctionType::ParamAttrsList ParamAttrs;
Reid Spencer950bf602007-01-26 08:19:09 +00001827 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1828 if (isVarArg) Params.pop_back();
1829
Reid Spencered96d1e2007-02-08 09:08:52 +00001830 $$.PAT = new PATypeHolder(
1831 HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg,
1832 ParamAttrs)));
Reid Spencer950bf602007-01-26 08:19:09 +00001833 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00001834 delete $1.PAT; // Delete the return type handle
Reid Spencer950bf602007-01-26 08:19:09 +00001835 delete $3; // Delete the argument list
Reid Spencere7c3c602006-11-30 06:36:44 +00001836 }
1837 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
Reid Spencered96d1e2007-02-08 09:08:52 +00001838 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
Reid Spencer950bf602007-01-26 08:19:09 +00001839 (unsigned)$2)));
1840 $$.S = $4.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00001841 delete $4.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00001842 }
1843 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
Reid Spencered96d1e2007-02-08 09:08:52 +00001844 const llvm::Type* ElemTy = $4.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00001845 if ((unsigned)$2 != $2)
1846 error("Unsigned result not equal to signed result");
1847 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1848 error("Elements of a PackedType must be integer or floating point");
1849 if (!isPowerOf2_32($2))
1850 error("PackedType length should be a power of 2");
Reid Spencered96d1e2007-02-08 09:08:52 +00001851 $$.PAT = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
Reid Spencer950bf602007-01-26 08:19:09 +00001852 (unsigned)$2)));
1853 $$.S = $4.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00001854 delete $4.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00001855 }
1856 | '{' TypeListI '}' { // Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001857 std::vector<const Type*> Elements;
1858 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1859 E = $2->end(); I != E; ++I)
Reid Spencered96d1e2007-02-08 09:08:52 +00001860 Elements.push_back(I->PAT->get());
1861 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
Reid Spencer950bf602007-01-26 08:19:09 +00001862 $$.S = Signless;
1863 delete $2;
Reid Spencere7c3c602006-11-30 06:36:44 +00001864 }
1865 | '{' '}' { // Empty structure type?
Reid Spencered96d1e2007-02-08 09:08:52 +00001866 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
Reid Spencer950bf602007-01-26 08:19:09 +00001867 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00001868 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001869 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001870 std::vector<const Type*> Elements;
1871 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1872 E = $3->end(); I != E; ++I) {
Reid Spencered96d1e2007-02-08 09:08:52 +00001873 Elements.push_back(I->PAT->get());
1874 delete I->PAT;
Reid Spencer52402b02007-01-02 05:45:11 +00001875 }
Reid Spencered96d1e2007-02-08 09:08:52 +00001876 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
Reid Spencer950bf602007-01-26 08:19:09 +00001877 $$.S = Signless;
1878 delete $3;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001879 }
1880 | '<' '{' '}' '>' { // Empty packed structure type?
Reid Spencered96d1e2007-02-08 09:08:52 +00001881 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
Reid Spencer950bf602007-01-26 08:19:09 +00001882 $$.S = Signless;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001883 }
Reid Spencere7c3c602006-11-30 06:36:44 +00001884 | UpRTypes '*' { // Pointer type?
Reid Spencered96d1e2007-02-08 09:08:52 +00001885 if ($1.PAT->get() == Type::LabelTy)
Reid Spencer950bf602007-01-26 08:19:09 +00001886 error("Cannot form a pointer to a basic block");
Reid Spencered96d1e2007-02-08 09:08:52 +00001887 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get())));
Reid Spencer950bf602007-01-26 08:19:09 +00001888 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00001889 delete $1.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00001890 }
1891 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001892
1893// TypeList - Used for struct declarations and as a basis for function type
1894// declaration type lists
1895//
Reid Spencere77e35e2006-12-01 20:26:20 +00001896TypeListI
1897 : UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001898 $$ = new std::list<PATypeInfo>();
1899 $$->push_back($1);
Reid Spencere77e35e2006-12-01 20:26:20 +00001900 }
1901 | TypeListI ',' UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001902 ($$=$1)->push_back($3);
1903 }
1904 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001905
1906// ArgTypeList - List of types for a function type declaration...
Reid Spencere77e35e2006-12-01 20:26:20 +00001907ArgTypeListI
Reid Spencer950bf602007-01-26 08:19:09 +00001908 : TypeListI
Reid Spencere7c3c602006-11-30 06:36:44 +00001909 | TypeListI ',' DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001910 PATypeInfo VoidTI;
Reid Spencered96d1e2007-02-08 09:08:52 +00001911 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
Reid Spencer950bf602007-01-26 08:19:09 +00001912 VoidTI.S = Signless;
1913 ($$=$1)->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001914 }
1915 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001916 $$ = new std::list<PATypeInfo>();
1917 PATypeInfo VoidTI;
Reid Spencered96d1e2007-02-08 09:08:52 +00001918 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
Reid Spencer950bf602007-01-26 08:19:09 +00001919 VoidTI.S = Signless;
1920 $$->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001921 }
1922 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001923 $$ = new std::list<PATypeInfo>();
1924 }
1925 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001926
1927// ConstVal - The various declarations that go into the constant pool. This
1928// production is used ONLY to represent constants that show up AFTER a 'const',
1929// 'constant' or 'global' token at global scope. Constants that can be inlined
1930// into other expressions (such as integers and constexprs) are handled by the
1931// ResolvedVal, ValueRef and ConstValueRef productions.
1932//
Reid Spencer950bf602007-01-26 08:19:09 +00001933ConstVal
1934 : Types '[' ConstVector ']' { // Nonempty unsized arr
Reid Spencered96d1e2007-02-08 09:08:52 +00001935 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00001936 if (ATy == 0)
1937 error("Cannot make array constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00001938 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00001939 const Type *ETy = ATy->getElementType();
1940 int NumElements = ATy->getNumElements();
1941
1942 // Verify that we have the correct size...
1943 if (NumElements != -1 && NumElements != (int)$3->size())
1944 error("Type mismatch: constant sized array initialized with " +
1945 utostr($3->size()) + " arguments, but has size of " +
1946 itostr(NumElements) + "");
1947
1948 // Verify all elements are correct type!
1949 std::vector<Constant*> Elems;
1950 for (unsigned i = 0; i < $3->size(); i++) {
1951 Constant *C = (*$3)[i].C;
1952 const Type* ValTy = C->getType();
1953 if (ETy != ValTy)
1954 error("Element #" + utostr(i) + " is not of type '" +
1955 ETy->getDescription() +"' as required!\nIt is of type '"+
1956 ValTy->getDescription() + "'");
1957 Elems.push_back(C);
1958 }
1959 $$.C = ConstantArray::get(ATy, Elems);
1960 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00001961 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00001962 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00001963 }
1964 | Types '[' ']' {
Reid Spencered96d1e2007-02-08 09:08:52 +00001965 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00001966 if (ATy == 0)
1967 error("Cannot make array constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00001968 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00001969 int NumElements = ATy->getNumElements();
1970 if (NumElements != -1 && NumElements != 0)
1971 error("Type mismatch: constant sized array initialized with 0"
1972 " arguments, but has size of " + itostr(NumElements) +"");
1973 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1974 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00001975 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00001976 }
1977 | Types 'c' STRINGCONSTANT {
Reid Spencered96d1e2007-02-08 09:08:52 +00001978 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00001979 if (ATy == 0)
1980 error("Cannot make array constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00001981 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00001982 int NumElements = ATy->getNumElements();
1983 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1984 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1985 error("String arrays require type i8, not '" + ETy->getDescription() +
1986 "'");
1987 char *EndStr = UnEscapeLexed($3, true);
1988 if (NumElements != -1 && NumElements != (EndStr-$3))
1989 error("Can't build string constant of size " +
1990 itostr((int)(EndStr-$3)) + " when array has size " +
1991 itostr(NumElements) + "");
1992 std::vector<Constant*> Vals;
1993 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1994 Vals.push_back(ConstantInt::get(ETy, *C));
1995 free($3);
1996 $$.C = ConstantArray::get(ATy, Vals);
1997 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00001998 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00001999 }
2000 | Types '<' ConstVector '>' { // Nonempty unsized arr
Reid Spencered96d1e2007-02-08 09:08:52 +00002001 const PackedType *PTy = dyn_cast<PackedType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002002 if (PTy == 0)
2003 error("Cannot make packed constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00002004 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00002005 const Type *ETy = PTy->getElementType();
2006 int NumElements = PTy->getNumElements();
2007 // Verify that we have the correct size...
2008 if (NumElements != -1 && NumElements != (int)$3->size())
2009 error("Type mismatch: constant sized packed initialized with " +
2010 utostr($3->size()) + " arguments, but has size of " +
2011 itostr(NumElements) + "");
2012 // Verify all elements are correct type!
2013 std::vector<Constant*> Elems;
2014 for (unsigned i = 0; i < $3->size(); i++) {
2015 Constant *C = (*$3)[i].C;
2016 const Type* ValTy = C->getType();
2017 if (ETy != ValTy)
2018 error("Element #" + utostr(i) + " is not of type '" +
2019 ETy->getDescription() +"' as required!\nIt is of type '"+
2020 ValTy->getDescription() + "'");
2021 Elems.push_back(C);
2022 }
2023 $$.C = ConstantPacked::get(PTy, Elems);
2024 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002025 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00002026 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002027 }
2028 | Types '{' ConstVector '}' {
Reid Spencered96d1e2007-02-08 09:08:52 +00002029 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002030 if (STy == 0)
2031 error("Cannot make struct constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00002032 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00002033 if ($3->size() != STy->getNumContainedTypes())
2034 error("Illegal number of initializers for structure type");
2035
2036 // Check to ensure that constants are compatible with the type initializer!
2037 std::vector<Constant*> Fields;
2038 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2039 Constant *C = (*$3)[i].C;
2040 if (C->getType() != STy->getElementType(i))
2041 error("Expected type '" + STy->getElementType(i)->getDescription() +
2042 "' for element #" + utostr(i) + " of structure initializer");
2043 Fields.push_back(C);
2044 }
2045 $$.C = ConstantStruct::get(STy, Fields);
2046 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002047 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00002048 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002049 }
2050 | Types '{' '}' {
Reid Spencered96d1e2007-02-08 09:08:52 +00002051 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002052 if (STy == 0)
2053 error("Cannot make struct constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00002054 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00002055 if (STy->getNumContainedTypes() != 0)
2056 error("Illegal number of initializers for structure type");
2057 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2058 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002059 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00002060 }
Reid Spencer950bf602007-01-26 08:19:09 +00002061 | Types '<' '{' ConstVector '}' '>' {
Reid Spencered96d1e2007-02-08 09:08:52 +00002062 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002063 if (STy == 0)
2064 error("Cannot make packed struct constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00002065 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00002066 if ($4->size() != STy->getNumContainedTypes())
2067 error("Illegal number of initializers for packed structure type");
Reid Spencere7c3c602006-11-30 06:36:44 +00002068
Reid Spencer950bf602007-01-26 08:19:09 +00002069 // Check to ensure that constants are compatible with the type initializer!
2070 std::vector<Constant*> Fields;
2071 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2072 Constant *C = (*$4)[i].C;
2073 if (C->getType() != STy->getElementType(i))
2074 error("Expected type '" + STy->getElementType(i)->getDescription() +
2075 "' for element #" + utostr(i) + " of packed struct initializer");
2076 Fields.push_back(C);
Reid Spencer280d8012006-12-01 23:40:53 +00002077 }
Reid Spencer950bf602007-01-26 08:19:09 +00002078 $$.C = ConstantStruct::get(STy, Fields);
2079 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002080 delete $1.PAT;
Reid Spencere77e35e2006-12-01 20:26:20 +00002081 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00002082 }
Reid Spencer950bf602007-01-26 08:19:09 +00002083 | Types '<' '{' '}' '>' {
Reid Spencered96d1e2007-02-08 09:08:52 +00002084 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002085 if (STy == 0)
2086 error("Cannot make packed struct constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00002087 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00002088 if (STy->getNumContainedTypes() != 0)
2089 error("Illegal number of initializers for packed structure type");
2090 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2091 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002092 delete $1.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002093 }
2094 | Types NULL_TOK {
Reid Spencered96d1e2007-02-08 09:08:52 +00002095 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002096 if (PTy == 0)
2097 error("Cannot make null pointer constant with type: '" +
Reid Spencered96d1e2007-02-08 09:08:52 +00002098 $1.PAT->get()->getDescription() + "'");
Reid Spencer950bf602007-01-26 08:19:09 +00002099 $$.C = ConstantPointerNull::get(PTy);
2100 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002101 delete $1.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002102 }
2103 | Types UNDEF {
Reid Spencered96d1e2007-02-08 09:08:52 +00002104 $$.C = UndefValue::get($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002105 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002106 delete $1.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002107 }
2108 | Types SymbolicValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00002109 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00002110 if (Ty == 0)
2111 error("Global const reference must be a pointer type, not" +
Reid Spencered96d1e2007-02-08 09:08:52 +00002112 $1.PAT->get()->getDescription());
Reid Spencer950bf602007-01-26 08:19:09 +00002113
2114 // ConstExprs can exist in the body of a function, thus creating
2115 // GlobalValues whenever they refer to a variable. Because we are in
2116 // the context of a function, getExistingValue will search the functions
2117 // symbol table instead of the module symbol table for the global symbol,
2118 // which throws things all off. To get around this, we just tell
2119 // getExistingValue that we are at global scope here.
2120 //
2121 Function *SavedCurFn = CurFun.CurrentFunction;
2122 CurFun.CurrentFunction = 0;
2123 Value *V = getExistingValue(Ty, $2);
2124 CurFun.CurrentFunction = SavedCurFn;
2125
2126 // If this is an initializer for a constant pointer, which is referencing a
2127 // (currently) undefined variable, create a stub now that shall be replaced
2128 // in the future with the right type of variable.
2129 //
2130 if (V == 0) {
2131 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2132 const PointerType *PT = cast<PointerType>(Ty);
2133
2134 // First check to see if the forward references value is already created!
2135 PerModuleInfo::GlobalRefsType::iterator I =
2136 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2137
2138 if (I != CurModule.GlobalRefs.end()) {
2139 V = I->second; // Placeholder already exists, use it...
2140 $2.destroy();
2141 } else {
2142 std::string Name;
2143 if ($2.Type == ValID::NameVal) Name = $2.Name;
2144
2145 // Create the forward referenced global.
2146 GlobalValue *GV;
2147 if (const FunctionType *FTy =
2148 dyn_cast<FunctionType>(PT->getElementType())) {
2149 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2150 CurModule.CurrentModule);
2151 } else {
2152 GV = new GlobalVariable(PT->getElementType(), false,
2153 GlobalValue::ExternalLinkage, 0,
2154 Name, CurModule.CurrentModule);
2155 }
2156
2157 // Keep track of the fact that we have a forward ref to recycle it
2158 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2159 V = GV;
2160 }
2161 }
2162 $$.C = cast<GlobalValue>(V);
2163 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002164 delete $1.PAT; // Free the type handle
Reid Spencer950bf602007-01-26 08:19:09 +00002165 }
2166 | Types ConstExpr {
Reid Spencered96d1e2007-02-08 09:08:52 +00002167 if ($1.PAT->get() != $2.C->getType())
Reid Spencer950bf602007-01-26 08:19:09 +00002168 error("Mismatched types for constant expression");
2169 $$ = $2;
2170 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002171 delete $1.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002172 }
2173 | Types ZEROINITIALIZER {
Reid Spencered96d1e2007-02-08 09:08:52 +00002174 const Type *Ty = $1.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002175 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2176 error("Cannot create a null initialized value of this type");
2177 $$.C = Constant::getNullValue(Ty);
2178 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00002179 delete $1.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002180 }
2181 | SIntType EINT64VAL { // integral constants
2182 const Type *Ty = $1.T;
2183 if (!ConstantInt::isValueValidForType(Ty, $2))
2184 error("Constant value doesn't fit in type");
2185 $$.C = ConstantInt::get(Ty, $2);
2186 $$.S = Signed;
2187 }
2188 | UIntType EUINT64VAL { // integral constants
2189 const Type *Ty = $1.T;
2190 if (!ConstantInt::isValueValidForType(Ty, $2))
2191 error("Constant value doesn't fit in type");
2192 $$.C = ConstantInt::get(Ty, $2);
2193 $$.S = Unsigned;
2194 }
2195 | BOOL TRUETOK { // Boolean constants
2196 $$.C = ConstantInt::get(Type::Int1Ty, true);
2197 $$.S = Unsigned;
2198 }
2199 | BOOL FALSETOK { // Boolean constants
2200 $$.C = ConstantInt::get(Type::Int1Ty, false);
2201 $$.S = Unsigned;
2202 }
2203 | FPType FPVAL { // Float & Double constants
2204 if (!ConstantFP::isValueValidForType($1.T, $2))
2205 error("Floating point constant invalid for type");
2206 $$.C = ConstantFP::get($1.T, $2);
2207 $$.S = Signless;
2208 }
2209 ;
2210
2211ConstExpr
2212 : CastOps '(' ConstVal TO Types ')' {
2213 const Type* SrcTy = $3.C->getType();
Reid Spencered96d1e2007-02-08 09:08:52 +00002214 const Type* DstTy = $5.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002215 Signedness SrcSign = $3.S;
2216 Signedness DstSign = $5.S;
2217 if (!SrcTy->isFirstClassType())
2218 error("cast constant expression from a non-primitive type: '" +
2219 SrcTy->getDescription() + "'");
2220 if (!DstTy->isFirstClassType())
2221 error("cast constant expression to a non-primitive type: '" +
2222 DstTy->getDescription() + "'");
2223 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2224 $$.S = DstSign;
Reid Spencered96d1e2007-02-08 09:08:52 +00002225 delete $5.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002226 }
2227 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2228 const Type *Ty = $3.C->getType();
2229 if (!isa<PointerType>(Ty))
2230 error("GetElementPtr requires a pointer operand");
2231
2232 std::vector<Value*> VIndices;
2233 std::vector<Constant*> CIndices;
2234 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2235
2236 delete $4;
2237 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2238 $$.S = Signless;
2239 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002240 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002241 if (!$3.C->getType()->isInteger() ||
2242 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2243 error("Select condition must be bool type");
2244 if ($5.C->getType() != $7.C->getType())
2245 error("Select operand types must match");
2246 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2247 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002248 }
2249 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002250 const Type *Ty = $3.C->getType();
2251 if (Ty != $5.C->getType())
2252 error("Binary operator types must match");
2253 // First, make sure we're dealing with the right opcode by upgrading from
2254 // obsolete versions.
2255 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2256
2257 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2258 // To retain backward compatibility with these early compilers, we emit a
2259 // cast to the appropriate integer type automatically if we are in the
2260 // broken case. See PR424 for more information.
2261 if (!isa<PointerType>(Ty)) {
2262 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2263 } else {
2264 const Type *IntPtrTy = 0;
2265 switch (CurModule.CurrentModule->getPointerSize()) {
2266 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2267 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2268 default: error("invalid pointer binary constant expr");
2269 }
2270 $$.C = ConstantExpr::get(Opcode,
2271 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2272 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2273 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2274 }
2275 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002276 }
2277 | LogicalOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002278 const Type* Ty = $3.C->getType();
2279 if (Ty != $5.C->getType())
2280 error("Logical operator types must match");
2281 if (!Ty->isInteger()) {
2282 if (!isa<PackedType>(Ty) ||
2283 !cast<PackedType>(Ty)->getElementType()->isInteger())
2284 error("Logical operator requires integer operands");
2285 }
2286 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2287 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2288 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002289 }
2290 | SetCondOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002291 const Type* Ty = $3.C->getType();
2292 if (Ty != $5.C->getType())
2293 error("setcc operand types must match");
2294 unsigned short pred;
2295 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2296 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2297 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002298 }
Reid Spencer57f28f92006-12-03 07:10:26 +00002299 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002300 if ($4.C->getType() != $6.C->getType())
2301 error("icmp operand types must match");
2302 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2303 $$.S = Unsigned;
Reid Spencer57f28f92006-12-03 07:10:26 +00002304 }
2305 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002306 if ($4.C->getType() != $6.C->getType())
2307 error("fcmp operand types must match");
2308 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2309 $$.S = Unsigned;
Reid Spencer229e9362006-12-02 22:14:11 +00002310 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002311 | ShiftOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002312 if (!$5.C->getType()->isInteger() ||
2313 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2314 error("Shift count for shift constant must be unsigned byte");
Reid Spencer832254e2007-02-02 02:16:23 +00002315 const Type* Ty = $3.C->getType();
Reid Spencer950bf602007-01-26 08:19:09 +00002316 if (!$3.C->getType()->isInteger())
2317 error("Shift constant expression requires integer operand");
Reid Spencer832254e2007-02-02 02:16:23 +00002318 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2319 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
Reid Spencer950bf602007-01-26 08:19:09 +00002320 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002321 }
2322 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002323 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2324 error("Invalid extractelement operands");
2325 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2326 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002327 }
2328 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002329 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2330 error("Invalid insertelement operands");
2331 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2332 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002333 }
2334 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002335 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2336 error("Invalid shufflevector operands");
2337 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2338 $$.S = $3.S;
2339 }
2340 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002341
2342
2343// ConstVector - A list of comma separated constants.
Reid Spencere77e35e2006-12-01 20:26:20 +00002344ConstVector
Reid Spencer950bf602007-01-26 08:19:09 +00002345 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2346 | ConstVal {
2347 $$ = new std::vector<ConstInfo>();
2348 $$->push_back($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002349 }
Reid Spencere77e35e2006-12-01 20:26:20 +00002350 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002351
2352
2353// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
Reid Spencer950bf602007-01-26 08:19:09 +00002354GlobalType
2355 : GLOBAL { $$ = false; }
2356 | CONSTANT { $$ = true; }
2357 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002358
2359
2360//===----------------------------------------------------------------------===//
2361// Rules to match Modules
2362//===----------------------------------------------------------------------===//
2363
2364// Module rule: Capture the result of parsing the whole file into a result
2365// variable...
2366//
Reid Spencer950bf602007-01-26 08:19:09 +00002367Module
2368 : FunctionList {
2369 $$ = ParserResult = $1;
2370 CurModule.ModuleDone();
Reid Spencere7c3c602006-11-30 06:36:44 +00002371 }
Jeff Cohenac2dca92007-01-21 19:30:52 +00002372 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002373
Reid Spencer950bf602007-01-26 08:19:09 +00002374// FunctionList - A list of functions, preceeded by a constant pool.
2375//
2376FunctionList
2377 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2378 | FunctionList FunctionProto { $$ = $1; }
2379 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2380 | FunctionList IMPLEMENTATION { $$ = $1; }
2381 | ConstPool {
2382 $$ = CurModule.CurrentModule;
2383 // Emit an error if there are any unresolved types left.
2384 if (!CurModule.LateResolveTypes.empty()) {
2385 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2386 if (DID.Type == ValID::NameVal) {
2387 error("Reference to an undefined type: '"+DID.getName() + "'");
2388 } else {
2389 error("Reference to an undefined type: #" + itostr(DID.Num));
2390 }
2391 }
2392 }
2393 ;
Reid Spencer78720742006-12-02 20:21:22 +00002394
Reid Spencere7c3c602006-11-30 06:36:44 +00002395// ConstPool - Constants with optional names assigned to them.
Reid Spencer950bf602007-01-26 08:19:09 +00002396ConstPool
2397 : ConstPool OptAssign TYPE TypesV {
2398 // Eagerly resolve types. This is not an optimization, this is a
2399 // requirement that is due to the fact that we could have this:
2400 //
2401 // %list = type { %list * }
2402 // %list = type { %list * } ; repeated type decl
2403 //
2404 // If types are not resolved eagerly, then the two types will not be
2405 // determined to be the same type!
2406 //
Reid Spencered96d1e2007-02-08 09:08:52 +00002407 const Type* Ty = $4.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002408 ResolveTypeTo($2, Ty);
2409
2410 if (!setTypeName(Ty, $2) && !$2) {
2411 // If this is a named type that is not a redefinition, add it to the slot
2412 // table.
2413 CurModule.Types.push_back(Ty);
Reid Spencera50d5962006-12-02 04:11:07 +00002414 }
Reid Spencered96d1e2007-02-08 09:08:52 +00002415 delete $4.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00002416 }
2417 | ConstPool FunctionProto { // Function prototypes can be in const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002418 }
2419 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002420 }
Reid Spencer950bf602007-01-26 08:19:09 +00002421 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2422 if ($5.C == 0)
2423 error("Global value initializer is not a constant");
2424 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2425 } GlobalVarAttributes {
2426 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002427 }
Reid Spencer950bf602007-01-26 08:19:09 +00002428 | ConstPool OptAssign EXTERNAL GlobalType Types {
Reid Spencered96d1e2007-02-08 09:08:52 +00002429 const Type *Ty = $5.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002430 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
Reid Spencered96d1e2007-02-08 09:08:52 +00002431 delete $5.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002432 } GlobalVarAttributes {
2433 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002434 }
Reid Spencer950bf602007-01-26 08:19:09 +00002435 | ConstPool OptAssign DLLIMPORT GlobalType Types {
Reid Spencered96d1e2007-02-08 09:08:52 +00002436 const Type *Ty = $5.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002437 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
Reid Spencered96d1e2007-02-08 09:08:52 +00002438 delete $5.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002439 } GlobalVarAttributes {
2440 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002441 }
Reid Spencer950bf602007-01-26 08:19:09 +00002442 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
Reid Spencered96d1e2007-02-08 09:08:52 +00002443 const Type *Ty = $5.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002444 CurGV =
2445 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
Reid Spencered96d1e2007-02-08 09:08:52 +00002446 delete $5.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002447 } GlobalVarAttributes {
2448 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002449 }
2450 | ConstPool TARGET TargetDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002451 }
2452 | ConstPool DEPLIBS '=' LibrariesDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002453 }
2454 | /* empty: end of list */ {
Reid Spencer950bf602007-01-26 08:19:09 +00002455 }
2456 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002457
Reid Spencer950bf602007-01-26 08:19:09 +00002458AsmBlock
2459 : STRINGCONSTANT {
2460 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2461 char *EndStr = UnEscapeLexed($1, true);
2462 std::string NewAsm($1, EndStr);
2463 free($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002464
Reid Spencer950bf602007-01-26 08:19:09 +00002465 if (AsmSoFar.empty())
2466 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2467 else
2468 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2469 }
2470 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002471
Reid Spencer950bf602007-01-26 08:19:09 +00002472BigOrLittle
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00002473 : BIG { $$ = Module::BigEndian; }
Reid Spencer950bf602007-01-26 08:19:09 +00002474 | LITTLE { $$ = Module::LittleEndian; }
2475 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002476
2477TargetDefinition
2478 : ENDIAN '=' BigOrLittle {
Reid Spencer950bf602007-01-26 08:19:09 +00002479 CurModule.setEndianness($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002480 }
2481 | POINTERSIZE '=' EUINT64VAL {
Reid Spencer950bf602007-01-26 08:19:09 +00002482 if ($3 == 32)
2483 CurModule.setPointerSize(Module::Pointer32);
2484 else if ($3 == 64)
2485 CurModule.setPointerSize(Module::Pointer64);
2486 else
2487 error("Invalid pointer size: '" + utostr($3) + "'");
Reid Spencere7c3c602006-11-30 06:36:44 +00002488 }
2489 | TRIPLE '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002490 CurModule.CurrentModule->setTargetTriple($3);
2491 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002492 }
2493 | DATALAYOUT '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002494 CurModule.CurrentModule->setDataLayout($3);
2495 free($3);
2496 }
2497 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002498
2499LibrariesDefinition
Reid Spencer950bf602007-01-26 08:19:09 +00002500 : '[' LibList ']'
2501 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002502
2503LibList
2504 : LibList ',' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002505 CurModule.CurrentModule->addLibrary($3);
2506 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002507 }
Reid Spencer950bf602007-01-26 08:19:09 +00002508 | STRINGCONSTANT {
2509 CurModule.CurrentModule->addLibrary($1);
2510 free($1);
2511 }
2512 | /* empty: end of list */ { }
2513 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002514
2515//===----------------------------------------------------------------------===//
2516// Rules to match Function Headers
2517//===----------------------------------------------------------------------===//
2518
Reid Spencer950bf602007-01-26 08:19:09 +00002519Name
2520 : VAR_ID | STRINGCONSTANT
2521 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002522
Reid Spencer950bf602007-01-26 08:19:09 +00002523OptName
2524 : Name
2525 | /*empty*/ { $$ = 0; }
2526 ;
2527
2528ArgVal
2529 : Types OptName {
Reid Spencered96d1e2007-02-08 09:08:52 +00002530 if ($1.PAT->get() == Type::VoidTy)
Reid Spencer950bf602007-01-26 08:19:09 +00002531 error("void typed arguments are invalid");
2532 $$ = new std::pair<PATypeInfo, char*>($1, $2);
Reid Spencer52402b02007-01-02 05:45:11 +00002533 }
Reid Spencer950bf602007-01-26 08:19:09 +00002534 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002535
Reid Spencer950bf602007-01-26 08:19:09 +00002536ArgListH
2537 : ArgListH ',' ArgVal {
2538 $$ = $1;
2539 $$->push_back(*$3);
Reid Spencere77e35e2006-12-01 20:26:20 +00002540 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002541 }
2542 | ArgVal {
Reid Spencer950bf602007-01-26 08:19:09 +00002543 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2544 $$->push_back(*$1);
2545 delete $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002546 }
Reid Spencer950bf602007-01-26 08:19:09 +00002547 ;
2548
2549ArgList
2550 : ArgListH { $$ = $1; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002551 | ArgListH ',' DOTDOTDOT {
Reid Spencere7c3c602006-11-30 06:36:44 +00002552 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00002553 PATypeInfo VoidTI;
Reid Spencered96d1e2007-02-08 09:08:52 +00002554 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
Reid Spencer950bf602007-01-26 08:19:09 +00002555 VoidTI.S = Signless;
2556 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002557 }
2558 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00002559 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2560 PATypeInfo VoidTI;
Reid Spencered96d1e2007-02-08 09:08:52 +00002561 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
Reid Spencer950bf602007-01-26 08:19:09 +00002562 VoidTI.S = Signless;
2563 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002564 }
Reid Spencer950bf602007-01-26 08:19:09 +00002565 | /* empty */ { $$ = 0; }
2566 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002567
Reid Spencer71d2ec92006-12-31 06:02:26 +00002568FunctionHeaderH
2569 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00002570 UnEscapeLexed($3);
2571 std::string FunctionName($3);
2572 free($3); // Free strdup'd memory!
Reid Spencere7c3c602006-11-30 06:36:44 +00002573
Reid Spencered96d1e2007-02-08 09:08:52 +00002574 const Type* RetTy = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002575
2576 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2577 error("LLVM functions cannot return aggregate types");
2578
Reid Spenceref9b9a72007-02-05 20:47:22 +00002579 std::vector<const Type*> ParamTyList;
Reid Spencer950bf602007-01-26 08:19:09 +00002580
2581 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2582 // i8*. We check here for those names and override the parameter list
2583 // types to ensure the prototype is correct.
2584 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
Reid Spenceref9b9a72007-02-05 20:47:22 +00002585 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
Reid Spencer950bf602007-01-26 08:19:09 +00002586 } else if (FunctionName == "llvm.va_copy") {
Reid Spenceref9b9a72007-02-05 20:47:22 +00002587 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2588 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
Reid Spencer950bf602007-01-26 08:19:09 +00002589 } else if ($5) { // If there are arguments...
2590 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2591 I = $5->begin(), E = $5->end(); I != E; ++I) {
Reid Spencered96d1e2007-02-08 09:08:52 +00002592 const Type *Ty = I->first.PAT->get();
Reid Spenceref9b9a72007-02-05 20:47:22 +00002593 ParamTyList.push_back(Ty);
Reid Spencer950bf602007-01-26 08:19:09 +00002594 }
2595 }
2596
Reid Spenceref9b9a72007-02-05 20:47:22 +00002597 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2598 if (isVarArg)
2599 ParamTyList.pop_back();
Reid Spencer950bf602007-01-26 08:19:09 +00002600
Reid Spencerb7046c72007-01-29 05:41:34 +00002601 // Convert the CSRet calling convention into the corresponding parameter
2602 // attribute.
2603 FunctionType::ParamAttrsList ParamAttrs;
2604 if ($1 == OldCallingConv::CSRet) {
2605 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2606 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2607 }
2608
Reid Spenceref9b9a72007-02-05 20:47:22 +00002609 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
Reid Spencerb7046c72007-01-29 05:41:34 +00002610 ParamAttrs);
Reid Spencer950bf602007-01-26 08:19:09 +00002611 const PointerType *PFT = PointerType::get(FT);
Reid Spencered96d1e2007-02-08 09:08:52 +00002612 delete $2.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002613
2614 ValID ID;
2615 if (!FunctionName.empty()) {
2616 ID = ValID::create((char*)FunctionName.c_str());
2617 } else {
2618 ID = ValID::create((int)CurModule.Values[PFT].size());
2619 }
2620
2621 Function *Fn = 0;
Reid Spencered96d1e2007-02-08 09:08:52 +00002622 Module* M = CurModule.CurrentModule;
2623
Reid Spencer950bf602007-01-26 08:19:09 +00002624 // See if this function was forward referenced. If so, recycle the object.
2625 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2626 // Move the function to the end of the list, from whereever it was
2627 // previously inserted.
2628 Fn = cast<Function>(FWRef);
Reid Spencered96d1e2007-02-08 09:08:52 +00002629 M->getFunctionList().remove(Fn);
2630 M->getFunctionList().push_back(Fn);
2631 } else if (!FunctionName.empty()) {
2632 GlobalValue *Conflict = M->getFunction(FunctionName);
2633 if (!Conflict)
2634 Conflict = M->getNamedGlobal(FunctionName);
2635 if (Conflict && PFT == Conflict->getType()) {
2636 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2637 // We have two function definitions that conflict, same type, same
2638 // name. We should really check to make sure that this is the result
2639 // of integer type planes collapsing and generate an error if it is
2640 // not, but we'll just rename on the assumption that it is. However,
2641 // let's do it intelligently and rename the internal linkage one
2642 // if there is one.
2643 std::string NewName(makeNameUnique(FunctionName));
2644 if (Conflict->hasInternalLinkage()) {
2645 Conflict->setName(NewName);
2646 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2647 CurModule.RenameMap[Key] = NewName;
2648 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2649 InsertValue(Fn, CurModule.Values);
2650 } else {
2651 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2652 InsertValue(Fn, CurModule.Values);
2653 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2654 CurModule.RenameMap[Key] = NewName;
2655 }
2656 } else {
2657 // If they are not both definitions, then just use the function we
2658 // found since the types are the same.
2659 Fn = cast<Function>(Conflict);
Reid Spenceref9b9a72007-02-05 20:47:22 +00002660
Reid Spencered96d1e2007-02-08 09:08:52 +00002661 // Make sure to strip off any argument names so we can't get
2662 // conflicts.
2663 if (Fn->isDeclaration())
2664 for (Function::arg_iterator AI = Fn->arg_begin(),
2665 AE = Fn->arg_end(); AI != AE; ++AI)
2666 AI->setName("");
2667 }
2668 } else if (Conflict) {
2669 // We have two globals with the same name and different types.
2670 // Previously, this was permitted because the symbol table had
2671 // "type planes" and names only needed to be distinct within a
2672 // type plane. After PR411 was fixed, this is no loner the case.
2673 // To resolve this we must rename one of the two.
2674 if (Conflict->hasInternalLinkage()) {
2675 // We can safely renamed the Conflict.
2676 Conflict->setName(makeNameUnique(Conflict->getName()));
2677 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2678 CurModule.RenameMap[Key] = Conflict->getName();
2679 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2680 InsertValue(Fn, CurModule.Values);
2681 } else if (CurFun.Linkage == GlobalValue::InternalLinkage) {
2682 // We can safely rename the function we're defining
2683 std::string NewName = makeNameUnique(FunctionName);
2684 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2685 InsertValue(Fn, CurModule.Values);
2686 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2687 CurModule.RenameMap[Key] = NewName;
2688 } else {
2689 // We can't quietly rename either of these things, but we must
2690 // rename one of them. Generate a warning about the renaming and
2691 // elect to rename the thing we're now defining.
2692 std::string NewName = makeNameUnique(FunctionName);
2693 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2694 "' may cause linkage errors");
2695 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2696 InsertValue(Fn, CurModule.Values);
2697 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2698 CurModule.RenameMap[Key] = NewName;
2699 }
Reid Spenceref9b9a72007-02-05 20:47:22 +00002700 } else {
Reid Spencered96d1e2007-02-08 09:08:52 +00002701 // There's no conflict, just define the function
2702 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2703 InsertValue(Fn, CurModule.Values);
Reid Spenceref9b9a72007-02-05 20:47:22 +00002704 }
Reid Spencer950bf602007-01-26 08:19:09 +00002705 }
2706
2707 CurFun.FunctionStart(Fn);
2708
2709 if (CurFun.isDeclare) {
2710 // If we have declaration, always overwrite linkage. This will allow us
2711 // to correctly handle cases, when pointer to function is passed as
2712 // argument to another function.
2713 Fn->setLinkage(CurFun.Linkage);
2714 }
Reid Spencerb7046c72007-01-29 05:41:34 +00002715 Fn->setCallingConv(upgradeCallingConv($1));
Reid Spencer950bf602007-01-26 08:19:09 +00002716 Fn->setAlignment($8);
2717 if ($7) {
2718 Fn->setSection($7);
2719 free($7);
2720 }
2721
2722 // Add all of the arguments we parsed to the function...
2723 if ($5) { // Is null if empty...
2724 if (isVarArg) { // Nuke the last entry
Reid Spencered96d1e2007-02-08 09:08:52 +00002725 assert($5->back().first.PAT->get() == Type::VoidTy &&
Reid Spencer950bf602007-01-26 08:19:09 +00002726 $5->back().second == 0 && "Not a varargs marker");
Reid Spencered96d1e2007-02-08 09:08:52 +00002727 delete $5->back().first.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00002728 $5->pop_back(); // Delete the last entry
2729 }
2730 Function::arg_iterator ArgIt = Fn->arg_begin();
Reid Spenceref9b9a72007-02-05 20:47:22 +00002731 Function::arg_iterator ArgEnd = Fn->arg_end();
2732 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2733 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2734 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
Reid Spencered96d1e2007-02-08 09:08:52 +00002735 delete I->first.PAT; // Delete the typeholder...
Reid Spencer950bf602007-01-26 08:19:09 +00002736 setValueName(ArgIt, I->second); // Insert arg into symtab...
2737 InsertValue(ArgIt);
2738 }
2739 delete $5; // We're now done with the argument list
2740 }
2741 }
2742 ;
2743
2744BEGIN
2745 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
Jeff Cohenac2dca92007-01-21 19:30:52 +00002746 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002747
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002748FunctionHeader
2749 : OptLinkage FunctionHeaderH BEGIN {
Reid Spencer950bf602007-01-26 08:19:09 +00002750 $$ = CurFun.CurrentFunction;
2751
2752 // Make sure that we keep track of the linkage type even if there was a
2753 // previous "declare".
2754 $$->setLinkage($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002755 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002756 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002757
Reid Spencer950bf602007-01-26 08:19:09 +00002758END
2759 : ENDTOK | '}' // Allow end of '}' to end a function
2760 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002761
Reid Spencer950bf602007-01-26 08:19:09 +00002762Function
2763 : BasicBlockList END {
2764 $$ = $1;
2765 };
Reid Spencere7c3c602006-11-30 06:36:44 +00002766
Reid Spencere77e35e2006-12-01 20:26:20 +00002767FnDeclareLinkage
Reid Spencered96d1e2007-02-08 09:08:52 +00002768 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
2769 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
2770 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002771 ;
2772
2773FunctionProto
Reid Spencered96d1e2007-02-08 09:08:52 +00002774 : DECLARE { CurFun.isDeclare = true; }
2775 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
Reid Spencer950bf602007-01-26 08:19:09 +00002776 $$ = CurFun.CurrentFunction;
2777 CurFun.FunctionDone();
2778
2779 }
2780 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002781
2782//===----------------------------------------------------------------------===//
2783// Rules to match Basic Blocks
2784//===----------------------------------------------------------------------===//
2785
Reid Spencer950bf602007-01-26 08:19:09 +00002786OptSideEffect
2787 : /* empty */ { $$ = false; }
2788 | SIDEEFFECT { $$ = true; }
2789 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002790
Reid Spencere77e35e2006-12-01 20:26:20 +00002791ConstValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002792 // A reference to a direct constant
2793 : ESINT64VAL { $$ = ValID::create($1); }
2794 | EUINT64VAL { $$ = ValID::create($1); }
2795 | FPVAL { $$ = ValID::create($1); }
2796 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2797 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2798 | NULL_TOK { $$ = ValID::createNull(); }
2799 | UNDEF { $$ = ValID::createUndef(); }
2800 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2801 | '<' ConstVector '>' { // Nonempty unsized packed vector
2802 const Type *ETy = (*$2)[0].C->getType();
2803 int NumElements = $2->size();
2804 PackedType* pt = PackedType::get(ETy, NumElements);
2805 PATypeHolder* PTy = new PATypeHolder(
2806 HandleUpRefs(PackedType::get(ETy, NumElements)));
2807
2808 // Verify all elements are correct type!
2809 std::vector<Constant*> Elems;
2810 for (unsigned i = 0; i < $2->size(); i++) {
2811 Constant *C = (*$2)[i].C;
2812 const Type *CTy = C->getType();
2813 if (ETy != CTy)
2814 error("Element #" + utostr(i) + " is not of type '" +
2815 ETy->getDescription() +"' as required!\nIt is of type '" +
2816 CTy->getDescription() + "'");
2817 Elems.push_back(C);
Reid Spencere7c3c602006-11-30 06:36:44 +00002818 }
Reid Spencer950bf602007-01-26 08:19:09 +00002819 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2820 delete PTy; delete $2;
2821 }
2822 | ConstExpr {
2823 $$ = ValID::create($1.C);
2824 }
2825 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2826 char *End = UnEscapeLexed($3, true);
2827 std::string AsmStr = std::string($3, End);
2828 End = UnEscapeLexed($5, true);
2829 std::string Constraints = std::string($5, End);
2830 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2831 free($3);
2832 free($5);
2833 }
2834 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002835
Reid Spencer950bf602007-01-26 08:19:09 +00002836// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2837// another value.
2838//
2839SymbolicValueRef
2840 : INTVAL { $$ = ValID::create($1); }
2841 | Name { $$ = ValID::create($1); }
2842 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002843
2844// ValueRef - A reference to a definition... either constant or symbolic
Reid Spencerf459d392006-12-02 16:19:52 +00002845ValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002846 : SymbolicValueRef | ConstValueRef
Reid Spencerf459d392006-12-02 16:19:52 +00002847 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002848
Reid Spencer950bf602007-01-26 08:19:09 +00002849
Reid Spencere7c3c602006-11-30 06:36:44 +00002850// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2851// type immediately preceeds the value reference, and allows complex constant
2852// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
Reid Spencer950bf602007-01-26 08:19:09 +00002853ResolvedVal
2854 : Types ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00002855 const Type *Ty = $1.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00002856 $$.S = $1.S;
2857 $$.V = getVal(Ty, $2);
Reid Spencered96d1e2007-02-08 09:08:52 +00002858 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00002859 }
Reid Spencer950bf602007-01-26 08:19:09 +00002860 ;
2861
2862BasicBlockList
2863 : BasicBlockList BasicBlock {
2864 $$ = $1;
2865 }
2866 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2867 $$ = $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002868 };
2869
2870
2871// Basic blocks are terminated by branching instructions:
2872// br, br/cc, switch, ret
2873//
Reid Spencer950bf602007-01-26 08:19:09 +00002874BasicBlock
2875 : InstructionList OptAssign BBTerminatorInst {
2876 setValueName($3, $2);
2877 InsertValue($3);
2878 $1->getInstList().push_back($3);
2879 InsertValue($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002880 $$ = $1;
2881 }
Reid Spencer950bf602007-01-26 08:19:09 +00002882 ;
2883
2884InstructionList
2885 : InstructionList Inst {
2886 if ($2.I)
2887 $1->getInstList().push_back($2.I);
2888 $$ = $1;
2889 }
2890 | /* empty */ {
2891 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2892 // Make sure to move the basic block to the correct location in the
2893 // function, instead of leaving it inserted wherever it was first
2894 // referenced.
2895 Function::BasicBlockListType &BBL =
2896 CurFun.CurrentFunction->getBasicBlockList();
2897 BBL.splice(BBL.end(), BBL, $$);
2898 }
2899 | LABELSTR {
2900 $$ = CurBB = getBBVal(ValID::create($1), true);
2901 // Make sure to move the basic block to the correct location in the
2902 // function, instead of leaving it inserted wherever it was first
2903 // referenced.
2904 Function::BasicBlockListType &BBL =
2905 CurFun.CurrentFunction->getBasicBlockList();
2906 BBL.splice(BBL.end(), BBL, $$);
2907 }
2908 ;
2909
2910Unwind : UNWIND | EXCEPT;
2911
2912BBTerminatorInst
2913 : RET ResolvedVal { // Return with a result...
2914 $$ = new ReturnInst($2.V);
2915 }
2916 | RET VOID { // Return with no result...
2917 $$ = new ReturnInst();
2918 }
2919 | BR LABEL ValueRef { // Unconditional Branch...
2920 BasicBlock* tmpBB = getBBVal($3);
2921 $$ = new BranchInst(tmpBB);
2922 } // Conditional Branch...
2923 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2924 BasicBlock* tmpBBA = getBBVal($6);
2925 BasicBlock* tmpBBB = getBBVal($9);
2926 Value* tmpVal = getVal(Type::Int1Ty, $3);
2927 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2928 }
2929 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2930 Value* tmpVal = getVal($2.T, $3);
2931 BasicBlock* tmpBB = getBBVal($6);
2932 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2933 $$ = S;
2934 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2935 E = $8->end();
2936 for (; I != E; ++I) {
2937 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2938 S->addCase(CI, I->second);
2939 else
2940 error("Switch case is constant, but not a simple integer");
2941 }
2942 delete $8;
2943 }
2944 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2945 Value* tmpVal = getVal($2.T, $3);
2946 BasicBlock* tmpBB = getBBVal($6);
2947 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2948 $$ = S;
2949 }
2950 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2951 TO LABEL ValueRef Unwind LABEL ValueRef {
2952 const PointerType *PFTy;
2953 const FunctionType *Ty;
2954
Reid Spencered96d1e2007-02-08 09:08:52 +00002955 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
Reid Spencer950bf602007-01-26 08:19:09 +00002956 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2957 // Pull out the types of all of the arguments...
2958 std::vector<const Type*> ParamTypes;
2959 if ($6) {
2960 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2961 I != E; ++I)
2962 ParamTypes.push_back((*I).V->getType());
2963 }
Reid Spencerb7046c72007-01-29 05:41:34 +00002964 FunctionType::ParamAttrsList ParamAttrs;
2965 if ($2 == OldCallingConv::CSRet) {
2966 ParamAttrs.push_back(FunctionType::NoAttributeSet);
2967 ParamAttrs.push_back(FunctionType::StructRetAttribute);
2968 }
Reid Spencer950bf602007-01-26 08:19:09 +00002969 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2970 if (isVarArg) ParamTypes.pop_back();
Reid Spencered96d1e2007-02-08 09:08:52 +00002971 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
Reid Spencer950bf602007-01-26 08:19:09 +00002972 PFTy = PointerType::get(Ty);
2973 }
2974 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2975 BasicBlock *Normal = getBBVal($10);
2976 BasicBlock *Except = getBBVal($13);
2977
2978 // Create the call node...
2979 if (!$6) { // Has no arguments?
2980 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2981 } else { // Has arguments?
2982 // Loop through FunctionType's arguments and ensure they are specified
2983 // correctly!
2984 //
2985 FunctionType::param_iterator I = Ty->param_begin();
2986 FunctionType::param_iterator E = Ty->param_end();
2987 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2988
2989 std::vector<Value*> Args;
2990 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2991 if ((*ArgI).V->getType() != *I)
2992 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2993 (*I)->getDescription() + "'");
2994 Args.push_back((*ArgI).V);
2995 }
2996
2997 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2998 error("Invalid number of parameters detected");
2999
3000 $$ = new InvokeInst(V, Normal, Except, Args);
3001 }
Reid Spencerb7046c72007-01-29 05:41:34 +00003002 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
Reid Spencered96d1e2007-02-08 09:08:52 +00003003 delete $3.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00003004 delete $6;
3005 }
3006 | Unwind {
3007 $$ = new UnwindInst();
3008 }
3009 | UNREACHABLE {
3010 $$ = new UnreachableInst();
3011 }
3012 ;
3013
3014JumpTable
3015 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3016 $$ = $1;
3017 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3018
3019 if (V == 0)
3020 error("May only switch on a constant pool value");
3021
3022 BasicBlock* tmpBB = getBBVal($6);
3023 $$->push_back(std::make_pair(V, tmpBB));
3024 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003025 | IntType ConstValueRef ',' LABEL ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003026 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3027 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3028
3029 if (V == 0)
3030 error("May only switch on a constant pool value");
3031
3032 BasicBlock* tmpBB = getBBVal($5);
3033 $$->push_back(std::make_pair(V, tmpBB));
3034 }
3035 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003036
3037Inst
3038 : OptAssign InstVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003039 bool omit = false;
3040 if ($1)
3041 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3042 if (BCI->getSrcTy() == BCI->getDestTy() &&
3043 BCI->getOperand(0)->getName() == $1)
3044 // This is a useless bit cast causing a name redefinition. It is
3045 // a bit cast from a type to the same type of an operand with the
3046 // same name as the name we would give this instruction. Since this
3047 // instruction results in no code generation, it is safe to omit
3048 // the instruction. This situation can occur because of collapsed
3049 // type planes. For example:
3050 // %X = add int %Y, %Z
3051 // %X = cast int %Y to uint
3052 // After upgrade, this looks like:
3053 // %X = add i32 %Y, %Z
3054 // %X = bitcast i32 to i32
3055 // The bitcast is clearly useless so we omit it.
3056 omit = true;
3057 if (omit) {
3058 $$.I = 0;
3059 $$.S = Signless;
3060 } else {
3061 setValueName($2.I, $1);
3062 InsertValue($2.I);
3063 $$ = $2;
Reid Spencerf5626a32007-01-01 01:20:41 +00003064 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003065 };
3066
Reid Spencer950bf602007-01-26 08:19:09 +00003067PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3068 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3069 $$.S = $1.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00003070 Value* tmpVal = getVal($1.PAT->get(), $3);
Reid Spencer950bf602007-01-26 08:19:09 +00003071 BasicBlock* tmpBB = getBBVal($5);
3072 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
Reid Spencered96d1e2007-02-08 09:08:52 +00003073 delete $1.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003074 }
3075 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
Reid Spencere7c3c602006-11-30 06:36:44 +00003076 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00003077 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3078 BasicBlock* tmpBB = getBBVal($6);
3079 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3080 }
3081 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003082
Reid Spencer950bf602007-01-26 08:19:09 +00003083ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3084 $$ = new std::vector<ValueInfo>();
Reid Spencerf8483652006-12-02 15:16:01 +00003085 $$->push_back($1);
3086 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003087 | ValueRefList ',' ResolvedVal {
Reid Spencere7c3c602006-11-30 06:36:44 +00003088 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00003089 $1->push_back($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00003090 };
3091
3092// ValueRefListE - Just like ValueRefList, except that it may also be empty!
3093ValueRefListE
Reid Spencer950bf602007-01-26 08:19:09 +00003094 : ValueRefList
3095 | /*empty*/ { $$ = 0; }
Reid Spencere7c3c602006-11-30 06:36:44 +00003096 ;
3097
3098OptTailCall
3099 : TAIL CALL {
Reid Spencer950bf602007-01-26 08:19:09 +00003100 $$ = true;
Reid Spencere7c3c602006-11-30 06:36:44 +00003101 }
Reid Spencer950bf602007-01-26 08:19:09 +00003102 | CALL {
3103 $$ = false;
3104 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003105 ;
3106
Reid Spencer950bf602007-01-26 08:19:09 +00003107InstVal
3108 : ArithmeticOps Types ValueRef ',' ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00003109 const Type* Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003110 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3111 error("Arithmetic operator requires integer, FP, or packed operands");
3112 if (isa<PackedType>(Ty) &&
3113 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3114 error("Remainder not supported on packed types");
3115 // Upgrade the opcode from obsolete versions before we do anything with it.
3116 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3117 Value* val1 = getVal(Ty, $3);
3118 Value* val2 = getVal(Ty, $5);
3119 $$.I = BinaryOperator::create(Opcode, val1, val2);
3120 if ($$.I == 0)
3121 error("binary operator returned null");
3122 $$.S = $2.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00003123 delete $2.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003124 }
3125 | LogicalOps Types ValueRef ',' ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00003126 const Type *Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003127 if (!Ty->isInteger()) {
3128 if (!isa<PackedType>(Ty) ||
3129 !cast<PackedType>(Ty)->getElementType()->isInteger())
3130 error("Logical operator requires integral operands");
3131 }
3132 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3133 Value* tmpVal1 = getVal(Ty, $3);
3134 Value* tmpVal2 = getVal(Ty, $5);
3135 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3136 if ($$.I == 0)
3137 error("binary operator returned null");
3138 $$.S = $2.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00003139 delete $2.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003140 }
3141 | SetCondOps Types ValueRef ',' ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00003142 const Type* Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003143 if(isa<PackedType>(Ty))
3144 error("PackedTypes currently not supported in setcc instructions");
3145 unsigned short pred;
3146 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3147 Value* tmpVal1 = getVal(Ty, $3);
3148 Value* tmpVal2 = getVal(Ty, $5);
3149 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3150 if ($$.I == 0)
3151 error("binary operator returned null");
3152 $$.S = Unsigned;
Reid Spencered96d1e2007-02-08 09:08:52 +00003153 delete $2.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003154 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003155 | ICMP IPredicates Types ValueRef ',' ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00003156 const Type *Ty = $3.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003157 if (isa<PackedType>(Ty))
3158 error("PackedTypes currently not supported in icmp instructions");
3159 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3160 error("icmp requires integer or pointer typed operands");
3161 Value* tmpVal1 = getVal(Ty, $4);
3162 Value* tmpVal2 = getVal(Ty, $6);
3163 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3164 $$.S = Unsigned;
Reid Spencered96d1e2007-02-08 09:08:52 +00003165 delete $3.PAT;
Reid Spencer57f28f92006-12-03 07:10:26 +00003166 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003167 | FCMP FPredicates Types ValueRef ',' ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00003168 const Type *Ty = $3.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003169 if (isa<PackedType>(Ty))
3170 error("PackedTypes currently not supported in fcmp instructions");
3171 else if (!Ty->isFloatingPoint())
3172 error("fcmp instruction requires floating point operands");
3173 Value* tmpVal1 = getVal(Ty, $4);
3174 Value* tmpVal2 = getVal(Ty, $6);
3175 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3176 $$.S = Unsigned;
Reid Spencered96d1e2007-02-08 09:08:52 +00003177 delete $3.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00003178 }
3179 | NOT ResolvedVal {
3180 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3181 const Type *Ty = $2.V->getType();
3182 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3183 if (Ones == 0)
3184 error("Expected integral type for not instruction");
3185 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3186 if ($$.I == 0)
3187 error("Could not create a xor instruction");
3188 $$.S = $2.S
Reid Spencer229e9362006-12-02 22:14:11 +00003189 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003190 | ShiftOps ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003191 if (!$4.V->getType()->isInteger() ||
3192 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3193 error("Shift amount must be int8");
Reid Spencer832254e2007-02-02 02:16:23 +00003194 const Type* Ty = $2.V->getType();
3195 if (!Ty->isInteger())
Reid Spencer950bf602007-01-26 08:19:09 +00003196 error("Shift constant expression requires integer operand");
Reid Spencer832254e2007-02-02 02:16:23 +00003197 Value* ShiftAmt = 0;
3198 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3199 if (Constant *C = dyn_cast<Constant>($4.V))
3200 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3201 else
3202 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3203 else
3204 ShiftAmt = $4.V;
3205 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
Reid Spencer950bf602007-01-26 08:19:09 +00003206 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003207 }
Reid Spencerfcb5df82006-12-01 22:34:43 +00003208 | CastOps ResolvedVal TO Types {
Reid Spencered96d1e2007-02-08 09:08:52 +00003209 const Type *DstTy = $4.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003210 if (!DstTy->isFirstClassType())
3211 error("cast instruction to a non-primitive type: '" +
3212 DstTy->getDescription() + "'");
3213 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3214 $$.S = $4.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00003215 delete $4.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003216 }
3217 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003218 if (!$2.V->getType()->isInteger() ||
3219 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3220 error("select condition must be bool");
3221 if ($4.V->getType() != $6.V->getType())
3222 error("select value types should match");
3223 $$.I = new SelectInst($2.V, $4.V, $6.V);
3224 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003225 }
3226 | VAARG ResolvedVal ',' Types {
Reid Spencered96d1e2007-02-08 09:08:52 +00003227 const Type *Ty = $4.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003228 NewVarArgs = true;
3229 $$.I = new VAArgInst($2.V, Ty);
3230 $$.S = $4.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00003231 delete $4.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00003232 }
3233 | VAARG_old ResolvedVal ',' Types {
3234 const Type* ArgTy = $2.V->getType();
Reid Spencered96d1e2007-02-08 09:08:52 +00003235 const Type* DstTy = $4.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003236 ObsoleteVarArgs = true;
3237 Function* NF = cast<Function>(CurModule.CurrentModule->
3238 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3239
3240 //b = vaarg a, t ->
3241 //foo = alloca 1 of t
3242 //bar = vacopy a
3243 //store bar -> foo
3244 //b = vaarg foo, t
3245 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3246 CurBB->getInstList().push_back(foo);
3247 CallInst* bar = new CallInst(NF, $2.V);
3248 CurBB->getInstList().push_back(bar);
3249 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3250 $$.I = new VAArgInst(foo, DstTy);
3251 $$.S = $4.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00003252 delete $4.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00003253 }
3254 | VANEXT_old ResolvedVal ',' Types {
3255 const Type* ArgTy = $2.V->getType();
Reid Spencered96d1e2007-02-08 09:08:52 +00003256 const Type* DstTy = $4.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003257 ObsoleteVarArgs = true;
3258 Function* NF = cast<Function>(CurModule.CurrentModule->
3259 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3260
3261 //b = vanext a, t ->
3262 //foo = alloca 1 of t
3263 //bar = vacopy a
3264 //store bar -> foo
3265 //tmp = vaarg foo, t
3266 //b = load foo
3267 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3268 CurBB->getInstList().push_back(foo);
3269 CallInst* bar = new CallInst(NF, $2.V);
3270 CurBB->getInstList().push_back(bar);
3271 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3272 Instruction* tmp = new VAArgInst(foo, DstTy);
3273 CurBB->getInstList().push_back(tmp);
3274 $$.I = new LoadInst(foo);
3275 $$.S = $4.S;
Reid Spencered96d1e2007-02-08 09:08:52 +00003276 delete $4.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003277 }
3278 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003279 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3280 error("Invalid extractelement operands");
3281 $$.I = new ExtractElementInst($2.V, $4.V);
3282 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003283 }
3284 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003285 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3286 error("Invalid insertelement operands");
3287 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3288 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003289 }
3290 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003291 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3292 error("Invalid shufflevector operands");
3293 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3294 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003295 }
3296 | PHI_TOK PHIList {
Reid Spencer950bf602007-01-26 08:19:09 +00003297 const Type *Ty = $2.P->front().first->getType();
3298 if (!Ty->isFirstClassType())
3299 error("PHI node operands must be of first class type");
3300 PHINode *PHI = new PHINode(Ty);
3301 PHI->reserveOperandSpace($2.P->size());
3302 while ($2.P->begin() != $2.P->end()) {
3303 if ($2.P->front().first->getType() != Ty)
3304 error("All elements of a PHI node must be of the same type");
3305 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3306 $2.P->pop_front();
3307 }
3308 $$.I = PHI;
3309 $$.S = $2.S;
3310 delete $2.P; // Free the list...
Reid Spencere7c3c602006-11-30 06:36:44 +00003311 }
3312 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00003313
3314 // Handle the short call syntax
3315 const PointerType *PFTy;
3316 const FunctionType *FTy;
Reid Spencered96d1e2007-02-08 09:08:52 +00003317 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
Reid Spencer950bf602007-01-26 08:19:09 +00003318 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3319 // Pull out the types of all of the arguments...
3320 std::vector<const Type*> ParamTypes;
3321 if ($6) {
3322 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3323 I != E; ++I)
3324 ParamTypes.push_back((*I).V->getType());
Reid Spencerc4d96252007-01-13 00:03:30 +00003325 }
Reid Spencer950bf602007-01-26 08:19:09 +00003326
Reid Spencerb7046c72007-01-29 05:41:34 +00003327 FunctionType::ParamAttrsList ParamAttrs;
3328 if ($2 == OldCallingConv::CSRet) {
3329 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3330 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3331 }
Reid Spencer950bf602007-01-26 08:19:09 +00003332 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3333 if (isVarArg) ParamTypes.pop_back();
3334
Reid Spencered96d1e2007-02-08 09:08:52 +00003335 const Type *RetTy = $3.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003336 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3337 error("Functions cannot return aggregate types");
3338
Reid Spencerb7046c72007-01-29 05:41:34 +00003339 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
Reid Spencer950bf602007-01-26 08:19:09 +00003340 PFTy = PointerType::get(FTy);
Reid Spencerf8483652006-12-02 15:16:01 +00003341 }
Reid Spencer950bf602007-01-26 08:19:09 +00003342
3343 // First upgrade any intrinsic calls.
3344 std::vector<Value*> Args;
3345 if ($6)
3346 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3347 Args.push_back((*$6)[i].V);
3348 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3349
3350 // If we got an upgraded intrinsic
3351 if (Inst) {
3352 $$.I = Inst;
3353 $$.S = Signless;
3354 } else {
3355 // Get the function we're calling
3356 Value *V = getVal(PFTy, $4);
3357
3358 // Check the argument values match
3359 if (!$6) { // Has no arguments?
3360 // Make sure no arguments is a good thing!
3361 if (FTy->getNumParams() != 0)
3362 error("No arguments passed to a function that expects arguments");
3363 } else { // Has arguments?
3364 // Loop through FunctionType's arguments and ensure they are specified
3365 // correctly!
3366 //
3367 FunctionType::param_iterator I = FTy->param_begin();
3368 FunctionType::param_iterator E = FTy->param_end();
3369 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3370
3371 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3372 if ((*ArgI).V->getType() != *I)
3373 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3374 (*I)->getDescription() + "'");
3375
3376 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3377 error("Invalid number of parameters detected");
3378 }
3379
3380 // Create the call instruction
3381 CallInst *CI = new CallInst(V, Args);
3382 CI->setTailCall($1);
Reid Spencerb7046c72007-01-29 05:41:34 +00003383 CI->setCallingConv(upgradeCallingConv($2));
Reid Spencer950bf602007-01-26 08:19:09 +00003384 $$.I = CI;
3385 $$.S = $3.S;
3386 }
Reid Spencered96d1e2007-02-08 09:08:52 +00003387 delete $3.PAT;
Reid Spencer950bf602007-01-26 08:19:09 +00003388 delete $6;
Reid Spencere7c3c602006-11-30 06:36:44 +00003389 }
Reid Spencer950bf602007-01-26 08:19:09 +00003390 | MemoryInst {
3391 $$ = $1;
3392 }
3393 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003394
3395
3396// IndexList - List of indices for GEP based instructions...
3397IndexList
Reid Spencer950bf602007-01-26 08:19:09 +00003398 : ',' ValueRefList { $$ = $2; }
3399 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
Reid Spencere7c3c602006-11-30 06:36:44 +00003400 ;
3401
3402OptVolatile
Reid Spencer950bf602007-01-26 08:19:09 +00003403 : VOLATILE { $$ = true; }
3404 | /* empty */ { $$ = false; }
Reid Spencere7c3c602006-11-30 06:36:44 +00003405 ;
3406
Reid Spencer950bf602007-01-26 08:19:09 +00003407MemoryInst
3408 : MALLOC Types OptCAlign {
Reid Spencered96d1e2007-02-08 09:08:52 +00003409 const Type *Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003410 $$.S = $2.S;
3411 $$.I = new MallocInst(Ty, 0, $3);
Reid Spencered96d1e2007-02-08 09:08:52 +00003412 delete $2.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003413 }
3414 | MALLOC Types ',' UINT ValueRef OptCAlign {
Reid Spencered96d1e2007-02-08 09:08:52 +00003415 const Type *Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003416 $$.S = $2.S;
3417 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
Reid Spencered96d1e2007-02-08 09:08:52 +00003418 delete $2.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003419 }
3420 | ALLOCA Types OptCAlign {
Reid Spencered96d1e2007-02-08 09:08:52 +00003421 const Type *Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003422 $$.S = $2.S;
3423 $$.I = new AllocaInst(Ty, 0, $3);
Reid Spencered96d1e2007-02-08 09:08:52 +00003424 delete $2.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003425 }
3426 | ALLOCA Types ',' UINT ValueRef OptCAlign {
Reid Spencered96d1e2007-02-08 09:08:52 +00003427 const Type *Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003428 $$.S = $2.S;
3429 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
Reid Spencered96d1e2007-02-08 09:08:52 +00003430 delete $2.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003431 }
3432 | FREE ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003433 const Type *PTy = $2.V->getType();
3434 if (!isa<PointerType>(PTy))
3435 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3436 $$.I = new FreeInst($2.V);
3437 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00003438 }
3439 | OptVolatile LOAD Types ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00003440 const Type* Ty = $3.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003441 $$.S = $3.S;
3442 if (!isa<PointerType>(Ty))
3443 error("Can't load from nonpointer type: " + Ty->getDescription());
3444 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3445 error("Can't load from pointer of non-first-class type: " +
3446 Ty->getDescription());
3447 Value* tmpVal = getVal(Ty, $4);
3448 $$.I = new LoadInst(tmpVal, "", $1);
Reid Spencered96d1e2007-02-08 09:08:52 +00003449 delete $3.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003450 }
3451 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
Reid Spencered96d1e2007-02-08 09:08:52 +00003452 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
Reid Spencer950bf602007-01-26 08:19:09 +00003453 if (!PTy)
3454 error("Can't store to a nonpointer type: " +
Reid Spencered96d1e2007-02-08 09:08:52 +00003455 $5.PAT->get()->getDescription());
Reid Spencer950bf602007-01-26 08:19:09 +00003456 const Type *ElTy = PTy->getElementType();
Reid Spencered96d1e2007-02-08 09:08:52 +00003457 Value *StoreVal = $3.V;
Reid Spencer950bf602007-01-26 08:19:09 +00003458 Value* tmpVal = getVal(PTy, $6);
Reid Spencered96d1e2007-02-08 09:08:52 +00003459 if (ElTy != $3.V->getType()) {
3460 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3461 if (!StoreVal)
3462 error("Can't store '" + $3.V->getType()->getDescription() +
3463 "' into space of type '" + ElTy->getDescription() + "'");
3464 else {
3465 PTy = PointerType::get(StoreVal->getType());
3466 if (Constant *C = dyn_cast<Constant>(tmpVal))
3467 tmpVal = ConstantExpr::getBitCast(C, PTy);
3468 else
3469 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3470 }
3471 }
3472 $$.I = new StoreInst(StoreVal, tmpVal, $1);
Reid Spencer950bf602007-01-26 08:19:09 +00003473 $$.S = Signless;
Reid Spencered96d1e2007-02-08 09:08:52 +00003474 delete $5.PAT;
Reid Spencere7c3c602006-11-30 06:36:44 +00003475 }
3476 | GETELEMENTPTR Types ValueRef IndexList {
Reid Spencered96d1e2007-02-08 09:08:52 +00003477 const Type* Ty = $2.PAT->get();
Reid Spencer950bf602007-01-26 08:19:09 +00003478 if (!isa<PointerType>(Ty))
3479 error("getelementptr insn requires pointer operand");
3480
3481 std::vector<Value*> VIndices;
3482 upgradeGEPIndices(Ty, $4, VIndices);
3483
3484 Value* tmpVal = getVal(Ty, $3);
3485 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3486 $$.S = Signless;
Reid Spencered96d1e2007-02-08 09:08:52 +00003487 delete $2.PAT;
Reid Spencer30d0c582007-01-15 00:26:18 +00003488 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00003489 };
3490
Reid Spencer950bf602007-01-26 08:19:09 +00003491
Reid Spencere7c3c602006-11-30 06:36:44 +00003492%%
3493
3494int yyerror(const char *ErrorMsg) {
3495 std::string where
3496 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencered96d1e2007-02-08 09:08:52 +00003497 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
Reid Spencer950bf602007-01-26 08:19:09 +00003498 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3499 if (yychar != YYEMPTY && yychar != 0)
3500 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3501 "'.";
Reid Spencer71d2ec92006-12-31 06:02:26 +00003502 std::cerr << "llvm-upgrade: " << errMsg << '\n';
Reid Spencer950bf602007-01-26 08:19:09 +00003503 std::cout << "llvm-upgrade: parse failed.\n";
Reid Spencere7c3c602006-11-30 06:36:44 +00003504 exit(1);
3505}
Reid Spencer319a7302007-01-05 17:20:02 +00003506
Reid Spencer30d0c582007-01-15 00:26:18 +00003507void warning(const std::string& ErrorMsg) {
Reid Spencer319a7302007-01-05 17:20:02 +00003508 std::string where
3509 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencered96d1e2007-02-08 09:08:52 +00003510 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
Reid Spencer950bf602007-01-26 08:19:09 +00003511 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3512 if (yychar != YYEMPTY && yychar != 0)
3513 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3514 "'.";
Reid Spencer319a7302007-01-05 17:20:02 +00003515 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3516}
Reid Spencer950bf602007-01-26 08:19:09 +00003517
3518void error(const std::string& ErrorMsg, int LineNo) {
3519 if (LineNo == -1) LineNo = Upgradelineno;
3520 Upgradelineno = LineNo;
3521 yyerror(ErrorMsg.c_str());
3522}
3523