blob: cf36340d46cb66fc31473f7bdf4955491cf9c958 [file] [log] [blame]
Reid Spencer950bf602007-01-26 08:19:09 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
Reid Spencere7c3c602006-11-30 06:36:44 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer950bf602007-01-26 08:19:09 +00005// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencere7c3c602006-11-30 06:36:44 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencer950bf602007-01-26 08:19:09 +000010// This file implements the bison parser for LLVM assembly languages files.
Reid Spencere7c3c602006-11-30 06:36:44 +000011//
12//===----------------------------------------------------------------------===//
13
14%{
Reid Spencer319a7302007-01-05 17:20:02 +000015#include "UpgradeInternals.h"
Reid Spencer950bf602007-01-26 08:19:09 +000016#include "llvm/CallingConv.h"
17#include "llvm/InlineAsm.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/SymbolTable.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/Support/MathExtras.h"
Reid Spencere7c3c602006-11-30 06:36:44 +000024#include <algorithm>
Reid Spencere7c3c602006-11-30 06:36:44 +000025#include <iostream>
Reid Spencer950bf602007-01-26 08:19:09 +000026#include <list>
27#include <utility>
28
29// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30// relating to upreferences in the input stream.
31//
32//#define DEBUG_UPREFS 1
33#ifdef DEBUG_UPREFS
34#define UR_OUT(X) std::cerr << X
35#else
36#define UR_OUT(X)
37#endif
Reid Spencere7c3c602006-11-30 06:36:44 +000038
Reid Spencere77e35e2006-12-01 20:26:20 +000039#define YYERROR_VERBOSE 1
Reid Spencer96839be2006-11-30 16:50:26 +000040#define YYINCLUDED_STDLIB_H
Reid Spencere77e35e2006-12-01 20:26:20 +000041#define YYDEBUG 1
Reid Spencere7c3c602006-11-30 06:36:44 +000042
Reid Spencer950bf602007-01-26 08:19:09 +000043int yylex();
Reid Spencere7c3c602006-11-30 06:36:44 +000044int yyparse();
45
Reid Spencer950bf602007-01-26 08:19:09 +000046int yyerror(const char*);
47static void warning(const std::string& WarningMsg);
48
49namespace llvm {
50
Reid Spencer950bf602007-01-26 08:19:09 +000051std::istream* LexInput;
Reid Spencere7c3c602006-11-30 06:36:44 +000052static std::string CurFilename;
Reid Spencer96839be2006-11-30 16:50:26 +000053
Reid Spencer71d2ec92006-12-31 06:02:26 +000054// This bool controls whether attributes are ever added to function declarations
55// definitions and calls.
56static bool AddAttributes = false;
57
Reid Spencer950bf602007-01-26 08:19:09 +000058static Module *ParserResult;
59static bool ObsoleteVarArgs;
60static bool NewVarArgs;
61static BasicBlock *CurBB;
62static GlobalVariable *CurGV;
Reid Spencera50d5962006-12-02 04:11:07 +000063
Reid Spencer950bf602007-01-26 08:19:09 +000064// This contains info used when building the body of a function. It is
65// destroyed when the function is completed.
66//
67typedef std::vector<Value *> ValueList; // Numbered defs
68
69typedef std::pair<std::string,const Type*> RenameMapKey;
70typedef std::map<RenameMapKey,std::string> RenameMapType;
71
72static void
73ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
75
76static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
85
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
95 //
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
97 GlobalRefsType;
98 GlobalRefsType GlobalRefs;
99
100 void ModuleDone() {
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
104 //
105 ResolveDefinitions(LateResolveValues);
106
107 // Check to make sure that all global value forward references have been
108 // resolved!
109 //
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
112
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
114 I != E; ++I) {
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
117 }
118 error(UndefinedReferences);
119 return;
120 }
121
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
128 dataLayout += "-";
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
131 }
132 CurrentModule->setDataLayout(dataLayout);
133 }
134
135 Values.clear(); // Clear out function local definitions
136 Types.clear();
137 CurrentModule = 0;
138 }
139
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
149 Ret = I->second;
150 GlobalRefs.erase(I);
151 }
152 return Ret;
153 }
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
156} CurModule;
157
158Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
160
161static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
163
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
168
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
Reid Spencerb7046c72007-01-29 05:41:34 +0000174 unsigned LastCC;
Reid Spencer950bf602007-01-26 08:19:09 +0000175 unsigned NextBBNum;
176
177 inline PerFunctionInfo() {
178 CurrentFunction = 0;
179 isDeclare = false;
180 Linkage = GlobalValue::ExternalLinkage;
181 }
182
183 inline void FunctionStart(Function *M) {
184 CurrentFunction = M;
185 NextBBNum = 0;
186 }
187
188 void FunctionDone() {
189 NumberedBlocks.clear();
190
191 // Any forward referenced blocks left?
192 if (!BBForwardRefs.empty()) {
193 error("Undefined reference to label " +
194 BBForwardRefs.begin()->first->getName());
195 return;
196 }
197
198 // Resolve all forward references now.
199 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
200
201 Values.clear(); // Clear out function local definitions
202 RenameMap.clear();
Reid Spencer950bf602007-01-26 08:19:09 +0000203 CurrentFunction = 0;
204 isDeclare = false;
205 Linkage = GlobalValue::ExternalLinkage;
206 }
207} CurFun; // Info for the current function...
208
209static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
210
211
212//===----------------------------------------------------------------------===//
213// Code to handle definitions of all the types
214//===----------------------------------------------------------------------===//
215
216static int InsertValue(Value *V,
217 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
218 if (V->hasName()) return -1; // Is this a numbered definition?
219
220 // Yes, insert the value into the value table...
221 ValueList &List = ValueTab[V->getType()];
222 List.push_back(V);
223 return List.size()-1;
224}
225
Reid Spencerd7c4f8c2007-01-26 19:59:25 +0000226static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
Reid Spencer950bf602007-01-26 08:19:09 +0000227 switch (D.Type) {
228 case ValID::NumberVal: // Is it a numbered definition?
229 // Module constants occupy the lowest numbered slots...
230 if ((unsigned)D.Num < CurModule.Types.size()) {
231 return CurModule.Types[(unsigned)D.Num];
232 }
233 break;
234 case ValID::NameVal: // Is it a named definition?
235 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
236 D.destroy(); // Free old strdup'd memory...
237 return N;
238 }
239 break;
240 default:
241 error("Internal parser error: Invalid symbol type reference");
242 return 0;
243 }
244
245 // If we reached here, we referenced either a symbol that we don't know about
246 // or an id number that hasn't been read yet. We may be referencing something
247 // forward, so just create an entry to be resolved later and get to it...
248 //
249 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
250
251
252 if (inFunctionScope()) {
253 if (D.Type == ValID::NameVal) {
254 error("Reference to an undefined type: '" + D.getName() + "'");
255 return 0;
256 } else {
257 error("Reference to an undefined type: #" + itostr(D.Num));
258 return 0;
259 }
260 }
261
262 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
263 if (I != CurModule.LateResolveTypes.end())
264 return I->second;
265
266 Type *Typ = OpaqueType::get();
267 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
268 return Typ;
269 }
270
271// getExistingValue - Look up the value specified by the provided type and
272// the provided ValID. If the value exists and has already been defined, return
273// it. Otherwise return null.
274//
275static Value *getExistingValue(const Type *Ty, const ValID &D) {
276 if (isa<FunctionType>(Ty)) {
277 error("Functions are not values and must be referenced as pointers");
278 }
279
280 switch (D.Type) {
281 case ValID::NumberVal: { // Is it a numbered definition?
282 unsigned Num = (unsigned)D.Num;
283
284 // Module constants occupy the lowest numbered slots...
285 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
286 if (VI != CurModule.Values.end()) {
287 if (Num < VI->second.size())
288 return VI->second[Num];
289 Num -= VI->second.size();
290 }
291
292 // Make sure that our type is within bounds
293 VI = CurFun.Values.find(Ty);
294 if (VI == CurFun.Values.end()) return 0;
295
296 // Check that the number is within bounds...
297 if (VI->second.size() <= Num) return 0;
298
299 return VI->second[Num];
300 }
301
302 case ValID::NameVal: { // Is it a named definition?
303 // Get the name out of the ID
304 std::string Name(D.Name);
305 Value* V = 0;
306 RenameMapKey Key = std::make_pair(Name, Ty);
307 if (inFunctionScope()) {
308 // See if the name was renamed
309 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
310 std::string LookupName;
311 if (I != CurFun.RenameMap.end())
312 LookupName = I->second;
313 else
314 LookupName = Name;
315 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
316 V = SymTab.lookup(Ty, LookupName);
317 }
318 if (!V) {
319 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
320 std::string LookupName;
321 if (I != CurModule.RenameMap.end())
322 LookupName = I->second;
323 else
324 LookupName = Name;
325 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
326 }
327 if (V == 0)
328 return 0;
329
330 D.destroy(); // Free old strdup'd memory...
331 return V;
332 }
333
334 // Check to make sure that "Ty" is an integral type, and that our
335 // value will fit into the specified type...
336 case ValID::ConstSIntVal: // Is it a constant pool reference??
337 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
338 error("Signed integral constant '" + itostr(D.ConstPool64) +
339 "' is invalid for type '" + Ty->getDescription() + "'");
340 }
341 return ConstantInt::get(Ty, D.ConstPool64);
342
343 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
344 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
345 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
346 error("Integral constant '" + utostr(D.UConstPool64) +
347 "' is invalid or out of range");
348 else // This is really a signed reference. Transmogrify.
349 return ConstantInt::get(Ty, D.ConstPool64);
350 } else
351 return ConstantInt::get(Ty, D.UConstPool64);
352
353 case ValID::ConstFPVal: // Is it a floating point const pool reference?
354 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
355 error("FP constant invalid for type");
356 return ConstantFP::get(Ty, D.ConstPoolFP);
357
358 case ValID::ConstNullVal: // Is it a null value?
359 if (!isa<PointerType>(Ty))
360 error("Cannot create a a non pointer null");
361 return ConstantPointerNull::get(cast<PointerType>(Ty));
362
363 case ValID::ConstUndefVal: // Is it an undef value?
364 return UndefValue::get(Ty);
365
366 case ValID::ConstZeroVal: // Is it a zero value?
367 return Constant::getNullValue(Ty);
368
369 case ValID::ConstantVal: // Fully resolved constant?
370 if (D.ConstantValue->getType() != Ty)
371 error("Constant expression type different from required type");
372 return D.ConstantValue;
373
374 case ValID::InlineAsmVal: { // Inline asm expression
375 const PointerType *PTy = dyn_cast<PointerType>(Ty);
376 const FunctionType *FTy =
377 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
378 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
379 error("Invalid type for asm constraint string");
380 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
381 D.IAD->HasSideEffects);
382 D.destroy(); // Free InlineAsmDescriptor.
383 return IA;
384 }
385 default:
386 assert(0 && "Unhandled case");
387 return 0;
388 } // End of switch
389
390 assert(0 && "Unhandled case");
391 return 0;
392}
393
394// getVal - This function is identical to getExistingValue, except that if a
395// value is not already defined, it "improvises" by creating a placeholder var
396// that looks and acts just like the requested variable. When the value is
397// defined later, all uses of the placeholder variable are replaced with the
398// real thing.
399//
400static Value *getVal(const Type *Ty, const ValID &ID) {
401 if (Ty == Type::LabelTy)
402 error("Cannot use a basic block here");
403
404 // See if the value has already been defined.
405 Value *V = getExistingValue(Ty, ID);
406 if (V) return V;
407
408 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
409 error("Invalid use of a composite type");
410
411 // If we reached here, we referenced either a symbol that we don't know about
412 // or an id number that hasn't been read yet. We may be referencing something
413 // forward, so just create an entry to be resolved later and get to it...
Reid Spencer950bf602007-01-26 08:19:09 +0000414 V = new Argument(Ty);
415
416 // Remember where this forward reference came from. FIXME, shouldn't we try
417 // to recycle these things??
418 CurModule.PlaceHolderInfo.insert(
419 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
420
421 if (inFunctionScope())
422 InsertValue(V, CurFun.LateResolveValues);
423 else
424 InsertValue(V, CurModule.LateResolveValues);
425 return V;
426}
427
428/// getBBVal - This is used for two purposes:
429/// * If isDefinition is true, a new basic block with the specified ID is being
430/// defined.
431/// * If isDefinition is true, this is a reference to a basic block, which may
432/// or may not be a forward reference.
433///
434static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
435 assert(inFunctionScope() && "Can't get basic block at global scope");
436
437 std::string Name;
438 BasicBlock *BB = 0;
439 switch (ID.Type) {
440 default:
441 error("Illegal label reference " + ID.getName());
442 break;
443 case ValID::NumberVal: // Is it a numbered definition?
444 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
445 CurFun.NumberedBlocks.resize(ID.Num+1);
446 BB = CurFun.NumberedBlocks[ID.Num];
447 break;
448 case ValID::NameVal: // Is it a named definition?
449 Name = ID.Name;
450 if (Value *N = CurFun.CurrentFunction->
451 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
452 if (N->getType() != Type::LabelTy)
453 error("Name '" + Name + "' does not refer to a BasicBlock");
454 BB = cast<BasicBlock>(N);
455 }
456 break;
457 }
458
459 // See if the block has already been defined.
460 if (BB) {
461 // If this is the definition of the block, make sure the existing value was
462 // just a forward reference. If it was a forward reference, there will be
463 // an entry for it in the PlaceHolderInfo map.
464 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
465 // The existing value was a definition, not a forward reference.
466 error("Redefinition of label " + ID.getName());
467
468 ID.destroy(); // Free strdup'd memory.
469 return BB;
470 }
471
472 // Otherwise this block has not been seen before.
473 BB = new BasicBlock("", CurFun.CurrentFunction);
474 if (ID.Type == ValID::NameVal) {
475 BB->setName(ID.Name);
476 } else {
477 CurFun.NumberedBlocks[ID.Num] = BB;
478 }
479
480 // If this is not a definition, keep track of it so we can use it as a forward
481 // reference.
482 if (!isDefinition) {
483 // Remember where this forward reference came from.
484 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
485 } else {
486 // The forward declaration could have been inserted anywhere in the
487 // function: insert it into the correct place now.
488 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
489 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
490 }
491 ID.destroy();
492 return BB;
493}
494
495
496//===----------------------------------------------------------------------===//
497// Code to handle forward references in instructions
498//===----------------------------------------------------------------------===//
499//
500// This code handles the late binding needed with statements that reference
501// values not defined yet... for example, a forward branch, or the PHI node for
502// a loop body.
503//
504// This keeps a table (CurFun.LateResolveValues) of all such forward references
505// and back patchs after we are done.
506//
507
Reid Spencer7de2e012007-01-29 19:08:46 +0000508/// This function determines if two function types differ only in their use of
509/// the sret parameter attribute in the first argument. If they are identical
510/// in all other respects, it returns true. Otherwise, it returns false.
511bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
512 const FunctionType *F2) {
513 if (F1->getReturnType() != F2->getReturnType() ||
514 F1->getNumParams() != F2->getNumParams() ||
515 F1->getParamAttrs(0) != F2->getParamAttrs(0))
516 return false;
517 unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
518 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
519 if (F1->getParamType(i) != F2->getParamType(i) ||
520 unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
521 unsigned(F2->getParamAttrs(i+1)) & SRetMask)
522 return false;
523 }
524 return true;
525}
526
Reid Spencer950bf602007-01-26 08:19:09 +0000527// ResolveDefinitions - If we could not resolve some defs at parsing
528// time (forward branches, phi functions for loops, etc...) resolve the
529// defs now...
530//
531static void
532ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
533 std::map<const Type*,ValueList> *FutureLateResolvers) {
534 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
535 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
536 E = LateResolvers.end(); LRI != E; ++LRI) {
537 ValueList &List = LRI->second;
538 while (!List.empty()) {
539 Value *V = List.back();
540 List.pop_back();
541
542 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
543 CurModule.PlaceHolderInfo.find(V);
544 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
545
546 ValID &DID = PHI->second.first;
547
548 Value *TheRealValue = getExistingValue(LRI->first, DID);
549 if (TheRealValue) {
550 V->replaceAllUsesWith(TheRealValue);
551 delete V;
552 CurModule.PlaceHolderInfo.erase(PHI);
553 } else if (FutureLateResolvers) {
554 // Functions have their unresolved items forwarded to the module late
555 // resolver table
556 InsertValue(V, *FutureLateResolvers);
557 } else {
558 if (DID.Type == ValID::NameVal) {
Reid Spencer7de2e012007-01-29 19:08:46 +0000559 // The upgrade of csretcc to sret param attribute may have caused a
560 // function to not be found because the param attribute changed the
561 // type of the called function. Detect this situation and insert a
562 // cast as necessary.
563 bool fixed = false;
564 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
565 if (const FunctionType *FTy =
566 dyn_cast<FunctionType>(PTy->getElementType()))
567 if (Function *OtherF =
568 CurModule.CurrentModule->getNamedFunction(DID.getName()))
569 if (FuncTysDifferOnlyBySRet(FTy,OtherF->getFunctionType())) {
570 V->replaceAllUsesWith(ConstantExpr::getBitCast(OtherF, PTy));
571 fixed = true;
572 }
573 if (!fixed) {
574 error("Reference to an invalid definition: '" +DID.getName()+
575 "' of type '" + V->getType()->getDescription() + "'",
576 PHI->second.second);
577 return;
578 }
Reid Spencer950bf602007-01-26 08:19:09 +0000579 } else {
580 error("Reference to an invalid definition: #" +
581 itostr(DID.Num) + " of type '" +
582 V->getType()->getDescription() + "'", PHI->second.second);
583 return;
584 }
585 }
586 }
587 }
588
589 LateResolvers.clear();
590}
591
592// ResolveTypeTo - A brand new type was just declared. This means that (if
593// name is not null) things referencing Name can be resolved. Otherwise, things
594// refering to the number can be resolved. Do this now.
595//
596static void ResolveTypeTo(char *Name, const Type *ToTy) {
597 ValID D;
598 if (Name) D = ValID::create(Name);
599 else D = ValID::create((int)CurModule.Types.size());
600
601 std::map<ValID, PATypeHolder>::iterator I =
602 CurModule.LateResolveTypes.find(D);
603 if (I != CurModule.LateResolveTypes.end()) {
604 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
605 CurModule.LateResolveTypes.erase(I);
606 }
607}
608
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000609/// @brief This just makes any name given to it unique, up to MAX_UINT times.
Reid Spencer950bf602007-01-26 08:19:09 +0000610static std::string makeNameUnique(const std::string& Name) {
611 static unsigned UniqueNameCounter = 1;
612 std::string Result(Name);
613 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
614 return Result;
615}
616
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000617/// This is the implementation portion of TypeHasInteger. It traverses the
618/// type given, avoiding recursive types, and returns true as soon as it finds
619/// an integer type. If no integer type is found, it returns false.
620static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
621 // Handle some easy cases
622 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
623 return false;
624 if (Ty->isInteger())
625 return true;
626 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
627 return STy->getElementType()->isInteger();
628
629 // Avoid type structure recursion
630 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
631 I != E; ++I)
632 if (Ty == *I)
633 return false;
634
635 // Push us on the type stack
636 Stack.push_back(Ty);
637
638 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
639 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
640 return true;
641 FunctionType::param_iterator I = FTy->param_begin();
642 FunctionType::param_iterator E = FTy->param_end();
643 for (; I != E; ++I)
644 if (TypeHasIntegerI(*I, Stack))
645 return true;
646 return false;
647 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
648 StructType::element_iterator I = STy->element_begin();
649 StructType::element_iterator E = STy->element_end();
650 for (; I != E; ++I) {
651 if (TypeHasIntegerI(*I, Stack))
652 return true;
653 }
654 return false;
655 }
656 // There shouldn't be anything else, but its definitely not integer
657 assert(0 && "What type is this?");
658 return false;
659}
660
661/// This is the interface to TypeHasIntegerI. It just provides the type stack,
662/// to avoid recursion, and then calls TypeHasIntegerI.
663static inline bool TypeHasInteger(const Type *Ty) {
664 std::vector<const Type*> TyStack;
665 return TypeHasIntegerI(Ty, TyStack);
666}
667
Reid Spencer950bf602007-01-26 08:19:09 +0000668// setValueName - Set the specified value to the name given. The name may be
669// null potentially, in which case this is a noop. The string passed in is
670// assumed to be a malloc'd string buffer, and is free'd by this function.
671//
672static void setValueName(Value *V, char *NameStr) {
673 if (NameStr) {
674 std::string Name(NameStr); // Copy string
675 free(NameStr); // Free old string
676
677 if (V->getType() == Type::VoidTy) {
678 error("Can't assign name '" + Name + "' to value with void type");
679 return;
680 }
681
Reid Spencer950bf602007-01-26 08:19:09 +0000682 assert(inFunctionScope() && "Must be in function scope");
683
684 // Search the function's symbol table for an existing value of this name
685 Value* Existing = 0;
686 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
687 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
688 for ( ; PI != PE; ++PI) {
689 SymbolTable::value_const_iterator VI = PI->second.find(Name);
690 if (VI != PI->second.end()) {
691 Existing = VI->second;
692 break;
693 }
694 }
695 if (Existing) {
Anton Korobeynikovce13b852007-01-28 15:25:24 +0000696 // An existing value of the same name was found. This might have happened
697 // because of the integer type planes collapsing in LLVM 2.0.
698 if (Existing->getType() == V->getType() &&
699 !TypeHasInteger(Existing->getType())) {
700 // If the type does not contain any integers in them then this can't be
701 // a type plane collapsing issue. It truly is a redefinition and we
702 // should error out as the assembly is invalid.
703 error("Redefinition of value named '" + Name + "' of type '" +
704 V->getType()->getDescription() + "'");
705 return;
Reid Spencer950bf602007-01-26 08:19:09 +0000706 }
707 // In LLVM 2.0 we don't allow names to be re-used for any values in a
708 // function, regardless of Type. Previously re-use of names was okay as
709 // long as they were distinct types. With type planes collapsing because
710 // of the signedness change and because of PR411, this can no longer be
711 // supported. We must search the entire symbol table for a conflicting
712 // name and make the name unique. No warning is needed as this can't
713 // cause a problem.
714 std::string NewName = makeNameUnique(Name);
715 // We're changing the name but it will probably be used by other
716 // instructions as operands later on. Consequently we have to retain
717 // a mapping of the renaming that we're doing.
718 RenameMapKey Key = std::make_pair(Name,V->getType());
719 CurFun.RenameMap[Key] = NewName;
720 Name = NewName;
721 }
722
723 // Set the name.
724 V->setName(Name);
725 }
726}
727
728/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
729/// this is a declaration, otherwise it is a definition.
730static GlobalVariable *
731ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
732 bool isConstantGlobal, const Type *Ty,
733 Constant *Initializer) {
734 if (isa<FunctionType>(Ty))
735 error("Cannot declare global vars of function type");
736
737 const PointerType *PTy = PointerType::get(Ty);
738
739 std::string Name;
740 if (NameStr) {
741 Name = NameStr; // Copy string
742 free(NameStr); // Free old string
743 }
744
745 // See if this global value was forward referenced. If so, recycle the
746 // object.
747 ValID ID;
748 if (!Name.empty()) {
749 ID = ValID::create((char*)Name.c_str());
750 } else {
751 ID = ValID::create((int)CurModule.Values[PTy].size());
752 }
753
754 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
755 // Move the global to the end of the list, from whereever it was
756 // previously inserted.
757 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
758 CurModule.CurrentModule->getGlobalList().remove(GV);
759 CurModule.CurrentModule->getGlobalList().push_back(GV);
760 GV->setInitializer(Initializer);
761 GV->setLinkage(Linkage);
762 GV->setConstant(isConstantGlobal);
763 InsertValue(GV, CurModule.Values);
764 return GV;
765 }
766
767 // If this global has a name, check to see if there is already a definition
768 // of this global in the module and emit warnings if there are conflicts.
769 if (!Name.empty()) {
770 // The global has a name. See if there's an existing one of the same name.
771 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
772 // We found an existing global ov the same name. This isn't allowed
773 // in LLVM 2.0. Consequently, we must alter the name of the global so it
774 // can at least compile. This can happen because of type planes
775 // There is alread a global of the same name which means there is a
776 // conflict. Let's see what we can do about it.
777 std::string NewName(makeNameUnique(Name));
778 if (Linkage == GlobalValue::InternalLinkage) {
779 // The linkage type is internal so just warn about the rename without
780 // invoking "scarey language" about linkage failures. GVars with
781 // InternalLinkage can be renamed at will.
782 warning("Global variable '" + Name + "' was renamed to '"+
783 NewName + "'");
784 } else {
785 // The linkage of this gval is external so we can't reliably rename
786 // it because it could potentially create a linking problem.
787 // However, we can't leave the name conflict in the output either or
788 // it won't assemble with LLVM 2.0. So, all we can do is rename
789 // this one to something unique and emit a warning about the problem.
790 warning("Renaming global variable '" + Name + "' to '" + NewName +
791 "' may cause linkage errors");
792 }
793
794 // Put the renaming in the global rename map
795 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
796 CurModule.RenameMap[Key] = NewName;
797
798 // Rename it
799 Name = NewName;
800 }
801 }
802
803 // Otherwise there is no existing GV to use, create one now.
804 GlobalVariable *GV =
805 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
806 CurModule.CurrentModule);
807 InsertValue(GV, CurModule.Values);
808 return GV;
809}
810
811// setTypeName - Set the specified type to the name given. The name may be
812// null potentially, in which case this is a noop. The string passed in is
813// assumed to be a malloc'd string buffer, and is freed by this function.
814//
815// This function returns true if the type has already been defined, but is
816// allowed to be redefined in the specified context. If the name is a new name
817// for the type plane, it is inserted and false is returned.
818static bool setTypeName(const Type *T, char *NameStr) {
819 assert(!inFunctionScope() && "Can't give types function-local names");
820 if (NameStr == 0) return false;
821
822 std::string Name(NameStr); // Copy string
823 free(NameStr); // Free old string
824
825 // We don't allow assigning names to void type
826 if (T == Type::VoidTy) {
827 error("Can't assign name '" + Name + "' to the void type");
828 return false;
829 }
830
831 // Set the type name, checking for conflicts as we do so.
832 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
833
834 if (AlreadyExists) { // Inserting a name that is already defined???
835 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
836 assert(Existing && "Conflict but no matching type?");
837
838 // There is only one case where this is allowed: when we are refining an
839 // opaque type. In this case, Existing will be an opaque type.
840 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
841 // We ARE replacing an opaque type!
842 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
843 return true;
844 }
845
846 // Otherwise, this is an attempt to redefine a type. That's okay if
847 // the redefinition is identical to the original. This will be so if
848 // Existing and T point to the same Type object. In this one case we
849 // allow the equivalent redefinition.
850 if (Existing == T) return true; // Yes, it's equal.
851
852 // Any other kind of (non-equivalent) redefinition is an error.
853 error("Redefinition of type named '" + Name + "' in the '" +
854 T->getDescription() + "' type plane");
855 }
856
857 return false;
858}
859
860//===----------------------------------------------------------------------===//
861// Code for handling upreferences in type names...
862//
863
864// TypeContains - Returns true if Ty directly contains E in it.
865//
866static bool TypeContains(const Type *Ty, const Type *E) {
867 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
868 E) != Ty->subtype_end();
869}
870
871namespace {
872 struct UpRefRecord {
873 // NestingLevel - The number of nesting levels that need to be popped before
874 // this type is resolved.
875 unsigned NestingLevel;
876
877 // LastContainedTy - This is the type at the current binding level for the
878 // type. Every time we reduce the nesting level, this gets updated.
879 const Type *LastContainedTy;
880
881 // UpRefTy - This is the actual opaque type that the upreference is
882 // represented with.
883 OpaqueType *UpRefTy;
884
885 UpRefRecord(unsigned NL, OpaqueType *URTy)
886 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
887 };
888}
889
890// UpRefs - A list of the outstanding upreferences that need to be resolved.
891static std::vector<UpRefRecord> UpRefs;
892
893/// HandleUpRefs - Every time we finish a new layer of types, this function is
894/// called. It loops through the UpRefs vector, which is a list of the
895/// currently active types. For each type, if the up reference is contained in
896/// the newly completed type, we decrement the level count. When the level
897/// count reaches zero, the upreferenced type is the type that is passed in:
898/// thus we can complete the cycle.
899///
900static PATypeHolder HandleUpRefs(const Type *ty) {
901 // If Ty isn't abstract, or if there are no up-references in it, then there is
902 // nothing to resolve here.
903 if (!ty->isAbstract() || UpRefs.empty()) return ty;
904
905 PATypeHolder Ty(ty);
906 UR_OUT("Type '" << Ty->getDescription() <<
907 "' newly formed. Resolving upreferences.\n" <<
908 UpRefs.size() << " upreferences active!\n");
909
910 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
911 // to zero), we resolve them all together before we resolve them to Ty. At
912 // the end of the loop, if there is anything to resolve to Ty, it will be in
913 // this variable.
914 OpaqueType *TypeToResolve = 0;
915
916 for (unsigned i = 0; i != UpRefs.size(); ++i) {
917 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
918 << UpRefs[i].second->getDescription() << ") = "
919 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
920 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
921 // Decrement level of upreference
922 unsigned Level = --UpRefs[i].NestingLevel;
923 UpRefs[i].LastContainedTy = Ty;
924 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
925 if (Level == 0) { // Upreference should be resolved!
926 if (!TypeToResolve) {
927 TypeToResolve = UpRefs[i].UpRefTy;
928 } else {
929 UR_OUT(" * Resolving upreference for "
930 << UpRefs[i].second->getDescription() << "\n";
931 std::string OldName = UpRefs[i].UpRefTy->getDescription());
932 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
933 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
934 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
935 }
936 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
937 --i; // Do not skip the next element...
938 }
939 }
940 }
941
942 if (TypeToResolve) {
943 UR_OUT(" * Resolving upreference for "
944 << UpRefs[i].second->getDescription() << "\n";
945 std::string OldName = TypeToResolve->getDescription());
946 TypeToResolve->refineAbstractTypeTo(Ty);
947 }
948
949 return Ty;
950}
951
952static inline Instruction::TermOps
953getTermOp(TermOps op) {
954 switch (op) {
955 default : assert(0 && "Invalid OldTermOp");
956 case RetOp : return Instruction::Ret;
957 case BrOp : return Instruction::Br;
958 case SwitchOp : return Instruction::Switch;
959 case InvokeOp : return Instruction::Invoke;
960 case UnwindOp : return Instruction::Unwind;
961 case UnreachableOp: return Instruction::Unreachable;
962 }
963}
964
965static inline Instruction::BinaryOps
966getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
967 switch (op) {
968 default : assert(0 && "Invalid OldBinaryOps");
969 case SetEQ :
970 case SetNE :
971 case SetLE :
972 case SetGE :
973 case SetLT :
974 case SetGT : assert(0 && "Should use getCompareOp");
975 case AddOp : return Instruction::Add;
976 case SubOp : return Instruction::Sub;
977 case MulOp : return Instruction::Mul;
978 case DivOp : {
979 // This is an obsolete instruction so we must upgrade it based on the
980 // types of its operands.
981 bool isFP = Ty->isFloatingPoint();
982 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
983 // If its a packed type we want to use the element type
984 isFP = PTy->getElementType()->isFloatingPoint();
985 if (isFP)
986 return Instruction::FDiv;
987 else if (Sign == Signed)
988 return Instruction::SDiv;
989 return Instruction::UDiv;
990 }
991 case UDivOp : return Instruction::UDiv;
992 case SDivOp : return Instruction::SDiv;
993 case FDivOp : return Instruction::FDiv;
994 case RemOp : {
995 // This is an obsolete instruction so we must upgrade it based on the
996 // types of its operands.
997 bool isFP = Ty->isFloatingPoint();
998 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
999 // If its a packed type we want to use the element type
1000 isFP = PTy->getElementType()->isFloatingPoint();
1001 // Select correct opcode
1002 if (isFP)
1003 return Instruction::FRem;
1004 else if (Sign == Signed)
1005 return Instruction::SRem;
1006 return Instruction::URem;
1007 }
1008 case URemOp : return Instruction::URem;
1009 case SRemOp : return Instruction::SRem;
1010 case FRemOp : return Instruction::FRem;
Reid Spencer832254e2007-02-02 02:16:23 +00001011 case LShrOp : return Instruction::LShr;
1012 case AShrOp : return Instruction::AShr;
1013 case ShlOp : return Instruction::Shl;
1014 case ShrOp :
1015 if (Sign == Signed)
1016 return Instruction::AShr;
1017 return Instruction::LShr;
Reid Spencer950bf602007-01-26 08:19:09 +00001018 case AndOp : return Instruction::And;
1019 case OrOp : return Instruction::Or;
1020 case XorOp : return Instruction::Xor;
1021 }
1022}
1023
1024static inline Instruction::OtherOps
1025getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1026 Signedness Sign) {
1027 bool isSigned = Sign == Signed;
1028 bool isFP = Ty->isFloatingPoint();
1029 switch (op) {
1030 default : assert(0 && "Invalid OldSetCC");
1031 case SetEQ :
1032 if (isFP) {
1033 predicate = FCmpInst::FCMP_OEQ;
1034 return Instruction::FCmp;
1035 } else {
1036 predicate = ICmpInst::ICMP_EQ;
1037 return Instruction::ICmp;
1038 }
1039 case SetNE :
1040 if (isFP) {
1041 predicate = FCmpInst::FCMP_UNE;
1042 return Instruction::FCmp;
1043 } else {
1044 predicate = ICmpInst::ICMP_NE;
1045 return Instruction::ICmp;
1046 }
1047 case SetLE :
1048 if (isFP) {
1049 predicate = FCmpInst::FCMP_OLE;
1050 return Instruction::FCmp;
1051 } else {
1052 if (isSigned)
1053 predicate = ICmpInst::ICMP_SLE;
1054 else
1055 predicate = ICmpInst::ICMP_ULE;
1056 return Instruction::ICmp;
1057 }
1058 case SetGE :
1059 if (isFP) {
1060 predicate = FCmpInst::FCMP_OGE;
1061 return Instruction::FCmp;
1062 } else {
1063 if (isSigned)
1064 predicate = ICmpInst::ICMP_SGE;
1065 else
1066 predicate = ICmpInst::ICMP_UGE;
1067 return Instruction::ICmp;
1068 }
1069 case SetLT :
1070 if (isFP) {
1071 predicate = FCmpInst::FCMP_OLT;
1072 return Instruction::FCmp;
1073 } else {
1074 if (isSigned)
1075 predicate = ICmpInst::ICMP_SLT;
1076 else
1077 predicate = ICmpInst::ICMP_ULT;
1078 return Instruction::ICmp;
1079 }
1080 case SetGT :
1081 if (isFP) {
1082 predicate = FCmpInst::FCMP_OGT;
1083 return Instruction::FCmp;
1084 } else {
1085 if (isSigned)
1086 predicate = ICmpInst::ICMP_SGT;
1087 else
1088 predicate = ICmpInst::ICMP_UGT;
1089 return Instruction::ICmp;
1090 }
1091 }
1092}
1093
1094static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1095 switch (op) {
1096 default : assert(0 && "Invalid OldMemoryOps");
1097 case MallocOp : return Instruction::Malloc;
1098 case FreeOp : return Instruction::Free;
1099 case AllocaOp : return Instruction::Alloca;
1100 case LoadOp : return Instruction::Load;
1101 case StoreOp : return Instruction::Store;
1102 case GetElementPtrOp : return Instruction::GetElementPtr;
1103 }
1104}
1105
1106static inline Instruction::OtherOps
1107getOtherOp(OtherOps op, Signedness Sign) {
1108 switch (op) {
1109 default : assert(0 && "Invalid OldOtherOps");
1110 case PHIOp : return Instruction::PHI;
1111 case CallOp : return Instruction::Call;
Reid Spencer950bf602007-01-26 08:19:09 +00001112 case SelectOp : return Instruction::Select;
1113 case UserOp1 : return Instruction::UserOp1;
1114 case UserOp2 : return Instruction::UserOp2;
1115 case VAArg : return Instruction::VAArg;
1116 case ExtractElementOp : return Instruction::ExtractElement;
1117 case InsertElementOp : return Instruction::InsertElement;
1118 case ShuffleVectorOp : return Instruction::ShuffleVector;
1119 case ICmpOp : return Instruction::ICmp;
1120 case FCmpOp : return Instruction::FCmp;
Reid Spencer950bf602007-01-26 08:19:09 +00001121 };
1122}
1123
1124static inline Value*
1125getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1126 Signedness DstSign, bool ForceInstruction = false) {
1127 Instruction::CastOps Opcode;
1128 const Type* SrcTy = Src->getType();
1129 if (op == CastOp) {
1130 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1131 // fp -> ptr cast is no longer supported but we must upgrade this
1132 // by doing a double cast: fp -> int -> ptr
1133 SrcTy = Type::Int64Ty;
1134 Opcode = Instruction::IntToPtr;
1135 if (isa<Constant>(Src)) {
1136 Src = ConstantExpr::getCast(Instruction::FPToUI,
1137 cast<Constant>(Src), SrcTy);
1138 } else {
1139 std::string NewName(makeNameUnique(Src->getName()));
1140 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1141 }
1142 } else if (isa<IntegerType>(DstTy) &&
1143 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1144 // cast type %x to bool was previously defined as setne type %x, null
1145 // The cast semantic is now to truncate, not compare so we must retain
1146 // the original intent by replacing the cast with a setne
1147 Constant* Null = Constant::getNullValue(SrcTy);
1148 Instruction::OtherOps Opcode = Instruction::ICmp;
1149 unsigned short predicate = ICmpInst::ICMP_NE;
1150 if (SrcTy->isFloatingPoint()) {
1151 Opcode = Instruction::FCmp;
1152 predicate = FCmpInst::FCMP_ONE;
1153 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1154 error("Invalid cast to bool");
1155 }
1156 if (isa<Constant>(Src) && !ForceInstruction)
1157 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1158 else
1159 return CmpInst::create(Opcode, predicate, Src, Null);
1160 }
1161 // Determine the opcode to use by calling CastInst::getCastOpcode
1162 Opcode =
1163 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1164
1165 } else switch (op) {
1166 default: assert(0 && "Invalid cast token");
1167 case TruncOp: Opcode = Instruction::Trunc; break;
1168 case ZExtOp: Opcode = Instruction::ZExt; break;
1169 case SExtOp: Opcode = Instruction::SExt; break;
1170 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1171 case FPExtOp: Opcode = Instruction::FPExt; break;
1172 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1173 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1174 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1175 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1176 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1177 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1178 case BitCastOp: Opcode = Instruction::BitCast; break;
1179 }
1180
1181 if (isa<Constant>(Src) && !ForceInstruction)
1182 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1183 return CastInst::create(Opcode, Src, DstTy);
1184}
1185
1186static Instruction *
1187upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1188 std::vector<Value*>& Args) {
1189
1190 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1191 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1192 if (Args.size() != 2)
1193 error("Invalid prototype for " + Name + " prototype");
1194 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1195 } else {
Reid Spencer950bf602007-01-26 08:19:09 +00001196 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1197 std::vector<const Type*> Params;
1198 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1199 if (Args.size() != 1)
1200 error("Invalid prototype for " + Name + " prototype");
1201 Params.push_back(PtrTy);
1202 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1203 const PointerType *PFTy = PointerType::get(FTy);
1204 Value* Func = getVal(PFTy, ID);
Reid Spencer832254e2007-02-02 02:16:23 +00001205 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
Reid Spencer950bf602007-01-26 08:19:09 +00001206 return new CallInst(Func, Args);
1207 } else if (Name == "llvm.va_copy") {
1208 if (Args.size() != 2)
1209 error("Invalid prototype for " + Name + " prototype");
1210 Params.push_back(PtrTy);
1211 Params.push_back(PtrTy);
1212 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1213 const PointerType *PFTy = PointerType::get(FTy);
1214 Value* Func = getVal(PFTy, ID);
Reid Spencer832254e2007-02-02 02:16:23 +00001215 std::string InstName0(makeNameUnique("va0"));
1216 std::string InstName1(makeNameUnique("va1"));
Reid Spencer950bf602007-01-26 08:19:09 +00001217 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1218 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1219 return new CallInst(Func, Args);
1220 }
1221 }
1222 return 0;
1223}
1224
1225const Type* upgradeGEPIndices(const Type* PTy,
1226 std::vector<ValueInfo> *Indices,
1227 std::vector<Value*> &VIndices,
1228 std::vector<Constant*> *CIndices = 0) {
1229 // Traverse the indices with a gep_type_iterator so we can build the list
1230 // of constant and value indices for use later. Also perform upgrades
1231 VIndices.clear();
1232 if (CIndices) CIndices->clear();
1233 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1234 VIndices.push_back((*Indices)[i].V);
1235 generic_gep_type_iterator<std::vector<Value*>::iterator>
1236 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1237 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1238 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1239 Value *Index = VIndices[i];
1240 if (CIndices && !isa<Constant>(Index))
1241 error("Indices to constant getelementptr must be constants");
1242 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1243 // struct indices to i32 struct indices with ZExt for compatibility.
1244 else if (isa<StructType>(*GTI)) { // Only change struct indices
1245 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1246 if (CUI->getType()->getBitWidth() == 8)
1247 Index =
1248 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1249 } else {
1250 // Make sure that unsigned SequentialType indices are zext'd to
1251 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1252 // all indices for SequentialType elements. We must retain the same
1253 // semantic (zext) for unsigned types.
1254 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
Reid Spencer38f682b2007-01-26 20:31:18 +00001255 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
Reid Spencer950bf602007-01-26 08:19:09 +00001256 if (CIndices)
1257 Index = ConstantExpr::getCast(Instruction::ZExt,
1258 cast<Constant>(Index), Type::Int64Ty);
1259 else
1260 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
Reid Spencer832254e2007-02-02 02:16:23 +00001261 makeNameUnique("gep"), CurBB);
Reid Spencer38f682b2007-01-26 20:31:18 +00001262 VIndices[i] = Index;
1263 }
Reid Spencer950bf602007-01-26 08:19:09 +00001264 }
1265 // Add to the CIndices list, if requested.
1266 if (CIndices)
1267 CIndices->push_back(cast<Constant>(Index));
1268 }
1269
1270 const Type *IdxTy =
1271 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1272 if (!IdxTy)
1273 error("Index list invalid for constant getelementptr");
1274 return IdxTy;
1275}
1276
Reid Spencerb7046c72007-01-29 05:41:34 +00001277unsigned upgradeCallingConv(unsigned CC) {
1278 switch (CC) {
1279 case OldCallingConv::C : return CallingConv::C;
1280 case OldCallingConv::CSRet : return CallingConv::C;
1281 case OldCallingConv::Fast : return CallingConv::Fast;
1282 case OldCallingConv::Cold : return CallingConv::Cold;
1283 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1284 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1285 default:
1286 return CC;
1287 }
1288}
1289
Reid Spencer950bf602007-01-26 08:19:09 +00001290Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1291 bool debug, bool addAttrs)
Reid Spencere7c3c602006-11-30 06:36:44 +00001292{
1293 Upgradelineno = 1;
1294 CurFilename = infile;
Reid Spencer96839be2006-11-30 16:50:26 +00001295 LexInput = &in;
Reid Spencere77e35e2006-12-01 20:26:20 +00001296 yydebug = debug;
Reid Spencer71d2ec92006-12-31 06:02:26 +00001297 AddAttributes = addAttrs;
Reid Spencer950bf602007-01-26 08:19:09 +00001298 ObsoleteVarArgs = false;
1299 NewVarArgs = false;
Reid Spencere7c3c602006-11-30 06:36:44 +00001300
Reid Spencer950bf602007-01-26 08:19:09 +00001301 CurModule.CurrentModule = new Module(CurFilename);
1302
1303 // Check to make sure the parser succeeded
Reid Spencere7c3c602006-11-30 06:36:44 +00001304 if (yyparse()) {
Reid Spencer950bf602007-01-26 08:19:09 +00001305 if (ParserResult)
1306 delete ParserResult;
Reid Spencer30d0c582007-01-15 00:26:18 +00001307 std::cerr << "llvm-upgrade: parse failed.\n";
Reid Spencer30d0c582007-01-15 00:26:18 +00001308 return 0;
1309 }
1310
Reid Spencer950bf602007-01-26 08:19:09 +00001311 // Check to make sure that parsing produced a result
1312 if (!ParserResult) {
1313 std::cerr << "llvm-upgrade: no parse result.\n";
1314 return 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001315 }
1316
Reid Spencer950bf602007-01-26 08:19:09 +00001317 // Reset ParserResult variable while saving its value for the result.
1318 Module *Result = ParserResult;
1319 ParserResult = 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001320
Reid Spencer950bf602007-01-26 08:19:09 +00001321 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
Reid Spencer30d0c582007-01-15 00:26:18 +00001322 {
Reid Spencer950bf602007-01-26 08:19:09 +00001323 Function* F;
1324 if ((F = Result->getNamedFunction("llvm.va_start"))
1325 && F->getFunctionType()->getNumParams() == 0)
1326 ObsoleteVarArgs = true;
1327 if((F = Result->getNamedFunction("llvm.va_copy"))
1328 && F->getFunctionType()->getNumParams() == 1)
1329 ObsoleteVarArgs = true;
Reid Spencer280d8012006-12-01 23:40:53 +00001330 }
Reid Spencer319a7302007-01-05 17:20:02 +00001331
Reid Spencer950bf602007-01-26 08:19:09 +00001332 if (ObsoleteVarArgs && NewVarArgs) {
1333 error("This file is corrupt: it uses both new and old style varargs");
1334 return 0;
Reid Spencer319a7302007-01-05 17:20:02 +00001335 }
Reid Spencer319a7302007-01-05 17:20:02 +00001336
Reid Spencer950bf602007-01-26 08:19:09 +00001337 if(ObsoleteVarArgs) {
1338 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1339 if (F->arg_size() != 0) {
1340 error("Obsolete va_start takes 0 argument");
Reid Spencer319a7302007-01-05 17:20:02 +00001341 return 0;
1342 }
Reid Spencer950bf602007-01-26 08:19:09 +00001343
1344 //foo = va_start()
1345 // ->
1346 //bar = alloca typeof(foo)
1347 //va_start(bar)
1348 //foo = load bar
Reid Spencer319a7302007-01-05 17:20:02 +00001349
Reid Spencer950bf602007-01-26 08:19:09 +00001350 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1351 const Type* ArgTy = F->getFunctionType()->getReturnType();
1352 const Type* ArgTyPtr = PointerType::get(ArgTy);
1353 Function* NF = cast<Function>(Result->getOrInsertFunction(
1354 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1355
1356 while (!F->use_empty()) {
1357 CallInst* CI = cast<CallInst>(F->use_back());
1358 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1359 new CallInst(NF, bar, "", CI);
1360 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1361 CI->replaceAllUsesWith(foo);
1362 CI->getParent()->getInstList().erase(CI);
Reid Spencerf8383de2007-01-06 06:04:32 +00001363 }
Reid Spencer950bf602007-01-26 08:19:09 +00001364 Result->getFunctionList().erase(F);
Reid Spencerf8383de2007-01-06 06:04:32 +00001365 }
Reid Spencer950bf602007-01-26 08:19:09 +00001366
1367 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1368 if(F->arg_size() != 1) {
1369 error("Obsolete va_end takes 1 argument");
1370 return 0;
Reid Spencerf8383de2007-01-06 06:04:32 +00001371 }
Reid Spencerf8383de2007-01-06 06:04:32 +00001372
Reid Spencer950bf602007-01-26 08:19:09 +00001373 //vaend foo
1374 // ->
1375 //bar = alloca 1 of typeof(foo)
1376 //vaend bar
1377 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1378 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1379 const Type* ArgTyPtr = PointerType::get(ArgTy);
1380 Function* NF = cast<Function>(Result->getOrInsertFunction(
1381 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
Reid Spencerf8383de2007-01-06 06:04:32 +00001382
Reid Spencer950bf602007-01-26 08:19:09 +00001383 while (!F->use_empty()) {
1384 CallInst* CI = cast<CallInst>(F->use_back());
1385 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1386 new StoreInst(CI->getOperand(1), bar, CI);
1387 new CallInst(NF, bar, "", CI);
1388 CI->getParent()->getInstList().erase(CI);
Reid Spencere77e35e2006-12-01 20:26:20 +00001389 }
Reid Spencer950bf602007-01-26 08:19:09 +00001390 Result->getFunctionList().erase(F);
Reid Spencere77e35e2006-12-01 20:26:20 +00001391 }
Reid Spencer950bf602007-01-26 08:19:09 +00001392
1393 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1394 if(F->arg_size() != 1) {
1395 error("Obsolete va_copy takes 1 argument");
1396 return 0;
Reid Spencere77e35e2006-12-01 20:26:20 +00001397 }
Reid Spencer950bf602007-01-26 08:19:09 +00001398 //foo = vacopy(bar)
1399 // ->
1400 //a = alloca 1 of typeof(foo)
1401 //b = alloca 1 of typeof(foo)
1402 //store bar -> b
1403 //vacopy(a, b)
1404 //foo = load a
1405
1406 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1407 const Type* ArgTy = F->getFunctionType()->getReturnType();
1408 const Type* ArgTyPtr = PointerType::get(ArgTy);
1409 Function* NF = cast<Function>(Result->getOrInsertFunction(
1410 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
Reid Spencere77e35e2006-12-01 20:26:20 +00001411
Reid Spencer950bf602007-01-26 08:19:09 +00001412 while (!F->use_empty()) {
1413 CallInst* CI = cast<CallInst>(F->use_back());
1414 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1415 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1416 new StoreInst(CI->getOperand(1), b, CI);
1417 new CallInst(NF, a, b, "", CI);
1418 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1419 CI->replaceAllUsesWith(foo);
1420 CI->getParent()->getInstList().erase(CI);
1421 }
1422 Result->getFunctionList().erase(F);
Reid Spencer319a7302007-01-05 17:20:02 +00001423 }
1424 }
1425
Reid Spencer52402b02007-01-02 05:45:11 +00001426 return Result;
1427}
1428
Reid Spencer950bf602007-01-26 08:19:09 +00001429} // end llvm namespace
Reid Spencer319a7302007-01-05 17:20:02 +00001430
Reid Spencer950bf602007-01-26 08:19:09 +00001431using namespace llvm;
Reid Spencer30d0c582007-01-15 00:26:18 +00001432
Reid Spencere7c3c602006-11-30 06:36:44 +00001433%}
1434
Reid Spencere77e35e2006-12-01 20:26:20 +00001435%union {
Reid Spencer950bf602007-01-26 08:19:09 +00001436 llvm::Module *ModuleVal;
1437 llvm::Function *FunctionVal;
1438 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1439 llvm::BasicBlock *BasicBlockVal;
1440 llvm::TerminatorInst *TermInstVal;
1441 llvm::InstrInfo InstVal;
1442 llvm::ConstInfo ConstVal;
1443 llvm::ValueInfo ValueVal;
1444 llvm::PATypeInfo TypeVal;
1445 llvm::TypeInfo PrimType;
1446 llvm::PHIListInfo PHIList;
1447 std::list<llvm::PATypeInfo> *TypeList;
1448 std::vector<llvm::ValueInfo> *ValueList;
1449 std::vector<llvm::ConstInfo> *ConstVector;
1450
1451
1452 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1453 // Represent the RHS of PHI node
1454 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1455
1456 llvm::GlobalValue::LinkageTypes Linkage;
1457 int64_t SInt64Val;
1458 uint64_t UInt64Val;
1459 int SIntVal;
1460 unsigned UIntVal;
1461 double FPVal;
1462 bool BoolVal;
1463
1464 char *StrVal; // This memory is strdup'd!
1465 llvm::ValID ValIDVal; // strdup'd memory maybe!
1466
1467 llvm::BinaryOps BinaryOpVal;
1468 llvm::TermOps TermOpVal;
1469 llvm::MemoryOps MemOpVal;
1470 llvm::OtherOps OtherOpVal;
1471 llvm::CastOps CastOpVal;
1472 llvm::ICmpInst::Predicate IPred;
1473 llvm::FCmpInst::Predicate FPred;
1474 llvm::Module::Endianness Endianness;
Reid Spencere77e35e2006-12-01 20:26:20 +00001475}
1476
Reid Spencer950bf602007-01-26 08:19:09 +00001477%type <ModuleVal> Module FunctionList
1478%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1479%type <BasicBlockVal> BasicBlock InstructionList
1480%type <TermInstVal> BBTerminatorInst
1481%type <InstVal> Inst InstVal MemoryInst
1482%type <ConstVal> ConstVal ConstExpr
1483%type <ConstVector> ConstVector
1484%type <ArgList> ArgList ArgListH
1485%type <ArgVal> ArgVal
1486%type <PHIList> PHIList
1487%type <ValueList> ValueRefList ValueRefListE // For call param lists
1488%type <ValueList> IndexList // For GEP derived indices
1489%type <TypeList> TypeListI ArgTypeListI
1490%type <JumpTable> JumpTable
1491%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1492%type <BoolVal> OptVolatile // 'volatile' or not
1493%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1494%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1495%type <Linkage> OptLinkage
1496%type <Endianness> BigOrLittle
Reid Spencere77e35e2006-12-01 20:26:20 +00001497
Reid Spencer950bf602007-01-26 08:19:09 +00001498// ValueRef - Unresolved reference to a definition or BB
1499%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1500%type <ValueVal> ResolvedVal // <type> <valref> pair
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001501
Reid Spencer950bf602007-01-26 08:19:09 +00001502// Tokens and types for handling constant integer values
1503//
1504// ESINT64VAL - A negative number within long long range
1505%token <SInt64Val> ESINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001506
Reid Spencer950bf602007-01-26 08:19:09 +00001507// EUINT64VAL - A positive number within uns. long long range
1508%token <UInt64Val> EUINT64VAL
1509%type <SInt64Val> EINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001510
Reid Spencer950bf602007-01-26 08:19:09 +00001511%token <SIntVal> SINTVAL // Signed 32 bit ints...
1512%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1513%type <SIntVal> INTVAL
1514%token <FPVal> FPVAL // Float or Double constant
Reid Spencere77e35e2006-12-01 20:26:20 +00001515
Reid Spencer950bf602007-01-26 08:19:09 +00001516// Built in types...
1517%type <TypeVal> Types TypesV UpRTypes UpRTypesV
1518%type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1519%token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1520%token <PrimType> FLOAT DOUBLE TYPE LABEL
Reid Spencere77e35e2006-12-01 20:26:20 +00001521
Reid Spencer950bf602007-01-26 08:19:09 +00001522%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1523%type <StrVal> Name OptName OptAssign
1524%type <UIntVal> OptAlign OptCAlign
1525%type <StrVal> OptSection SectionString
1526
1527%token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1528%token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1529%token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1530%token DLLIMPORT DLLEXPORT EXTERN_WEAK
1531%token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1532%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1533%token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1534%token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1535%token DATALAYOUT
1536%type <UIntVal> OptCallingConv
1537
1538// Basic Block Terminating Operators
1539%token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1540%token UNWIND EXCEPT
1541
1542// Binary Operators
1543%type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
Reid Spencer832254e2007-02-02 02:16:23 +00001544%type <BinaryOpVal> ShiftOps
Reid Spencer950bf602007-01-26 08:19:09 +00001545%token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
Reid Spencer832254e2007-02-02 02:16:23 +00001546%token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
Reid Spencer950bf602007-01-26 08:19:09 +00001547%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1548%token <OtherOpVal> ICMP FCMP
1549
1550// Memory Instructions
1551%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1552
1553// Other Operators
Reid Spencer832254e2007-02-02 02:16:23 +00001554%token <OtherOpVal> PHI_TOK SELECT VAARG
Reid Spencer950bf602007-01-26 08:19:09 +00001555%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1556%token VAARG_old VANEXT_old //OBSOLETE
1557
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001558// Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
Reid Spencer950bf602007-01-26 08:19:09 +00001559%type <IPred> IPredicates
1560%type <FPred> FPredicates
1561%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1562%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1563
1564%token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1565%token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1566%type <CastOpVal> CastOps
Reid Spencere7c3c602006-11-30 06:36:44 +00001567
1568%start Module
1569
1570%%
1571
1572// Handle constant integer size restriction and conversion...
Reid Spencer950bf602007-01-26 08:19:09 +00001573//
1574INTVAL
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001575 : SINTVAL
Reid Spencer950bf602007-01-26 08:19:09 +00001576 | UINTVAL {
1577 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1578 error("Value too large for type");
1579 $$ = (int32_t)$1;
1580 }
1581 ;
1582
1583EINT64VAL
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001584 : ESINT64VAL // These have same type and can't cause problems...
Reid Spencer950bf602007-01-26 08:19:09 +00001585 | EUINT64VAL {
1586 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1587 error("Value too large for type");
1588 $$ = (int64_t)$1;
1589 };
Reid Spencere7c3c602006-11-30 06:36:44 +00001590
1591// Operations that are notably excluded from this list include:
1592// RET, BR, & SWITCH because they end basic blocks and are treated specially.
Reid Spencer950bf602007-01-26 08:19:09 +00001593//
1594ArithmeticOps
1595 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1596 ;
1597
1598LogicalOps
1599 : AND | OR | XOR
1600 ;
1601
1602SetCondOps
1603 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1604 ;
1605
1606IPredicates
1607 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1608 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1609 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1610 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1611 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1612 ;
1613
1614FPredicates
1615 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1616 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1617 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1618 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1619 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1620 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1621 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1622 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1623 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1624 ;
1625ShiftOps
1626 : SHL | SHR | ASHR | LSHR
1627 ;
1628
1629CastOps
1630 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1631 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1632 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001633
1634// These are some types that allow classification if we only want a particular
1635// thing... for example, only a signed, unsigned, or integral type.
Reid Spencer950bf602007-01-26 08:19:09 +00001636SIntType
1637 : LONG | INT | SHORT | SBYTE
1638 ;
1639
1640UIntType
1641 : ULONG | UINT | USHORT | UBYTE
1642 ;
1643
1644IntType
1645 : SIntType | UIntType
1646 ;
1647
1648FPType
1649 : FLOAT | DOUBLE
1650 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001651
1652// OptAssign - Value producing statements have an optional assignment component
Reid Spencer950bf602007-01-26 08:19:09 +00001653OptAssign
1654 : Name '=' {
Reid Spencere7c3c602006-11-30 06:36:44 +00001655 $$ = $1;
1656 }
1657 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001658 $$ = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00001659 };
1660
1661OptLinkage
Reid Spencer950bf602007-01-26 08:19:09 +00001662 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1663 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1664 | WEAK { $$ = GlobalValue::WeakLinkage; }
1665 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1666 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1667 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1668 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1669 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1670 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001671
1672OptCallingConv
Reid Spencerb7046c72007-01-29 05:41:34 +00001673 : /*empty*/ { CurFun.LastCC = $$ = OldCallingConv::C; }
1674 | CCC_TOK { CurFun.LastCC = $$ = OldCallingConv::C; }
1675 | CSRETCC_TOK { CurFun.LastCC = $$ = OldCallingConv::CSRet; }
1676 | FASTCC_TOK { CurFun.LastCC = $$ = OldCallingConv::Fast; }
1677 | COLDCC_TOK { CurFun.LastCC = $$ = OldCallingConv::Cold; }
1678 | X86_STDCALLCC_TOK { CurFun.LastCC = $$ = OldCallingConv::X86_StdCall; }
1679 | X86_FASTCALLCC_TOK { CurFun.LastCC = $$ = OldCallingConv::X86_FastCall; }
Reid Spencer950bf602007-01-26 08:19:09 +00001680 | CC_TOK EUINT64VAL {
1681 if ((unsigned)$2 != $2)
1682 error("Calling conv too large");
1683 $$ = $2;
1684 }
1685 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001686
1687// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1688// a comma before it.
1689OptAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001690 : /*empty*/ { $$ = 0; }
1691 | ALIGN EUINT64VAL {
1692 $$ = $2;
1693 if ($$ != 0 && !isPowerOf2_32($$))
1694 error("Alignment must be a power of two");
1695 }
1696 ;
Reid Spencerf0cf1322006-12-07 04:23:03 +00001697
Reid Spencere7c3c602006-11-30 06:36:44 +00001698OptCAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001699 : /*empty*/ { $$ = 0; }
1700 | ',' ALIGN EUINT64VAL {
1701 $$ = $3;
1702 if ($$ != 0 && !isPowerOf2_32($$))
1703 error("Alignment must be a power of two");
1704 }
1705 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001706
1707SectionString
Reid Spencer950bf602007-01-26 08:19:09 +00001708 : SECTION STRINGCONSTANT {
1709 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1710 if ($2[i] == '"' || $2[i] == '\\')
1711 error("Invalid character in section name");
1712 $$ = $2;
1713 }
1714 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001715
Reid Spencer950bf602007-01-26 08:19:09 +00001716OptSection
1717 : /*empty*/ { $$ = 0; }
1718 | SectionString { $$ = $1; }
1719 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001720
Reid Spencer950bf602007-01-26 08:19:09 +00001721// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1722// is set to be the global we are processing.
1723//
Reid Spencere7c3c602006-11-30 06:36:44 +00001724GlobalVarAttributes
Reid Spencer950bf602007-01-26 08:19:09 +00001725 : /* empty */ {}
1726 | ',' GlobalVarAttribute GlobalVarAttributes {}
1727 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001728
Reid Spencer950bf602007-01-26 08:19:09 +00001729GlobalVarAttribute
1730 : SectionString {
1731 CurGV->setSection($1);
1732 free($1);
1733 }
1734 | ALIGN EUINT64VAL {
1735 if ($2 != 0 && !isPowerOf2_32($2))
1736 error("Alignment must be a power of two");
1737 CurGV->setAlignment($2);
1738
1739 }
1740 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001741
1742//===----------------------------------------------------------------------===//
1743// Types includes all predefined types... except void, because it can only be
1744// used in specific contexts (function returning void for example). To have
1745// access to it, a user must explicitly use TypesV.
1746//
1747
1748// TypesV includes all of 'Types', but it also includes the void type.
Reid Spencer950bf602007-01-26 08:19:09 +00001749TypesV
1750 : Types
1751 | VOID {
1752 $$.T = new PATypeHolder($1.T);
1753 $$.S = Signless;
1754 }
1755 ;
1756
1757UpRTypesV
1758 : UpRTypes
1759 | VOID {
1760 $$.T = new PATypeHolder($1.T);
1761 $$.S = Signless;
1762 }
1763 ;
1764
1765Types
1766 : UpRTypes {
1767 if (!UpRefs.empty())
1768 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1769 $$ = $1;
1770 }
1771 ;
1772
1773PrimType
1774 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1775 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1776 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001777
1778// Derived types are added later...
Reid Spencera50d5962006-12-02 04:11:07 +00001779UpRTypes
Reid Spencer950bf602007-01-26 08:19:09 +00001780 : PrimType {
1781 $$.T = new PATypeHolder($1.T);
1782 $$.S = $1.S;
Reid Spencera50d5962006-12-02 04:11:07 +00001783 }
Reid Spencer950bf602007-01-26 08:19:09 +00001784 | OPAQUE {
1785 $$.T = new PATypeHolder(OpaqueType::get());
1786 $$.S = Signless;
1787 }
1788 | SymbolicValueRef { // Named types are also simple types...
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00001789 const Type* tmp = getType($1);
Reid Spencer950bf602007-01-26 08:19:09 +00001790 $$.T = new PATypeHolder(tmp);
1791 $$.S = Signless; // FIXME: what if its signed?
Reid Spencer78720742006-12-02 20:21:22 +00001792 }
1793 | '\\' EUINT64VAL { // Type UpReference
Reid Spencer950bf602007-01-26 08:19:09 +00001794 if ($2 > (uint64_t)~0U)
1795 error("Value out of range");
1796 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1797 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1798 $$.T = new PATypeHolder(OT);
1799 $$.S = Signless;
1800 UR_OUT("New Upreference!\n");
Reid Spencere7c3c602006-11-30 06:36:44 +00001801 }
1802 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
Reid Spencer950bf602007-01-26 08:19:09 +00001803 std::vector<const Type*> Params;
1804 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1805 E = $3->end(); I != E; ++I) {
1806 Params.push_back(I->T->get());
1807 delete I->T;
Reid Spencer52402b02007-01-02 05:45:11 +00001808 }
Reid Spencerb7046c72007-01-29 05:41:34 +00001809 FunctionType::ParamAttrsList ParamAttrs;
1810 if (CurFun.LastCC == OldCallingConv::CSRet) {
1811 ParamAttrs.push_back(FunctionType::NoAttributeSet);
1812 ParamAttrs.push_back(FunctionType::StructRetAttribute);
1813 }
Reid Spencer950bf602007-01-26 08:19:09 +00001814 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1815 if (isVarArg) Params.pop_back();
1816
Reid Spencerb7046c72007-01-29 05:41:34 +00001817 $$.T = new PATypeHolder(
1818 HandleUpRefs(FunctionType::get($1.T->get(),Params,isVarArg, ParamAttrs)));
Reid Spencer950bf602007-01-26 08:19:09 +00001819 $$.S = $1.S;
1820 delete $1.T; // Delete the return type handle
1821 delete $3; // Delete the argument list
Reid Spencere7c3c602006-11-30 06:36:44 +00001822 }
1823 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
Reid Spencer950bf602007-01-26 08:19:09 +00001824 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1825 (unsigned)$2)));
1826 $$.S = $4.S;
1827 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001828 }
1829 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
Reid Spencer950bf602007-01-26 08:19:09 +00001830 const llvm::Type* ElemTy = $4.T->get();
1831 if ((unsigned)$2 != $2)
1832 error("Unsigned result not equal to signed result");
1833 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1834 error("Elements of a PackedType must be integer or floating point");
1835 if (!isPowerOf2_32($2))
1836 error("PackedType length should be a power of 2");
1837 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1838 (unsigned)$2)));
1839 $$.S = $4.S;
1840 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001841 }
1842 | '{' TypeListI '}' { // Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001843 std::vector<const Type*> Elements;
1844 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1845 E = $2->end(); I != E; ++I)
1846 Elements.push_back(I->T->get());
1847 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1848 $$.S = Signless;
1849 delete $2;
Reid Spencere7c3c602006-11-30 06:36:44 +00001850 }
1851 | '{' '}' { // Empty structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001852 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1853 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00001854 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001855 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001856 std::vector<const Type*> Elements;
1857 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1858 E = $3->end(); I != E; ++I) {
1859 Elements.push_back(I->T->get());
1860 delete I->T;
Reid Spencer52402b02007-01-02 05:45:11 +00001861 }
Reid Spencer950bf602007-01-26 08:19:09 +00001862 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1863 $$.S = Signless;
1864 delete $3;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001865 }
1866 | '<' '{' '}' '>' { // Empty packed structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001867 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1868 $$.S = Signless;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001869 }
Reid Spencere7c3c602006-11-30 06:36:44 +00001870 | UpRTypes '*' { // Pointer type?
Reid Spencer950bf602007-01-26 08:19:09 +00001871 if ($1.T->get() == Type::LabelTy)
1872 error("Cannot form a pointer to a basic block");
1873 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1874 $$.S = $1.S;
1875 delete $1.T;
1876 }
1877 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001878
1879// TypeList - Used for struct declarations and as a basis for function type
1880// declaration type lists
1881//
Reid Spencere77e35e2006-12-01 20:26:20 +00001882TypeListI
1883 : UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001884 $$ = new std::list<PATypeInfo>();
1885 $$->push_back($1);
Reid Spencere77e35e2006-12-01 20:26:20 +00001886 }
1887 | TypeListI ',' UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001888 ($$=$1)->push_back($3);
1889 }
1890 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001891
1892// ArgTypeList - List of types for a function type declaration...
Reid Spencere77e35e2006-12-01 20:26:20 +00001893ArgTypeListI
Reid Spencer950bf602007-01-26 08:19:09 +00001894 : TypeListI
Reid Spencere7c3c602006-11-30 06:36:44 +00001895 | TypeListI ',' DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001896 PATypeInfo VoidTI;
1897 VoidTI.T = new PATypeHolder(Type::VoidTy);
1898 VoidTI.S = Signless;
1899 ($$=$1)->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001900 }
1901 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001902 $$ = new std::list<PATypeInfo>();
1903 PATypeInfo VoidTI;
1904 VoidTI.T = new PATypeHolder(Type::VoidTy);
1905 VoidTI.S = Signless;
1906 $$->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001907 }
1908 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001909 $$ = new std::list<PATypeInfo>();
1910 }
1911 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001912
1913// ConstVal - The various declarations that go into the constant pool. This
1914// production is used ONLY to represent constants that show up AFTER a 'const',
1915// 'constant' or 'global' token at global scope. Constants that can be inlined
1916// into other expressions (such as integers and constexprs) are handled by the
1917// ResolvedVal, ValueRef and ConstValueRef productions.
1918//
Reid Spencer950bf602007-01-26 08:19:09 +00001919ConstVal
1920 : Types '[' ConstVector ']' { // Nonempty unsized arr
1921 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1922 if (ATy == 0)
1923 error("Cannot make array constant with type: '" +
1924 $1.T->get()->getDescription() + "'");
1925 const Type *ETy = ATy->getElementType();
1926 int NumElements = ATy->getNumElements();
1927
1928 // Verify that we have the correct size...
1929 if (NumElements != -1 && NumElements != (int)$3->size())
1930 error("Type mismatch: constant sized array initialized with " +
1931 utostr($3->size()) + " arguments, but has size of " +
1932 itostr(NumElements) + "");
1933
1934 // Verify all elements are correct type!
1935 std::vector<Constant*> Elems;
1936 for (unsigned i = 0; i < $3->size(); i++) {
1937 Constant *C = (*$3)[i].C;
1938 const Type* ValTy = C->getType();
1939 if (ETy != ValTy)
1940 error("Element #" + utostr(i) + " is not of type '" +
1941 ETy->getDescription() +"' as required!\nIt is of type '"+
1942 ValTy->getDescription() + "'");
1943 Elems.push_back(C);
1944 }
1945 $$.C = ConstantArray::get(ATy, Elems);
1946 $$.S = $1.S;
1947 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001948 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00001949 }
1950 | Types '[' ']' {
Reid Spencer950bf602007-01-26 08:19:09 +00001951 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1952 if (ATy == 0)
1953 error("Cannot make array constant with type: '" +
1954 $1.T->get()->getDescription() + "'");
1955 int NumElements = ATy->getNumElements();
1956 if (NumElements != -1 && NumElements != 0)
1957 error("Type mismatch: constant sized array initialized with 0"
1958 " arguments, but has size of " + itostr(NumElements) +"");
1959 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1960 $$.S = $1.S;
1961 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001962 }
1963 | Types 'c' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00001964 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1965 if (ATy == 0)
1966 error("Cannot make array constant with type: '" +
1967 $1.T->get()->getDescription() + "'");
1968 int NumElements = ATy->getNumElements();
1969 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1970 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1971 error("String arrays require type i8, not '" + ETy->getDescription() +
1972 "'");
1973 char *EndStr = UnEscapeLexed($3, true);
1974 if (NumElements != -1 && NumElements != (EndStr-$3))
1975 error("Can't build string constant of size " +
1976 itostr((int)(EndStr-$3)) + " when array has size " +
1977 itostr(NumElements) + "");
1978 std::vector<Constant*> Vals;
1979 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1980 Vals.push_back(ConstantInt::get(ETy, *C));
1981 free($3);
1982 $$.C = ConstantArray::get(ATy, Vals);
1983 $$.S = $1.S;
1984 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001985 }
1986 | Types '<' ConstVector '>' { // Nonempty unsized arr
Reid Spencer950bf602007-01-26 08:19:09 +00001987 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1988 if (PTy == 0)
1989 error("Cannot make packed constant with type: '" +
1990 $1.T->get()->getDescription() + "'");
1991 const Type *ETy = PTy->getElementType();
1992 int NumElements = PTy->getNumElements();
1993 // Verify that we have the correct size...
1994 if (NumElements != -1 && NumElements != (int)$3->size())
1995 error("Type mismatch: constant sized packed initialized with " +
1996 utostr($3->size()) + " arguments, but has size of " +
1997 itostr(NumElements) + "");
1998 // Verify all elements are correct type!
1999 std::vector<Constant*> Elems;
2000 for (unsigned i = 0; i < $3->size(); i++) {
2001 Constant *C = (*$3)[i].C;
2002 const Type* ValTy = C->getType();
2003 if (ETy != ValTy)
2004 error("Element #" + utostr(i) + " is not of type '" +
2005 ETy->getDescription() +"' as required!\nIt is of type '"+
2006 ValTy->getDescription() + "'");
2007 Elems.push_back(C);
2008 }
2009 $$.C = ConstantPacked::get(PTy, Elems);
2010 $$.S = $1.S;
2011 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002012 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002013 }
2014 | Types '{' ConstVector '}' {
Reid Spencer950bf602007-01-26 08:19:09 +00002015 const StructType *STy = dyn_cast<StructType>($1.T->get());
2016 if (STy == 0)
2017 error("Cannot make struct constant with type: '" +
2018 $1.T->get()->getDescription() + "'");
2019 if ($3->size() != STy->getNumContainedTypes())
2020 error("Illegal number of initializers for structure type");
2021
2022 // Check to ensure that constants are compatible with the type initializer!
2023 std::vector<Constant*> Fields;
2024 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2025 Constant *C = (*$3)[i].C;
2026 if (C->getType() != STy->getElementType(i))
2027 error("Expected type '" + STy->getElementType(i)->getDescription() +
2028 "' for element #" + utostr(i) + " of structure initializer");
2029 Fields.push_back(C);
2030 }
2031 $$.C = ConstantStruct::get(STy, Fields);
2032 $$.S = $1.S;
2033 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002034 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002035 }
2036 | Types '{' '}' {
Reid Spencer950bf602007-01-26 08:19:09 +00002037 const StructType *STy = dyn_cast<StructType>($1.T->get());
2038 if (STy == 0)
2039 error("Cannot make struct constant with type: '" +
2040 $1.T->get()->getDescription() + "'");
2041 if (STy->getNumContainedTypes() != 0)
2042 error("Illegal number of initializers for structure type");
2043 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2044 $$.S = $1.S;
2045 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002046 }
Reid Spencer950bf602007-01-26 08:19:09 +00002047 | Types '<' '{' ConstVector '}' '>' {
2048 const StructType *STy = dyn_cast<StructType>($1.T->get());
2049 if (STy == 0)
2050 error("Cannot make packed struct constant with type: '" +
2051 $1.T->get()->getDescription() + "'");
2052 if ($4->size() != STy->getNumContainedTypes())
2053 error("Illegal number of initializers for packed structure type");
Reid Spencere7c3c602006-11-30 06:36:44 +00002054
Reid Spencer950bf602007-01-26 08:19:09 +00002055 // Check to ensure that constants are compatible with the type initializer!
2056 std::vector<Constant*> Fields;
2057 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2058 Constant *C = (*$4)[i].C;
2059 if (C->getType() != STy->getElementType(i))
2060 error("Expected type '" + STy->getElementType(i)->getDescription() +
2061 "' for element #" + utostr(i) + " of packed struct initializer");
2062 Fields.push_back(C);
Reid Spencer280d8012006-12-01 23:40:53 +00002063 }
Reid Spencer950bf602007-01-26 08:19:09 +00002064 $$.C = ConstantStruct::get(STy, Fields);
2065 $$.S = $1.S;
2066 delete $1.T;
Reid Spencere77e35e2006-12-01 20:26:20 +00002067 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00002068 }
Reid Spencer950bf602007-01-26 08:19:09 +00002069 | Types '<' '{' '}' '>' {
2070 const StructType *STy = dyn_cast<StructType>($1.T->get());
2071 if (STy == 0)
2072 error("Cannot make packed struct constant with type: '" +
2073 $1.T->get()->getDescription() + "'");
2074 if (STy->getNumContainedTypes() != 0)
2075 error("Illegal number of initializers for packed structure type");
2076 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2077 $$.S = $1.S;
2078 delete $1.T;
2079 }
2080 | Types NULL_TOK {
2081 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
2082 if (PTy == 0)
2083 error("Cannot make null pointer constant with type: '" +
2084 $1.T->get()->getDescription() + "'");
2085 $$.C = ConstantPointerNull::get(PTy);
2086 $$.S = $1.S;
2087 delete $1.T;
2088 }
2089 | Types UNDEF {
2090 $$.C = UndefValue::get($1.T->get());
2091 $$.S = $1.S;
2092 delete $1.T;
2093 }
2094 | Types SymbolicValueRef {
2095 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
2096 if (Ty == 0)
2097 error("Global const reference must be a pointer type, not" +
2098 $1.T->get()->getDescription());
2099
2100 // ConstExprs can exist in the body of a function, thus creating
2101 // GlobalValues whenever they refer to a variable. Because we are in
2102 // the context of a function, getExistingValue will search the functions
2103 // symbol table instead of the module symbol table for the global symbol,
2104 // which throws things all off. To get around this, we just tell
2105 // getExistingValue that we are at global scope here.
2106 //
2107 Function *SavedCurFn = CurFun.CurrentFunction;
2108 CurFun.CurrentFunction = 0;
2109 Value *V = getExistingValue(Ty, $2);
2110 CurFun.CurrentFunction = SavedCurFn;
2111
2112 // If this is an initializer for a constant pointer, which is referencing a
2113 // (currently) undefined variable, create a stub now that shall be replaced
2114 // in the future with the right type of variable.
2115 //
2116 if (V == 0) {
2117 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2118 const PointerType *PT = cast<PointerType>(Ty);
2119
2120 // First check to see if the forward references value is already created!
2121 PerModuleInfo::GlobalRefsType::iterator I =
2122 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2123
2124 if (I != CurModule.GlobalRefs.end()) {
2125 V = I->second; // Placeholder already exists, use it...
2126 $2.destroy();
2127 } else {
2128 std::string Name;
2129 if ($2.Type == ValID::NameVal) Name = $2.Name;
2130
2131 // Create the forward referenced global.
2132 GlobalValue *GV;
2133 if (const FunctionType *FTy =
2134 dyn_cast<FunctionType>(PT->getElementType())) {
2135 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2136 CurModule.CurrentModule);
2137 } else {
2138 GV = new GlobalVariable(PT->getElementType(), false,
2139 GlobalValue::ExternalLinkage, 0,
2140 Name, CurModule.CurrentModule);
2141 }
2142
2143 // Keep track of the fact that we have a forward ref to recycle it
2144 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2145 V = GV;
2146 }
2147 }
2148 $$.C = cast<GlobalValue>(V);
2149 $$.S = $1.S;
2150 delete $1.T; // Free the type handle
2151 }
2152 | Types ConstExpr {
2153 if ($1.T->get() != $2.C->getType())
2154 error("Mismatched types for constant expression");
2155 $$ = $2;
2156 $$.S = $1.S;
2157 delete $1.T;
2158 }
2159 | Types ZEROINITIALIZER {
2160 const Type *Ty = $1.T->get();
2161 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2162 error("Cannot create a null initialized value of this type");
2163 $$.C = Constant::getNullValue(Ty);
2164 $$.S = $1.S;
2165 delete $1.T;
2166 }
2167 | SIntType EINT64VAL { // integral constants
2168 const Type *Ty = $1.T;
2169 if (!ConstantInt::isValueValidForType(Ty, $2))
2170 error("Constant value doesn't fit in type");
2171 $$.C = ConstantInt::get(Ty, $2);
2172 $$.S = Signed;
2173 }
2174 | UIntType EUINT64VAL { // integral constants
2175 const Type *Ty = $1.T;
2176 if (!ConstantInt::isValueValidForType(Ty, $2))
2177 error("Constant value doesn't fit in type");
2178 $$.C = ConstantInt::get(Ty, $2);
2179 $$.S = Unsigned;
2180 }
2181 | BOOL TRUETOK { // Boolean constants
2182 $$.C = ConstantInt::get(Type::Int1Ty, true);
2183 $$.S = Unsigned;
2184 }
2185 | BOOL FALSETOK { // Boolean constants
2186 $$.C = ConstantInt::get(Type::Int1Ty, false);
2187 $$.S = Unsigned;
2188 }
2189 | FPType FPVAL { // Float & Double constants
2190 if (!ConstantFP::isValueValidForType($1.T, $2))
2191 error("Floating point constant invalid for type");
2192 $$.C = ConstantFP::get($1.T, $2);
2193 $$.S = Signless;
2194 }
2195 ;
2196
2197ConstExpr
2198 : CastOps '(' ConstVal TO Types ')' {
2199 const Type* SrcTy = $3.C->getType();
2200 const Type* DstTy = $5.T->get();
2201 Signedness SrcSign = $3.S;
2202 Signedness DstSign = $5.S;
2203 if (!SrcTy->isFirstClassType())
2204 error("cast constant expression from a non-primitive type: '" +
2205 SrcTy->getDescription() + "'");
2206 if (!DstTy->isFirstClassType())
2207 error("cast constant expression to a non-primitive type: '" +
2208 DstTy->getDescription() + "'");
2209 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2210 $$.S = DstSign;
2211 delete $5.T;
2212 }
2213 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2214 const Type *Ty = $3.C->getType();
2215 if (!isa<PointerType>(Ty))
2216 error("GetElementPtr requires a pointer operand");
2217
2218 std::vector<Value*> VIndices;
2219 std::vector<Constant*> CIndices;
2220 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2221
2222 delete $4;
2223 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2224 $$.S = Signless;
2225 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002226 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002227 if (!$3.C->getType()->isInteger() ||
2228 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2229 error("Select condition must be bool type");
2230 if ($5.C->getType() != $7.C->getType())
2231 error("Select operand types must match");
2232 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2233 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002234 }
2235 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002236 const Type *Ty = $3.C->getType();
2237 if (Ty != $5.C->getType())
2238 error("Binary operator types must match");
2239 // First, make sure we're dealing with the right opcode by upgrading from
2240 // obsolete versions.
2241 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2242
2243 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2244 // To retain backward compatibility with these early compilers, we emit a
2245 // cast to the appropriate integer type automatically if we are in the
2246 // broken case. See PR424 for more information.
2247 if (!isa<PointerType>(Ty)) {
2248 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2249 } else {
2250 const Type *IntPtrTy = 0;
2251 switch (CurModule.CurrentModule->getPointerSize()) {
2252 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2253 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2254 default: error("invalid pointer binary constant expr");
2255 }
2256 $$.C = ConstantExpr::get(Opcode,
2257 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2258 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2259 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2260 }
2261 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002262 }
2263 | LogicalOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002264 const Type* Ty = $3.C->getType();
2265 if (Ty != $5.C->getType())
2266 error("Logical operator types must match");
2267 if (!Ty->isInteger()) {
2268 if (!isa<PackedType>(Ty) ||
2269 !cast<PackedType>(Ty)->getElementType()->isInteger())
2270 error("Logical operator requires integer operands");
2271 }
2272 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2273 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2274 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002275 }
2276 | SetCondOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002277 const Type* Ty = $3.C->getType();
2278 if (Ty != $5.C->getType())
2279 error("setcc operand types must match");
2280 unsigned short pred;
2281 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2282 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2283 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002284 }
Reid Spencer57f28f92006-12-03 07:10:26 +00002285 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002286 if ($4.C->getType() != $6.C->getType())
2287 error("icmp operand types must match");
2288 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2289 $$.S = Unsigned;
Reid Spencer57f28f92006-12-03 07:10:26 +00002290 }
2291 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002292 if ($4.C->getType() != $6.C->getType())
2293 error("fcmp operand types must match");
2294 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2295 $$.S = Unsigned;
Reid Spencer229e9362006-12-02 22:14:11 +00002296 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002297 | ShiftOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002298 if (!$5.C->getType()->isInteger() ||
2299 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2300 error("Shift count for shift constant must be unsigned byte");
Reid Spencer832254e2007-02-02 02:16:23 +00002301 const Type* Ty = $3.C->getType();
Reid Spencer950bf602007-01-26 08:19:09 +00002302 if (!$3.C->getType()->isInteger())
2303 error("Shift constant expression requires integer operand");
Reid Spencer832254e2007-02-02 02:16:23 +00002304 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2305 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
Reid Spencer950bf602007-01-26 08:19:09 +00002306 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002307 }
2308 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002309 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2310 error("Invalid extractelement operands");
2311 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2312 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002313 }
2314 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002315 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2316 error("Invalid insertelement operands");
2317 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2318 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002319 }
2320 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002321 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2322 error("Invalid shufflevector operands");
2323 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2324 $$.S = $3.S;
2325 }
2326 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002327
2328
2329// ConstVector - A list of comma separated constants.
Reid Spencere77e35e2006-12-01 20:26:20 +00002330ConstVector
Reid Spencer950bf602007-01-26 08:19:09 +00002331 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2332 | ConstVal {
2333 $$ = new std::vector<ConstInfo>();
2334 $$->push_back($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002335 }
Reid Spencere77e35e2006-12-01 20:26:20 +00002336 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002337
2338
2339// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
Reid Spencer950bf602007-01-26 08:19:09 +00002340GlobalType
2341 : GLOBAL { $$ = false; }
2342 | CONSTANT { $$ = true; }
2343 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002344
2345
2346//===----------------------------------------------------------------------===//
2347// Rules to match Modules
2348//===----------------------------------------------------------------------===//
2349
2350// Module rule: Capture the result of parsing the whole file into a result
2351// variable...
2352//
Reid Spencer950bf602007-01-26 08:19:09 +00002353Module
2354 : FunctionList {
2355 $$ = ParserResult = $1;
2356 CurModule.ModuleDone();
Reid Spencere7c3c602006-11-30 06:36:44 +00002357 }
Jeff Cohenac2dca92007-01-21 19:30:52 +00002358 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002359
Reid Spencer950bf602007-01-26 08:19:09 +00002360// FunctionList - A list of functions, preceeded by a constant pool.
2361//
2362FunctionList
2363 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2364 | FunctionList FunctionProto { $$ = $1; }
2365 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2366 | FunctionList IMPLEMENTATION { $$ = $1; }
2367 | ConstPool {
2368 $$ = CurModule.CurrentModule;
2369 // Emit an error if there are any unresolved types left.
2370 if (!CurModule.LateResolveTypes.empty()) {
2371 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2372 if (DID.Type == ValID::NameVal) {
2373 error("Reference to an undefined type: '"+DID.getName() + "'");
2374 } else {
2375 error("Reference to an undefined type: #" + itostr(DID.Num));
2376 }
2377 }
2378 }
2379 ;
Reid Spencer78720742006-12-02 20:21:22 +00002380
Reid Spencere7c3c602006-11-30 06:36:44 +00002381// ConstPool - Constants with optional names assigned to them.
Reid Spencer950bf602007-01-26 08:19:09 +00002382ConstPool
2383 : ConstPool OptAssign TYPE TypesV {
2384 // Eagerly resolve types. This is not an optimization, this is a
2385 // requirement that is due to the fact that we could have this:
2386 //
2387 // %list = type { %list * }
2388 // %list = type { %list * } ; repeated type decl
2389 //
2390 // If types are not resolved eagerly, then the two types will not be
2391 // determined to be the same type!
2392 //
2393 const Type* Ty = $4.T->get();
2394 ResolveTypeTo($2, Ty);
2395
2396 if (!setTypeName(Ty, $2) && !$2) {
2397 // If this is a named type that is not a redefinition, add it to the slot
2398 // table.
2399 CurModule.Types.push_back(Ty);
Reid Spencera50d5962006-12-02 04:11:07 +00002400 }
Reid Spencer950bf602007-01-26 08:19:09 +00002401 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002402 }
2403 | ConstPool FunctionProto { // Function prototypes can be in const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002404 }
2405 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002406 }
Reid Spencer950bf602007-01-26 08:19:09 +00002407 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2408 if ($5.C == 0)
2409 error("Global value initializer is not a constant");
2410 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2411 } GlobalVarAttributes {
2412 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002413 }
Reid Spencer950bf602007-01-26 08:19:09 +00002414 | ConstPool OptAssign EXTERNAL GlobalType Types {
2415 const Type *Ty = $5.T->get();
2416 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2417 delete $5.T;
2418 } GlobalVarAttributes {
2419 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002420 }
Reid Spencer950bf602007-01-26 08:19:09 +00002421 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2422 const Type *Ty = $5.T->get();
2423 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2424 delete $5.T;
2425 } GlobalVarAttributes {
2426 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002427 }
Reid Spencer950bf602007-01-26 08:19:09 +00002428 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2429 const Type *Ty = $5.T->get();
2430 CurGV =
2431 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2432 delete $5.T;
2433 } GlobalVarAttributes {
2434 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002435 }
2436 | ConstPool TARGET TargetDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002437 }
2438 | ConstPool DEPLIBS '=' LibrariesDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002439 }
2440 | /* empty: end of list */ {
Reid Spencer950bf602007-01-26 08:19:09 +00002441 }
2442 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002443
Reid Spencer950bf602007-01-26 08:19:09 +00002444AsmBlock
2445 : STRINGCONSTANT {
2446 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2447 char *EndStr = UnEscapeLexed($1, true);
2448 std::string NewAsm($1, EndStr);
2449 free($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002450
Reid Spencer950bf602007-01-26 08:19:09 +00002451 if (AsmSoFar.empty())
2452 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2453 else
2454 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2455 }
2456 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002457
Reid Spencer950bf602007-01-26 08:19:09 +00002458BigOrLittle
Reid Spencerd7c4f8c2007-01-26 19:59:25 +00002459 : BIG { $$ = Module::BigEndian; }
Reid Spencer950bf602007-01-26 08:19:09 +00002460 | LITTLE { $$ = Module::LittleEndian; }
2461 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002462
2463TargetDefinition
2464 : ENDIAN '=' BigOrLittle {
Reid Spencer950bf602007-01-26 08:19:09 +00002465 CurModule.setEndianness($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002466 }
2467 | POINTERSIZE '=' EUINT64VAL {
Reid Spencer950bf602007-01-26 08:19:09 +00002468 if ($3 == 32)
2469 CurModule.setPointerSize(Module::Pointer32);
2470 else if ($3 == 64)
2471 CurModule.setPointerSize(Module::Pointer64);
2472 else
2473 error("Invalid pointer size: '" + utostr($3) + "'");
Reid Spencere7c3c602006-11-30 06:36:44 +00002474 }
2475 | TRIPLE '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002476 CurModule.CurrentModule->setTargetTriple($3);
2477 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002478 }
2479 | DATALAYOUT '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002480 CurModule.CurrentModule->setDataLayout($3);
2481 free($3);
2482 }
2483 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002484
2485LibrariesDefinition
Reid Spencer950bf602007-01-26 08:19:09 +00002486 : '[' LibList ']'
2487 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002488
2489LibList
2490 : LibList ',' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002491 CurModule.CurrentModule->addLibrary($3);
2492 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002493 }
Reid Spencer950bf602007-01-26 08:19:09 +00002494 | STRINGCONSTANT {
2495 CurModule.CurrentModule->addLibrary($1);
2496 free($1);
2497 }
2498 | /* empty: end of list */ { }
2499 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002500
2501//===----------------------------------------------------------------------===//
2502// Rules to match Function Headers
2503//===----------------------------------------------------------------------===//
2504
Reid Spencer950bf602007-01-26 08:19:09 +00002505Name
2506 : VAR_ID | STRINGCONSTANT
2507 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002508
Reid Spencer950bf602007-01-26 08:19:09 +00002509OptName
2510 : Name
2511 | /*empty*/ { $$ = 0; }
2512 ;
2513
2514ArgVal
2515 : Types OptName {
2516 if ($1.T->get() == Type::VoidTy)
2517 error("void typed arguments are invalid");
2518 $$ = new std::pair<PATypeInfo, char*>($1, $2);
Reid Spencer52402b02007-01-02 05:45:11 +00002519 }
Reid Spencer950bf602007-01-26 08:19:09 +00002520 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002521
Reid Spencer950bf602007-01-26 08:19:09 +00002522ArgListH
2523 : ArgListH ',' ArgVal {
2524 $$ = $1;
2525 $$->push_back(*$3);
Reid Spencere77e35e2006-12-01 20:26:20 +00002526 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002527 }
2528 | ArgVal {
Reid Spencer950bf602007-01-26 08:19:09 +00002529 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2530 $$->push_back(*$1);
2531 delete $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002532 }
Reid Spencer950bf602007-01-26 08:19:09 +00002533 ;
2534
2535ArgList
2536 : ArgListH { $$ = $1; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002537 | ArgListH ',' DOTDOTDOT {
Reid Spencere7c3c602006-11-30 06:36:44 +00002538 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00002539 PATypeInfo VoidTI;
2540 VoidTI.T = new PATypeHolder(Type::VoidTy);
2541 VoidTI.S = Signless;
2542 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002543 }
2544 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00002545 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2546 PATypeInfo VoidTI;
2547 VoidTI.T = new PATypeHolder(Type::VoidTy);
2548 VoidTI.S = Signless;
2549 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002550 }
Reid Spencer950bf602007-01-26 08:19:09 +00002551 | /* empty */ { $$ = 0; }
2552 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002553
Reid Spencer71d2ec92006-12-31 06:02:26 +00002554FunctionHeaderH
2555 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00002556 UnEscapeLexed($3);
2557 std::string FunctionName($3);
2558 free($3); // Free strdup'd memory!
Reid Spencere7c3c602006-11-30 06:36:44 +00002559
Reid Spencer950bf602007-01-26 08:19:09 +00002560 const Type* RetTy = $2.T->get();
2561
2562 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2563 error("LLVM functions cannot return aggregate types");
2564
2565 std::vector<const Type*> ParamTypeList;
2566
2567 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2568 // i8*. We check here for those names and override the parameter list
2569 // types to ensure the prototype is correct.
2570 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2571 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2572 } else if (FunctionName == "llvm.va_copy") {
2573 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2574 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2575 } else if ($5) { // If there are arguments...
2576 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2577 I = $5->begin(), E = $5->end(); I != E; ++I) {
2578 const Type *Ty = I->first.T->get();
2579 ParamTypeList.push_back(Ty);
2580 }
2581 }
2582
2583 bool isVarArg =
2584 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2585 if (isVarArg) ParamTypeList.pop_back();
2586
Reid Spencerb7046c72007-01-29 05:41:34 +00002587 // Convert the CSRet calling convention into the corresponding parameter
2588 // attribute.
2589 FunctionType::ParamAttrsList ParamAttrs;
2590 if ($1 == OldCallingConv::CSRet) {
2591 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2592 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2593 }
2594
2595 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg,
2596 ParamAttrs);
Reid Spencer950bf602007-01-26 08:19:09 +00002597 const PointerType *PFT = PointerType::get(FT);
2598 delete $2.T;
2599
2600 ValID ID;
2601 if (!FunctionName.empty()) {
2602 ID = ValID::create((char*)FunctionName.c_str());
2603 } else {
2604 ID = ValID::create((int)CurModule.Values[PFT].size());
2605 }
2606
2607 Function *Fn = 0;
2608 // See if this function was forward referenced. If so, recycle the object.
2609 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2610 // Move the function to the end of the list, from whereever it was
2611 // previously inserted.
2612 Fn = cast<Function>(FWRef);
2613 CurModule.CurrentModule->getFunctionList().remove(Fn);
2614 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2615 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2616 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2617 // If this is the case, either we need to be a forward decl, or it needs
2618 // to be.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002619 if (!CurFun.isDeclare && !Fn->isDeclaration())
Reid Spencer950bf602007-01-26 08:19:09 +00002620 error("Redefinition of function '" + FunctionName + "'");
2621
2622 // Make sure to strip off any argument names so we can't get conflicts.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002623 if (Fn->isDeclaration())
Reid Spencer950bf602007-01-26 08:19:09 +00002624 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2625 AI != AE; ++AI)
2626 AI->setName("");
2627 } else { // Not already defined?
2628 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2629 CurModule.CurrentModule);
2630
2631 InsertValue(Fn, CurModule.Values);
2632 }
2633
2634 CurFun.FunctionStart(Fn);
2635
2636 if (CurFun.isDeclare) {
2637 // If we have declaration, always overwrite linkage. This will allow us
2638 // to correctly handle cases, when pointer to function is passed as
2639 // argument to another function.
2640 Fn->setLinkage(CurFun.Linkage);
2641 }
Reid Spencerb7046c72007-01-29 05:41:34 +00002642 Fn->setCallingConv(upgradeCallingConv($1));
Reid Spencer950bf602007-01-26 08:19:09 +00002643 Fn->setAlignment($8);
2644 if ($7) {
2645 Fn->setSection($7);
2646 free($7);
2647 }
2648
2649 // Add all of the arguments we parsed to the function...
2650 if ($5) { // Is null if empty...
2651 if (isVarArg) { // Nuke the last entry
2652 assert($5->back().first.T->get() == Type::VoidTy &&
2653 $5->back().second == 0 && "Not a varargs marker");
2654 delete $5->back().first.T;
2655 $5->pop_back(); // Delete the last entry
2656 }
2657 Function::arg_iterator ArgIt = Fn->arg_begin();
2658 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2659 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2660 delete I->first.T; // Delete the typeholder...
2661 setValueName(ArgIt, I->second); // Insert arg into symtab...
2662 InsertValue(ArgIt);
2663 }
2664 delete $5; // We're now done with the argument list
2665 }
2666 }
2667 ;
2668
2669BEGIN
2670 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
Jeff Cohenac2dca92007-01-21 19:30:52 +00002671 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002672
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002673FunctionHeader
2674 : OptLinkage FunctionHeaderH BEGIN {
Reid Spencer950bf602007-01-26 08:19:09 +00002675 $$ = CurFun.CurrentFunction;
2676
2677 // Make sure that we keep track of the linkage type even if there was a
2678 // previous "declare".
2679 $$->setLinkage($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002680 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002681 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002682
Reid Spencer950bf602007-01-26 08:19:09 +00002683END
2684 : ENDTOK | '}' // Allow end of '}' to end a function
2685 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002686
Reid Spencer950bf602007-01-26 08:19:09 +00002687Function
2688 : BasicBlockList END {
2689 $$ = $1;
2690 };
Reid Spencere7c3c602006-11-30 06:36:44 +00002691
Reid Spencere77e35e2006-12-01 20:26:20 +00002692FnDeclareLinkage
Reid Spencer950bf602007-01-26 08:19:09 +00002693 : /*default*/
2694 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2695 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002696 ;
2697
2698FunctionProto
Reid Spencer950bf602007-01-26 08:19:09 +00002699 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2700 $$ = CurFun.CurrentFunction;
2701 CurFun.FunctionDone();
2702
2703 }
2704 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002705
2706//===----------------------------------------------------------------------===//
2707// Rules to match Basic Blocks
2708//===----------------------------------------------------------------------===//
2709
Reid Spencer950bf602007-01-26 08:19:09 +00002710OptSideEffect
2711 : /* empty */ { $$ = false; }
2712 | SIDEEFFECT { $$ = true; }
2713 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002714
Reid Spencere77e35e2006-12-01 20:26:20 +00002715ConstValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002716 // A reference to a direct constant
2717 : ESINT64VAL { $$ = ValID::create($1); }
2718 | EUINT64VAL { $$ = ValID::create($1); }
2719 | FPVAL { $$ = ValID::create($1); }
2720 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2721 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2722 | NULL_TOK { $$ = ValID::createNull(); }
2723 | UNDEF { $$ = ValID::createUndef(); }
2724 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2725 | '<' ConstVector '>' { // Nonempty unsized packed vector
2726 const Type *ETy = (*$2)[0].C->getType();
2727 int NumElements = $2->size();
2728 PackedType* pt = PackedType::get(ETy, NumElements);
2729 PATypeHolder* PTy = new PATypeHolder(
2730 HandleUpRefs(PackedType::get(ETy, NumElements)));
2731
2732 // Verify all elements are correct type!
2733 std::vector<Constant*> Elems;
2734 for (unsigned i = 0; i < $2->size(); i++) {
2735 Constant *C = (*$2)[i].C;
2736 const Type *CTy = C->getType();
2737 if (ETy != CTy)
2738 error("Element #" + utostr(i) + " is not of type '" +
2739 ETy->getDescription() +"' as required!\nIt is of type '" +
2740 CTy->getDescription() + "'");
2741 Elems.push_back(C);
Reid Spencere7c3c602006-11-30 06:36:44 +00002742 }
Reid Spencer950bf602007-01-26 08:19:09 +00002743 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2744 delete PTy; delete $2;
2745 }
2746 | ConstExpr {
2747 $$ = ValID::create($1.C);
2748 }
2749 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2750 char *End = UnEscapeLexed($3, true);
2751 std::string AsmStr = std::string($3, End);
2752 End = UnEscapeLexed($5, true);
2753 std::string Constraints = std::string($5, End);
2754 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2755 free($3);
2756 free($5);
2757 }
2758 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002759
Reid Spencer950bf602007-01-26 08:19:09 +00002760// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2761// another value.
2762//
2763SymbolicValueRef
2764 : INTVAL { $$ = ValID::create($1); }
2765 | Name { $$ = ValID::create($1); }
2766 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002767
2768// ValueRef - A reference to a definition... either constant or symbolic
Reid Spencerf459d392006-12-02 16:19:52 +00002769ValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002770 : SymbolicValueRef | ConstValueRef
Reid Spencerf459d392006-12-02 16:19:52 +00002771 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002772
Reid Spencer950bf602007-01-26 08:19:09 +00002773
Reid Spencere7c3c602006-11-30 06:36:44 +00002774// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2775// type immediately preceeds the value reference, and allows complex constant
2776// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
Reid Spencer950bf602007-01-26 08:19:09 +00002777ResolvedVal
2778 : Types ValueRef {
2779 const Type *Ty = $1.T->get();
2780 $$.S = $1.S;
2781 $$.V = getVal(Ty, $2);
2782 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002783 }
Reid Spencer950bf602007-01-26 08:19:09 +00002784 ;
2785
2786BasicBlockList
2787 : BasicBlockList BasicBlock {
2788 $$ = $1;
2789 }
2790 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2791 $$ = $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002792 };
2793
2794
2795// Basic blocks are terminated by branching instructions:
2796// br, br/cc, switch, ret
2797//
Reid Spencer950bf602007-01-26 08:19:09 +00002798BasicBlock
2799 : InstructionList OptAssign BBTerminatorInst {
2800 setValueName($3, $2);
2801 InsertValue($3);
2802 $1->getInstList().push_back($3);
2803 InsertValue($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002804 $$ = $1;
2805 }
Reid Spencer950bf602007-01-26 08:19:09 +00002806 ;
2807
2808InstructionList
2809 : InstructionList Inst {
2810 if ($2.I)
2811 $1->getInstList().push_back($2.I);
2812 $$ = $1;
2813 }
2814 | /* empty */ {
2815 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2816 // Make sure to move the basic block to the correct location in the
2817 // function, instead of leaving it inserted wherever it was first
2818 // referenced.
2819 Function::BasicBlockListType &BBL =
2820 CurFun.CurrentFunction->getBasicBlockList();
2821 BBL.splice(BBL.end(), BBL, $$);
2822 }
2823 | LABELSTR {
2824 $$ = CurBB = getBBVal(ValID::create($1), true);
2825 // Make sure to move the basic block to the correct location in the
2826 // function, instead of leaving it inserted wherever it was first
2827 // referenced.
2828 Function::BasicBlockListType &BBL =
2829 CurFun.CurrentFunction->getBasicBlockList();
2830 BBL.splice(BBL.end(), BBL, $$);
2831 }
2832 ;
2833
2834Unwind : UNWIND | EXCEPT;
2835
2836BBTerminatorInst
2837 : RET ResolvedVal { // Return with a result...
2838 $$ = new ReturnInst($2.V);
2839 }
2840 | RET VOID { // Return with no result...
2841 $$ = new ReturnInst();
2842 }
2843 | BR LABEL ValueRef { // Unconditional Branch...
2844 BasicBlock* tmpBB = getBBVal($3);
2845 $$ = new BranchInst(tmpBB);
2846 } // Conditional Branch...
2847 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2848 BasicBlock* tmpBBA = getBBVal($6);
2849 BasicBlock* tmpBBB = getBBVal($9);
2850 Value* tmpVal = getVal(Type::Int1Ty, $3);
2851 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2852 }
2853 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2854 Value* tmpVal = getVal($2.T, $3);
2855 BasicBlock* tmpBB = getBBVal($6);
2856 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2857 $$ = S;
2858 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2859 E = $8->end();
2860 for (; I != E; ++I) {
2861 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2862 S->addCase(CI, I->second);
2863 else
2864 error("Switch case is constant, but not a simple integer");
2865 }
2866 delete $8;
2867 }
2868 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2869 Value* tmpVal = getVal($2.T, $3);
2870 BasicBlock* tmpBB = getBBVal($6);
2871 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2872 $$ = S;
2873 }
2874 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2875 TO LABEL ValueRef Unwind LABEL ValueRef {
2876 const PointerType *PFTy;
2877 const FunctionType *Ty;
2878
2879 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2880 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2881 // Pull out the types of all of the arguments...
2882 std::vector<const Type*> ParamTypes;
2883 if ($6) {
2884 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2885 I != E; ++I)
2886 ParamTypes.push_back((*I).V->getType());
2887 }
Reid Spencerb7046c72007-01-29 05:41:34 +00002888 FunctionType::ParamAttrsList ParamAttrs;
2889 if ($2 == OldCallingConv::CSRet) {
2890 ParamAttrs.push_back(FunctionType::NoAttributeSet);
2891 ParamAttrs.push_back(FunctionType::StructRetAttribute);
2892 }
Reid Spencer950bf602007-01-26 08:19:09 +00002893 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2894 if (isVarArg) ParamTypes.pop_back();
Reid Spencerb7046c72007-01-29 05:41:34 +00002895 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg, ParamAttrs);
Reid Spencer950bf602007-01-26 08:19:09 +00002896 PFTy = PointerType::get(Ty);
2897 }
2898 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2899 BasicBlock *Normal = getBBVal($10);
2900 BasicBlock *Except = getBBVal($13);
2901
2902 // Create the call node...
2903 if (!$6) { // Has no arguments?
2904 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2905 } else { // Has arguments?
2906 // Loop through FunctionType's arguments and ensure they are specified
2907 // correctly!
2908 //
2909 FunctionType::param_iterator I = Ty->param_begin();
2910 FunctionType::param_iterator E = Ty->param_end();
2911 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2912
2913 std::vector<Value*> Args;
2914 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2915 if ((*ArgI).V->getType() != *I)
2916 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2917 (*I)->getDescription() + "'");
2918 Args.push_back((*ArgI).V);
2919 }
2920
2921 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2922 error("Invalid number of parameters detected");
2923
2924 $$ = new InvokeInst(V, Normal, Except, Args);
2925 }
Reid Spencerb7046c72007-01-29 05:41:34 +00002926 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
Reid Spencer950bf602007-01-26 08:19:09 +00002927 delete $3.T;
2928 delete $6;
2929 }
2930 | Unwind {
2931 $$ = new UnwindInst();
2932 }
2933 | UNREACHABLE {
2934 $$ = new UnreachableInst();
2935 }
2936 ;
2937
2938JumpTable
2939 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2940 $$ = $1;
2941 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2942
2943 if (V == 0)
2944 error("May only switch on a constant pool value");
2945
2946 BasicBlock* tmpBB = getBBVal($6);
2947 $$->push_back(std::make_pair(V, tmpBB));
2948 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002949 | IntType ConstValueRef ',' LABEL ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00002950 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2951 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2952
2953 if (V == 0)
2954 error("May only switch on a constant pool value");
2955
2956 BasicBlock* tmpBB = getBBVal($5);
2957 $$->push_back(std::make_pair(V, tmpBB));
2958 }
2959 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002960
2961Inst
2962 : OptAssign InstVal {
Reid Spencer950bf602007-01-26 08:19:09 +00002963 bool omit = false;
2964 if ($1)
2965 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2966 if (BCI->getSrcTy() == BCI->getDestTy() &&
2967 BCI->getOperand(0)->getName() == $1)
2968 // This is a useless bit cast causing a name redefinition. It is
2969 // a bit cast from a type to the same type of an operand with the
2970 // same name as the name we would give this instruction. Since this
2971 // instruction results in no code generation, it is safe to omit
2972 // the instruction. This situation can occur because of collapsed
2973 // type planes. For example:
2974 // %X = add int %Y, %Z
2975 // %X = cast int %Y to uint
2976 // After upgrade, this looks like:
2977 // %X = add i32 %Y, %Z
2978 // %X = bitcast i32 to i32
2979 // The bitcast is clearly useless so we omit it.
2980 omit = true;
2981 if (omit) {
2982 $$.I = 0;
2983 $$.S = Signless;
2984 } else {
2985 setValueName($2.I, $1);
2986 InsertValue($2.I);
2987 $$ = $2;
Reid Spencerf5626a32007-01-01 01:20:41 +00002988 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002989 };
2990
Reid Spencer950bf602007-01-26 08:19:09 +00002991PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2992 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2993 $$.S = $1.S;
2994 Value* tmpVal = getVal($1.T->get(), $3);
2995 BasicBlock* tmpBB = getBBVal($5);
2996 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
2997 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002998 }
2999 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
Reid Spencere7c3c602006-11-30 06:36:44 +00003000 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00003001 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3002 BasicBlock* tmpBB = getBBVal($6);
3003 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3004 }
3005 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003006
Reid Spencer950bf602007-01-26 08:19:09 +00003007ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3008 $$ = new std::vector<ValueInfo>();
Reid Spencerf8483652006-12-02 15:16:01 +00003009 $$->push_back($1);
3010 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003011 | ValueRefList ',' ResolvedVal {
Reid Spencere7c3c602006-11-30 06:36:44 +00003012 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00003013 $1->push_back($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00003014 };
3015
3016// ValueRefListE - Just like ValueRefList, except that it may also be empty!
3017ValueRefListE
Reid Spencer950bf602007-01-26 08:19:09 +00003018 : ValueRefList
3019 | /*empty*/ { $$ = 0; }
Reid Spencere7c3c602006-11-30 06:36:44 +00003020 ;
3021
3022OptTailCall
3023 : TAIL CALL {
Reid Spencer950bf602007-01-26 08:19:09 +00003024 $$ = true;
Reid Spencere7c3c602006-11-30 06:36:44 +00003025 }
Reid Spencer950bf602007-01-26 08:19:09 +00003026 | CALL {
3027 $$ = false;
3028 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003029 ;
3030
Reid Spencer950bf602007-01-26 08:19:09 +00003031InstVal
3032 : ArithmeticOps Types ValueRef ',' ValueRef {
3033 const Type* Ty = $2.T->get();
3034 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3035 error("Arithmetic operator requires integer, FP, or packed operands");
3036 if (isa<PackedType>(Ty) &&
3037 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3038 error("Remainder not supported on packed types");
3039 // Upgrade the opcode from obsolete versions before we do anything with it.
3040 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3041 Value* val1 = getVal(Ty, $3);
3042 Value* val2 = getVal(Ty, $5);
3043 $$.I = BinaryOperator::create(Opcode, val1, val2);
3044 if ($$.I == 0)
3045 error("binary operator returned null");
3046 $$.S = $2.S;
3047 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003048 }
3049 | LogicalOps Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003050 const Type *Ty = $2.T->get();
3051 if (!Ty->isInteger()) {
3052 if (!isa<PackedType>(Ty) ||
3053 !cast<PackedType>(Ty)->getElementType()->isInteger())
3054 error("Logical operator requires integral operands");
3055 }
3056 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3057 Value* tmpVal1 = getVal(Ty, $3);
3058 Value* tmpVal2 = getVal(Ty, $5);
3059 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3060 if ($$.I == 0)
3061 error("binary operator returned null");
3062 $$.S = $2.S;
3063 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003064 }
3065 | SetCondOps Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003066 const Type* Ty = $2.T->get();
3067 if(isa<PackedType>(Ty))
3068 error("PackedTypes currently not supported in setcc instructions");
3069 unsigned short pred;
3070 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3071 Value* tmpVal1 = getVal(Ty, $3);
3072 Value* tmpVal2 = getVal(Ty, $5);
3073 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3074 if ($$.I == 0)
3075 error("binary operator returned null");
3076 $$.S = Unsigned;
3077 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003078 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003079 | ICMP IPredicates Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003080 const Type *Ty = $3.T->get();
3081 if (isa<PackedType>(Ty))
3082 error("PackedTypes currently not supported in icmp instructions");
3083 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3084 error("icmp requires integer or pointer typed operands");
3085 Value* tmpVal1 = getVal(Ty, $4);
3086 Value* tmpVal2 = getVal(Ty, $6);
3087 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3088 $$.S = Unsigned;
3089 delete $3.T;
Reid Spencer57f28f92006-12-03 07:10:26 +00003090 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003091 | FCMP FPredicates Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003092 const Type *Ty = $3.T->get();
3093 if (isa<PackedType>(Ty))
3094 error("PackedTypes currently not supported in fcmp instructions");
3095 else if (!Ty->isFloatingPoint())
3096 error("fcmp instruction requires floating point operands");
3097 Value* tmpVal1 = getVal(Ty, $4);
3098 Value* tmpVal2 = getVal(Ty, $6);
3099 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3100 $$.S = Unsigned;
3101 delete $3.T;
3102 }
3103 | NOT ResolvedVal {
3104 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3105 const Type *Ty = $2.V->getType();
3106 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3107 if (Ones == 0)
3108 error("Expected integral type for not instruction");
3109 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3110 if ($$.I == 0)
3111 error("Could not create a xor instruction");
3112 $$.S = $2.S
Reid Spencer229e9362006-12-02 22:14:11 +00003113 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003114 | ShiftOps ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003115 if (!$4.V->getType()->isInteger() ||
3116 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3117 error("Shift amount must be int8");
Reid Spencer832254e2007-02-02 02:16:23 +00003118 const Type* Ty = $2.V->getType();
3119 if (!Ty->isInteger())
Reid Spencer950bf602007-01-26 08:19:09 +00003120 error("Shift constant expression requires integer operand");
Reid Spencer832254e2007-02-02 02:16:23 +00003121 Value* ShiftAmt = 0;
3122 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3123 if (Constant *C = dyn_cast<Constant>($4.V))
3124 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3125 else
3126 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3127 else
3128 ShiftAmt = $4.V;
3129 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
Reid Spencer950bf602007-01-26 08:19:09 +00003130 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003131 }
Reid Spencerfcb5df82006-12-01 22:34:43 +00003132 | CastOps ResolvedVal TO Types {
Reid Spencer950bf602007-01-26 08:19:09 +00003133 const Type *DstTy = $4.T->get();
3134 if (!DstTy->isFirstClassType())
3135 error("cast instruction to a non-primitive type: '" +
3136 DstTy->getDescription() + "'");
3137 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3138 $$.S = $4.S;
3139 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003140 }
3141 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003142 if (!$2.V->getType()->isInteger() ||
3143 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3144 error("select condition must be bool");
3145 if ($4.V->getType() != $6.V->getType())
3146 error("select value types should match");
3147 $$.I = new SelectInst($2.V, $4.V, $6.V);
3148 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003149 }
3150 | VAARG ResolvedVal ',' Types {
Reid Spencer950bf602007-01-26 08:19:09 +00003151 const Type *Ty = $4.T->get();
3152 NewVarArgs = true;
3153 $$.I = new VAArgInst($2.V, Ty);
3154 $$.S = $4.S;
3155 delete $4.T;
3156 }
3157 | VAARG_old ResolvedVal ',' Types {
3158 const Type* ArgTy = $2.V->getType();
3159 const Type* DstTy = $4.T->get();
3160 ObsoleteVarArgs = true;
3161 Function* NF = cast<Function>(CurModule.CurrentModule->
3162 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3163
3164 //b = vaarg a, t ->
3165 //foo = alloca 1 of t
3166 //bar = vacopy a
3167 //store bar -> foo
3168 //b = vaarg foo, t
3169 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3170 CurBB->getInstList().push_back(foo);
3171 CallInst* bar = new CallInst(NF, $2.V);
3172 CurBB->getInstList().push_back(bar);
3173 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3174 $$.I = new VAArgInst(foo, DstTy);
3175 $$.S = $4.S;
3176 delete $4.T;
3177 }
3178 | VANEXT_old ResolvedVal ',' Types {
3179 const Type* ArgTy = $2.V->getType();
3180 const Type* DstTy = $4.T->get();
3181 ObsoleteVarArgs = true;
3182 Function* NF = cast<Function>(CurModule.CurrentModule->
3183 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3184
3185 //b = vanext a, t ->
3186 //foo = alloca 1 of t
3187 //bar = vacopy a
3188 //store bar -> foo
3189 //tmp = vaarg foo, t
3190 //b = load foo
3191 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3192 CurBB->getInstList().push_back(foo);
3193 CallInst* bar = new CallInst(NF, $2.V);
3194 CurBB->getInstList().push_back(bar);
3195 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3196 Instruction* tmp = new VAArgInst(foo, DstTy);
3197 CurBB->getInstList().push_back(tmp);
3198 $$.I = new LoadInst(foo);
3199 $$.S = $4.S;
3200 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003201 }
3202 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003203 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3204 error("Invalid extractelement operands");
3205 $$.I = new ExtractElementInst($2.V, $4.V);
3206 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003207 }
3208 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003209 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3210 error("Invalid insertelement operands");
3211 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3212 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003213 }
3214 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003215 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3216 error("Invalid shufflevector operands");
3217 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3218 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003219 }
3220 | PHI_TOK PHIList {
Reid Spencer950bf602007-01-26 08:19:09 +00003221 const Type *Ty = $2.P->front().first->getType();
3222 if (!Ty->isFirstClassType())
3223 error("PHI node operands must be of first class type");
3224 PHINode *PHI = new PHINode(Ty);
3225 PHI->reserveOperandSpace($2.P->size());
3226 while ($2.P->begin() != $2.P->end()) {
3227 if ($2.P->front().first->getType() != Ty)
3228 error("All elements of a PHI node must be of the same type");
3229 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3230 $2.P->pop_front();
3231 }
3232 $$.I = PHI;
3233 $$.S = $2.S;
3234 delete $2.P; // Free the list...
Reid Spencere7c3c602006-11-30 06:36:44 +00003235 }
3236 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00003237
3238 // Handle the short call syntax
3239 const PointerType *PFTy;
3240 const FunctionType *FTy;
3241 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3242 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3243 // Pull out the types of all of the arguments...
3244 std::vector<const Type*> ParamTypes;
3245 if ($6) {
3246 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3247 I != E; ++I)
3248 ParamTypes.push_back((*I).V->getType());
Reid Spencerc4d96252007-01-13 00:03:30 +00003249 }
Reid Spencer950bf602007-01-26 08:19:09 +00003250
Reid Spencerb7046c72007-01-29 05:41:34 +00003251 FunctionType::ParamAttrsList ParamAttrs;
3252 if ($2 == OldCallingConv::CSRet) {
3253 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3254 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3255 }
Reid Spencer950bf602007-01-26 08:19:09 +00003256 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3257 if (isVarArg) ParamTypes.pop_back();
3258
3259 const Type *RetTy = $3.T->get();
3260 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3261 error("Functions cannot return aggregate types");
3262
Reid Spencerb7046c72007-01-29 05:41:34 +00003263 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
Reid Spencer950bf602007-01-26 08:19:09 +00003264 PFTy = PointerType::get(FTy);
Reid Spencerf8483652006-12-02 15:16:01 +00003265 }
Reid Spencer950bf602007-01-26 08:19:09 +00003266
3267 // First upgrade any intrinsic calls.
3268 std::vector<Value*> Args;
3269 if ($6)
3270 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3271 Args.push_back((*$6)[i].V);
3272 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3273
3274 // If we got an upgraded intrinsic
3275 if (Inst) {
3276 $$.I = Inst;
3277 $$.S = Signless;
3278 } else {
3279 // Get the function we're calling
3280 Value *V = getVal(PFTy, $4);
3281
3282 // Check the argument values match
3283 if (!$6) { // Has no arguments?
3284 // Make sure no arguments is a good thing!
3285 if (FTy->getNumParams() != 0)
3286 error("No arguments passed to a function that expects arguments");
3287 } else { // Has arguments?
3288 // Loop through FunctionType's arguments and ensure they are specified
3289 // correctly!
3290 //
3291 FunctionType::param_iterator I = FTy->param_begin();
3292 FunctionType::param_iterator E = FTy->param_end();
3293 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3294
3295 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3296 if ((*ArgI).V->getType() != *I)
3297 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3298 (*I)->getDescription() + "'");
3299
3300 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3301 error("Invalid number of parameters detected");
3302 }
3303
3304 // Create the call instruction
3305 CallInst *CI = new CallInst(V, Args);
3306 CI->setTailCall($1);
Reid Spencerb7046c72007-01-29 05:41:34 +00003307 CI->setCallingConv(upgradeCallingConv($2));
Reid Spencer950bf602007-01-26 08:19:09 +00003308 $$.I = CI;
3309 $$.S = $3.S;
3310 }
3311 delete $3.T;
3312 delete $6;
Reid Spencere7c3c602006-11-30 06:36:44 +00003313 }
Reid Spencer950bf602007-01-26 08:19:09 +00003314 | MemoryInst {
3315 $$ = $1;
3316 }
3317 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003318
3319
3320// IndexList - List of indices for GEP based instructions...
3321IndexList
Reid Spencer950bf602007-01-26 08:19:09 +00003322 : ',' ValueRefList { $$ = $2; }
3323 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
Reid Spencere7c3c602006-11-30 06:36:44 +00003324 ;
3325
3326OptVolatile
Reid Spencer950bf602007-01-26 08:19:09 +00003327 : VOLATILE { $$ = true; }
3328 | /* empty */ { $$ = false; }
Reid Spencere7c3c602006-11-30 06:36:44 +00003329 ;
3330
Reid Spencer950bf602007-01-26 08:19:09 +00003331MemoryInst
3332 : MALLOC Types OptCAlign {
3333 const Type *Ty = $2.T->get();
3334 $$.S = $2.S;
3335 $$.I = new MallocInst(Ty, 0, $3);
3336 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003337 }
3338 | MALLOC Types ',' UINT ValueRef OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003339 const Type *Ty = $2.T->get();
3340 $$.S = $2.S;
3341 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3342 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003343 }
3344 | ALLOCA Types OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003345 const Type *Ty = $2.T->get();
3346 $$.S = $2.S;
3347 $$.I = new AllocaInst(Ty, 0, $3);
3348 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003349 }
3350 | ALLOCA Types ',' UINT ValueRef OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003351 const Type *Ty = $2.T->get();
3352 $$.S = $2.S;
3353 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3354 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003355 }
3356 | FREE ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003357 const Type *PTy = $2.V->getType();
3358 if (!isa<PointerType>(PTy))
3359 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3360 $$.I = new FreeInst($2.V);
3361 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00003362 }
3363 | OptVolatile LOAD Types ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003364 const Type* Ty = $3.T->get();
3365 $$.S = $3.S;
3366 if (!isa<PointerType>(Ty))
3367 error("Can't load from nonpointer type: " + Ty->getDescription());
3368 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3369 error("Can't load from pointer of non-first-class type: " +
3370 Ty->getDescription());
3371 Value* tmpVal = getVal(Ty, $4);
3372 $$.I = new LoadInst(tmpVal, "", $1);
3373 delete $3.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003374 }
3375 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003376 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3377 if (!PTy)
3378 error("Can't store to a nonpointer type: " +
3379 $5.T->get()->getDescription());
3380 const Type *ElTy = PTy->getElementType();
3381 if (ElTy != $3.V->getType())
3382 error("Can't store '" + $3.V->getType()->getDescription() +
3383 "' into space of type '" + ElTy->getDescription() + "'");
3384 Value* tmpVal = getVal(PTy, $6);
3385 $$.I = new StoreInst($3.V, tmpVal, $1);
3386 $$.S = Signless;
3387 delete $5.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003388 }
3389 | GETELEMENTPTR Types ValueRef IndexList {
Reid Spencer950bf602007-01-26 08:19:09 +00003390 const Type* Ty = $2.T->get();
3391 if (!isa<PointerType>(Ty))
3392 error("getelementptr insn requires pointer operand");
3393
3394 std::vector<Value*> VIndices;
3395 upgradeGEPIndices(Ty, $4, VIndices);
3396
3397 Value* tmpVal = getVal(Ty, $3);
3398 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3399 $$.S = Signless;
3400 delete $2.T;
Reid Spencer30d0c582007-01-15 00:26:18 +00003401 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00003402 };
3403
Reid Spencer950bf602007-01-26 08:19:09 +00003404
Reid Spencere7c3c602006-11-30 06:36:44 +00003405%%
3406
3407int yyerror(const char *ErrorMsg) {
3408 std::string where
3409 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencer950bf602007-01-26 08:19:09 +00003410 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3411 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3412 if (yychar != YYEMPTY && yychar != 0)
3413 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3414 "'.";
Reid Spencer71d2ec92006-12-31 06:02:26 +00003415 std::cerr << "llvm-upgrade: " << errMsg << '\n';
Reid Spencer950bf602007-01-26 08:19:09 +00003416 std::cout << "llvm-upgrade: parse failed.\n";
Reid Spencere7c3c602006-11-30 06:36:44 +00003417 exit(1);
3418}
Reid Spencer319a7302007-01-05 17:20:02 +00003419
Reid Spencer30d0c582007-01-15 00:26:18 +00003420void warning(const std::string& ErrorMsg) {
Reid Spencer319a7302007-01-05 17:20:02 +00003421 std::string where
3422 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencer950bf602007-01-26 08:19:09 +00003423 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3424 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3425 if (yychar != YYEMPTY && yychar != 0)
3426 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3427 "'.";
Reid Spencer319a7302007-01-05 17:20:02 +00003428 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3429}
Reid Spencer950bf602007-01-26 08:19:09 +00003430
3431void error(const std::string& ErrorMsg, int LineNo) {
3432 if (LineNo == -1) LineNo = Upgradelineno;
3433 Upgradelineno = LineNo;
3434 yyerror(ErrorMsg.c_str());
3435}
3436