blob: 3f5a7fbc586b3973da3ac9c3d8dee0914a0ed07e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
Steve Naroff3fafa102007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/Basic/TargetInfo.h"
18#include "llvm/ADT/SmallVector.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000019#include "llvm/ADT/StringExtras.h"
Ted Kremenek738e6c02007-10-31 17:10:13 +000020#include "llvm/Bitcode/Serialize.h"
21#include "llvm/Bitcode/Deserialize.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000022
Chris Lattner4b009652007-07-25 00:24:17 +000023using namespace clang;
24
25enum FloatingRank {
26 FloatRank, DoubleRank, LongDoubleRank
27};
28
29ASTContext::~ASTContext() {
30 // Deallocate all the types.
31 while (!Types.empty()) {
32 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(Types.back())) {
33 // Destroy the object, but don't call delete. These are malloc'd.
34 FT->~FunctionTypeProto();
35 free(FT);
36 } else {
37 delete Types.back();
38 }
39 Types.pop_back();
40 }
41}
42
43void ASTContext::PrintStats() const {
44 fprintf(stderr, "*** AST Context Stats:\n");
45 fprintf(stderr, " %d types total.\n", (int)Types.size());
46 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
47 unsigned NumVector = 0, NumComplex = 0;
48 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
49
50 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Steve Naroff948fd372007-09-17 14:16:13 +000051 unsigned NumObjcInterfaces = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000052
53 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
54 Type *T = Types[i];
55 if (isa<BuiltinType>(T))
56 ++NumBuiltin;
57 else if (isa<PointerType>(T))
58 ++NumPointer;
59 else if (isa<ReferenceType>(T))
60 ++NumReference;
61 else if (isa<ComplexType>(T))
62 ++NumComplex;
63 else if (isa<ArrayType>(T))
64 ++NumArray;
65 else if (isa<VectorType>(T))
66 ++NumVector;
67 else if (isa<FunctionTypeNoProto>(T))
68 ++NumFunctionNP;
69 else if (isa<FunctionTypeProto>(T))
70 ++NumFunctionP;
71 else if (isa<TypedefType>(T))
72 ++NumTypeName;
73 else if (TagType *TT = dyn_cast<TagType>(T)) {
74 ++NumTagged;
75 switch (TT->getDecl()->getKind()) {
76 default: assert(0 && "Unknown tagged type!");
77 case Decl::Struct: ++NumTagStruct; break;
78 case Decl::Union: ++NumTagUnion; break;
79 case Decl::Class: ++NumTagClass; break;
80 case Decl::Enum: ++NumTagEnum; break;
81 }
Steve Naroff948fd372007-09-17 14:16:13 +000082 } else if (isa<ObjcInterfaceType>(T))
83 ++NumObjcInterfaces;
84 else {
Chris Lattner4b009652007-07-25 00:24:17 +000085 assert(0 && "Unknown type!");
86 }
87 }
88
89 fprintf(stderr, " %d builtin types\n", NumBuiltin);
90 fprintf(stderr, " %d pointer types\n", NumPointer);
91 fprintf(stderr, " %d reference types\n", NumReference);
92 fprintf(stderr, " %d complex types\n", NumComplex);
93 fprintf(stderr, " %d array types\n", NumArray);
94 fprintf(stderr, " %d vector types\n", NumVector);
95 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
96 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
97 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
98 fprintf(stderr, " %d tagged types\n", NumTagged);
99 fprintf(stderr, " %d struct types\n", NumTagStruct);
100 fprintf(stderr, " %d union types\n", NumTagUnion);
101 fprintf(stderr, " %d class types\n", NumTagClass);
102 fprintf(stderr, " %d enum types\n", NumTagEnum);
Steve Naroff948fd372007-09-17 14:16:13 +0000103 fprintf(stderr, " %d interface types\n", NumObjcInterfaces);
Chris Lattner4b009652007-07-25 00:24:17 +0000104 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
105 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
106 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
107 NumFunctionP*sizeof(FunctionTypeProto)+
108 NumFunctionNP*sizeof(FunctionTypeNoProto)+
109 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)));
110}
111
112
113void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
114 Types.push_back((R = QualType(new BuiltinType(K),0)).getTypePtr());
115}
116
Chris Lattner4b009652007-07-25 00:24:17 +0000117void ASTContext::InitBuiltinTypes() {
118 assert(VoidTy.isNull() && "Context reinitialized?");
119
120 // C99 6.2.5p19.
121 InitBuiltinType(VoidTy, BuiltinType::Void);
122
123 // C99 6.2.5p2.
124 InitBuiltinType(BoolTy, BuiltinType::Bool);
125 // C99 6.2.5p3.
126 if (Target.isCharSigned(SourceLocation()))
127 InitBuiltinType(CharTy, BuiltinType::Char_S);
128 else
129 InitBuiltinType(CharTy, BuiltinType::Char_U);
130 // C99 6.2.5p4.
131 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
132 InitBuiltinType(ShortTy, BuiltinType::Short);
133 InitBuiltinType(IntTy, BuiltinType::Int);
134 InitBuiltinType(LongTy, BuiltinType::Long);
135 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
136
137 // C99 6.2.5p6.
138 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
139 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
140 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
141 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
142 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
143
144 // C99 6.2.5p10.
145 InitBuiltinType(FloatTy, BuiltinType::Float);
146 InitBuiltinType(DoubleTy, BuiltinType::Double);
147 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
148
149 // C99 6.2.5p11.
150 FloatComplexTy = getComplexType(FloatTy);
151 DoubleComplexTy = getComplexType(DoubleTy);
152 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Steve Naroff9d12c902007-10-15 14:41:52 +0000153
154 BuiltinVaListType = QualType();
155 ObjcIdType = QualType();
156 IdStructType = 0;
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000157 ObjcClassType = QualType();
158 ClassStructType = 0;
159
Steve Narofff2e30312007-10-15 23:35:17 +0000160 ObjcConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000161
162 // void * type
163 VoidPtrTy = getPointerType(VoidTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000164}
165
166//===----------------------------------------------------------------------===//
167// Type Sizing and Analysis
168//===----------------------------------------------------------------------===//
169
170/// getTypeSize - Return the size of the specified type, in bits. This method
171/// does not work on incomplete types.
172std::pair<uint64_t, unsigned>
173ASTContext::getTypeInfo(QualType T, SourceLocation L) {
174 T = T.getCanonicalType();
175 uint64_t Size;
176 unsigned Align;
177 switch (T->getTypeClass()) {
178 case Type::TypeName: assert(0 && "Not a canonical type!");
179 case Type::FunctionNoProto:
180 case Type::FunctionProto:
181 default:
182 assert(0 && "Incomplete types have no size!");
Steve Naroff83c13012007-08-30 01:06:46 +0000183 case Type::VariableArray:
184 assert(0 && "VLAs not implemented yet!");
185 case Type::ConstantArray: {
186 ConstantArrayType *CAT = cast<ConstantArrayType>(T);
187
Chris Lattner4b009652007-07-25 00:24:17 +0000188 std::pair<uint64_t, unsigned> EltInfo =
Steve Naroff83c13012007-08-30 01:06:46 +0000189 getTypeInfo(CAT->getElementType(), L);
190 Size = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000191 Align = EltInfo.second;
192 break;
193 }
194 case Type::Vector: {
195 std::pair<uint64_t, unsigned> EltInfo =
196 getTypeInfo(cast<VectorType>(T)->getElementType(), L);
197 Size = EltInfo.first*cast<VectorType>(T)->getNumElements();
198 // FIXME: Vector alignment is not the alignment of its elements.
199 Align = EltInfo.second;
200 break;
201 }
202
203 case Type::Builtin: {
204 // FIXME: need to use TargetInfo to derive the target specific sizes. This
205 // implementation will suffice for play with vector support.
Chris Lattner858eece2007-09-22 18:29:59 +0000206 const llvm::fltSemantics *F;
Chris Lattner4b009652007-07-25 00:24:17 +0000207 switch (cast<BuiltinType>(T)->getKind()) {
208 default: assert(0 && "Unknown builtin type!");
209 case BuiltinType::Void:
210 assert(0 && "Incomplete types have no size!");
211 case BuiltinType::Bool: Target.getBoolInfo(Size, Align, L); break;
212 case BuiltinType::Char_S:
213 case BuiltinType::Char_U:
214 case BuiltinType::UChar:
215 case BuiltinType::SChar: Target.getCharInfo(Size, Align, L); break;
216 case BuiltinType::UShort:
217 case BuiltinType::Short: Target.getShortInfo(Size, Align, L); break;
218 case BuiltinType::UInt:
219 case BuiltinType::Int: Target.getIntInfo(Size, Align, L); break;
220 case BuiltinType::ULong:
221 case BuiltinType::Long: Target.getLongInfo(Size, Align, L); break;
222 case BuiltinType::ULongLong:
223 case BuiltinType::LongLong: Target.getLongLongInfo(Size, Align, L); break;
Chris Lattner858eece2007-09-22 18:29:59 +0000224 case BuiltinType::Float: Target.getFloatInfo(Size, Align, F, L); break;
225 case BuiltinType::Double: Target.getDoubleInfo(Size, Align, F, L);break;
226 case BuiltinType::LongDouble:Target.getLongDoubleInfo(Size,Align,F,L);break;
Chris Lattner4b009652007-07-25 00:24:17 +0000227 }
228 break;
229 }
230 case Type::Pointer: Target.getPointerInfo(Size, Align, L); break;
231 case Type::Reference:
232 // "When applied to a reference or a reference type, the result is the size
233 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
234 // FIXME: This is wrong for struct layout!
235 return getTypeInfo(cast<ReferenceType>(T)->getReferenceeType(), L);
236
237 case Type::Complex: {
238 // Complex types have the same alignment as their elements, but twice the
239 // size.
240 std::pair<uint64_t, unsigned> EltInfo =
241 getTypeInfo(cast<ComplexType>(T)->getElementType(), L);
242 Size = EltInfo.first*2;
243 Align = EltInfo.second;
244 break;
245 }
246 case Type::Tagged:
Chris Lattnereb56d292007-08-27 17:38:00 +0000247 TagType *TT = cast<TagType>(T);
248 if (RecordType *RT = dyn_cast<RecordType>(TT)) {
Devang Patel7a78e432007-11-01 19:11:01 +0000249 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl(), L);
Chris Lattnereb56d292007-08-27 17:38:00 +0000250 Size = Layout.getSize();
251 Align = Layout.getAlignment();
252 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(TT->getDecl())) {
Chris Lattner90a018d2007-08-28 18:24:31 +0000253 return getTypeInfo(ED->getIntegerType(), L);
Chris Lattnereb56d292007-08-27 17:38:00 +0000254 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000255 assert(0 && "Unimplemented type sizes!");
Chris Lattnereb56d292007-08-27 17:38:00 +0000256 }
Chris Lattner4b009652007-07-25 00:24:17 +0000257 break;
258 }
259
260 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
261 return std::make_pair(Size, Align);
262}
263
Devang Patel7a78e432007-11-01 19:11:01 +0000264/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000265/// specified record (struct/union/class), which indicates its size and field
266/// position information.
Devang Patel7a78e432007-11-01 19:11:01 +0000267const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D,
268 SourceLocation L) {
Chris Lattner4b009652007-07-25 00:24:17 +0000269 assert(D->isDefinition() && "Cannot get layout of forward declarations!");
270
271 // Look up this layout, if already laid out, return what we have.
Devang Patel7a78e432007-11-01 19:11:01 +0000272 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000273 if (Entry) return *Entry;
274
Devang Patel7a78e432007-11-01 19:11:01 +0000275 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
276 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
277 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000278 Entry = NewEntry;
279
280 uint64_t *FieldOffsets = new uint64_t[D->getNumMembers()];
281 uint64_t RecordSize = 0;
282 unsigned RecordAlign = 8; // Default alignment = 1 byte = 8 bits.
283
284 if (D->getKind() != Decl::Union) {
285 // Layout each field, for now, just sequentially, respecting alignment. In
286 // the future, this will need to be tweakable by targets.
287 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
288 const FieldDecl *FD = D->getMember(i);
289 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType(), L);
290 uint64_t FieldSize = FieldInfo.first;
291 unsigned FieldAlign = FieldInfo.second;
292
293 // Round up the current record size to the field's alignment boundary.
294 RecordSize = (RecordSize+FieldAlign-1) & ~(FieldAlign-1);
295
296 // Place this field at the current location.
297 FieldOffsets[i] = RecordSize;
298
299 // Reserve space for this field.
300 RecordSize += FieldSize;
301
302 // Remember max struct/class alignment.
303 RecordAlign = std::max(RecordAlign, FieldAlign);
304 }
305
306 // Finally, round the size of the total struct up to the alignment of the
307 // struct itself.
308 RecordSize = (RecordSize+RecordAlign-1) & ~(RecordAlign-1);
309 } else {
310 // Union layout just puts each member at the start of the record.
311 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
312 const FieldDecl *FD = D->getMember(i);
313 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType(), L);
314 uint64_t FieldSize = FieldInfo.first;
315 unsigned FieldAlign = FieldInfo.second;
316
317 // Round up the current record size to the field's alignment boundary.
318 RecordSize = std::max(RecordSize, FieldSize);
319
320 // Place this field at the start of the record.
321 FieldOffsets[i] = 0;
322
323 // Remember max struct/class alignment.
324 RecordAlign = std::max(RecordAlign, FieldAlign);
325 }
326 }
327
328 NewEntry->SetLayout(RecordSize, RecordAlign, FieldOffsets);
329 return *NewEntry;
330}
331
Chris Lattner4b009652007-07-25 00:24:17 +0000332//===----------------------------------------------------------------------===//
333// Type creation/memoization methods
334//===----------------------------------------------------------------------===//
335
336
337/// getComplexType - Return the uniqued reference to the type for a complex
338/// number with the specified element type.
339QualType ASTContext::getComplexType(QualType T) {
340 // Unique pointers, to guarantee there is only one pointer of a particular
341 // structure.
342 llvm::FoldingSetNodeID ID;
343 ComplexType::Profile(ID, T);
344
345 void *InsertPos = 0;
346 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
347 return QualType(CT, 0);
348
349 // If the pointee type isn't canonical, this won't be a canonical type either,
350 // so fill in the canonical type field.
351 QualType Canonical;
352 if (!T->isCanonical()) {
353 Canonical = getComplexType(T.getCanonicalType());
354
355 // Get the new insert position for the node we care about.
356 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
357 assert(NewIP == 0 && "Shouldn't be in the map!");
358 }
359 ComplexType *New = new ComplexType(T, Canonical);
360 Types.push_back(New);
361 ComplexTypes.InsertNode(New, InsertPos);
362 return QualType(New, 0);
363}
364
365
366/// getPointerType - Return the uniqued reference to the type for a pointer to
367/// the specified type.
368QualType ASTContext::getPointerType(QualType T) {
369 // Unique pointers, to guarantee there is only one pointer of a particular
370 // structure.
371 llvm::FoldingSetNodeID ID;
372 PointerType::Profile(ID, T);
373
374 void *InsertPos = 0;
375 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
376 return QualType(PT, 0);
377
378 // If the pointee type isn't canonical, this won't be a canonical type either,
379 // so fill in the canonical type field.
380 QualType Canonical;
381 if (!T->isCanonical()) {
382 Canonical = getPointerType(T.getCanonicalType());
383
384 // Get the new insert position for the node we care about.
385 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
386 assert(NewIP == 0 && "Shouldn't be in the map!");
387 }
388 PointerType *New = new PointerType(T, Canonical);
389 Types.push_back(New);
390 PointerTypes.InsertNode(New, InsertPos);
391 return QualType(New, 0);
392}
393
394/// getReferenceType - Return the uniqued reference to the type for a reference
395/// to the specified type.
396QualType ASTContext::getReferenceType(QualType T) {
397 // Unique pointers, to guarantee there is only one pointer of a particular
398 // structure.
399 llvm::FoldingSetNodeID ID;
400 ReferenceType::Profile(ID, T);
401
402 void *InsertPos = 0;
403 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
404 return QualType(RT, 0);
405
406 // If the referencee type isn't canonical, this won't be a canonical type
407 // either, so fill in the canonical type field.
408 QualType Canonical;
409 if (!T->isCanonical()) {
410 Canonical = getReferenceType(T.getCanonicalType());
411
412 // Get the new insert position for the node we care about.
413 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
414 assert(NewIP == 0 && "Shouldn't be in the map!");
415 }
416
417 ReferenceType *New = new ReferenceType(T, Canonical);
418 Types.push_back(New);
419 ReferenceTypes.InsertNode(New, InsertPos);
420 return QualType(New, 0);
421}
422
Steve Naroff83c13012007-08-30 01:06:46 +0000423/// getConstantArrayType - Return the unique reference to the type for an
424/// array of the specified element type.
425QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroff24c9b982007-08-30 18:10:14 +0000426 const llvm::APInt &ArySize,
427 ArrayType::ArraySizeModifier ASM,
428 unsigned EltTypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +0000429 llvm::FoldingSetNodeID ID;
Steve Naroff83c13012007-08-30 01:06:46 +0000430 ConstantArrayType::Profile(ID, EltTy, ArySize);
Chris Lattner4b009652007-07-25 00:24:17 +0000431
432 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +0000433 if (ConstantArrayType *ATP =
434 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +0000435 return QualType(ATP, 0);
436
437 // If the element type isn't canonical, this won't be a canonical type either,
438 // so fill in the canonical type field.
439 QualType Canonical;
440 if (!EltTy->isCanonical()) {
Steve Naroff24c9b982007-08-30 18:10:14 +0000441 Canonical = getConstantArrayType(EltTy.getCanonicalType(), ArySize,
442 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +0000443 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +0000444 ConstantArrayType *NewIP =
445 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
446
Chris Lattner4b009652007-07-25 00:24:17 +0000447 assert(NewIP == 0 && "Shouldn't be in the map!");
448 }
449
Steve Naroff24c9b982007-08-30 18:10:14 +0000450 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize,
451 ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +0000452 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000453 Types.push_back(New);
454 return QualType(New, 0);
455}
456
Steve Naroffe2579e32007-08-30 18:14:25 +0000457/// getVariableArrayType - Returns a non-unique reference to the type for a
458/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +0000459QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
460 ArrayType::ArraySizeModifier ASM,
461 unsigned EltTypeQuals) {
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000462 if (NumElts) {
463 // Since we don't unique expressions, it isn't possible to unique VLA's
464 // that have an expression provided for their size.
465
Ted Kremenek2058dc42007-10-30 16:41:53 +0000466 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
467 ASM, EltTypeQuals);
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000468
Ted Kremenek2058dc42007-10-30 16:41:53 +0000469 CompleteVariableArrayTypes.push_back(New);
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000470 Types.push_back(New);
471 return QualType(New, 0);
472 }
473 else {
474 // No size is provided for the VLA. These we can unique.
475 llvm::FoldingSetNodeID ID;
476 VariableArrayType::Profile(ID, EltTy);
477
478 void *InsertPos = 0;
479 if (VariableArrayType *ATP =
480 IncompleteVariableArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
481 return QualType(ATP, 0);
482
483 // If the element type isn't canonical, this won't be a canonical type
484 // either, so fill in the canonical type field.
485 QualType Canonical;
486
487 if (!EltTy->isCanonical()) {
488 Canonical = getVariableArrayType(EltTy.getCanonicalType(), NumElts,
489 ASM, EltTypeQuals);
490
491 // Get the new insert position for the node we care about.
492 VariableArrayType *NewIP =
493 IncompleteVariableArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
494
495 assert(NewIP == 0 && "Shouldn't be in the map!");
496 }
497
498 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
499 ASM, EltTypeQuals);
500
501 IncompleteVariableArrayTypes.InsertNode(New, InsertPos);
502 Types.push_back(New);
503 return QualType(New, 0);
504 }
Steve Naroff83c13012007-08-30 01:06:46 +0000505}
506
Chris Lattner4b009652007-07-25 00:24:17 +0000507/// getVectorType - Return the unique reference to a vector type of
508/// the specified element type and size. VectorType must be a built-in type.
509QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
510 BuiltinType *baseType;
511
512 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
513 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
514
515 // Check if we've already instantiated a vector of this type.
516 llvm::FoldingSetNodeID ID;
517 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
518 void *InsertPos = 0;
519 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
520 return QualType(VTP, 0);
521
522 // If the element type isn't canonical, this won't be a canonical type either,
523 // so fill in the canonical type field.
524 QualType Canonical;
525 if (!vecType->isCanonical()) {
526 Canonical = getVectorType(vecType.getCanonicalType(), NumElts);
527
528 // Get the new insert position for the node we care about.
529 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
530 assert(NewIP == 0 && "Shouldn't be in the map!");
531 }
532 VectorType *New = new VectorType(vecType, NumElts, Canonical);
533 VectorTypes.InsertNode(New, InsertPos);
534 Types.push_back(New);
535 return QualType(New, 0);
536}
537
538/// getOCUVectorType - Return the unique reference to an OCU vector type of
539/// the specified element type and size. VectorType must be a built-in type.
540QualType ASTContext::getOCUVectorType(QualType vecType, unsigned NumElts) {
541 BuiltinType *baseType;
542
543 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
544 assert(baseType != 0 && "getOCUVectorType(): Expecting a built-in type");
545
546 // Check if we've already instantiated a vector of this type.
547 llvm::FoldingSetNodeID ID;
548 VectorType::Profile(ID, vecType, NumElts, Type::OCUVector);
549 void *InsertPos = 0;
550 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
551 return QualType(VTP, 0);
552
553 // If the element type isn't canonical, this won't be a canonical type either,
554 // so fill in the canonical type field.
555 QualType Canonical;
556 if (!vecType->isCanonical()) {
557 Canonical = getOCUVectorType(vecType.getCanonicalType(), NumElts);
558
559 // Get the new insert position for the node we care about.
560 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
561 assert(NewIP == 0 && "Shouldn't be in the map!");
562 }
563 OCUVectorType *New = new OCUVectorType(vecType, NumElts, Canonical);
564 VectorTypes.InsertNode(New, InsertPos);
565 Types.push_back(New);
566 return QualType(New, 0);
567}
568
569/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
570///
571QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) {
572 // Unique functions, to guarantee there is only one function of a particular
573 // structure.
574 llvm::FoldingSetNodeID ID;
575 FunctionTypeNoProto::Profile(ID, ResultTy);
576
577 void *InsertPos = 0;
578 if (FunctionTypeNoProto *FT =
579 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos))
580 return QualType(FT, 0);
581
582 QualType Canonical;
583 if (!ResultTy->isCanonical()) {
584 Canonical = getFunctionTypeNoProto(ResultTy.getCanonicalType());
585
586 // Get the new insert position for the node we care about.
587 FunctionTypeNoProto *NewIP =
588 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos);
589 assert(NewIP == 0 && "Shouldn't be in the map!");
590 }
591
592 FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical);
593 Types.push_back(New);
594 FunctionTypeProtos.InsertNode(New, InsertPos);
595 return QualType(New, 0);
596}
597
598/// getFunctionType - Return a normal function type with a typed argument
599/// list. isVariadic indicates whether the argument list includes '...'.
600QualType ASTContext::getFunctionType(QualType ResultTy, QualType *ArgArray,
601 unsigned NumArgs, bool isVariadic) {
602 // Unique functions, to guarantee there is only one function of a particular
603 // structure.
604 llvm::FoldingSetNodeID ID;
605 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic);
606
607 void *InsertPos = 0;
608 if (FunctionTypeProto *FTP =
609 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos))
610 return QualType(FTP, 0);
611
612 // Determine whether the type being created is already canonical or not.
613 bool isCanonical = ResultTy->isCanonical();
614 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
615 if (!ArgArray[i]->isCanonical())
616 isCanonical = false;
617
618 // If this type isn't canonical, get the canonical version of it.
619 QualType Canonical;
620 if (!isCanonical) {
621 llvm::SmallVector<QualType, 16> CanonicalArgs;
622 CanonicalArgs.reserve(NumArgs);
623 for (unsigned i = 0; i != NumArgs; ++i)
624 CanonicalArgs.push_back(ArgArray[i].getCanonicalType());
625
626 Canonical = getFunctionType(ResultTy.getCanonicalType(),
627 &CanonicalArgs[0], NumArgs,
628 isVariadic);
629
630 // Get the new insert position for the node we care about.
631 FunctionTypeProto *NewIP =
632 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos);
633 assert(NewIP == 0 && "Shouldn't be in the map!");
634 }
635
636 // FunctionTypeProto objects are not allocated with new because they have a
637 // variable size array (for parameter types) at the end of them.
638 FunctionTypeProto *FTP =
639 (FunctionTypeProto*)malloc(sizeof(FunctionTypeProto) +
640 NumArgs*sizeof(QualType));
641 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic,
642 Canonical);
643 Types.push_back(FTP);
644 FunctionTypeProtos.InsertNode(FTP, InsertPos);
645 return QualType(FTP, 0);
646}
647
648/// getTypedefType - Return the unique reference to the type for the
649/// specified typename decl.
650QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
651 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
652
653 QualType Canonical = Decl->getUnderlyingType().getCanonicalType();
654 Decl->TypeForDecl = new TypedefType(Decl, Canonical);
655 Types.push_back(Decl->TypeForDecl);
656 return QualType(Decl->TypeForDecl, 0);
657}
658
Steve Naroff81f1bba2007-09-06 21:24:23 +0000659/// getObjcInterfaceType - Return the unique reference to the type for the
660/// specified ObjC interface decl.
661QualType ASTContext::getObjcInterfaceType(ObjcInterfaceDecl *Decl) {
662 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
663
664 Decl->TypeForDecl = new ObjcInterfaceType(Decl);
665 Types.push_back(Decl->TypeForDecl);
666 return QualType(Decl->TypeForDecl, 0);
667}
668
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000669/// getObjcQualifiedInterfaceType - Return a
670/// ObjcQualifiedInterfaceType type for the given interface decl and
671/// the conforming protocol list.
672QualType ASTContext::getObjcQualifiedInterfaceType(ObjcInterfaceDecl *Decl,
673 ObjcProtocolDecl **Protocols, unsigned NumProtocols) {
674 ObjcInterfaceType *IType =
675 cast<ObjcInterfaceType>(getObjcInterfaceType(Decl));
676
677 llvm::FoldingSetNodeID ID;
678 ObjcQualifiedInterfaceType::Profile(ID, IType, Protocols, NumProtocols);
679
680 void *InsertPos = 0;
681 if (ObjcQualifiedInterfaceType *QT =
682 ObjcQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
683 return QualType(QT, 0);
684
685 // No Match;
Chris Lattnerd855a6e2007-10-11 03:36:41 +0000686 ObjcQualifiedInterfaceType *QType =
687 new ObjcQualifiedInterfaceType(IType, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000688 Types.push_back(QType);
689 ObjcQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
690 return QualType(QType, 0);
691}
692
Steve Naroff0604dd92007-08-01 18:02:17 +0000693/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique
694/// TypeOfExpr AST's (since expression's are never shared). For example,
695/// multiple declarations that refer to "typeof(x)" all contain different
696/// DeclRefExpr's. This doesn't effect the type checker, since it operates
697/// on canonical type's (which are always unique).
Steve Naroff11b649c2007-08-01 17:20:42 +0000698QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
Steve Naroff7cbb1462007-07-31 12:34:36 +0000699 QualType Canonical = tofExpr->getType().getCanonicalType();
Steve Naroff0604dd92007-08-01 18:02:17 +0000700 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
701 Types.push_back(toe);
702 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000703}
704
Steve Naroff0604dd92007-08-01 18:02:17 +0000705/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
706/// TypeOfType AST's. The only motivation to unique these nodes would be
707/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
708/// an issue. This doesn't effect the type checker, since it operates
709/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +0000710QualType ASTContext::getTypeOfType(QualType tofType) {
711 QualType Canonical = tofType.getCanonicalType();
Steve Naroff0604dd92007-08-01 18:02:17 +0000712 TypeOfType *tot = new TypeOfType(tofType, Canonical);
713 Types.push_back(tot);
714 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000715}
716
Chris Lattner4b009652007-07-25 00:24:17 +0000717/// getTagDeclType - Return the unique reference to the type for the
718/// specified TagDecl (struct/union/class/enum) decl.
719QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +0000720 assert (Decl);
721
Ted Kremenekf05026d2007-11-14 00:03:20 +0000722 // The decl stores the type cache.
Ted Kremenekae8fa032007-11-26 21:16:01 +0000723 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Ted Kremenekf05026d2007-11-14 00:03:20 +0000724
725 TagType* T = new TagType(Decl, QualType());
Ted Kremenekae8fa032007-11-26 21:16:01 +0000726 Types.push_back(T);
727 Decl->TypeForDecl = T;
Ted Kremenekf05026d2007-11-14 00:03:20 +0000728
729 return QualType(T, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000730}
731
732/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
733/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
734/// needs to agree with the definition in <stddef.h>.
735QualType ASTContext::getSizeType() const {
736 // On Darwin, size_t is defined as a "long unsigned int".
737 // FIXME: should derive from "Target".
738 return UnsignedLongTy;
739}
740
741/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
742/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
743QualType ASTContext::getPointerDiffType() const {
744 // On Darwin, ptrdiff_t is defined as a "int". This seems like a bug...
745 // FIXME: should derive from "Target".
746 return IntTy;
747}
748
749/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
750/// routine will assert if passed a built-in type that isn't an integer or enum.
751static int getIntegerRank(QualType t) {
752 if (const TagType *TT = dyn_cast<TagType>(t.getCanonicalType())) {
753 assert(TT->getDecl()->getKind() == Decl::Enum && "not an int or enum");
754 return 4;
755 }
756
757 const BuiltinType *BT = cast<BuiltinType>(t.getCanonicalType());
758 switch (BT->getKind()) {
759 default:
760 assert(0 && "getIntegerRank(): not a built-in integer");
761 case BuiltinType::Bool:
762 return 1;
763 case BuiltinType::Char_S:
764 case BuiltinType::Char_U:
765 case BuiltinType::SChar:
766 case BuiltinType::UChar:
767 return 2;
768 case BuiltinType::Short:
769 case BuiltinType::UShort:
770 return 3;
771 case BuiltinType::Int:
772 case BuiltinType::UInt:
773 return 4;
774 case BuiltinType::Long:
775 case BuiltinType::ULong:
776 return 5;
777 case BuiltinType::LongLong:
778 case BuiltinType::ULongLong:
779 return 6;
780 }
781}
782
783/// getFloatingRank - Return a relative rank for floating point types.
784/// This routine will assert if passed a built-in type that isn't a float.
785static int getFloatingRank(QualType T) {
786 T = T.getCanonicalType();
787 if (ComplexType *CT = dyn_cast<ComplexType>(T))
788 return getFloatingRank(CT->getElementType());
789
790 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner5003e8b2007-11-01 05:03:41 +0000791 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +0000792 case BuiltinType::Float: return FloatRank;
793 case BuiltinType::Double: return DoubleRank;
794 case BuiltinType::LongDouble: return LongDoubleRank;
795 }
796}
797
Steve Narofffa0c4532007-08-27 01:41:48 +0000798/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
799/// point or a complex type (based on typeDomain/typeSize).
800/// 'typeDomain' is a real floating point or complex type.
801/// 'typeSize' is a real floating point or complex type.
Steve Naroff3cf497f2007-08-27 01:27:54 +0000802QualType ASTContext::getFloatingTypeOfSizeWithinDomain(
803 QualType typeSize, QualType typeDomain) const {
804 if (typeDomain->isComplexType()) {
805 switch (getFloatingRank(typeSize)) {
Steve Narofffa0c4532007-08-27 01:41:48 +0000806 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +0000807 case FloatRank: return FloatComplexTy;
808 case DoubleRank: return DoubleComplexTy;
809 case LongDoubleRank: return LongDoubleComplexTy;
810 }
Chris Lattner4b009652007-07-25 00:24:17 +0000811 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000812 if (typeDomain->isRealFloatingType()) {
813 switch (getFloatingRank(typeSize)) {
Steve Narofffa0c4532007-08-27 01:41:48 +0000814 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +0000815 case FloatRank: return FloatTy;
816 case DoubleRank: return DoubleTy;
817 case LongDoubleRank: return LongDoubleTy;
818 }
819 }
820 assert(0 && "getFloatingTypeOfSizeWithinDomain(): illegal domain");
Chris Lattner1d2b4612007-09-16 19:23:47 +0000821 //an invalid return value, but the assert
822 //will ensure that this code is never reached.
823 return VoidTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000824}
825
Steve Naroff45fc9822007-08-27 15:30:22 +0000826/// compareFloatingType - Handles 3 different combos:
827/// float/float, float/complex, complex/complex.
828/// If lt > rt, return 1. If lt == rt, return 0. If lt < rt, return -1.
829int ASTContext::compareFloatingType(QualType lt, QualType rt) {
830 if (getFloatingRank(lt) == getFloatingRank(rt))
831 return 0;
832 if (getFloatingRank(lt) > getFloatingRank(rt))
833 return 1;
834 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +0000835}
836
837// maxIntegerType - Returns the highest ranked integer type. Handles 3 case:
838// unsigned/unsigned, signed/signed, signed/unsigned. C99 6.3.1.8p1.
839QualType ASTContext::maxIntegerType(QualType lhs, QualType rhs) {
840 if (lhs == rhs) return lhs;
841
842 bool t1Unsigned = lhs->isUnsignedIntegerType();
843 bool t2Unsigned = rhs->isUnsignedIntegerType();
844
845 if ((t1Unsigned && t2Unsigned) || (!t1Unsigned && !t2Unsigned))
846 return getIntegerRank(lhs) >= getIntegerRank(rhs) ? lhs : rhs;
847
848 // We have two integer types with differing signs
849 QualType unsignedType = t1Unsigned ? lhs : rhs;
850 QualType signedType = t1Unsigned ? rhs : lhs;
851
852 if (getIntegerRank(unsignedType) >= getIntegerRank(signedType))
853 return unsignedType;
854 else {
855 // FIXME: Need to check if the signed type can represent all values of the
856 // unsigned type. If it can, then the result is the signed type.
857 // If it can't, then the result is the unsigned version of the signed type.
858 // Should probably add a helper that returns a signed integer type from
859 // an unsigned (and vice versa). C99 6.3.1.8.
860 return signedType;
861 }
862}
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000863
864// getCFConstantStringType - Return the type used for constant CFStrings.
865QualType ASTContext::getCFConstantStringType() {
866 if (!CFConstantStringTypeDecl) {
867 CFConstantStringTypeDecl = new RecordDecl(Decl::Struct, SourceLocation(),
Steve Naroff0add5d22007-11-03 11:27:19 +0000868 &Idents.get("NSConstantString"),
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000869 0);
Anders Carlssonbb2cf512007-11-19 00:25:30 +0000870 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000871
872 // const int *isa;
873 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +0000874 // int flags;
875 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000876 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +0000877 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000878 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +0000879 FieldTypes[3] = LongTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000880 // Create fields
Anders Carlssonbb2cf512007-11-19 00:25:30 +0000881 FieldDecl *FieldDecls[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000882
Anders Carlssonbb2cf512007-11-19 00:25:30 +0000883 for (unsigned i = 0; i < 4; ++i)
Steve Naroffdc1ad762007-09-14 02:20:46 +0000884 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000885
886 CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
887 }
888
889 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +0000890}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000891
Anders Carlssone3f02572007-10-29 06:33:42 +0000892// This returns true if a type has been typedefed to BOOL:
893// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +0000894static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +0000895 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnercb034cb2007-10-30 20:27:44 +0000896 return !strcmp(TT->getDecl()->getName(), "BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +0000897
898 return false;
899}
900
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000901/// getObjcEncodingTypeSize returns size of type for objective-c encoding
902/// purpose.
903int ASTContext::getObjcEncodingTypeSize(QualType type) {
904 SourceLocation Loc;
905 uint64_t sz = getTypeSize(type, Loc);
906
907 // Make all integer and enum types at least as large as an int
908 if (sz > 0 && type->isIntegralType())
909 sz = std::max(sz, getTypeSize(IntTy, Loc));
910 // Treat arrays as pointers, since that's how they're passed in.
911 else if (type->isArrayType())
912 sz = getTypeSize(VoidPtrTy, Loc);
913 return sz / getTypeSize(CharTy, Loc);
914}
915
916/// getObjcEncodingForMethodDecl - Return the encoded type for this method
917/// declaration.
918void ASTContext::getObjcEncodingForMethodDecl(ObjcMethodDecl *Decl,
919 std::string& S)
920{
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +0000921 // Encode type qualifer, 'in', 'inout', etc. for the return type.
922 getObjcEncodingForTypeQualifier(Decl->getObjcDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000923 // Encode result type.
924 getObjcEncodingForType(Decl->getResultType(), S);
925 // Compute size of all parameters.
926 // Start with computing size of a pointer in number of bytes.
927 // FIXME: There might(should) be a better way of doing this computation!
928 SourceLocation Loc;
929 int PtrSize = getTypeSize(VoidPtrTy, Loc) / getTypeSize(CharTy, Loc);
930 // The first two arguments (self and _cmd) are pointers; account for
931 // their size.
932 int ParmOffset = 2 * PtrSize;
933 int NumOfParams = Decl->getNumParams();
934 for (int i = 0; i < NumOfParams; i++) {
935 QualType PType = Decl->getParamDecl(i)->getType();
936 int sz = getObjcEncodingTypeSize (PType);
937 assert (sz > 0 && "getObjcEncodingForMethodDecl - Incomplete param type");
938 ParmOffset += sz;
939 }
940 S += llvm::utostr(ParmOffset);
941 S += "@0:";
942 S += llvm::utostr(PtrSize);
943
944 // Argument types.
945 ParmOffset = 2 * PtrSize;
946 for (int i = 0; i < NumOfParams; i++) {
947 QualType PType = Decl->getParamDecl(i)->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +0000948 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000949 // 'in', 'inout', etc.
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +0000950 getObjcEncodingForTypeQualifier(
951 Decl->getParamDecl(i)->getObjcDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000952 getObjcEncodingForType(PType, S);
953 S += llvm::utostr(ParmOffset);
954 ParmOffset += getObjcEncodingTypeSize(PType);
955 }
956}
957
Anders Carlsson36f07d82007-10-29 05:01:08 +0000958void ASTContext::getObjcEncodingForType(QualType T, std::string& S) const
959{
Anders Carlssone3f02572007-10-29 06:33:42 +0000960 // FIXME: This currently doesn't encode:
961 // @ An object (whether statically typed or typed id)
962 // # A class object (Class)
963 // : A method selector (SEL)
964 // {name=type...} A structure
965 // (name=type...) A union
966 // bnum A bit field of num bits
967
968 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +0000969 char encoding;
970 switch (BT->getKind()) {
971 case BuiltinType::Void:
972 encoding = 'v';
973 break;
974 case BuiltinType::Bool:
975 encoding = 'B';
976 break;
977 case BuiltinType::Char_U:
978 case BuiltinType::UChar:
979 encoding = 'C';
980 break;
981 case BuiltinType::UShort:
982 encoding = 'S';
983 break;
984 case BuiltinType::UInt:
985 encoding = 'I';
986 break;
987 case BuiltinType::ULong:
988 encoding = 'L';
989 break;
990 case BuiltinType::ULongLong:
991 encoding = 'Q';
992 break;
993 case BuiltinType::Char_S:
994 case BuiltinType::SChar:
995 encoding = 'c';
996 break;
997 case BuiltinType::Short:
998 encoding = 's';
999 break;
1000 case BuiltinType::Int:
1001 encoding = 'i';
1002 break;
1003 case BuiltinType::Long:
1004 encoding = 'l';
1005 break;
1006 case BuiltinType::LongLong:
1007 encoding = 'q';
1008 break;
1009 case BuiltinType::Float:
1010 encoding = 'f';
1011 break;
1012 case BuiltinType::Double:
1013 encoding = 'd';
1014 break;
1015 case BuiltinType::LongDouble:
1016 encoding = 'd';
1017 break;
1018 default:
1019 assert(0 && "Unhandled builtin type kind");
1020 }
1021
1022 S += encoding;
Anders Carlssone3f02572007-10-29 06:33:42 +00001023 } else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001024 QualType PointeeTy = PT->getPointeeType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001025 if (isObjcIdType(PointeeTy) || PointeeTy->isObjcInterfaceType()) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001026 S += '@';
1027 return;
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001028 } else if (isObjcClassType(PointeeTy)) {
1029 S += '#';
1030 return;
1031 } else if (isObjcSelType(PointeeTy)) {
1032 S += ':';
1033 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001034 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00001035
1036 if (PointeeTy->isCharType()) {
1037 // char pointer types should be encoded as '*' unless it is a
1038 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00001039 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001040 S += '*';
1041 return;
1042 }
1043 }
1044
1045 S += '^';
1046 getObjcEncodingForType(PT->getPointeeType(), S);
Anders Carlssone3f02572007-10-29 06:33:42 +00001047 } else if (const ArrayType *AT = T->getAsArrayType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001048 S += '[';
1049
1050 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1051 S += llvm::utostr(CAT->getSize().getZExtValue());
1052 else
1053 assert(0 && "Unhandled array type!");
1054
1055 getObjcEncodingForType(AT->getElementType(), S);
1056 S += ']';
Anders Carlsson5695bb72007-10-30 00:06:20 +00001057 } else if (T->getAsFunctionType()) {
1058 S += '?';
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00001059 } else if (const RecordType *RTy = T->getAsRecordType()) {
1060 RecordDecl *RDecl= RTy->getDecl();
1061 S += '{';
1062 S += RDecl->getName();
1063 S += '=';
1064 for (int i = 0; i < RDecl->getNumMembers(); i++) {
1065 FieldDecl *field = RDecl->getMember(i);
1066 getObjcEncodingForType(field->getType(), S);
1067 }
1068 S += '}';
Anders Carlsson36f07d82007-10-29 05:01:08 +00001069 } else
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00001070 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001071}
1072
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001073void ASTContext::getObjcEncodingForTypeQualifier(Decl::ObjcDeclQualifier QT,
1074 std::string& S) const {
1075 if (QT & Decl::OBJC_TQ_In)
1076 S += 'n';
1077 if (QT & Decl::OBJC_TQ_Inout)
1078 S += 'N';
1079 if (QT & Decl::OBJC_TQ_Out)
1080 S += 'o';
1081 if (QT & Decl::OBJC_TQ_Bycopy)
1082 S += 'O';
1083 if (QT & Decl::OBJC_TQ_Byref)
1084 S += 'R';
1085 if (QT & Decl::OBJC_TQ_Oneway)
1086 S += 'V';
1087}
1088
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001089void ASTContext::setBuiltinVaListType(QualType T)
1090{
1091 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
1092
1093 BuiltinVaListType = T;
1094}
1095
Steve Naroff9d12c902007-10-15 14:41:52 +00001096void ASTContext::setObjcIdType(TypedefDecl *TD)
1097{
1098 assert(ObjcIdType.isNull() && "'id' type already set!");
1099
1100 ObjcIdType = getTypedefType(TD);
1101
1102 // typedef struct objc_object *id;
1103 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1104 assert(ptr && "'id' incorrectly typed");
1105 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1106 assert(rec && "'id' incorrectly typed");
1107 IdStructType = rec;
1108}
1109
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001110void ASTContext::setObjcSelType(TypedefDecl *TD)
1111{
1112 assert(ObjcSelType.isNull() && "'SEL' type already set!");
1113
1114 ObjcSelType = getTypedefType(TD);
1115
1116 // typedef struct objc_selector *SEL;
1117 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1118 assert(ptr && "'SEL' incorrectly typed");
1119 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1120 assert(rec && "'SEL' incorrectly typed");
1121 SelStructType = rec;
1122}
1123
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001124void ASTContext::setObjcProtoType(TypedefDecl *TD)
1125{
1126 assert(ObjcProtoType.isNull() && "'Protocol' type already set!");
1127
1128 // typedef struct Protocol Protocol;
1129 ObjcProtoType = TD->getUnderlyingType();
1130 // Protocol * type
1131 ObjcProtoType = getPointerType(ObjcProtoType);
1132 ProtoStructType = TD->getUnderlyingType()->getAsStructureType();
1133}
1134
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001135void ASTContext::setObjcClassType(TypedefDecl *TD)
1136{
1137 assert(ObjcClassType.isNull() && "'Class' type already set!");
1138
1139 ObjcClassType = getTypedefType(TD);
1140
1141 // typedef struct objc_class *Class;
1142 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1143 assert(ptr && "'Class' incorrectly typed");
1144 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1145 assert(rec && "'Class' incorrectly typed");
1146 ClassStructType = rec;
1147}
1148
Steve Narofff2e30312007-10-15 23:35:17 +00001149void ASTContext::setObjcConstantStringInterface(ObjcInterfaceDecl *Decl) {
1150 assert(ObjcConstantStringType.isNull() &&
1151 "'NSConstantString' type already set!");
1152
1153 ObjcConstantStringType = getObjcInterfaceType(Decl);
1154}
1155
Steve Naroff85f0dc52007-10-15 20:41:53 +00001156bool ASTContext::builtinTypesAreCompatible(QualType lhs, QualType rhs) {
1157 const BuiltinType *lBuiltin = lhs->getAsBuiltinType();
1158 const BuiltinType *rBuiltin = rhs->getAsBuiltinType();
1159
1160 return lBuiltin->getKind() == rBuiltin->getKind();
1161}
1162
1163
1164bool ASTContext::objcTypesAreCompatible(QualType lhs, QualType rhs) {
1165 if (lhs->isObjcInterfaceType() && isObjcIdType(rhs))
1166 return true;
1167 else if (isObjcIdType(lhs) && rhs->isObjcInterfaceType())
1168 return true;
1169 return false;
1170}
1171
1172bool ASTContext::interfaceTypesAreCompatible(QualType lhs, QualType rhs) {
1173 return true; // FIXME: IMPLEMENT.
1174}
1175
Chris Lattner5003e8b2007-11-01 05:03:41 +00001176bool ASTContext::vectorTypesAreCompatible(QualType lhs, QualType rhs) {
1177 const VectorType *lVector = lhs->getAsVectorType();
1178 const VectorType *rVector = rhs->getAsVectorType();
1179
1180 if ((lVector->getElementType().getCanonicalType() ==
1181 rVector->getElementType().getCanonicalType()) &&
1182 (lVector->getNumElements() == rVector->getNumElements()))
1183 return true;
1184 return false;
1185}
1186
Steve Naroff85f0dc52007-10-15 20:41:53 +00001187// C99 6.2.7p1: If both are complete types, then the following additional
1188// requirements apply...FIXME (handle compatibility across source files).
1189bool ASTContext::tagTypesAreCompatible(QualType lhs, QualType rhs) {
1190 TagDecl *ldecl = cast<TagType>(lhs.getCanonicalType())->getDecl();
1191 TagDecl *rdecl = cast<TagType>(rhs.getCanonicalType())->getDecl();
1192
1193 if (ldecl->getKind() == Decl::Struct && rdecl->getKind() == Decl::Struct) {
1194 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1195 return true;
1196 }
1197 if (ldecl->getKind() == Decl::Union && rdecl->getKind() == Decl::Union) {
1198 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1199 return true;
1200 }
Steve Naroff4a5e2072007-11-07 06:03:51 +00001201 // "Class" and "id" are compatible built-in structure types.
1202 if (isObjcIdType(lhs) && isObjcClassType(rhs) ||
1203 isObjcClassType(lhs) && isObjcIdType(rhs))
1204 return true;
Steve Naroff85f0dc52007-10-15 20:41:53 +00001205 return false;
1206}
1207
1208bool ASTContext::pointerTypesAreCompatible(QualType lhs, QualType rhs) {
1209 // C99 6.7.5.1p2: For two pointer types to be compatible, both shall be
1210 // identically qualified and both shall be pointers to compatible types.
1211 if (lhs.getQualifiers() != rhs.getQualifiers())
1212 return false;
1213
1214 QualType ltype = cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
1215 QualType rtype = cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
1216
1217 return typesAreCompatible(ltype, rtype);
1218}
1219
Bill Wendling6a9d8542007-12-03 07:33:35 +00001220// C++ 5.17p6: When the left operand of an assignment operator denotes a
Steve Naroff85f0dc52007-10-15 20:41:53 +00001221// reference to T, the operation assigns to the object of type T denoted by the
1222// reference.
1223bool ASTContext::referenceTypesAreCompatible(QualType lhs, QualType rhs) {
1224 QualType ltype = lhs;
1225
1226 if (lhs->isReferenceType())
1227 ltype = cast<ReferenceType>(lhs.getCanonicalType())->getReferenceeType();
1228
1229 QualType rtype = rhs;
1230
1231 if (rhs->isReferenceType())
1232 rtype = cast<ReferenceType>(rhs.getCanonicalType())->getReferenceeType();
1233
1234 return typesAreCompatible(ltype, rtype);
1235}
1236
1237bool ASTContext::functionTypesAreCompatible(QualType lhs, QualType rhs) {
1238 const FunctionType *lbase = cast<FunctionType>(lhs.getCanonicalType());
1239 const FunctionType *rbase = cast<FunctionType>(rhs.getCanonicalType());
1240 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1241 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1242
1243 // first check the return types (common between C99 and K&R).
1244 if (!typesAreCompatible(lbase->getResultType(), rbase->getResultType()))
1245 return false;
1246
1247 if (lproto && rproto) { // two C99 style function prototypes
1248 unsigned lproto_nargs = lproto->getNumArgs();
1249 unsigned rproto_nargs = rproto->getNumArgs();
1250
1251 if (lproto_nargs != rproto_nargs)
1252 return false;
1253
1254 // both prototypes have the same number of arguments.
1255 if ((lproto->isVariadic() && !rproto->isVariadic()) ||
1256 (rproto->isVariadic() && !lproto->isVariadic()))
1257 return false;
1258
1259 // The use of ellipsis agree...now check the argument types.
1260 for (unsigned i = 0; i < lproto_nargs; i++)
1261 if (!typesAreCompatible(lproto->getArgType(i), rproto->getArgType(i)))
1262 return false;
1263 return true;
1264 }
1265 if (!lproto && !rproto) // two K&R style function decls, nothing to do.
1266 return true;
1267
1268 // we have a mixture of K&R style with C99 prototypes
1269 const FunctionTypeProto *proto = lproto ? lproto : rproto;
1270
1271 if (proto->isVariadic())
1272 return false;
1273
1274 // FIXME: Each parameter type T in the prototype must be compatible with the
1275 // type resulting from applying the usual argument conversions to T.
1276 return true;
1277}
1278
1279bool ASTContext::arrayTypesAreCompatible(QualType lhs, QualType rhs) {
1280 QualType ltype = cast<ArrayType>(lhs.getCanonicalType())->getElementType();
1281 QualType rtype = cast<ArrayType>(rhs.getCanonicalType())->getElementType();
1282
1283 if (!typesAreCompatible(ltype, rtype))
1284 return false;
1285
1286 // FIXME: If both types specify constant sizes, then the sizes must also be
1287 // the same. Even if the sizes are the same, GCC produces an error.
1288 return true;
1289}
1290
1291/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
1292/// both shall have the identically qualified version of a compatible type.
1293/// C99 6.2.7p1: Two types have compatible types if their types are the
1294/// same. See 6.7.[2,3,5] for additional rules.
1295bool ASTContext::typesAreCompatible(QualType lhs, QualType rhs) {
1296 QualType lcanon = lhs.getCanonicalType();
1297 QualType rcanon = rhs.getCanonicalType();
1298
1299 // If two types are identical, they are are compatible
1300 if (lcanon == rcanon)
1301 return true;
Bill Wendling6a9d8542007-12-03 07:33:35 +00001302
1303 // C++ [expr]: If an expression initially has the type "reference to T", the
1304 // type is adjusted to "T" prior to any further analysis, the expression
1305 // designates the object or function denoted by the reference, and the
1306 // expression is an lvalue.
1307 if (lcanon->getTypeClass() == Type::Reference)
1308 lcanon = cast<ReferenceType>(lcanon)->getReferenceeType();
1309 if (rcanon->getTypeClass() == Type::Reference)
1310 rcanon = cast<ReferenceType>(rcanon)->getReferenceeType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00001311
1312 // If the canonical type classes don't match, they can't be compatible
1313 if (lcanon->getTypeClass() != rcanon->getTypeClass()) {
1314 // For Objective-C, it is possible for two types to be compatible
1315 // when their classes don't match (when dealing with "id"). If either type
1316 // is an interface, we defer to objcTypesAreCompatible().
1317 if (lcanon->isObjcInterfaceType() || rcanon->isObjcInterfaceType())
1318 return objcTypesAreCompatible(lcanon, rcanon);
1319 return false;
1320 }
1321 switch (lcanon->getTypeClass()) {
1322 case Type::Pointer:
1323 return pointerTypesAreCompatible(lcanon, rcanon);
Steve Naroff85f0dc52007-10-15 20:41:53 +00001324 case Type::ConstantArray:
1325 case Type::VariableArray:
1326 return arrayTypesAreCompatible(lcanon, rcanon);
1327 case Type::FunctionNoProto:
1328 case Type::FunctionProto:
1329 return functionTypesAreCompatible(lcanon, rcanon);
1330 case Type::Tagged: // handle structures, unions
1331 return tagTypesAreCompatible(lcanon, rcanon);
1332 case Type::Builtin:
1333 return builtinTypesAreCompatible(lcanon, rcanon);
1334 case Type::ObjcInterface:
1335 return interfaceTypesAreCompatible(lcanon, rcanon);
Chris Lattner5003e8b2007-11-01 05:03:41 +00001336 case Type::Vector:
1337 case Type::OCUVector:
1338 return vectorTypesAreCompatible(lcanon, rcanon);
Steve Naroff85f0dc52007-10-15 20:41:53 +00001339 default:
1340 assert(0 && "unexpected type");
1341 }
1342 return true; // should never get here...
1343}
Ted Kremenek738e6c02007-10-31 17:10:13 +00001344
Ted Kremenek738e6c02007-10-31 17:10:13 +00001345/// Emit - Serialize an ASTContext object to Bitcode.
1346void ASTContext::Emit(llvm::Serializer& S) const {
Ted Kremenek9af4d5c2007-10-31 20:00:03 +00001347 S.EmitRef(SourceMgr);
1348 S.EmitRef(Target);
1349 S.EmitRef(Idents);
1350 S.EmitRef(Selectors);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001351
Ted Kremenek68228a92007-10-31 22:44:07 +00001352 // Emit the size of the type vector so that we can reserve that size
1353 // when we reconstitute the ASTContext object.
Ted Kremenek0199d9f2007-11-06 22:26:16 +00001354 S.EmitInt(Types.size());
1355
Ted Kremenek034a78c2007-11-13 22:02:55 +00001356 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
1357 I!=E;++I)
1358 (*I)->Emit(S);
Ted Kremenek0199d9f2007-11-06 22:26:16 +00001359
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00001360 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001361}
1362
Ted Kremenekacba3612007-11-13 00:25:37 +00001363ASTContext* ASTContext::Create(llvm::Deserializer& D) {
Ted Kremenek68228a92007-10-31 22:44:07 +00001364 SourceManager &SM = D.ReadRef<SourceManager>();
1365 TargetInfo &t = D.ReadRef<TargetInfo>();
1366 IdentifierTable &idents = D.ReadRef<IdentifierTable>();
1367 SelectorTable &sels = D.ReadRef<SelectorTable>();
1368
1369 unsigned size_reserve = D.ReadInt();
1370
1371 ASTContext* A = new ASTContext(SM,t,idents,sels,size_reserve);
1372
Ted Kremenek034a78c2007-11-13 22:02:55 +00001373 for (unsigned i = 0; i < size_reserve; ++i)
1374 Type::Create(*A,i,D);
Ted Kremenek0199d9f2007-11-06 22:26:16 +00001375
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00001376 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
Ted Kremenek68228a92007-10-31 22:44:07 +00001377
1378 return A;
1379}